repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
torch2424/Feather
app/build/generated/source/r/debug/com/torch2424/feather/R.java
68577
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.torch2424.feather; public final class R { public static final class attr { /** <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int adSize=0x7f010000; /** <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int adSizes=0x7f010001; /** <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int adUnitId=0x7f010002; /** <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>holo_dark</code></td><td>0</td><td></td></tr> <tr><td><code>holo_light</code></td><td>1</td><td></td></tr> </table> */ public static final int appTheme=0x7f010017; /** <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>classic</code></td><td>1</td><td></td></tr> <tr><td><code>grayscale</code></td><td>2</td><td></td></tr> <tr><td><code>monochrome</code></td><td>3</td><td></td></tr> </table> */ public static final int buyButtonAppearance=0x7f01001e; /** <p>May be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. <p>May be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>match_parent</code></td><td>-1</td><td></td></tr> <tr><td><code>wrap_content</code></td><td>-2</td><td></td></tr> </table> */ public static final int buyButtonHeight=0x7f01001b; /** <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>buy_with_google</code></td><td>1</td><td></td></tr> <tr><td><code>buy_now</code></td><td>2</td><td></td></tr> <tr><td><code>book_now</code></td><td>3</td><td></td></tr> <tr><td><code>donate_with_google</code></td><td>4</td><td></td></tr> </table> */ public static final int buyButtonText=0x7f01001d; /** <p>May be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. <p>May be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>match_parent</code></td><td>-1</td><td></td></tr> <tr><td><code>wrap_content</code></td><td>-2</td><td></td></tr> </table> */ public static final int buyButtonWidth=0x7f01001c; /** <p>Must be a floating point value, such as "<code>1.2</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int cameraBearing=0x7f010008; /** <p>Must be a floating point value, such as "<code>1.2</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int cameraTargetLat=0x7f010009; /** <p>Must be a floating point value, such as "<code>1.2</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int cameraTargetLng=0x7f01000a; /** <p>Must be a floating point value, such as "<code>1.2</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int cameraTilt=0x7f01000b; /** <p>Must be a floating point value, such as "<code>1.2</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int cameraZoom=0x7f01000c; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int circleCrop=0x7f010006; /** <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>production</code></td><td>1</td><td></td></tr> <tr><td><code>sandbox</code></td><td>0</td><td></td></tr> <tr><td><code>strict_sandbox</code></td><td>2</td><td></td></tr> </table> */ public static final int environment=0x7f010018; /** <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>buyButton</code></td><td>1</td><td></td></tr> <tr><td><code>selectionDetails</code></td><td>2</td><td></td></tr> </table> */ public static final int fragmentMode=0x7f01001a; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int fragmentStyle=0x7f010019; /** <p>Must be a floating point value, such as "<code>1.2</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int imageAspectRatio=0x7f010005; /** <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>none</code></td><td>0</td><td></td></tr> <tr><td><code>adjust_width</code></td><td>1</td><td></td></tr> <tr><td><code>adjust_height</code></td><td>2</td><td></td></tr> </table> */ public static final int imageAspectRatioAdjust=0x7f010004; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int liteMode=0x7f01000d; /** <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>none</code></td><td>0</td><td></td></tr> <tr><td><code>normal</code></td><td>1</td><td></td></tr> <tr><td><code>satellite</code></td><td>2</td><td></td></tr> <tr><td><code>terrain</code></td><td>3</td><td></td></tr> <tr><td><code>hybrid</code></td><td>4</td><td></td></tr> </table> */ public static final int mapType=0x7f010007; /** <p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". */ public static final int maskedWalletDetailsBackground=0x7f010021; /** <p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". */ public static final int maskedWalletDetailsButtonBackground=0x7f010023; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int maskedWalletDetailsButtonTextAppearance=0x7f010022; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int maskedWalletDetailsHeaderTextAppearance=0x7f010020; /** <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>classic</code></td><td>1</td><td></td></tr> <tr><td><code>monochrome</code></td><td>2</td><td></td></tr> </table> */ public static final int maskedWalletDetailsLogoImageType=0x7f010025; /** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int maskedWalletDetailsLogoTextColor=0x7f010024; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int maskedWalletDetailsTextAppearance=0x7f01001f; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int uiCompass=0x7f01000e; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int uiMapToolbar=0x7f010016; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int uiRotateGestures=0x7f01000f; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int uiScrollGestures=0x7f010010; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int uiTiltGestures=0x7f010011; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int uiZoomControls=0x7f010012; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int uiZoomGestures=0x7f010013; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int useViewLifecycle=0x7f010014; /** <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>slide</code></td><td>1</td><td></td></tr> <tr><td><code>none</code></td><td>2</td><td></td></tr> </table> */ public static final int windowTransitionStyle=0x7f010003; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int zOrderOnTop=0x7f010015; } public static final class color { public static final int blue=0x7f050000; public static final int common_action_bar_splitter=0x7f050001; public static final int common_signin_btn_dark_text_default=0x7f050002; public static final int common_signin_btn_dark_text_disabled=0x7f050003; public static final int common_signin_btn_dark_text_focused=0x7f050004; public static final int common_signin_btn_dark_text_pressed=0x7f050005; public static final int common_signin_btn_default_background=0x7f050006; public static final int common_signin_btn_light_text_default=0x7f050007; public static final int common_signin_btn_light_text_disabled=0x7f050008; public static final int common_signin_btn_light_text_focused=0x7f050009; public static final int common_signin_btn_light_text_pressed=0x7f05000a; public static final int common_signin_btn_text_dark=0x7f05001a; public static final int common_signin_btn_text_light=0x7f05001b; public static final int transparent=0x7f05000b; public static final int wallet_bright_foreground_disabled_holo_light=0x7f05000c; public static final int wallet_bright_foreground_holo_dark=0x7f05000d; public static final int wallet_bright_foreground_holo_light=0x7f05000e; public static final int wallet_dim_foreground_disabled_holo_dark=0x7f05000f; public static final int wallet_dim_foreground_holo_dark=0x7f050010; public static final int wallet_dim_foreground_inverse_disabled_holo_dark=0x7f050011; public static final int wallet_dim_foreground_inverse_holo_dark=0x7f050012; public static final int wallet_highlighted_text_holo_dark=0x7f050013; public static final int wallet_highlighted_text_holo_light=0x7f050014; public static final int wallet_hint_foreground_holo_dark=0x7f050015; public static final int wallet_hint_foreground_holo_light=0x7f050016; public static final int wallet_holo_blue_light=0x7f050017; public static final int wallet_link_text_light=0x7f050018; public static final int wallet_primary_text_holo_light=0x7f05001c; public static final int wallet_secondary_text_holo_dark=0x7f05001d; public static final int white=0x7f050019; } public static final class dimen { public static final int activity_horizontal_margin=0x7f060000; public static final int activity_vertical_margin=0x7f060001; } public static final class drawable { public static final int common_full_open_on_phone=0x7f020000; public static final int common_ic_googleplayservices=0x7f020001; public static final int common_signin_btn_icon_dark=0x7f020002; public static final int common_signin_btn_icon_disabled_dark=0x7f020003; public static final int common_signin_btn_icon_disabled_focus_dark=0x7f020004; public static final int common_signin_btn_icon_disabled_focus_light=0x7f020005; public static final int common_signin_btn_icon_disabled_light=0x7f020006; public static final int common_signin_btn_icon_focus_dark=0x7f020007; public static final int common_signin_btn_icon_focus_light=0x7f020008; public static final int common_signin_btn_icon_light=0x7f020009; public static final int common_signin_btn_icon_normal_dark=0x7f02000a; public static final int common_signin_btn_icon_normal_light=0x7f02000b; public static final int common_signin_btn_icon_pressed_dark=0x7f02000c; public static final int common_signin_btn_icon_pressed_light=0x7f02000d; public static final int common_signin_btn_text_dark=0x7f02000e; public static final int common_signin_btn_text_disabled_dark=0x7f02000f; public static final int common_signin_btn_text_disabled_focus_dark=0x7f020010; public static final int common_signin_btn_text_disabled_focus_light=0x7f020011; public static final int common_signin_btn_text_disabled_light=0x7f020012; public static final int common_signin_btn_text_focus_dark=0x7f020013; public static final int common_signin_btn_text_focus_light=0x7f020014; public static final int common_signin_btn_text_light=0x7f020015; public static final int common_signin_btn_text_normal_dark=0x7f020016; public static final int common_signin_btn_text_normal_light=0x7f020017; public static final int common_signin_btn_text_pressed_dark=0x7f020018; public static final int common_signin_btn_text_pressed_light=0x7f020019; public static final int ic_launcher=0x7f02001a; public static final int ic_plusone_medium_off_client=0x7f02001b; public static final int ic_plusone_small_off_client=0x7f02001c; public static final int ic_plusone_standard_off_client=0x7f02001d; public static final int ic_plusone_tall_off_client=0x7f02001e; public static final int next=0x7f02001f; public static final int nextpress=0x7f020020; public static final int nexts=0x7f020021; public static final int playpause=0x7f020022; public static final int playpausepress=0x7f020023; public static final int playpauses=0x7f020024; public static final int powered_by_google_dark=0x7f020025; public static final int powered_by_google_light=0x7f020026; public static final int prev=0x7f020027; public static final int prevpress=0x7f020028; public static final int prevs=0x7f020029; public static final int quit=0x7f02002a; public static final int quitpress=0x7f02002b; public static final int quits=0x7f02002c; } public static final class id { public static final int Buttons=0x7f0b001d; public static final int VideoLayout=0x7f0b001a; public static final int VideoView=0x7f0b001b; public static final int adjust_height=0x7f0b0002; public static final int adjust_width=0x7f0b0003; public static final int book_now=0x7f0b0011; public static final int browserList=0x7f0b001c; public static final int buttons=0x7f0b002e; public static final int buyButton=0x7f0b000d; public static final int buy_now=0x7f0b0012; public static final int buy_with_google=0x7f0b0013; public static final int checkHeadset=0x7f0b0027; public static final int classic=0x7f0b0015; public static final int configTitle=0x7f0b0026; public static final int container=0x7f0b0025; public static final int currentDur=0x7f0b001f; public static final int donate_with_google=0x7f0b0014; public static final int filePath=0x7f0b0018; public static final int fileText=0x7f0b0021; public static final int grayscale=0x7f0b0016; public static final int holo_dark=0x7f0b0008; public static final int holo_light=0x7f0b0009; public static final int hybrid=0x7f0b0004; public static final int listView=0x7f0b0031; public static final int loop=0x7f0b0034; public static final int loopList=0x7f0b0029; public static final int match_parent=0x7f0b000f; public static final int maxDur=0x7f0b0020; public static final int message=0x7f0b002d; public static final int monochrome=0x7f0b0017; public static final int musicSort=0x7f0b0028; public static final int next=0x7f0b0022; public static final int noPlaylist=0x7f0b0032; public static final int noVideo=0x7f0b0019; public static final int none=0x7f0b0000; public static final int normal=0x7f0b0005; public static final int notifcation_icon=0x7f0b002c; public static final int notifylayout=0x7f0b002b; public static final int playlistActivity=0x7f0b0035; public static final int playpause=0x7f0b0023; public static final int prev=0x7f0b002f; public static final int previous=0x7f0b0024; public static final int production=0x7f0b000a; public static final int quit=0x7f0b0030; public static final int sandbox=0x7f0b000b; public static final int satellite=0x7f0b0006; public static final int saveConfig=0x7f0b002a; public static final int seek_bar=0x7f0b001e; public static final int selectionDetails=0x7f0b000e; public static final int settings=0x7f0b0036; public static final int shuffle=0x7f0b0033; public static final int slide=0x7f0b0001; public static final int strict_sandbox=0x7f0b000c; public static final int terrain=0x7f0b0007; public static final int wrap_content=0x7f0b0010; } public static final class integer { public static final int google_play_services_version=0x7f070000; } public static final class layout { public static final int activity_ui=0x7f030000; public static final int fsettings=0x7f030001; public static final int medianotification=0x7f030002; public static final int playlist=0x7f030003; } public static final class menu { public static final int edit_playlist=0x7f0a0000; public static final int fsettings=0x7f0a0001; public static final int ui=0x7f0a0002; } public static final class raw { public static final int gtm_analytics=0x7f040000; } public static final class string { public static final int ConfigTitle=0x7f080000; public static final int accept=0x7f080001; public static final int action_settings=0x7f080002; public static final int app_name=0x7f080003; public static final int common_android_wear_notification_needs_update_text=0x7f080004; public static final int common_android_wear_update_text=0x7f080005; public static final int common_android_wear_update_title=0x7f080006; public static final int common_google_play_services_enable_button=0x7f080007; public static final int common_google_play_services_enable_text=0x7f080008; public static final int common_google_play_services_enable_title=0x7f080009; public static final int common_google_play_services_error_notification_requested_by_msg=0x7f08000a; public static final int common_google_play_services_install_button=0x7f08000b; public static final int common_google_play_services_install_text_phone=0x7f08000c; public static final int common_google_play_services_install_text_tablet=0x7f08000d; public static final int common_google_play_services_install_title=0x7f08000e; public static final int common_google_play_services_invalid_account_text=0x7f08000f; public static final int common_google_play_services_invalid_account_title=0x7f080010; public static final int common_google_play_services_needs_enabling_title=0x7f080011; public static final int common_google_play_services_network_error_text=0x7f080012; public static final int common_google_play_services_network_error_title=0x7f080013; public static final int common_google_play_services_notification_needs_installation_title=0x7f080014; public static final int common_google_play_services_notification_needs_update_title=0x7f080015; public static final int common_google_play_services_notification_ticker=0x7f080016; public static final int common_google_play_services_sign_in_failed_text=0x7f080017; public static final int common_google_play_services_sign_in_failed_title=0x7f080018; public static final int common_google_play_services_unknown_issue=0x7f080019; public static final int common_google_play_services_unsupported_text=0x7f08001a; public static final int common_google_play_services_unsupported_title=0x7f08001b; public static final int common_google_play_services_update_button=0x7f08001c; public static final int common_google_play_services_update_text=0x7f08001d; public static final int common_google_play_services_update_title=0x7f08001e; public static final int common_open_on_phone=0x7f08001f; public static final int common_signin_button_text=0x7f080020; public static final int common_signin_button_text_long=0x7f080021; public static final int commono_google_play_services_api_unavailable_text=0x7f080022; public static final int create_calendar_message=0x7f080023; public static final int create_calendar_title=0x7f080024; public static final int decline=0x7f080025; public static final int headset=0x7f080026; public static final int hello_world=0x7f080027; public static final int loading=0x7f080028; public static final int loop=0x7f080029; public static final int loopList=0x7f08002a; public static final int menuPlaylist=0x7f08002b; public static final int musicSort=0x7f08002c; public static final int next=0x7f08002d; public static final int noPlaylist=0x7f08002e; public static final int noVideo=0x7f08002f; public static final int player_name=0x7f080030; public static final int playpause=0x7f080031; public static final int previous=0x7f080032; public static final int quit=0x7f080033; public static final int saveConfig=0x7f080034; public static final int settings=0x7f080035; public static final int shuffle=0x7f080036; public static final int store_picture_message=0x7f080037; public static final int store_picture_title=0x7f080038; public static final int title_activity_edit_playlist=0x7f080039; public static final int title_activity_feather_settings=0x7f08003a; public static final int title_activity_play_list=0x7f08003b; public static final int wallet_buy_button_place_holder=0x7f08003c; public static final int zero=0x7f08003d; } public static final class style { /** Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. API 11 theme customizations can go here. API 14 theme customizations can go here. */ public static final int AppBaseTheme=0x7f090000; /** All customizations that are NOT specific to a particular API-level can go here. */ public static final int AppTheme=0x7f090001; public static final int Theme_IAPTheme=0x7f090002; public static final int Transparent=0x7f090003; public static final int WalletFragmentDefaultButtonTextAppearance=0x7f090004; public static final int WalletFragmentDefaultDetailsHeaderTextAppearance=0x7f090005; public static final int WalletFragmentDefaultDetailsTextAppearance=0x7f090006; public static final int WalletFragmentDefaultStyle=0x7f090007; } public static final class styleable { /** Attributes that can be used with a AdsAttrs. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #AdsAttrs_adSize com.torch2424.feather:adSize}</code></td><td></td></tr> <tr><td><code>{@link #AdsAttrs_adSizes com.torch2424.feather:adSizes}</code></td><td></td></tr> <tr><td><code>{@link #AdsAttrs_adUnitId com.torch2424.feather:adUnitId}</code></td><td></td></tr> </table> @see #AdsAttrs_adSize @see #AdsAttrs_adSizes @see #AdsAttrs_adUnitId */ public static final int[] AdsAttrs = { 0x7f010000, 0x7f010001, 0x7f010002 }; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#adSize} attribute's value can be found in the {@link #AdsAttrs} array. <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.torch2424.feather:adSize */ public static final int AdsAttrs_adSize = 0; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#adSizes} attribute's value can be found in the {@link #AdsAttrs} array. <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.torch2424.feather:adSizes */ public static final int AdsAttrs_adSizes = 1; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#adUnitId} attribute's value can be found in the {@link #AdsAttrs} array. <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.torch2424.feather:adUnitId */ public static final int AdsAttrs_adUnitId = 2; /** Attributes that can be used with a CustomWalletTheme. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #CustomWalletTheme_windowTransitionStyle com.torch2424.feather:windowTransitionStyle}</code></td><td></td></tr> </table> @see #CustomWalletTheme_windowTransitionStyle */ public static final int[] CustomWalletTheme = { 0x7f010003 }; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#windowTransitionStyle} attribute's value can be found in the {@link #CustomWalletTheme} array. <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>slide</code></td><td>1</td><td></td></tr> <tr><td><code>none</code></td><td>2</td><td></td></tr> </table> @attr name com.torch2424.feather:windowTransitionStyle */ public static final int CustomWalletTheme_windowTransitionStyle = 0; /** Attributes that can be used with a LoadingImageView. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #LoadingImageView_circleCrop com.torch2424.feather:circleCrop}</code></td><td></td></tr> <tr><td><code>{@link #LoadingImageView_imageAspectRatio com.torch2424.feather:imageAspectRatio}</code></td><td></td></tr> <tr><td><code>{@link #LoadingImageView_imageAspectRatioAdjust com.torch2424.feather:imageAspectRatioAdjust}</code></td><td></td></tr> </table> @see #LoadingImageView_circleCrop @see #LoadingImageView_imageAspectRatio @see #LoadingImageView_imageAspectRatioAdjust */ public static final int[] LoadingImageView = { 0x7f010004, 0x7f010005, 0x7f010006 }; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#circleCrop} attribute's value can be found in the {@link #LoadingImageView} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.torch2424.feather:circleCrop */ public static final int LoadingImageView_circleCrop = 2; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#imageAspectRatio} attribute's value can be found in the {@link #LoadingImageView} array. <p>Must be a floating point value, such as "<code>1.2</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.torch2424.feather:imageAspectRatio */ public static final int LoadingImageView_imageAspectRatio = 1; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#imageAspectRatioAdjust} attribute's value can be found in the {@link #LoadingImageView} array. <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>none</code></td><td>0</td><td></td></tr> <tr><td><code>adjust_width</code></td><td>1</td><td></td></tr> <tr><td><code>adjust_height</code></td><td>2</td><td></td></tr> </table> @attr name com.torch2424.feather:imageAspectRatioAdjust */ public static final int LoadingImageView_imageAspectRatioAdjust = 0; /** Attributes that can be used with a MapAttrs. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #MapAttrs_cameraBearing com.torch2424.feather:cameraBearing}</code></td><td></td></tr> <tr><td><code>{@link #MapAttrs_cameraTargetLat com.torch2424.feather:cameraTargetLat}</code></td><td></td></tr> <tr><td><code>{@link #MapAttrs_cameraTargetLng com.torch2424.feather:cameraTargetLng}</code></td><td></td></tr> <tr><td><code>{@link #MapAttrs_cameraTilt com.torch2424.feather:cameraTilt}</code></td><td></td></tr> <tr><td><code>{@link #MapAttrs_cameraZoom com.torch2424.feather:cameraZoom}</code></td><td></td></tr> <tr><td><code>{@link #MapAttrs_liteMode com.torch2424.feather:liteMode}</code></td><td></td></tr> <tr><td><code>{@link #MapAttrs_mapType com.torch2424.feather:mapType}</code></td><td></td></tr> <tr><td><code>{@link #MapAttrs_uiCompass com.torch2424.feather:uiCompass}</code></td><td></td></tr> <tr><td><code>{@link #MapAttrs_uiMapToolbar com.torch2424.feather:uiMapToolbar}</code></td><td></td></tr> <tr><td><code>{@link #MapAttrs_uiRotateGestures com.torch2424.feather:uiRotateGestures}</code></td><td></td></tr> <tr><td><code>{@link #MapAttrs_uiScrollGestures com.torch2424.feather:uiScrollGestures}</code></td><td></td></tr> <tr><td><code>{@link #MapAttrs_uiTiltGestures com.torch2424.feather:uiTiltGestures}</code></td><td></td></tr> <tr><td><code>{@link #MapAttrs_uiZoomControls com.torch2424.feather:uiZoomControls}</code></td><td></td></tr> <tr><td><code>{@link #MapAttrs_uiZoomGestures com.torch2424.feather:uiZoomGestures}</code></td><td></td></tr> <tr><td><code>{@link #MapAttrs_useViewLifecycle com.torch2424.feather:useViewLifecycle}</code></td><td></td></tr> <tr><td><code>{@link #MapAttrs_zOrderOnTop com.torch2424.feather:zOrderOnTop}</code></td><td></td></tr> </table> @see #MapAttrs_cameraBearing @see #MapAttrs_cameraTargetLat @see #MapAttrs_cameraTargetLng @see #MapAttrs_cameraTilt @see #MapAttrs_cameraZoom @see #MapAttrs_liteMode @see #MapAttrs_mapType @see #MapAttrs_uiCompass @see #MapAttrs_uiMapToolbar @see #MapAttrs_uiRotateGestures @see #MapAttrs_uiScrollGestures @see #MapAttrs_uiTiltGestures @see #MapAttrs_uiZoomControls @see #MapAttrs_uiZoomGestures @see #MapAttrs_useViewLifecycle @see #MapAttrs_zOrderOnTop */ public static final int[] MapAttrs = { 0x7f010007, 0x7f010008, 0x7f010009, 0x7f01000a, 0x7f01000b, 0x7f01000c, 0x7f01000d, 0x7f01000e, 0x7f01000f, 0x7f010010, 0x7f010011, 0x7f010012, 0x7f010013, 0x7f010014, 0x7f010015, 0x7f010016 }; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#cameraBearing} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be a floating point value, such as "<code>1.2</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.torch2424.feather:cameraBearing */ public static final int MapAttrs_cameraBearing = 1; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#cameraTargetLat} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be a floating point value, such as "<code>1.2</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.torch2424.feather:cameraTargetLat */ public static final int MapAttrs_cameraTargetLat = 2; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#cameraTargetLng} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be a floating point value, such as "<code>1.2</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.torch2424.feather:cameraTargetLng */ public static final int MapAttrs_cameraTargetLng = 3; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#cameraTilt} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be a floating point value, such as "<code>1.2</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.torch2424.feather:cameraTilt */ public static final int MapAttrs_cameraTilt = 4; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#cameraZoom} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be a floating point value, such as "<code>1.2</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.torch2424.feather:cameraZoom */ public static final int MapAttrs_cameraZoom = 5; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#liteMode} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.torch2424.feather:liteMode */ public static final int MapAttrs_liteMode = 6; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#mapType} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>none</code></td><td>0</td><td></td></tr> <tr><td><code>normal</code></td><td>1</td><td></td></tr> <tr><td><code>satellite</code></td><td>2</td><td></td></tr> <tr><td><code>terrain</code></td><td>3</td><td></td></tr> <tr><td><code>hybrid</code></td><td>4</td><td></td></tr> </table> @attr name com.torch2424.feather:mapType */ public static final int MapAttrs_mapType = 0; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#uiCompass} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.torch2424.feather:uiCompass */ public static final int MapAttrs_uiCompass = 7; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#uiMapToolbar} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.torch2424.feather:uiMapToolbar */ public static final int MapAttrs_uiMapToolbar = 15; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#uiRotateGestures} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.torch2424.feather:uiRotateGestures */ public static final int MapAttrs_uiRotateGestures = 8; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#uiScrollGestures} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.torch2424.feather:uiScrollGestures */ public static final int MapAttrs_uiScrollGestures = 9; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#uiTiltGestures} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.torch2424.feather:uiTiltGestures */ public static final int MapAttrs_uiTiltGestures = 10; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#uiZoomControls} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.torch2424.feather:uiZoomControls */ public static final int MapAttrs_uiZoomControls = 11; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#uiZoomGestures} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.torch2424.feather:uiZoomGestures */ public static final int MapAttrs_uiZoomGestures = 12; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#useViewLifecycle} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.torch2424.feather:useViewLifecycle */ public static final int MapAttrs_useViewLifecycle = 13; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#zOrderOnTop} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.torch2424.feather:zOrderOnTop */ public static final int MapAttrs_zOrderOnTop = 14; /** Attributes that can be used with a WalletFragmentOptions. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #WalletFragmentOptions_appTheme com.torch2424.feather:appTheme}</code></td><td></td></tr> <tr><td><code>{@link #WalletFragmentOptions_environment com.torch2424.feather:environment}</code></td><td></td></tr> <tr><td><code>{@link #WalletFragmentOptions_fragmentMode com.torch2424.feather:fragmentMode}</code></td><td></td></tr> <tr><td><code>{@link #WalletFragmentOptions_fragmentStyle com.torch2424.feather:fragmentStyle}</code></td><td></td></tr> </table> @see #WalletFragmentOptions_appTheme @see #WalletFragmentOptions_environment @see #WalletFragmentOptions_fragmentMode @see #WalletFragmentOptions_fragmentStyle */ public static final int[] WalletFragmentOptions = { 0x7f010017, 0x7f010018, 0x7f010019, 0x7f01001a }; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#appTheme} attribute's value can be found in the {@link #WalletFragmentOptions} array. <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>holo_dark</code></td><td>0</td><td></td></tr> <tr><td><code>holo_light</code></td><td>1</td><td></td></tr> </table> @attr name com.torch2424.feather:appTheme */ public static final int WalletFragmentOptions_appTheme = 0; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#environment} attribute's value can be found in the {@link #WalletFragmentOptions} array. <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>production</code></td><td>1</td><td></td></tr> <tr><td><code>sandbox</code></td><td>0</td><td></td></tr> <tr><td><code>strict_sandbox</code></td><td>2</td><td></td></tr> </table> @attr name com.torch2424.feather:environment */ public static final int WalletFragmentOptions_environment = 1; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#fragmentMode} attribute's value can be found in the {@link #WalletFragmentOptions} array. <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>buyButton</code></td><td>1</td><td></td></tr> <tr><td><code>selectionDetails</code></td><td>2</td><td></td></tr> </table> @attr name com.torch2424.feather:fragmentMode */ public static final int WalletFragmentOptions_fragmentMode = 3; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#fragmentStyle} attribute's value can be found in the {@link #WalletFragmentOptions} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.torch2424.feather:fragmentStyle */ public static final int WalletFragmentOptions_fragmentStyle = 2; /** Attributes that can be used with a WalletFragmentStyle. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #WalletFragmentStyle_buyButtonAppearance com.torch2424.feather:buyButtonAppearance}</code></td><td></td></tr> <tr><td><code>{@link #WalletFragmentStyle_buyButtonHeight com.torch2424.feather:buyButtonHeight}</code></td><td></td></tr> <tr><td><code>{@link #WalletFragmentStyle_buyButtonText com.torch2424.feather:buyButtonText}</code></td><td></td></tr> <tr><td><code>{@link #WalletFragmentStyle_buyButtonWidth com.torch2424.feather:buyButtonWidth}</code></td><td></td></tr> <tr><td><code>{@link #WalletFragmentStyle_maskedWalletDetailsBackground com.torch2424.feather:maskedWalletDetailsBackground}</code></td><td></td></tr> <tr><td><code>{@link #WalletFragmentStyle_maskedWalletDetailsButtonBackground com.torch2424.feather:maskedWalletDetailsButtonBackground}</code></td><td></td></tr> <tr><td><code>{@link #WalletFragmentStyle_maskedWalletDetailsButtonTextAppearance com.torch2424.feather:maskedWalletDetailsButtonTextAppearance}</code></td><td></td></tr> <tr><td><code>{@link #WalletFragmentStyle_maskedWalletDetailsHeaderTextAppearance com.torch2424.feather:maskedWalletDetailsHeaderTextAppearance}</code></td><td></td></tr> <tr><td><code>{@link #WalletFragmentStyle_maskedWalletDetailsLogoImageType com.torch2424.feather:maskedWalletDetailsLogoImageType}</code></td><td></td></tr> <tr><td><code>{@link #WalletFragmentStyle_maskedWalletDetailsLogoTextColor com.torch2424.feather:maskedWalletDetailsLogoTextColor}</code></td><td></td></tr> <tr><td><code>{@link #WalletFragmentStyle_maskedWalletDetailsTextAppearance com.torch2424.feather:maskedWalletDetailsTextAppearance}</code></td><td></td></tr> </table> @see #WalletFragmentStyle_buyButtonAppearance @see #WalletFragmentStyle_buyButtonHeight @see #WalletFragmentStyle_buyButtonText @see #WalletFragmentStyle_buyButtonWidth @see #WalletFragmentStyle_maskedWalletDetailsBackground @see #WalletFragmentStyle_maskedWalletDetailsButtonBackground @see #WalletFragmentStyle_maskedWalletDetailsButtonTextAppearance @see #WalletFragmentStyle_maskedWalletDetailsHeaderTextAppearance @see #WalletFragmentStyle_maskedWalletDetailsLogoImageType @see #WalletFragmentStyle_maskedWalletDetailsLogoTextColor @see #WalletFragmentStyle_maskedWalletDetailsTextAppearance */ public static final int[] WalletFragmentStyle = { 0x7f01001b, 0x7f01001c, 0x7f01001d, 0x7f01001e, 0x7f01001f, 0x7f010020, 0x7f010021, 0x7f010022, 0x7f010023, 0x7f010024, 0x7f010025 }; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#buyButtonAppearance} attribute's value can be found in the {@link #WalletFragmentStyle} array. <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>classic</code></td><td>1</td><td></td></tr> <tr><td><code>grayscale</code></td><td>2</td><td></td></tr> <tr><td><code>monochrome</code></td><td>3</td><td></td></tr> </table> @attr name com.torch2424.feather:buyButtonAppearance */ public static final int WalletFragmentStyle_buyButtonAppearance = 3; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#buyButtonHeight} attribute's value can be found in the {@link #WalletFragmentStyle} array. <p>May be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. <p>May be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>match_parent</code></td><td>-1</td><td></td></tr> <tr><td><code>wrap_content</code></td><td>-2</td><td></td></tr> </table> @attr name com.torch2424.feather:buyButtonHeight */ public static final int WalletFragmentStyle_buyButtonHeight = 0; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#buyButtonText} attribute's value can be found in the {@link #WalletFragmentStyle} array. <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>buy_with_google</code></td><td>1</td><td></td></tr> <tr><td><code>buy_now</code></td><td>2</td><td></td></tr> <tr><td><code>book_now</code></td><td>3</td><td></td></tr> <tr><td><code>donate_with_google</code></td><td>4</td><td></td></tr> </table> @attr name com.torch2424.feather:buyButtonText */ public static final int WalletFragmentStyle_buyButtonText = 2; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#buyButtonWidth} attribute's value can be found in the {@link #WalletFragmentStyle} array. <p>May be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. <p>May be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>match_parent</code></td><td>-1</td><td></td></tr> <tr><td><code>wrap_content</code></td><td>-2</td><td></td></tr> </table> @attr name com.torch2424.feather:buyButtonWidth */ public static final int WalletFragmentStyle_buyButtonWidth = 1; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#maskedWalletDetailsBackground} attribute's value can be found in the {@link #WalletFragmentStyle} array. <p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". @attr name com.torch2424.feather:maskedWalletDetailsBackground */ public static final int WalletFragmentStyle_maskedWalletDetailsBackground = 6; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#maskedWalletDetailsButtonBackground} attribute's value can be found in the {@link #WalletFragmentStyle} array. <p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". <p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". @attr name com.torch2424.feather:maskedWalletDetailsButtonBackground */ public static final int WalletFragmentStyle_maskedWalletDetailsButtonBackground = 8; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#maskedWalletDetailsButtonTextAppearance} attribute's value can be found in the {@link #WalletFragmentStyle} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.torch2424.feather:maskedWalletDetailsButtonTextAppearance */ public static final int WalletFragmentStyle_maskedWalletDetailsButtonTextAppearance = 7; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#maskedWalletDetailsHeaderTextAppearance} attribute's value can be found in the {@link #WalletFragmentStyle} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.torch2424.feather:maskedWalletDetailsHeaderTextAppearance */ public static final int WalletFragmentStyle_maskedWalletDetailsHeaderTextAppearance = 5; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#maskedWalletDetailsLogoImageType} attribute's value can be found in the {@link #WalletFragmentStyle} array. <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>classic</code></td><td>1</td><td></td></tr> <tr><td><code>monochrome</code></td><td>2</td><td></td></tr> </table> @attr name com.torch2424.feather:maskedWalletDetailsLogoImageType */ public static final int WalletFragmentStyle_maskedWalletDetailsLogoImageType = 10; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#maskedWalletDetailsLogoTextColor} attribute's value can be found in the {@link #WalletFragmentStyle} array. <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.torch2424.feather:maskedWalletDetailsLogoTextColor */ public static final int WalletFragmentStyle_maskedWalletDetailsLogoTextColor = 9; /** <p>This symbol is the offset where the {@link com.torch2424.feather.R.attr#maskedWalletDetailsTextAppearance} attribute's value can be found in the {@link #WalletFragmentStyle} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.torch2424.feather:maskedWalletDetailsTextAppearance */ public static final int WalletFragmentStyle_maskedWalletDetailsTextAppearance = 4; }; }
apache-2.0
Eliminater74/BlackBox-Toolkit
app/src/main/java/com/kunalkene1797/blackboxkit/services/ProfileWidget.java
6851
/* * Copyright (C) 2015 Willi Ye * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.kunalkene1797.blackboxkit.services; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.widget.RemoteViews; import android.widget.RemoteViewsService; import com.kunalkene1797.blackboxkit.MainActivity; import com.kunalkene1797.blackboxkit.R; import com.kunalkene1797.blackboxkit.fragments.tools.ProfileFragment; import com.kunalkene1797.blackboxkit.utils.Utils; import com.kunalkene1797.blackboxkit.utils.database.ProfileDB; import com.kunalkene1797.blackboxkit.utils.root.Control; import com.kunalkene1797.blackboxkit.utils.root.RootUtils; import java.util.List; /** * Created by willi on 13.02.15. */ public class ProfileWidget extends AppWidgetProvider { private static final String PROFILE_BUTTON = "profile_button"; private static final String LIST_ITEM_CLICK = "list_item"; private static final String ITEM_ARG = "item_extra"; @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { super.onUpdate(context, appWidgetManager, appWidgetIds); for (int appWidgetId : appWidgetIds) { Intent svcIntent = new Intent(context, WidgetService.class); svcIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); svcIntent.setData(Uri.parse(svcIntent.toUri(Intent.URI_INTENT_SCHEME))); RemoteViews widget = new RemoteViews(context.getPackageName(), R.layout.profile_widget_layout); widget.setRemoteAdapter(R.id.profile_list, svcIntent); widget.setPendingIntentTemplate(R.id.profile_list, getPendingIntent(context, LIST_ITEM_CLICK)); widget.setOnClickPendingIntent(R.id.profile_button, getPendingIntent(context, PROFILE_BUTTON)); appWidgetManager.updateAppWidget(appWidgetId, widget); } } private PendingIntent getPendingIntent(Context context, String action) { Intent intent = new Intent(context, getClass()); intent.setAction(action); return PendingIntent.getBroadcast(context, 0, intent, 0); } @Override public void onReceive(@NonNull final Context context, @NonNull Intent intent) { if (intent.getAction().equals(PROFILE_BUTTON)) { Bundle args = new Bundle(); args.putString(MainActivity.LAUNCH_ARG, ProfileFragment.class.getSimpleName()); Intent launch = new Intent(context, MainActivity.class); launch.putExtras(args); launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); MainActivity.destroy(); context.startActivity(launch); } else if (intent.getAction().equals(LIST_ITEM_CLICK)) { if (!Utils.getBoolean("profileclicked", false, context)) { Utils.saveBoolean("profileclicked", true, context); Utils.toast(context.getString(R.string.press_again_to_apply), context); new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(2000); Utils.saveBoolean("profileclicked", false, context); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } else { Utils.saveBoolean("profileclicked", false, context); int position = intent.getIntExtra(ITEM_ARG, 0); ProfileDB profileDB = new ProfileDB(context); ProfileDB.ProfileItem profileItem = profileDB.getAllProfiles().get(position); RootUtils.SU su = new RootUtils.SU(); List<String> paths = profileItem.getPath(); for (int i = 0; i < paths.size(); i++) { Control.commandSaver(context, paths.get(i), profileItem.getCommands().get(i)); su.runCommand(profileItem.getCommands().get(i)); } su.close(); Utils.toast(context.getString(R.string.applied), context); } } super.onReceive(context, intent); } private static class ListViewFactory implements RemoteViewsService.RemoteViewsFactory { private final Context context; public static List<ProfileDB.ProfileItem> items; public ListViewFactory(Context context) { this.context = context; } @Override public long getItemId(int position) { return position; } @Override public void onCreate() { ProfileDB profileDB = new ProfileDB(context); items = profileDB.getAllProfiles(); } @Override public int getCount() { return items.size(); } @Override public void onDataSetChanged() { onCreate(); } @Override public int getViewTypeCount() { return 1; } @Override public RemoteViews getViewAt(int position) { RemoteViews row = new RemoteViews(context.getPackageName(), R.layout.profile_list); row.setTextViewText(R.id.text, items.get(position).getName()); Intent i = new Intent(); Bundle extras = new Bundle(); extras.putInt(ITEM_ARG, position); i.putExtras(extras); row.setOnClickFillInIntent(R.id.text, i); return (row); } @Override public RemoteViews getLoadingView() { return null; } @Override public boolean hasStableIds() { return true; } @Override public void onDestroy() { } } public static class WidgetService extends RemoteViewsService { @Override public RemoteViewsFactory onGetViewFactory(Intent intent) { return new ListViewFactory(getApplicationContext()); } } }
apache-2.0
TheProjecter/serene
src/serene/validation/schema/simplified/SNameClass.java
1376
/* Copyright 2010 Radu Cernuta Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package serene.validation.schema.simplified; import serene.bind.util.DocumentIndexedData; public abstract class SNameClass extends SComponent implements Identifier{ SimplifiedComponent parent; public SNameClass(int recordIndex, DocumentIndexedData documentIndexedData){ // TODO // Consider null the location data, if it is never needed (restrictions // control?). Changes should be made in the constructors of the // subclasses. super(recordIndex, documentIndexedData); } public SimplifiedComponent getParent(){ return parent; } void setParent(SimplifiedComponent parent, int childIndex){ this.parent = parent; this.childIndex = childIndex; } public String toString(){ return "abstract SNameClass"; } }
apache-2.0
mombergm/bigtop
bigtop-data-generators/bigpetstore-data-generator/src/main/java/org/apache/bigtop/datagenerators/bigpetstore/datareaders/ZipcodeReader.java
5491
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.bigtop.datagenerators.bigpetstore.datareaders; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; import java.util.Vector; import org.apache.bigtop.datagenerators.bigpetstore.datamodels.inputs.ZipcodeRecord; import org.apache.commons.lang3.tuple.Pair; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; public class ZipcodeReader { private static class ZipcodeLocationRecord { public final Pair<Double, Double> coordinates; public final String state; public final String city; public ZipcodeLocationRecord(Pair<Double, Double> coordinates, String city, String state) { this.coordinates = coordinates; this.city = city; this.state = state; } } InputStream zipcodeIncomesFile = null; InputStream zipcodePopulationFile = null; InputStream zipcodeCoordinatesFile = null; public void setIncomesFile(InputStream path) { this.zipcodeIncomesFile = path; } public void setPopulationFile(InputStream path) { this.zipcodePopulationFile = path; } public void setCoordinatesFile(InputStream path) { this.zipcodeCoordinatesFile = path; } private ImmutableMap<String, Double> readIncomeData(InputStream path) throws FileNotFoundException { Scanner scanner = new Scanner(path); // skip headers scanner.nextLine(); scanner.nextLine(); Map<String, Double> entries = Maps.newHashMap(); while(scanner.hasNextLine()) { String line = scanner.nextLine().trim(); String[] cols = line.split(","); // zipcodes are in the form "ZCTA5 XXXXX" String zipcode = cols[2].split(" ")[1].trim(); try { double medianHouseholdIncome = Integer.parseInt(cols[5].trim()); entries.put(zipcode, medianHouseholdIncome); } catch(NumberFormatException e) { } } scanner.close(); return ImmutableMap.copyOf(entries); } private ImmutableMap<String, Long> readPopulationData(InputStream path) throws FileNotFoundException { Scanner scanner = new Scanner(path); // skip header scanner.nextLine(); Map<String, Long> entries = Maps.newHashMap(); while(scanner.hasNextLine()) { String line = scanner.nextLine().trim(); if(line.length() == 0) continue; String[] cols = line.split(","); String zipcode = cols[0].trim(); Long population = Long.parseLong(cols[1].trim()); if(entries.containsKey(zipcode)) { entries.put(zipcode, Math.max(entries.get(zipcode), population)); } else { entries.put(zipcode, population); } } scanner.close(); return ImmutableMap.copyOf(entries); } private ImmutableMap<String, ZipcodeLocationRecord> readCoordinates(InputStream path) throws FileNotFoundException { Scanner scanner = new Scanner(path); // skip header scanner.nextLine(); Map<String, ZipcodeLocationRecord> entries = Maps.newHashMap(); while(scanner.hasNextLine()) { String line = scanner.nextLine().trim(); String[] cols = line.split(", "); // remove quote marks String zipcode = cols[0].substring(1, cols[0].length() - 1); String state = cols[1].substring(1, cols[1].length() - 1); Double latitude = Double.parseDouble(cols[2].substring(1, cols[2].length() - 1)); Double longitude = Double.parseDouble(cols[3].substring(1, cols[3].length() - 1)); String city = cols[4].substring(1, cols[4].length() - 1); Pair<Double, Double> coords = Pair.of(latitude, longitude); ZipcodeLocationRecord record = new ZipcodeLocationRecord(coords, city, state); entries.put(zipcode, record); } scanner.close(); return ImmutableMap.copyOf(entries); } public ImmutableList<ZipcodeRecord> readData() throws FileNotFoundException { ImmutableMap<String, Double> incomes = readIncomeData(this.zipcodeIncomesFile); ImmutableMap<String, Long> populations = readPopulationData(this.zipcodePopulationFile); ImmutableMap<String, ZipcodeLocationRecord> coordinates = readCoordinates(this.zipcodeCoordinatesFile); Set<String> zipcodeSubset = new HashSet<String>(incomes.keySet()); zipcodeSubset.retainAll(populations.keySet()); zipcodeSubset.retainAll(coordinates.keySet()); List<ZipcodeRecord> table = new Vector<ZipcodeRecord>(); for(String zipcode : zipcodeSubset) { ZipcodeRecord record = new ZipcodeRecord(zipcode, coordinates.get(zipcode).coordinates, coordinates.get(zipcode).city, coordinates.get(zipcode).state, incomes.get(zipcode), populations.get(zipcode)); table.add(record); } return ImmutableList.copyOf(table); } }
apache-2.0
yafengguo/Apache-beam
sdks/java/core/src/test/java/org/apache/beam/sdk/PipelineTest.java
9723
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.sdk; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.isA; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import com.google.common.collect.ImmutableList; import org.apache.beam.sdk.Pipeline.PipelineExecutionException; import org.apache.beam.sdk.options.PipelineOptions; import org.apache.beam.sdk.options.PipelineOptions.CheckEnabled; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.apache.beam.sdk.runners.PipelineRunner; import org.apache.beam.sdk.testing.CrashingRunner; import org.apache.beam.sdk.testing.ExpectedLogs; import org.apache.beam.sdk.testing.NeedsRunner; import org.apache.beam.sdk.testing.PAssert; import org.apache.beam.sdk.testing.RunnableOnService; import org.apache.beam.sdk.testing.TestPipeline; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.transforms.Flatten; import org.apache.beam.sdk.transforms.MapElements; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.transforms.SimpleFunction; import org.apache.beam.sdk.util.UserCodeException; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.PCollectionList; import org.apache.beam.sdk.values.PCollectionTuple; import org.apache.beam.sdk.values.PInput; import org.apache.beam.sdk.values.POutput; import org.apache.beam.sdk.values.TupleTag; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests for Pipeline. */ @RunWith(JUnit4.class) public class PipelineTest { @Rule public ExpectedLogs logged = ExpectedLogs.none(Pipeline.class); @Rule public ExpectedException thrown = ExpectedException.none(); static class PipelineWrapper extends Pipeline { protected PipelineWrapper(PipelineRunner<?> runner) { super(runner, PipelineOptionsFactory.create()); } } // Mock class that throws a user code exception during the call to // Pipeline.run(). static class TestPipelineRunnerThrowingUserException extends PipelineRunner<PipelineResult> { @Override public PipelineResult run(Pipeline pipeline) { Throwable t = new IllegalStateException("user code exception"); throw UserCodeException.wrap(t); } } // Mock class that throws an SDK or API client code exception during // the call to Pipeline.run(). static class TestPipelineRunnerThrowingSDKException extends PipelineRunner<PipelineResult> { @Override public PipelineResult run(Pipeline pipeline) { throw new IllegalStateException("SDK exception"); } } @Test public void testPipelineUserExceptionHandling() { Pipeline p = new PipelineWrapper( new TestPipelineRunnerThrowingUserException()); // Check pipeline runner correctly catches user errors. thrown.expect(PipelineExecutionException.class); thrown.expectCause(isA(IllegalStateException.class)); thrown.expectMessage("user code exception"); p.run(); } @Test public void testPipelineSDKExceptionHandling() { Pipeline p = new PipelineWrapper(new TestPipelineRunnerThrowingSDKException()); // Check pipeline runner correctly catches SDK errors. try { p.run(); fail("Should have thrown an exception."); } catch (RuntimeException exn) { // Make sure the exception isn't a UserCodeException. Assert.assertThat(exn, not(instanceOf(UserCodeException.class))); // Assert that the message is correct. Assert.assertThat(exn.getMessage(), containsString("SDK exception")); // RuntimeException should be IllegalStateException. Assert.assertThat(exn, instanceOf(IllegalStateException.class)); } } @Test @Category(RunnableOnService.class) public void testMultipleApply() { PTransform<PCollection<? extends String>, PCollection<String>> myTransform = addSuffix("+"); Pipeline p = TestPipeline.create(); PCollection<String> input = p.apply(Create.<String>of(ImmutableList.of("a", "b"))); PCollection<String> left = input.apply("Left1", myTransform).apply("Left2", myTransform); PCollection<String> right = input.apply("Right", myTransform); PCollection<String> both = PCollectionList.of(left).and(right) .apply(Flatten.<String>pCollections()); PAssert.that(both).containsInAnyOrder("a++", "b++", "a+", "b+"); p.run(); } private static PTransform<PCollection<? extends String>, PCollection<String>> addSuffix( final String suffix) { return MapElements.via(new SimpleFunction<String, String>() { @Override public String apply(String input) { return input + suffix; } }); } @Test public void testToString() { PipelineOptions options = PipelineOptionsFactory.as(PipelineOptions.class); options.setRunner(CrashingRunner.class); Pipeline pipeline = Pipeline.create(options); assertEquals("Pipeline#" + pipeline.hashCode(), pipeline.toString()); } @Test public void testStableUniqueNameOff() { Pipeline p = TestPipeline.create(); p.getOptions().setStableUniqueNames(CheckEnabled.OFF); p.apply(Create.of(5, 6, 7)); p.apply(Create.of(5, 6, 7)); logged.verifyNotLogged("does not have a stable unique name."); } @Test public void testStableUniqueNameWarning() { Pipeline p = TestPipeline.create(); p.getOptions().setStableUniqueNames(CheckEnabled.WARNING); p.apply(Create.of(5, 6, 7)); p.apply(Create.of(5, 6, 7)); logged.verifyWarn("does not have a stable unique name."); } @Test public void testStableUniqueNameError() { Pipeline p = TestPipeline.create(); p.getOptions().setStableUniqueNames(CheckEnabled.ERROR); p.apply(Create.of(5, 6, 7)); thrown.expectMessage("does not have a stable unique name."); p.apply(Create.of(5, 6, 7)); } /** * Tests that Pipeline supports a pass-through identity function. */ @Test @Category(RunnableOnService.class) public void testIdentityTransform() throws Exception { Pipeline pipeline = TestPipeline.create(); PCollection<Integer> output = pipeline .apply(Create.<Integer>of(1, 2, 3, 4)) .apply("IdentityTransform", new IdentityTransform<PCollection<Integer>>()); PAssert.that(output).containsInAnyOrder(1, 2, 3, 4); pipeline.run(); } private static class IdentityTransform<T extends PInput & POutput> extends PTransform<T, T> { @Override public T apply(T input) { return input; } } /** * Tests that Pipeline supports pulling an element out of a tuple as a transform. */ @Test @Category(RunnableOnService.class) public void testTupleProjectionTransform() throws Exception { Pipeline pipeline = TestPipeline.create(); PCollection<Integer> input = pipeline .apply(Create.<Integer>of(1, 2, 3, 4)); TupleTag<Integer> tag = new TupleTag<Integer>(); PCollectionTuple tuple = PCollectionTuple.of(tag, input); PCollection<Integer> output = tuple .apply("ProjectTag", new TupleProjectionTransform<Integer>(tag)); PAssert.that(output).containsInAnyOrder(1, 2, 3, 4); pipeline.run(); } private static class TupleProjectionTransform<T> extends PTransform<PCollectionTuple, PCollection<T>> { private TupleTag<T> tag; public TupleProjectionTransform(TupleTag<T> tag) { this.tag = tag; } @Override public PCollection<T> apply(PCollectionTuple input) { return input.get(tag); } } /** * Tests that Pipeline supports putting an element into a tuple as a transform. */ @Test @Category(RunnableOnService.class) public void testTupleInjectionTransform() throws Exception { Pipeline pipeline = TestPipeline.create(); PCollection<Integer> input = pipeline .apply(Create.<Integer>of(1, 2, 3, 4)); TupleTag<Integer> tag = new TupleTag<Integer>(); PCollectionTuple output = input .apply("ProjectTag", new TupleInjectionTransform<Integer>(tag)); PAssert.that(output.get(tag)).containsInAnyOrder(1, 2, 3, 4); pipeline.run(); } private static class TupleInjectionTransform<T> extends PTransform<PCollection<T>, PCollectionTuple> { private TupleTag<T> tag; public TupleInjectionTransform(TupleTag<T> tag) { this.tag = tag; } @Override public PCollectionTuple apply(PCollection<T> input) { return PCollectionTuple.of(tag, input); } } /** * Tests that an empty pipeline runs. */ @Test @Category(NeedsRunner.class) public void testEmptyPipeline() throws Exception { Pipeline pipeline = TestPipeline.create(); pipeline.run(); } }
apache-2.0
henryblue/TvRecyclerView
tvrecyclerview/src/main/java/app/com/tvrecyclerview/RowItem.java
770
package app.com.tvrecyclerview; public class RowItem { private int mPos; private int mX; private int mY; private int mWidth; private int mHeight; public int getPos() { return mPos; } public void setPos(int pos) { this.mPos = pos; } public int getX() { return mX; } public void setX(int x) { this.mX = x; } public int getY() { return mY; } public void setY(int y) { this.mY = y; } public int getWidth() { return mWidth; } public void setWidth(int width) { this.mWidth = width; } public int getHeight() { return mHeight; } public void setHeight(int height) { this.mHeight = height; } }
apache-2.0
code-orchestra/metaas-fork
src/main/java/uk/co/badgersinfoil/metaas/impl/ASTASImportStatement.java
729
package uk.co.badgersinfoil.metaas.impl; import uk.co.badgersinfoil.metaas.dom.ASImportStatement; import uk.co.badgersinfoil.metaas.impl.antlr.LinkedListTree; import java.util.List; /** * @author Anton.I.Neverov */ public class ASTASImportStatement extends ASTScriptElement implements ASImportStatement { public ASTASImportStatement(LinkedListTree ast) { super(ast); } public String getImportText() { return ASTUtils.identStarText(ast.getFirstChild()); } public List<Comment> getCommentsAfter() { return CommentUtils.getCommentAfter(this.getAST()); } public int getSpacerSize() { return SpacerUtil.calculateSpacerSize(ast); } }
apache-2.0
TheLimeGlass/skquery
src/main/java/com/w00tmast3r/skquery/elements/SimpleTypes.java
1353
package com.w00tmast3r.skquery.elements; import com.w00tmast3r.skquery.annotations.AbstractTask; import com.w00tmast3r.skquery.skript.EnumClassInfo; import com.w00tmast3r.skquery.skript.TypeClassInfo; import com.w00tmast3r.skquery.util.minecraft.MoonPhase; import java.sql.ResultSet; import org.bukkit.Art; import org.bukkit.Particle; import org.bukkit.Sound; import org.bukkit.WorldBorder; import org.bukkit.entity.Villager; import org.bukkit.event.entity.EntityRegainHealthEvent; import org.bukkit.event.inventory.InventoryType; import org.bukkit.scoreboard.DisplaySlot; public class SimpleTypes extends AbstractTask { @Override public void run() { EnumClassInfo.create(EntityRegainHealthEvent.RegainReason.class, "regainreason").register(); EnumClassInfo.create(Villager.Profession.class, "profession").register(); EnumClassInfo.create(InventoryType.class, "inventorytype").register(); EnumClassInfo.create(DisplaySlot.class, "displayslot").register(); EnumClassInfo.create(MoonPhase.class, "moonphase").register(); EnumClassInfo.create(Particle.class, "particle").register(); EnumClassInfo.create(Sound.class, "sound").register(); EnumClassInfo.create(Art.class, "art").register(); TypeClassInfo.create(WorldBorder.class, "worldborder").register(); TypeClassInfo.create(ResultSet.class, "queryresult").register(); } }
apache-2.0
Palo-IT/maven-jenkins-plugins
src/main/java/org/palo/it/forge/maven/plugins/jenkins/api/ProjectHelper.java
2662
/* * PALO IT source code: * ====================== * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Links: * ====== * Git : https://github.com/Palo-IT/Devoxx2014Raspberry */ package org.palo.it.forge.maven.plugins.jenkins.api; import java.util.Properties; import org.apache.maven.project.MavenProject; /** * ProjectHelper * * @author pguillerm * @since 30 juil. 2014 */ public class ProjectHelper { // ========================================================================= // ATTRIBUTES // ========================================================================= private final MavenProject project; // ========================================================================= // CONSTRUCTORS // ========================================================================= public ProjectHelper(MavenProject project) { super(); this.project = project; if (this.project == null) { throw new NullPointerException("maven project can't be null !"); } } // ========================================================================= // METHODS // ========================================================================= public ScmType getScmType() { final String scmTypeRaw = getProperty("forge.project.scm.type"); return ScmType.getEnum(scmTypeRaw); } /** * Allow to get maven property * * @param key the property key * @return property value */ public String getProperty(final String key) { String result = null; Properties properties = null; if (key != null) { properties = project.getProperties(); } if (properties != null && properties.containsKey(key)) { result = properties.getProperty(key); } return result; } }
apache-2.0
alexvasilkov/GestureViews
library/src/main/java/com/alexvasilkov/gestures/commons/RecyclePagerAdapter.java
2769
package com.alexvasilkov.gestures.commons; import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.RecyclerView; import androidx.viewpager.widget.PagerAdapter; import java.util.LinkedList; import java.util.Queue; /** * {@link PagerAdapter} implementation where each page is a regular view. Supports views recycling. * <p> * Inspired by {@link RecyclerView.Adapter}. */ public abstract class RecyclePagerAdapter<VH extends RecyclePagerAdapter.ViewHolder> extends PagerAdapter { private final Queue<VH> cache = new LinkedList<>(); private final SparseArray<VH> attached = new SparseArray<>(); public abstract VH onCreateViewHolder(@NonNull ViewGroup container); public abstract void onBindViewHolder(@NonNull VH holder, int position); public void onRecycleViewHolder(@NonNull VH holder) { } /** * Returns ViewHolder for given position if it exists within ViewPager, or null otherwise. * * @param position Item position * @return View holder for given position */ @Nullable public VH getViewHolder(int position) { return attached.get(position); } @NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) { VH holder = cache.poll(); if (holder == null) { holder = onCreateViewHolder(container); } attached.put(position, holder); // We should not use previous layout params, since ViewPager stores // important information there which cannot be reused container.addView(holder.itemView, null); onBindViewHolder(holder, position); return holder; } @SuppressWarnings("unchecked") @Override public void destroyItem(ViewGroup container, int position, @NonNull Object object) { VH holder = (VH) object; attached.remove(position); container.removeView(holder.itemView); cache.offer(holder); onRecycleViewHolder(holder); } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { ViewHolder holder = (ViewHolder) object; return holder.itemView == view; } @Override public int getItemPosition(@NonNull Object object) { // Forcing all views reinitialization when data set changed. // It should be safe because we're using views recycling logic. return POSITION_NONE; } public static class ViewHolder { public final View itemView; public ViewHolder(@NonNull View itemView) { this.itemView = itemView; } } }
apache-2.0
MegafonWebLab/histone-java
src/main/java/ru/histone/evaluator/functions/node/object/Group.java
2035
/** * Copyright 2013 MegaFon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.histone.evaluator.functions.node.object; import ru.histone.evaluator.functions.node.NodeFunction; import ru.histone.evaluator.nodes.Node; import ru.histone.evaluator.nodes.NodeFactory; import ru.histone.evaluator.nodes.ObjectHistoneNode; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Group extends NodeFunction<ObjectHistoneNode> { public Group(NodeFactory nodeFactory) { super(nodeFactory); } @Override public String getName() { return "group"; } @Override public Node execute(ObjectHistoneNode target, Node... args) { ObjectHistoneNode result = getNodeFactory().object(); if (args.length > 0) { if (!args[0].isString()) { return result; } String column = args[0].getAsString().getValue(); Map<Object, Node> map = target.getElements(); for (Map.Entry<Object, Node> entry : map.entrySet()) { Node val = entry.getValue().getProp(column); String key = val.getAsString().getValue(); if (!result.hasProp(val.getAsString().getValue())) { result.set(key, getNodeFactory().object()); } result.getProp(key).getAsObject().add(entry.getValue()); } } return result; } }
apache-2.0
Villemos/hbird-business
business/business-configurator/src/main/java/org/hbird/business/configurator/ConfiguratorComponent.java
3360
/** * Licensed to the Hummingbird Foundation (HF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The HF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hbird.business.configurator; import java.util.List; import org.hbird.business.api.IPublisher; import org.hbird.business.core.StartableEntity; import org.hbird.exchange.configurator.StartComponent; import org.hbird.exchange.configurator.StopComponent; import org.hbird.exchange.core.Command; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * * Component for starting other components. * * @author Gert Villemos * */ public class ConfiguratorComponent extends StartableEntity implements ApplicationContextAware { /** * */ private static final long serialVersionUID = 2865072999875952015L; public static final String DEFAULT_ID = "Configurator"; public static final String DEFAULT_NAME = "Configurator"; public static final String DEFAULT_DESCRIPTION = "A component for starting other components."; public static final String DEFAULT_DRIVER = ConfiguratorComponentDriver.class.getName(); protected ApplicationContext applicationContext; protected IPublisher publisher; /** * Default constructor. */ public ConfiguratorComponent(IPublisher publisher) { this(DEFAULT_ID, publisher); } /** * Default constructor. */ public ConfiguratorComponent(String ID, IPublisher publisher) { super(ID, DEFAULT_NAME); setDescription(DEFAULT_DESCRIPTION); setDriverName(DEFAULT_DRIVER); this.publisher = publisher; } /** * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context. * ApplicationContext) */ @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } /** * @see org.hbird.business.core.StartableEntity#createCommandList() */ @Override protected List<Command> createCommandList(List<Command> commands) { commands.add(new StartComponent("")); commands.add(new StopComponent("")); return commands; } /** * Initialization method. * * Typically called from the Spring XML file, using the init-method attribute. * * @throws Exception */ public void start() throws Exception { ConfiguratorComponentDriver driver = new ConfiguratorComponentDriver(applicationContext, publisher); driver.start(this); } }
apache-2.0
liunianmiyu/51bang
51bang-common/src/main/java/com/bangxuan/entity/FudaobanEntity.java
2520
package com.bangxuan.entity; import java.util.List; /** * @Description 辅导班 * @Author Zhangcc * @Date 2017/5/6 22:54 */ public class FudaobanEntity { private int id; private String name; private String logo; private String slogan; private String phone; public String getImages() { return images; } public void setImages(String images) { this.images = images; } public List<String> getImageList() { return imageList; } public void setImageList(List<String> imageList) { this.imageList = imageList; } public String getLogo() { return logo; } public void setLogo(String logo) { this.logo = logo; } private String addr; private String service; private String kemu; private String nianji; private String desc; private String feature; private String images; private List<String> imageList; private int isReview; 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 getSlogan() { return slogan; } public void setSlogan(String slogan) { this.slogan = slogan; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getAddr() { return addr; } public void setAddr(String addr) { this.addr = addr; } public String getService() { return service; } public void setService(String service) { this.service = service; } public String getKemu() { return kemu; } public void setKemu(String kemu) { this.kemu = kemu; } public String getNianji() { return nianji; } public void setNianji(String nianji) { this.nianji = nianji; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getFeature() { return feature; } public void setFeature(String feature) { this.feature = feature; } public int getIsReview() { return isReview; } public void setIsReview(int isReview) { this.isReview = isReview; } @Override public String toString() { return "FudaobanEntity{" + "name='" + name + '\'' + ", slogan='" + slogan + '\'' + ", phone='" + phone + '\'' + ", addr='" + addr + '\'' + ", service='" + service + '\'' + ", kemu='" + kemu + '\'' + ", nianji='" + nianji + '\'' + ", desc='" + desc + '\'' + ", feature='" + feature + '\'' + ", isReview=" + isReview + '}'; } }
apache-2.0
consulo/consulo-android
android/android/testSrc/com/android/tools/idea/rendering/ResourceFolderRepositoryTest.java
101384
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.rendering; import com.android.SdkConstants; import com.android.ide.common.rendering.api.*; import com.android.ide.common.res2.DataBindingResourceType; import com.android.ide.common.res2.ResourceFile; import com.android.ide.common.res2.ResourceItem; import com.android.resources.Density; import com.android.resources.ResourceFolderType; import com.android.resources.ResourceType; import com.android.tools.idea.databinding.DataBindingUtil; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.Document; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.xml.XmlFile; import com.intellij.psi.xml.XmlTag; import com.intellij.util.ui.UIUtil; import org.jetbrains.android.AndroidTestCase; import org.jetbrains.android.facet.AndroidFacet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.util.*; import static com.android.SdkConstants.*; import static com.android.tools.idea.rendering.ResourceFolderRepository.ourFullRescans; /** * TODO: Add XmlTags with Psi events to check childAdded etc working correctly! Currently they mostly seem to generate big rescans. * TODO: Test moving from one resource folder to another; should be simulated as an add in one folder and a remove in another; * check that in the ModuleResourceRepository test! * TODO: Test that adding and removing characters inside a {@code <string>} element does not cause a full rescan */ @SuppressWarnings({"UnusedDeclaration", "SpellCheckingInspection"}) public class ResourceFolderRepositoryTest extends AndroidTestCase { private static final String LAYOUT1 = "resourceRepository/layout.xml"; private static final String LAYOUT2 = "resourceRepository/layout2.xml"; private static final String LAYOUT_WITH_DATA_BINDING = "resourceRepository/layout_with_data_binding.xml"; private static final String VALUES1 = "resourceRepository/values.xml"; private static final String VALUES_EMPTY = "resourceRepository/empty.xml"; private static final String XLIFF = "resourceRepository/xliff.xml"; private static final String STRINGS = "resourceRepository/strings.xml"; private static final String DRAWABLE = "resourceRepository/logo.png"; @Override public void tearDown() throws Exception { ResourceFolderRegistry.reset(); super.tearDown(); } @Override public void setUp() throws Exception { super.setUp(); ResourceFolderRegistry.reset(); } private static void resetScanCounter() { ourFullRescans = 0; } private static void ensureIncremental() { assertEquals(0, ourFullRescans); } private static void ensureSingleScan() { assertEquals(1, ourFullRescans); } private ResourceFolderRepository createRepository() { List<VirtualFile> resourceDirectories = myFacet.getAllResourceDirectories(); assertNotNull(resourceDirectories); assertSize(1, resourceDirectories); VirtualFile dir = resourceDirectories.get(0); return ResourceFolderRegistry.get(myFacet, dir); } public void testComputeResourceStrings() throws Exception { // Tests the handling of markup to raw strings // For example, for this strings definition // <string name="title_template_step">Step <xliff:g id="step_number">%1$d</xliff:g>: Lorem Ipsum</string> // the resource value should be // Step %1$d: Lorem Ipsum VirtualFile file1 = myFixture.copyFileToProject(VALUES1, "res/values/myvalues.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); List<ResourceItem> labelList = resources.getResourceItem(ResourceType.STRING, "title_template_step"); assertNotNull(labelList); assertEquals(1, labelList.size()); ResourceItem label = labelList.get(0); ResourceValue resourceValue = label.getResourceValue(false); assertNotNull(resourceValue); assertEquals("Step ${step_number}: Lorem Ipsum", resourceValue.getValue()); // In the file, there's whitespace unlike example above // Test unicode escape handling: <string name="ellipsis">Here it is: \u2026!</string> labelList = resources.getResourceItem(ResourceType.STRING, "ellipsis"); assertNotNull(labelList); assertEquals(1, labelList.size()); label = labelList.get(0); resourceValue = label.getResourceValue(false); assertNotNull(resourceValue); assertEquals("Here it is: \u2026!", resourceValue.getValue()); // Make sure we pick up id's defined using types assertTrue(resources.hasResourceItem(ResourceType.ID, "action_next")); assertFalse(resources.hasResourceItem(ResourceType.ID, "action_next2")); } @SuppressWarnings("ConstantConditions") public void testXliff() throws Exception { // Tests the handling of xliff markup VirtualFile file1 = myFixture.copyFileToProject(XLIFF, "res/values/myvalues.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); assertEquals("Share your score of (1337) with (Bluetooth)!", resources.getResourceItem(ResourceType.STRING, "share_with_application").get(0).getResourceValue(false).getValue()); assertEquals("Call ${name}", resources.getResourceItem(ResourceType.STRING, "description_call").get(0).getResourceValue(false).getValue()); assertEquals("(42) mins (28) secs", resources.getResourceItem(ResourceType.STRING, "callDetailsDurationFormat").get(0).getResourceValue(false).getValue()); assertEquals("${number_of_sessions} sessions removed from your schedule", resources.getResourceItem(ResourceType.STRING, "other").get(0).getResourceValue(false).getValue()); } public void testInitialCreate() throws Exception { myFixture.copyFileToProject(LAYOUT1, "res/layout/layout1.xml"); myFixture.copyFileToProject(LAYOUT1, "res/layout/layout2.xml"); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); Collection<String> layouts = resources.getItemsOfType(ResourceType.LAYOUT); assertEquals(2, layouts.size()); assertNotNull(resources.getResourceItem(ResourceType.LAYOUT, "layout1")); assertNotNull(resources.getResourceItem(ResourceType.LAYOUT, "layout2")); } public void testAddFile() throws Exception { myFixture.copyFileToProject(LAYOUT1, "res/layout/layout1.xml"); myFixture.copyFileToProject(LAYOUT1, "res/layout/layout2.xml"); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); Collection<String> layouts = resources.getItemsOfType(ResourceType.LAYOUT); assertEquals(2, layouts.size()); assertNotNull(resources.getResourceItem(ResourceType.LAYOUT, "layout1")); assertNotNull(resources.getResourceItem(ResourceType.LAYOUT, "layout2")); long generation = resources.getModificationCount(); myFixture.copyFileToProject(LAYOUT1, "res/layout/layout2.xml"); assertEquals(generation, resources.getModificationCount()); // no changes in file: no new generation generation = resources.getModificationCount(); VirtualFile file3 = myFixture.copyFileToProject(LAYOUT1, "res/layout-xlarge-land/layout3.xml"); PsiFile psiFile3 = PsiManager.getInstance(getProject()).findFile(file3); assertNotNull(psiFile3); assertTrue(resources.getModificationCount() > generation); layouts = resources.getItemsOfType(ResourceType.LAYOUT); assertEquals(3, layouts.size()); } public void testAddUnrelatedFile() throws Exception { myFixture.copyFileToProject(LAYOUT1, "res/layout/layout1.xml"); myFixture.copyFileToProject(LAYOUT1, "res/layout/layout2.xml"); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); Collection<String> layouts = resources.getItemsOfType(ResourceType.LAYOUT); assertEquals(2, layouts.size()); assertNotNull(resources.getResourceItem(ResourceType.LAYOUT, "layout1")); assertNotNull(resources.getResourceItem(ResourceType.LAYOUT, "layout2")); long generation = resources.getModificationCount(); myFixture.copyFileToProject(LAYOUT1, "res/layout/layout2.unrelated"); assertEquals(generation, resources.getModificationCount()); // no changes in file: no new generation assertEquals(2, layouts.size()); myFixture.copyFileToProject(LAYOUT1, "src/layout/layout2.xml"); // not a resource folder assertEquals(generation, resources.getModificationCount()); // no changes in file: no new generation assertEquals(2, layouts.size()); } public void testDeleteResourceFile() throws Exception { ResourceFolderRepository resources = createRepository(); assertNotNull(resources); Collection<String> drawables = resources.getItemsOfType(ResourceType.DRAWABLE); assertEquals(drawables.toString(), 0, drawables.size()); long generation = resources.getModificationCount(); VirtualFile file4 = myFixture.copyFileToProject(LAYOUT1, "res/drawable-mdpi/foo.png"); final PsiFile psiFile4 = PsiManager.getInstance(getProject()).findFile(file4); assertNotNull(psiFile4); assertTrue(resources.getModificationCount() > generation); // Delete a file and make sure the item is removed from the repository (and modification count bumped) drawables = resources.getItemsOfType(ResourceType.DRAWABLE); assertEquals(1, drawables.size()); generation = resources.getModificationCount(); assertEquals("foo", drawables.iterator().next()); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { psiFile4.delete(); } }); drawables = resources.getItemsOfType(ResourceType.DRAWABLE); assertEquals(0, drawables.size()); assertTrue(resources.getModificationCount() > generation); } public void testDeleteResourceDirectory() throws Exception { myFixture.copyFileToProject(LAYOUT1, "res/layout/layout1.xml"); myFixture.copyFileToProject(LAYOUT1, "res/layout/layout2.xml"); final VirtualFile file3 = myFixture.copyFileToProject(LAYOUT1, "res/layout-xlarge-land/layout3.xml"); PsiFile psiFile3 = PsiManager.getInstance(getProject()).findFile(file3); assertNotNull(psiFile3); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); // Try deleting a whole resource directory and ensure we remove the files within long generation = resources.getModificationCount(); Collection<String> layouts = resources.getItemsOfType(ResourceType.LAYOUT); assertEquals(3, layouts.size()); final PsiDirectory directory = psiFile3.getContainingDirectory(); assertNotNull(directory); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { directory.delete(); } }); layouts = resources.getItemsOfType(ResourceType.LAYOUT); assertEquals(2, layouts.size()); assertTrue(resources.getModificationCount() > generation); } public void testRenameLayoutFile() throws Exception { final VirtualFile file2 = myFixture.copyFileToProject(LAYOUT1, "res/layout/layout2.xml"); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); // Check renames // rename layout file long generation = resources.getModificationCount(); assertTrue(resources.hasResourceItem(ResourceType.LAYOUT, "layout2")); assertFalse(resources.hasResourceItem(ResourceType.LAYOUT, "layout2b")); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { try { file2.rename(this, "layout2b.xml"); } catch (IOException e) { fail(e.toString()); } } }); assertTrue(resources.hasResourceItem(ResourceType.LAYOUT, "layout2b")); assertFalse(resources.hasResourceItem(ResourceType.LAYOUT, "layout2")); assertTrue(resources.getModificationCount() > generation); } public void testRenameDrawableFile() throws Exception { // rename drawable file final VirtualFile file5 = myFixture.copyFileToProject(LAYOUT1, "res/drawable-xhdpi/foo2.png"); ResourceFolderRepository resources = createRepository(); assertTrue(resources.hasResourceItem(ResourceType.DRAWABLE, "foo2")); assertFalse(resources.hasResourceItem(ResourceType.DRAWABLE, "foo3")); ResourceItem item = getOnlyItem(resources, ResourceType.DRAWABLE, "foo2"); assertTrue(item.getResourceValue(false) instanceof DensityBasedResourceValue); DensityBasedResourceValue rv = (DensityBasedResourceValue)item.getResourceValue(false); assertNotNull(rv); assertSame(Density.XHIGH, rv.getResourceDensity()); long generation = resources.getModificationCount(); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { try { file5.rename(this, "foo3.png"); } catch (IOException e) { fail(e.toString()); } } }); assertTrue(resources.hasResourceItem(ResourceType.DRAWABLE, "foo3")); assertFalse(resources.hasResourceItem(ResourceType.DRAWABLE, "foo2")); assertTrue(resources.getModificationCount() > generation); } public void testRenameValueFile() throws Exception { final VirtualFile file1 = myFixture.copyFileToProject(VALUES1, "res/values/myvalues.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); assertTrue(resources.hasResourceItem(ResourceType.STRING, "title_template_step")); List<ResourceItem> items = resources.getResourceItem(ResourceType.STRING, "title_template_step"); assertNotNull(items); assertEquals(1, items.size()); ResourceItem item = items.get(0); assertEquals("myvalues.xml", item.getSource().getFile().getName()); // Renaming a value file should have no visible effect WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { try { file1.rename(this, "renamedvalues.xml"); } catch (IOException e) { fail(e.toString()); } } }); assertTrue(resources.hasResourceItem(ResourceType.STRING, "title_template_step")); items = resources.getResourceItem(ResourceType.STRING, "title_template_step"); assertNotNull(items); assertEquals(1, items.size()); item = items.get(0); assertEquals("renamedvalues.xml", item.getSource().getFile().getName()); // TODO: Optimize this such that there's no modification change for this. It's tricky because // for file names we get separate notification from the old file deletion (beforePropertyChanged) // and the new file name (propertyChanged). (Note that I tried performing the rename via a // setName operation on the PsiFile instead of at the raw VirtualFile level, but the resulting // events were the same.) //assertEquals(generation, resources.getModificationCount()); } public void testRenameValueFileToInvalid() throws Exception { final VirtualFile file1 = myFixture.copyFileToProject(VALUES1, "res/values/myvalues.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); assertTrue(resources.hasResourceItem(ResourceType.STRING, "title_template_step")); long generation = resources.getModificationCount(); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { try { // After this rename, the values are no longer considered values since they're in an unrecognized file file1.rename(this, "renamedvalues.badextension"); } catch (IOException e) { fail(e.toString()); } } }); assertTrue(generation < resources.getModificationCount()); assertFalse(resources.hasResourceItem(ResourceType.STRING, "title_template_step")); } private static ResourceItem getOnlyItem(ResourceFolderRepository repository, ResourceType type, String name) { List<ResourceItem> item = repository.getResourceItem(type, name); assertNotNull(item); assertEquals(1, item.size()); return item.get(0); } public void testMoveFileResourceFileToNewConfiguration() throws Exception { // Move a file-based resource file from one configuration to another; verify that // items are preserved, generation changed (since it can affect config matching), // and resource files updated. final VirtualFile file1 = myFixture.copyFileToProject(LAYOUT1, "res/layout-land/layout1.xml"); final VirtualFile file2 = myFixture.copyFileToProject(LAYOUT1, "res/layout-port/dummy.ignore"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); ResourceItem item = getOnlyItem(resources, ResourceType.LAYOUT, "layout1"); assertEquals("land", item.getSource().getQualifiers()); ResourceItem idItem = getOnlyItem(resources, ResourceType.ID, "btn_title_refresh"); assertEquals("layout-land", idItem.getSource().getFile().getParentFile().getName()); long generation = resources.getModificationCount(); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { try { // Move file from one location to another file1.move(this, file2.getParent()); } catch (IOException e) { fail(e.toString()); } } }); assertTrue(generation < resources.getModificationCount()); assertTrue(resources.hasResourceItem(ResourceType.LAYOUT, "layout1")); item = getOnlyItem(resources, ResourceType.LAYOUT, "layout1"); assertEquals("port", item.getSource().getQualifiers()); idItem = getOnlyItem(resources, ResourceType.ID, "btn_title_refresh"); assertEquals("layout-port", idItem.getSource().getFile().getParentFile().getName()); } public void testMoveValueResourceFileToNewConfiguration() throws Exception { // Move a value file from one configuration to another; verify that // items are preserved, generation changed (since it can affect config matching), // and resource files updated. final VirtualFile file1 = myFixture.copyFileToProject(VALUES1, "res/values-en/layout1.xml"); final VirtualFile file2 = myFixture.copyFileToProject(VALUES1, "res/values-no/dummy.ignore"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); ResourceItem item = getOnlyItem(resources, ResourceType.STRING, "app_name"); assertEquals("en", item.getSource().getQualifiers()); assertEquals("en", item.getConfiguration().getLocaleQualifier().getLanguage()); //noinspection ConstantConditions assertEquals("Animations Demo", item.getResourceValue(false).getValue()); long generation = resources.getModificationCount(); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { try { // Move file from one location to another file1.move(this, file2.getParent()); } catch (IOException e) { fail(e.toString()); } } }); assertTrue(generation < resources.getModificationCount()); item = getOnlyItem(resources, ResourceType.STRING, "app_name"); assertEquals("no", item.getSource().getQualifiers()); assertEquals("no", item.getConfiguration().getLocaleQualifier().getLanguage()); //noinspection ConstantConditions assertEquals("Animations Demo", item.getResourceValue(false).getValue()); } public void testMoveResourceFileBetweenDensityFolders() throws Exception { // Regression test for https://code.google.com/p/android/issues/detail?id=61648 // Make sure we flush resource values when reusing resource items incrementally // Move a file-based resource file from one configuration to another; verify that // items are preserved, generation changed (since it can affect config matching), // and resource files updated. final VirtualFile file1 = myFixture.copyFileToProject(DRAWABLE, "res/drawable-mdpi/picture.png"); final VirtualFile file2 = myFixture.copyFileToProject(DRAWABLE, "res/drawable-hdpi/dummy.ignore"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); ResourceItem item = getOnlyItem(resources, ResourceType.DRAWABLE, "picture"); ResourceFile source = item.getSource(); assertNotNull(source); assertEquals("mdpi", source.getQualifiers()); ResourceValue resourceValue = item.getResourceValue(false); assertNotNull(resourceValue); String valuePath = resourceValue.getValue().replace(File.separatorChar, '/'); assertTrue(valuePath, valuePath.endsWith("res/drawable-mdpi/picture.png")); long generation = resources.getModificationCount(); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { try { // Move file from one location to another file1.move(this, file2.getParent()); } catch (IOException e) { fail(e.toString()); } } }); assertTrue(generation < resources.getModificationCount()); assertTrue(resources.hasResourceItem(ResourceType.DRAWABLE, "picture")); item = getOnlyItem(resources, ResourceType.DRAWABLE, "picture"); source = item.getSource(); assertNotNull(source); assertEquals("hdpi", source.getQualifiers()); resourceValue = item.getResourceValue(false); assertNotNull(resourceValue); valuePath = resourceValue.getValue().replace(File.separatorChar, '/'); assertTrue(valuePath, valuePath.endsWith("res/drawable-hdpi/picture.png")); } public void testMoveFileResourceFileToNewType() throws Exception { // Move a file resource file file from one folder to another, changing the type // (e.g. anim to animator), verify that resource types are updated final VirtualFile file1 = myFixture.copyFileToProject(LAYOUT1, "res/layout/layout1.xml"); final VirtualFile file2 = myFixture.copyFileToProject(LAYOUT1, "res/menu/dummy.ignore"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); assertTrue(resources.hasResourceItem(ResourceType.LAYOUT, "layout1")); long generation = resources.getModificationCount(); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { try { file1.move(this, file2.getParent()); } catch (IOException e) { fail(e.toString()); } } }); assertTrue(generation < resources.getModificationCount()); assertTrue(resources.hasResourceItem(ResourceType.MENU, "layout1")); assertFalse(resources.hasResourceItem(ResourceType.LAYOUT, "layout1")); ResourceItem item = getOnlyItem(resources, ResourceType.MENU, "layout1"); assertSame(ResourceFolderType.MENU, ((PsiResourceFile)item.getSource()).getFolderType()); } public void testMoveOutOfResourceFolder() throws Exception { // Move value files out of its resource folder; items should disappear final VirtualFile file1 = myFixture.copyFileToProject(VALUES1, "res/values/myvalues.xml"); final VirtualFile javaFile = myFixture.copyFileToProject(VALUES1, "src/my/pkg/Dummy.java"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); assertTrue(resources.hasResourceItem(ResourceType.STRING, "title_template_step")); long generation = resources.getModificationCount(); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { try { file1.move(this, javaFile.getParent()); } catch (IOException e) { fail(e.toString()); } } }); assertTrue(generation < resources.getModificationCount()); assertFalse(resources.hasResourceItem(ResourceType.STRING, "title_template_step")); } public void testMoveIntoResourceFolder() throws Exception { // Move value files out of its resource folder; items should disappear final VirtualFile file1 = myFixture.copyFileToProject(VALUES1, "res/values/dummy.ignore"); final VirtualFile xmlFile = myFixture.copyFileToProject(VALUES1, "src/my/pkg/values.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); final ResourceFolderRepository resources = createRepository(); assertNotNull(resources); assertFalse(resources.hasResourceItem(ResourceType.STRING, "title_template_step")); final long generation = resources.getModificationCount(); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { try { xmlFile.move(this, file1.getParent()); } catch (IOException e) { fail(e.toString()); } } }); assertTrue(generation < resources.getModificationCount()); assertTrue(resources.hasResourceItem(ResourceType.STRING, "title_template_step")); } public void testReplaceResourceFile() throws Exception { final VirtualFile file1 = myFixture.copyFileToProject(LAYOUT1, "res/layout/layout1.xml"); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); assertTrue(resources.hasResourceItem(ResourceType.LAYOUT, "layout1")); assertTrue(resources.hasResourceItem(ResourceType.ID, "btn_title_refresh")); assertFalse(resources.hasResourceItem(ResourceType.ID, "btn_title_refresh2")); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { try { myFixture.copyFileToProject(LAYOUT2, "res/layout/layout1.xml"); } catch (Exception e) { fail(e.toString()); } } }); // TODO: Find out how I can work around this! // This doesn't work because copyFileToProject does not trigger PSI file notifications! //assertTrue(resources.hasResourceItem(ResourceType.ID, "btn_title_refresh2")); //assertFalse(resources.hasResourceItem(ResourceType.ID, "btn_title_refresh")); //assertTrue(generation < resources.getModificationCount()); } public void testAddEmptyValueFile() throws Exception { myFixture.copyFileToProject(LAYOUT1, "res/layout/layout1.xml"); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); long generation = resources.getModificationCount(); assertEquals(generation, resources.getModificationCount()); } public void testRawFolder() throws Exception { // In this folder, any file extension is allowed myFixture.copyFileToProject(LAYOUT1, "res/raw/raw1.xml"); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); Collection<String> raw = resources.getItemsOfType(ResourceType.RAW); assertEquals(1, raw.size()); long generation = resources.getModificationCount(); final VirtualFile file2 = myFixture.copyFileToProject(LAYOUT1, "res/raw/numbers.random"); assertTrue(generation < resources.getModificationCount()); assertTrue(resources.hasResourceItem(ResourceType.RAW, "numbers")); raw = resources.getItemsOfType(ResourceType.RAW); assertEquals(2, raw.size()); generation = resources.getModificationCount(); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { try { file2.rename(this, "numbers2.whatever"); } catch (IOException e) { fail(e.toString()); } } }); assertTrue(resources.getModificationCount() > generation); assertTrue(resources.hasResourceItem(ResourceType.RAW, "numbers2")); assertFalse(resources.hasResourceItem(ResourceType.RAW, "numbers")); } public void testEditLayoutNoOp() throws Exception { resetScanCounter(); // Make some miscellaneous edits in the file that have no bearing on the // project resources and therefore end up doing no work VirtualFile file1 = myFixture.copyFileToProject(LAYOUT1, "res/layout/layout1.xml"); final PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); assert(psiFile1 instanceof XmlFile); final XmlFile xmlFile = (XmlFile)psiFile1; final ResourceFolderRepository resources = createRepository(); assertNotNull(resources); Collection<String> layouts = resources.getItemsOfType(ResourceType.LAYOUT); assertEquals(1, layouts.size()); assertNotNull(resources.getResourceItem(ResourceType.LAYOUT, "layout1")); final long initial = resources.getModificationCount(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject()); final Document document = documentManager.getDocument(psiFile1); assertNotNull(document); // Insert a comment at the beginning WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { XmlTag rootTag = xmlFile.getRootTag(); assertNotNull(rootTag); int rootTagOffset = rootTag.getTextOffset(); document.insertString(rootTagOffset, "<!-- This is a\nmultiline comment -->"); documentManager.commitDocument(document); // Edit the comment some more document.deleteString(rootTagOffset + 8, rootTagOffset + 8 + 5); documentManager.commitDocument(document); document.insertString(rootTagOffset + 8, "Replacement"); documentManager.commitDocument(document); } }); // Inserting the comment and editing it shouldn't have had any observable results on the resource repository assertEquals(initial, resources.getModificationCount()); assertTrue(resources.hasResourceItem(ResourceType.ID, "noteArea")); final XmlTag tag = findTagById(psiFile1, "noteArea"); assertNotNull(tag); // Now insert some whitespace before a tag WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { int indentAreaBeforeTag = tag.getTextOffset() - 1; document.insertString(indentAreaBeforeTag, " "); documentManager.commitDocument(document); document.deleteString(indentAreaBeforeTag, indentAreaBeforeTag + 2); documentManager.commitDocument(document); } }); // Space edits outside the tag shouldn't be observable assertEquals(initial, resources.getModificationCount()); // Edit text inside an element tag. No effect in value files! WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { final XmlTag header = findTagById(xmlFile, "header"); assertNotNull(header); int indentAreaBeforeTag = header.getSubTags()[0].getTextOffset(); document.insertString(indentAreaBeforeTag, " "); documentManager.commitDocument(document); } }); // Space edits inside the tag shouldn't be observable assertEquals(initial, resources.getModificationCount()); // Insert tag (without id) in layout file: ignored (only ids and file item matters) WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { final XmlTag header = findTagById(xmlFile, "text2"); assertNotNull(header); int indentAreaBeforeTag = header.getTextOffset() - 1; document.insertString(indentAreaBeforeTag, "<Button />"); documentManager.commitDocument(document); } }); // Non-id new tags shouldn't be observable assertEquals(initial, resources.getModificationCount()); // Shouldn't have done any full file rescans during the above edits ensureIncremental(); // Finally make an edit which *does* affect the project resources to ensure // that document edits actually *do* fire PSI events that are digested by // this repository final String elementDeclaration = "<Button android:id=\"@+id/newid\" />\n"; WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { final XmlTag tag = findTagById(psiFile1, "noteArea"); assertNotNull(tag); document.insertString(tag.getTextOffset() - 1, elementDeclaration); documentManager.commitDocument(document); } }); assertTrue(resources.isScanPending(psiFile1)); UIUtil.dispatchAllInvocationEvents(); UIUtil.invokeAndWaitIfNeeded(new Runnable() { @Override public void run() { ensureSingleScan(); assertTrue(resources.hasResourceItem(ResourceType.ID, "newid")); assertTrue(resources.getModificationCount() > initial); final long generation = resources.getModificationCount(); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { int startOffset = document.getText().indexOf(elementDeclaration); document.deleteString(startOffset, startOffset + elementDeclaration.length()); documentManager.commitDocument(document); } }); assertTrue(resources.isScanPending(psiFile1)); resetScanCounter(); ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { ensureSingleScan(); assertFalse(resources.hasResourceItem(ResourceType.ID, "newid")); assertTrue(resources.getModificationCount() > generation); } }); UIUtil.dispatchAllInvocationEvents(); } }); } public void testEditValueFileNoOp() throws Exception { resetScanCounter(); VirtualFile file1 = myFixture.copyFileToProject(VALUES1, "res/values/myvalues.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); Collection<String> strings = resources.getItemsOfType(ResourceType.STRING); assertEquals(8, strings.size()); assertTrue(resources.hasResourceItem(ResourceType.STRING, "app_name")); assertTrue(resources.hasResourceItem(ResourceType.INTEGER, "card_flip_time_full")); long initial = resources.getModificationCount(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject()); final Document document = documentManager.getDocument(psiFile1); assertNotNull(document); // Edit comment header; should be a no-op WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { int offset = document.getText().indexOf("Licensed under the"); document.insertString(offset, "This code is "); documentManager.commitDocument(document); } }); assertEquals(initial, resources.getModificationCount()); // Test edit text NOT under an item: no-op WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { int offset = document.getText().indexOf(" <item type=\"id\""); // insert BEFORE this document.insertString(offset, "Ignored text"); documentManager.commitDocument(document); } }); assertEquals(initial, resources.getModificationCount()); // Shouldn't have done any full file rescans during the above edits ensureIncremental(); } public void testInsertNewElementWithId() throws Exception { resetScanCounter(); // Make some miscellaneous edits in the file that have no bearing on the // project resources and therefore end up doing no work VirtualFile file1 = myFixture.copyFileToProject(LAYOUT1, "res/layout/layout1.xml"); final PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); assert(psiFile1 instanceof XmlFile); final XmlFile xmlFile = (XmlFile)psiFile1; final ResourceFolderRepository resources = createRepository(); assertNotNull(resources); Collection<String> layouts = resources.getItemsOfType(ResourceType.LAYOUT); assertEquals(1, layouts.size()); assertNotNull(resources.getResourceItem(ResourceType.LAYOUT, "layout1")); final long initial = resources.getModificationCount(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject()); final Document document = documentManager.getDocument(psiFile1); assertNotNull(document); // Insert tag (with an id) in layout file: should incrementally update set of ids WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { final XmlTag header = findTagById(xmlFile, "text2"); assertNotNull(header); int indentAreaBeforeTag = header.getTextOffset() - 1; document.insertString(indentAreaBeforeTag, "<LinearLayout android:id=\"@+id/newid1\"><Child android:id=\"@+id/newid2\"/></LinearLayout>"); documentManager.commitDocument(document); } }); // Currently, the PSI events delivered for the above edits results in PSI events without enough // info for incremental analysis assertTrue(resources.isScanPending(psiFile1)); UIUtil.dispatchAllInvocationEvents(); UIUtil.invokeAndWaitIfNeeded(new Runnable() { @Override public void run() { ensureSingleScan(); assertTrue(initial < resources.getModificationCount()); assertTrue(resources.hasResourceItem(ResourceType.ID, "newid1")); assertTrue(resources.hasResourceItem(ResourceType.ID, "newid2")); } }); } public void testEditIdAttributeValue() throws Exception { resetScanCounter(); // Edit the id attribute value of a layout item to change the set of available ids VirtualFile file1 = myFixture.copyFileToProject(LAYOUT1, "res/layout/layout1.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); Collection<String> layouts = resources.getItemsOfType(ResourceType.LAYOUT); assertEquals(1, layouts.size()); assertNotNull(resources.getResourceItem(ResourceType.LAYOUT, "layout1")); assertTrue(resources.hasResourceItem(ResourceType.ID, "noteArea")); assertFalse(resources.hasResourceItem(ResourceType.ID, "note2Area")); long generation = resources.getModificationCount(); final XmlTag tag = findTagById(psiFile1, "noteArea"); assertNotNull(tag); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { tag.setAttribute(ATTR_ID, ANDROID_URI, "@+id/note2Area"); } }); assertTrue(resources.hasResourceItem(ResourceType.ID, "note2Area")); assertFalse(resources.hasResourceItem(ResourceType.ID, "noteArea")); assertTrue(resources.getModificationCount() > generation); // Shouldn't have done any full file rescans during the above edits ensureIncremental(); } public void testEditIdAttributeValue2() throws Exception { // Edit the id attribute value: rather than by making a full value replacement, // perform a tiny edit on the character content; this takes a different code // path in the incremental updater resetScanCounter(); // Edit the id attribute value of a layout item to change the set of available ids VirtualFile file1 = myFixture.copyFileToProject(LAYOUT1, "res/layout/layout1.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); Collection<String> layouts = resources.getItemsOfType(ResourceType.LAYOUT); assertEquals(1, layouts.size()); assertNotNull(resources.getResourceItem(ResourceType.LAYOUT, "layout1")); assertTrue(resources.hasResourceItem(ResourceType.ID, "noteArea")); assertFalse(resources.hasResourceItem(ResourceType.ID, "note2Area")); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject()); final Document document = documentManager.getDocument(psiFile1); assertNotNull(document); // Edit value should cause update long generation = resources.getModificationCount(); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { final int offset = document.getText().indexOf("noteArea"); document.insertString(offset + 4, "2"); documentManager.commitDocument(document); } }); assertTrue(resources.hasResourceItem(ResourceType.ID, "note2Area")); assertFalse(resources.hasResourceItem(ResourceType.ID, "noteArea")); assertTrue(resources.getModificationCount() > generation); // Shouldn't have done any full file rescans during the above edits ensureIncremental(); } public void testEditValueText() throws Exception { resetScanCounter(); VirtualFile file1 = myFixture.copyFileToProject(VALUES1, "res/values/myvalues.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); Collection<String> strings = resources.getItemsOfType(ResourceType.STRING); assertEquals(8, strings.size()); assertTrue(resources.hasResourceItem(ResourceType.STRING, "app_name")); assertTrue(resources.hasResourceItem(ResourceType.INTEGER, "card_flip_time_full")); long generation = resources.getModificationCount(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject()); final Document document = documentManager.getDocument(psiFile1); assertNotNull(document); // Edit value should cause update final int screenSlideOffset = document.getText().indexOf("Screen Slide"); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { document.replaceString(screenSlideOffset + 3, screenSlideOffset + 3, "e"); documentManager.commitDocument(document); } }); // NO revision bump yet, because the resource value hasn't been observed! assertEquals(generation, resources.getModificationCount()); // Now observe it, do another edit, and see what happens List<ResourceItem> labelList = resources.getResourceItem(ResourceType.STRING, "title_screen_slide"); assertNotNull(labelList); assertEquals(1, labelList.size()); ResourceItem slideLabel = labelList.get(0); ResourceValue resourceValue = slideLabel.getResourceValue(false); assertNotNull(resourceValue); assertEquals("Screeen Slide", resourceValue.getValue()); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { document.deleteString(screenSlideOffset + 3, screenSlideOffset + 6); documentManager.commitDocument(document); } }); assertTrue(generation < resources.getModificationCount()); resourceValue = slideLabel.getResourceValue(false); assertNotNull(resourceValue); assertEquals("Scrn Slide", resourceValue.getValue()); // Shouldn't have done any full file rescans during the above edits ensureIncremental(); } public void testNestedEditValueText() throws Exception { resetScanCounter(); VirtualFile file1 = myFixture.copyFileToProject(VALUES1, "res/values/myvalues.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); List<ResourceItem> labelList = resources.getResourceItem(ResourceType.STRING, "title_template_step"); assertNotNull(labelList); assertEquals(1, labelList.size()); ResourceItem label = labelList.get(0); ResourceValue resourceValue = label.getResourceValue(false); assertNotNull(resourceValue); assertEquals("Step ${step_number}: Lorem Ipsum", resourceValue.getValue()); long generation = resources.getModificationCount(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject()); final Document document = documentManager.getDocument(psiFile1); assertNotNull(document); // Edit value should cause update final int textOffset = document.getText().indexOf("Lorem"); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { document.insertString(textOffset + 1, "l"); documentManager.commitDocument(document); } }); assertTrue(generation < resources.getModificationCount()); resourceValue = label.getResourceValue(false); assertNotNull(resourceValue); assertEquals("Step ${step_number}: Llorem Ipsum", resourceValue.getValue()); // Shouldn't have done any full file rescans during the above edits ensureIncremental(); } public void testEditValueName() throws Exception { resetScanCounter(); VirtualFile file1 = myFixture.copyFileToProject(VALUES1, "res/values/myvalues.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); Collection<String> strings = resources.getItemsOfType(ResourceType.STRING); assertEquals(8, strings.size()); assertTrue(resources.hasResourceItem(ResourceType.STRING, "app_name")); long generation = resources.getModificationCount(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject()); final Document document = documentManager.getDocument(psiFile1); assertNotNull(document); final int offset = document.getText().indexOf("app_name"); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { document.replaceString(offset, offset + 3, "rap"); documentManager.commitDocument(document); } }); assertTrue(generation < resources.getModificationCount()); assertTrue(resources.hasResourceItem(ResourceType.STRING, "rap_name")); assertFalse(resources.hasResourceItem(ResourceType.STRING, "app_name")); // Shouldn't have done any full file rescans during the above edits ensureIncremental(); } public void testAddValue() throws Exception { resetScanCounter(); VirtualFile file1 = myFixture.copyFileToProject(VALUES1, "res/values/myvalues.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); final ResourceFolderRepository resources = createRepository(); assertNotNull(resources); Collection<String> strings = resources.getItemsOfType(ResourceType.STRING); assertEquals(8, strings.size()); assertTrue(resources.hasResourceItem(ResourceType.STRING, "app_name")); // Incrementally add in a new item final long generation = resources.getModificationCount(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject()); final Document document = documentManager.getDocument(psiFile1); assertNotNull(document); final int offset = document.getText().indexOf(" <item type"); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { String firstHalf = "<string name=\"new_s"; String secondHalf = "tring\">New String</string>"; document.insertString(offset, firstHalf); documentManager.commitDocument(document); document.insertString(offset + firstHalf.length(), secondHalf); documentManager.commitDocument(document); } }); // This currently doesn't work incrementally because we get psi events that do not contain // enough info to be handled incrementally, so instead we do an asynchronous update (such that // we can do a single update rather than rescanning the file 20 times) assertTrue(resources.isScanPending(psiFile1)); UIUtil.dispatchAllInvocationEvents(); UIUtil.invokeAndWaitIfNeeded(new Runnable() { @Override public void run() { ensureSingleScan(); assertTrue(generation < resources.getModificationCount()); assertTrue(resources.hasResourceItem(ResourceType.STRING, "new_string")); //noinspection ConstantConditions assertEquals("New String", resources.getResourceItem(ResourceType.STRING, "new_string").get(0).getResourceValue(false).getValue()); } }); } public void testRemoveValue() throws Exception { resetScanCounter(); VirtualFile file1 = myFixture.copyFileToProject(VALUES1, "res/values/myvalues.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); Collection<String> strings = resources.getItemsOfType(ResourceType.STRING); assertEquals(8, strings.size()); assertTrue(resources.hasResourceItem(ResourceType.STRING, "app_name")); long generation = resources.getModificationCount(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject()); final Document document = documentManager.getDocument(psiFile1); assertNotNull(document); final String textToRemove = "<string name=\"app_name\">Animations Demo</string>"; WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { int offset = document.getText().indexOf(textToRemove); document.deleteString(offset, offset + textToRemove.length()); documentManager.commitDocument(document); } }); assertTrue(generation < resources.getModificationCount()); assertFalse(resources.hasResourceItem(ResourceType.STRING, "app_name")); // Shouldn't have done any full file rescans during the above edits ensureIncremental(); } public void testChangeType() throws Exception { resetScanCounter(); VirtualFile file1 = myFixture.copyFileToProject(VALUES1, "res/values/myvalues.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); final ResourceFolderRepository resources = createRepository(); assertNotNull(resources); assertTrue(resources.hasResourceItem(ResourceType.ID, "action_next")); assertFalse(resources.hasResourceItem(ResourceType.DIMEN, "action_next")); final long generation = resources.getModificationCount(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject()); final Document document = documentManager.getDocument(psiFile1); assertNotNull(document); final int offset = document.getText().indexOf("\"id\" name=\"action_next\" />") + 1; WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { document.replaceString(offset, offset + 2, "dimen"); documentManager.commitDocument(document); } }); assertTrue(resources.isScanPending(psiFile1)); UIUtil.dispatchAllInvocationEvents(); UIUtil.invokeAndWaitIfNeeded(new Runnable() { @Override public void run() { ensureSingleScan(); assertTrue(generation < resources.getModificationCount()); assertFalse(resources.hasResourceItem(ResourceType.ID, "action_next")); assertTrue(resources.hasResourceItem(ResourceType.DIMEN, "action_next")); } }); } public void testBreakNameAttribute() throws Exception { resetScanCounter(); VirtualFile file1 = myFixture.copyFileToProject(VALUES1, "res/values/myvalues.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); final ResourceFolderRepository resources = createRepository(); assertNotNull(resources); assertTrue(resources.hasResourceItem(ResourceType.STRING, "app_name")); final long generation = resources.getModificationCount(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject()); final Document document = documentManager.getDocument(psiFile1); assertNotNull(document); final int offset = document.getText().indexOf("name=\"app_name\">"); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { document.replaceString(offset + 2, offset + 3, "o"); // name => nome documentManager.commitDocument(document); } }); assertTrue(resources.isScanPending(psiFile1)); UIUtil.dispatchAllInvocationEvents(); UIUtil.invokeAndWaitIfNeeded(new Runnable() { @Override public void run() { ensureSingleScan(); assertTrue(generation < resources.getModificationCount()); assertFalse(resources.hasResourceItem(ResourceType.STRING, "app_name")); } }); } public void testChangeValueTypeByTagNameEdit() throws Exception { resetScanCounter(); VirtualFile file1 = myFixture.copyFileToProject(VALUES1, "res/values/myvalues.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); final ResourceFolderRepository resources = createRepository(); assertNotNull(resources); assertTrue(resources.hasResourceItem(ResourceType.INTEGER, "card_flip_time_half")); final long generation = resources.getModificationCount(); final XmlTag tag = findTagByName(psiFile1, "card_flip_time_half"); assertNotNull(tag); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { tag.setName("dimen"); // Change <integer> to <dimen> } }); assertTrue(resources.isScanPending(psiFile1)); UIUtil.dispatchAllInvocationEvents(); UIUtil.invokeAndWaitIfNeeded(new Runnable() { @Override public void run() { ensureSingleScan(); assertTrue(generation < resources.getModificationCount()); assertTrue(resources.hasResourceItem(ResourceType.DIMEN, "card_flip_time_half")); assertFalse(resources.hasResourceItem(ResourceType.INTEGER, "card_flip_time_half")); } }); } public void testEditStyleName() throws Exception { resetScanCounter(); VirtualFile file1 = myFixture.copyFileToProject(VALUES1, "res/values/myvalues.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); final ResourceFolderRepository resources = createRepository(); assertNotNull(resources); assertTrue(resources.hasResourceItem(ResourceType.STYLE, "DarkTheme")); // Change style name long generation = resources.getModificationCount(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject()); final Document document = documentManager.getDocument(psiFile1); assertNotNull(document); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { final int offset = document.getText().indexOf("DarkTheme"); document.replaceString(offset, offset + 4, "Light"); documentManager.commitDocument(document); } }); assertTrue(generation < resources.getModificationCount()); assertFalse(resources.hasResourceItem(ResourceType.STYLE, "DarkTheme")); assertTrue(resources.hasResourceItem(ResourceType.STYLE, "LightTheme")); // Shouldn't have done any full file rescans during the above edits ensureIncremental(); // Change style parent generation = resources.getModificationCount(); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { final int offset = document.getText().indexOf("android:Theme.Holo"); document.replaceString(offset, offset + "android:Theme.Holo".length(), "android:Theme.Light"); documentManager.commitDocument(document); } }); assertTrue(resources.isScanPending(psiFile1)); final long finalGeneration = generation; UIUtil.dispatchAllInvocationEvents(); UIUtil.invokeAndWaitIfNeeded(new Runnable() { @Override public void run() { ensureSingleScan(); assertTrue(finalGeneration < resources.getModificationCount()); ResourceItem style = getOnlyItem(resources, ResourceType.STYLE, "LightTheme"); ResourceValue resourceValue = style.getResourceValue(false); assertNotNull(resourceValue); assertTrue(resourceValue instanceof StyleResourceValue); StyleResourceValue srv = (StyleResourceValue)resourceValue; assertEquals("android:Theme.Light", srv.getParentStyle()); ResourceValue actionBarStyle = srv.getItem("actionBarStyle", true); assertNotNull(actionBarStyle); assertEquals("@style/DarkActionBar", actionBarStyle.getValue()); // (We don't expect editing the style parent to be incremental) } }); } public void testEditStyleItemText() throws Exception { resetScanCounter(); VirtualFile file1 = myFixture.copyFileToProject(VALUES1, "res/values/myvalues.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); assertTrue(resources.hasResourceItem(ResourceType.STYLE, "DarkTheme")); ResourceItem style = getOnlyItem(resources, ResourceType.STYLE, "DarkTheme"); StyleResourceValue srv = (StyleResourceValue)style.getResourceValue(false); assertNotNull(srv); ResourceValue actionBarStyle = srv.getItem("actionBarStyle", true); assertNotNull(actionBarStyle); assertEquals("@style/DarkActionBar", actionBarStyle.getValue()); long generation = resources.getModificationCount(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject()); final Document document = documentManager.getDocument(psiFile1); assertNotNull(document); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { final int offset = document.getText().indexOf("@style/DarkActionBar"); document.replaceString(offset + 7, offset + 11, "Light"); documentManager.commitDocument(document); } }); assertTrue(generation < resources.getModificationCount()); assertTrue(resources.hasResourceItem(ResourceType.STYLE, "DarkTheme")); style = getOnlyItem(resources, ResourceType.STYLE, "DarkTheme"); srv = (StyleResourceValue)style.getResourceValue(false); assertNotNull(srv); actionBarStyle = srv.getItem("actionBarStyle", true); assertNotNull(actionBarStyle); assertEquals("@style/LightActionBar", actionBarStyle.getValue()); // Shouldn't have done any full file rescans during the above edits ensureIncremental(); } public void testEditStyleItemName() throws Exception { resetScanCounter(); VirtualFile file1 = myFixture.copyFileToProject(VALUES1, "res/values/myvalues.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); assertTrue(resources.hasResourceItem(ResourceType.STYLE, "DarkTheme")); ResourceItem style = getOnlyItem(resources, ResourceType.STYLE, "DarkTheme"); StyleResourceValue srv = (StyleResourceValue)style.getResourceValue(false); assertNotNull(srv); ResourceValue actionBarStyle = srv.getItem("actionBarStyle", true); assertNotNull(actionBarStyle); assertEquals("@style/DarkActionBar", actionBarStyle.getValue()); long generation = resources.getModificationCount(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject()); final Document document = documentManager.getDocument(psiFile1); assertNotNull(document); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { final int offset = document.getText().indexOf("android:actionBarStyle"); document.insertString(offset + 8, "in"); documentManager.commitDocument(document); } }); assertTrue(generation < resources.getModificationCount()); assertTrue(resources.hasResourceItem(ResourceType.STYLE, "DarkTheme")); style = getOnlyItem(resources, ResourceType.STYLE, "DarkTheme"); srv = (StyleResourceValue)style.getResourceValue(false); assertNotNull(srv); actionBarStyle = srv.getItem("inactionBarStyle", true); assertNotNull(actionBarStyle); assertEquals("@style/DarkActionBar", actionBarStyle.getValue()); // Shouldn't have done any full file rescans during the above edits ensureIncremental(); } public void testEditDeclareStyleableAttr() throws Exception { // Check edits of the name in a <declare-styleable> element. resetScanCounter(); VirtualFile file1 = myFixture.copyFileToProject(VALUES1, "res/values/myvalues.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); assertTrue(resources.hasResourceItem(ResourceType.DECLARE_STYLEABLE, "MyCustomView")); assertTrue(resources.hasResourceItem(ResourceType.ATTR, "watchType")); ResourceItem style = getOnlyItem(resources, ResourceType.DECLARE_STYLEABLE, "MyCustomView"); DeclareStyleableResourceValue srv = (DeclareStyleableResourceValue)style.getResourceValue(false); assertNotNull(srv); assertEquals(5, srv.getAllAttributes().size()); AttrResourceValue watchType = findAttr(srv.getAllAttributes(), "watchType"); assertNotNull(watchType); assertEquals(2, watchType.getAttributeValues().size()); assertEquals(Integer.valueOf(1), watchType.getAttributeValues().get("type_stopwatch")); assertEquals(Integer.valueOf(0), watchType.getAttributeValues().get("type_countdown")); AttrResourceValue crash = findAttr(srv.getAllAttributes(), "crash"); assertNotNull(crash); assertNull(crash.getAttributeValues()); AttrResourceValue minWidth = findAttr(srv.getAllAttributes(), "minWidth"); assertNotNull(minWidth); assertFalse(resources.hasResourceItem(ResourceType.ATTR, "minWidth")); long generation = resources.getModificationCount(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject()); final Document document = documentManager.getDocument(psiFile1); assertNotNull(document); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { final int offset = document.getText().indexOf("MyCustomView"); document.insertString(offset + 8, "er"); documentManager.commitDocument(document); } }); assertTrue(generation < resources.getModificationCount()); assertTrue(resources.hasResourceItem(ResourceType.DECLARE_STYLEABLE, "MyCustomerView")); assertTrue(resources.hasResourceItem(ResourceType.ATTR, "watchType")); assertFalse(resources.hasResourceItem(ResourceType.DECLARE_STYLEABLE, "MyCustomView")); style = getOnlyItem(resources, ResourceType.DECLARE_STYLEABLE, "MyCustomerView"); srv = (DeclareStyleableResourceValue)style.getResourceValue(false); assertNotNull(srv); assertEquals(5, srv.getAllAttributes().size()); watchType = findAttr(srv.getAllAttributes(), "watchType"); assertNotNull(watchType); assertEquals(2, watchType.getAttributeValues().size()); assertEquals(Integer.valueOf(1), watchType.getAttributeValues().get("type_stopwatch")); // Shouldn't have done any full file rescans during the above edits ensureIncremental(); } public void testEditAttr() throws Exception { // Insert, remove and change <attr> attributes inside a <declare-styleable> and ensure that resetScanCounter(); VirtualFile file1 = myFixture.copyFileToProject(VALUES1, "res/values/myvalues.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); final ResourceFolderRepository resources = createRepository(); assertNotNull(resources); assertTrue(resources.hasResourceItem(ResourceType.DECLARE_STYLEABLE, "MyCustomView")); // Fetch resource value to ensure it gets replaced after update assertTrue(resources.hasResourceItem(ResourceType.ATTR, "watchType")); ResourceItem style = getOnlyItem(resources, ResourceType.DECLARE_STYLEABLE, "MyCustomView"); DeclareStyleableResourceValue srv = (DeclareStyleableResourceValue)style.getResourceValue(false); assertNotNull(srv); assertEquals(5, srv.getAllAttributes().size()); AttrResourceValue watchType = findAttr(srv.getAllAttributes(), "watchType"); assertNotNull(watchType); assertEquals(2, watchType.getAttributeValues().size()); assertEquals(Integer.valueOf(1), watchType.getAttributeValues().get("type_stopwatch")); assertEquals(Integer.valueOf(0), watchType.getAttributeValues().get("type_countdown")); AttrResourceValue crash = findAttr(srv.getAllAttributes(), "crash"); assertNotNull(crash); assertNull(crash.getAttributeValues()); final long generation = resources.getModificationCount(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject()); final Document document = documentManager.getDocument(psiFile1); assertNotNull(document); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { final int offset = document.getText().indexOf("watchType"); document.insertString(offset, "w"); documentManager.commitDocument(document); } }); assertFalse(resources.isScanPending(psiFile1)); assertTrue(generation < resources.getModificationCount()); assertTrue(resources.hasResourceItem(ResourceType.DECLARE_STYLEABLE, "MyCustomView")); assertFalse(resources.hasResourceItem(ResourceType.ATTR, "watchType")); assertTrue(resources.hasResourceItem(ResourceType.ATTR, "wwatchType")); style = getOnlyItem(resources, ResourceType.DECLARE_STYLEABLE, "MyCustomView"); srv = (DeclareStyleableResourceValue)style.getResourceValue(false); assertNotNull(srv); assertEquals(5, srv.getAllAttributes().size()); watchType = findAttr(srv.getAllAttributes(), "wwatchType"); assertNotNull(watchType); assertEquals(2, watchType.getAttributeValues().size()); assertEquals(Integer.valueOf(1), watchType.getAttributeValues().get("type_stopwatch")); // Shouldn't have done any full file rescans during the above edits ensureIncremental(); // Now insert a new item and delete one and make sure we're still okay resetScanCounter(); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { String crashAttr = "<attr name=\"crash\" format=\"boolean\" />"; final int offset = document.getText().indexOf(crashAttr); document.deleteString(offset, offset + crashAttr.length()); document.insertString(offset, "<attr name=\"newcrash\" format=\"integer\" />"); documentManager.commitDocument(document); } }); assertTrue(resources.isScanPending(psiFile1)); UIUtil.dispatchAllInvocationEvents(); UIUtil.invokeAndWaitIfNeeded(new Runnable() { @Override public void run() { ensureSingleScan(); assertTrue(generation < resources.getModificationCount()); assertTrue(resources.hasResourceItem(ResourceType.DECLARE_STYLEABLE, "MyCustomView")); assertFalse(resources.hasResourceItem(ResourceType.ATTR, "watchType")); assertTrue(resources.hasResourceItem(ResourceType.ATTR, "wwatchType")); ResourceItem style = getOnlyItem(resources, ResourceType.DECLARE_STYLEABLE, "MyCustomView"); DeclareStyleableResourceValue srv = (DeclareStyleableResourceValue)style.getResourceValue(false); assertNotNull(srv); assertEquals(5, srv.getAllAttributes().size()); AttrResourceValue watchType = findAttr(srv.getAllAttributes(), "wwatchType"); assertNotNull(watchType); assertEquals(2, watchType.getAttributeValues().size()); assertEquals(Integer.valueOf(1), watchType.getAttributeValues().get("type_stopwatch")); assertEquals(Integer.valueOf(0), watchType.getAttributeValues().get("type_countdown")); AttrResourceValue crash = findAttr(srv.getAllAttributes(), "crash"); assertNull(crash); AttrResourceValue newcrash = findAttr(srv.getAllAttributes(), "newcrash"); assertNotNull(newcrash); assertNull(newcrash.getAttributeValues()); } }); } public void testEditDeclareStyleableFlag() throws Exception { // Rename, add and remove <flag> and <enum> nodes under a declare styleable and assert // that the declare styleable parent is updated resetScanCounter(); VirtualFile file1 = myFixture.copyFileToProject(VALUES1, "res/values/myvalues.xml"); final PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); final ResourceFolderRepository resources = createRepository(); assertNotNull(resources); assertTrue(resources.hasResourceItem(ResourceType.DECLARE_STYLEABLE, "MyCustomView")); // Fetch resource value to ensure it gets replaced after update assertTrue(resources.hasResourceItem(ResourceType.ATTR, "watchType")); assertFalse(resources.hasResourceItem(ResourceType.ATTR, "ignore_no_format")); final ResourceItem style = getOnlyItem(resources, ResourceType.DECLARE_STYLEABLE, "MyCustomView"); final DeclareStyleableResourceValue srv = (DeclareStyleableResourceValue)style.getResourceValue(false); assertNotNull(srv); assertEquals(5, srv.getAllAttributes().size()); final AttrResourceValue flagType = findAttr(srv.getAllAttributes(), "flagType"); assertNotNull(flagType); assertEquals(2, flagType.getAttributeValues().size()); assertEquals(Integer.valueOf(16), flagType.getAttributeValues().get("flag1")); assertEquals(Integer.valueOf(32), flagType.getAttributeValues().get("flag2")); final long generation = resources.getModificationCount(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject()); final Document document = documentManager.getDocument(psiFile1); assertNotNull(document); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { final int offset = document.getText().indexOf("flag1"); document.insertString(offset + 1, "l"); documentManager.commitDocument(document); } }); assertTrue(resources.isScanPending(psiFile1)); UIUtil.dispatchAllInvocationEvents(); UIUtil.invokeAndWaitIfNeeded(new Runnable() { @Override public void run() { ensureSingleScan(); assertTrue(generation < resources.getModificationCount()); assertTrue(resources.hasResourceItem(ResourceType.DECLARE_STYLEABLE, "MyCustomView")); assertTrue(resources.hasResourceItem(ResourceType.ATTR, "flagType")); ResourceItem style = getOnlyItem(resources, ResourceType.DECLARE_STYLEABLE, "MyCustomView"); DeclareStyleableResourceValue srv = (DeclareStyleableResourceValue)style.getResourceValue(false); assertNotNull(srv); assertEquals(5, srv.getAllAttributes().size()); AttrResourceValue flagType = findAttr(srv.getAllAttributes(), "flagType"); assertNotNull(flagType); assertEquals(2, flagType.getAttributeValues().size()); assertNull(flagType.getAttributeValues().get("flag1")); assertEquals(Integer.valueOf(16), flagType.getAttributeValues().get("fllag1")); // Now insert a new enum and delete one and make sure we're still okay resetScanCounter(); long nextGeneration = resources.getModificationCount(); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { String enumAttr = "<enum name=\"type_stopwatch\" value=\"1\"/>"; int offset = document.getText().indexOf(enumAttr); document.deleteString(offset, offset + enumAttr.length()); String flagAttr = "<flag name=\"flag2\" value=\"0x20\"/>"; offset = document.getText().indexOf(flagAttr); document.insertString(offset, "<flag name=\"flag3\" value=\"0x40\"/>"); documentManager.commitDocument(document); } }); assertTrue(nextGeneration < resources.getModificationCount()); assertTrue(resources.hasResourceItem(ResourceType.DECLARE_STYLEABLE, "MyCustomView")); assertTrue(resources.hasResourceItem(ResourceType.ATTR, "watchType")); assertTrue(resources.hasResourceItem(ResourceType.ATTR, "flagType")); style = getOnlyItem(resources, ResourceType.DECLARE_STYLEABLE, "MyCustomView"); srv = (DeclareStyleableResourceValue)style.getResourceValue(false); assertNotNull(srv); assertEquals(5, srv.getAllAttributes().size()); flagType = findAttr(srv.getAllAttributes(), "flagType"); assertNotNull(flagType); assertEquals(3, flagType.getAttributeValues().size()); assertEquals(Integer.valueOf(16), flagType.getAttributeValues().get("fllag1")); assertEquals(Integer.valueOf(32), flagType.getAttributeValues().get("flag2")); assertEquals(Integer.valueOf(64), flagType.getAttributeValues().get("flag3")); AttrResourceValue watchType = findAttr(srv.getAllAttributes(), "watchType"); assertNotNull(watchType); assertEquals(1, watchType.getAttributeValues().size()); assertEquals(Integer.valueOf(0), watchType.getAttributeValues().get("type_countdown")); } }); } public void testEditPluralItems() throws Exception { resetScanCounter(); VirtualFile file1 = myFixture.copyFileToProject(VALUES1, "res/values/myvalues.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); // Test that our tools:quantity works correctly for getResourceValue() assertTrue(resources.hasResourceItem(ResourceType.PLURALS, "my_plural")); ResourceItem plural = getOnlyItem(resources, ResourceType.PLURALS, "my_plural"); ResourceValue resourceValue = plural.getResourceValue(false); assertNotNull(resourceValue); assertEquals("@string/hello_two", resourceValue.getValue()); // TODO: It would be nice to avoid updating the generation if you // edit a different item than the one being picked (default or via // tools:quantity) but for now we're not worrying about that optimization long generation = resources.getModificationCount(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject()); final Document document = documentManager.getDocument(psiFile1); assertNotNull(document); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { final int offset = document.getText().indexOf("@string/hello_two"); document.replaceString(offset + 9, offset + 10, "a"); documentManager.commitDocument(document); } }); plural = getOnlyItem(resources, ResourceType.PLURALS, "my_plural"); resourceValue = plural.getResourceValue(false); assertNotNull(resourceValue); assertEquals("@string/hallo_two", resourceValue.getValue()); assertTrue(generation < resources.getModificationCount()); // Shouldn't have done any full file rescans during the above edits ensureIncremental(); } public void testEditArrayItemText() throws Exception { resetScanCounter(); VirtualFile file1 = myFixture.copyFileToProject(VALUES1, "res/values/myvalues.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); // Test that our tools:index and fallback handling for arrays works correctly // for getResourceValue() assertTrue(resources.hasResourceItem(ResourceType.ARRAY, "security_questions")); ResourceItem array = getOnlyItem(resources, ResourceType.ARRAY, "security_questions"); ResourceValue resourceValue = array.getResourceValue(false); assertNotNull(resourceValue); assertEquals("Question 4", resourceValue.getValue()); assertTrue(resources.hasResourceItem(ResourceType.ARRAY, "integers")); array = getOnlyItem(resources, ResourceType.ARRAY, "integers"); resourceValue = array.getResourceValue(false); assertNotNull(resourceValue); assertEquals("10", resourceValue.getValue()); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject()); final Document document = documentManager.getDocument(psiFile1); assertNotNull(document); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { final int offset = document.getText().indexOf("Question 4"); document.insertString(offset, "Q"); documentManager.commitDocument(document); } }); assertTrue(resources.hasResourceItem(ResourceType.ARRAY, "security_questions")); array = getOnlyItem(resources, ResourceType.ARRAY, "security_questions"); resourceValue = array.getResourceValue(false); assertNotNull(resourceValue); assertEquals("QQuestion 4", resourceValue.getValue()); // Shouldn't have done any full file rescans during the above edits ensureIncremental(); } public void testAddArrayItemElements() throws Exception { resetScanCounter(); VirtualFile file1 = myFixture.copyFileToProject(VALUES1, "res/values/myvalues.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject()); final Document document = documentManager.getDocument(psiFile1); assertNotNull(document); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { final int offset = document.getText().indexOf("<item>Question 3</item>"); document.insertString(offset, "<item>Question 2.5</item>"); documentManager.commitDocument(document); } }); assertTrue(resources.hasResourceItem(ResourceType.ARRAY, "security_questions")); ResourceItem array = getOnlyItem(resources, ResourceType.ARRAY, "security_questions"); ResourceValue resourceValue = array.getResourceValue(false); assertNotNull(resourceValue); assertEquals("Question 3", resourceValue.getValue()); assertTrue(resourceValue instanceof ArrayResourceValue); ArrayResourceValue arv = (ArrayResourceValue)resourceValue; assertEquals(6, arv.getElementCount()); assertEquals("Question 2", arv.getElement(1)); assertEquals("Question 2.5", arv.getElement(2)); assertEquals("Question 3", arv.getElement(3)); // Shouldn't have done any full file rescans during the above edits ensureIncremental(); } public void testRemoveArrayItemElements() throws Exception { resetScanCounter(); VirtualFile file1 = myFixture.copyFileToProject(VALUES1, "res/values/myvalues.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); ResourceFolderRepository resources = createRepository(); assertNotNull(resources); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject()); final Document document = documentManager.getDocument(psiFile1); assertNotNull(document); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { String elementString = "<item>Question 3</item>"; final int offset = document.getText().indexOf(elementString); document.deleteString(offset, offset + elementString.length()); documentManager.commitDocument(document); } }); assertTrue(resources.hasResourceItem(ResourceType.ARRAY, "security_questions")); ResourceItem array = getOnlyItem(resources, ResourceType.ARRAY, "security_questions"); ResourceValue resourceValue = array.getResourceValue(false); assertNotNull(resourceValue); assertEquals("Question 5", resourceValue.getValue()); assertTrue(resourceValue instanceof ArrayResourceValue); ArrayResourceValue arv = (ArrayResourceValue)resourceValue; assertEquals(4, arv.getElementCount()); // Shouldn't have done any full file rescans during the above edits ensureIncremental(); } public void testGradualEdits() throws Exception { resetScanCounter(); // Gradually type in the contents of a value file and make sure we end up with a valid view of the world VirtualFile file1 = myFixture.copyFileToProject(VALUES_EMPTY, "res/values/myvalues.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); final ResourceFolderRepository resources = createRepository(); assertNotNull(resources); final long generation = resources.getModificationCount(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject()); final Document document = documentManager.getDocument(psiFile1); assertNotNull(document); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { document.deleteString(0, document.getTextLength()); documentManager.commitDocument(document); } }); final String contents = "<!--\n" + " -->\n" + "\n" + "<resources xmlns:xliff=\"urn:oasis:names:tc:xliff:document:1.2\">\n" + "\n" + " <!-- Titles -->\n" + " <string name=\"app_name\">Animations Demo</string>\n" + " <string name=\"title_zoom\">Zoom</string>\n" + " <string name=\"title_layout_changes\">Layout Changes</string>\n" + " <string name=\"title_template_step\">Step <xliff:g id=\"step_number\">%1$d</xliff:g>: Lorem\n" + " Ipsum</string>\n" + " <string name=\"ellipsis\">Here it is: \\u2026!</string>\n" + "\n" + " <item type=\"id\" name=\"action_next\" />\n" + "\n" + " <style name=\"DarkActionBar\" parent=\"android:Widget.Holo.ActionBar\">\n" + " <item name=\"android:background\">@android:color/transparent</item>\n" + " </style>\n" + "\n" + " <integer name=\"card_flip_time_half\">150</integer>\n" + "\n" + " <declare-styleable name=\"MyCustomView\">\n" + " <attr name=\"watchType\" format=\"enum\">\n" + " <enum name=\"type_countdown\" value=\"0\"/>\n" + " </attr>\n" + " <attr name=\"crash\" format=\"boolean\" />\n" + " </declare-styleable>\n" + "</resources>\n"; for (int i = 0; i < contents.length(); i++) { final int offset = i; final char character = contents.charAt(i); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { document.insertString(offset, String.valueOf(character)); documentManager.commitDocument(document); } }); } assertTrue(resources.isScanPending(psiFile1)); UIUtil.dispatchAllInvocationEvents(); UIUtil.invokeAndWaitIfNeeded(new Runnable() { @Override public void run() { ensureSingleScan(); assertTrue(generation < resources.getModificationCount()); assertTrue(resources.hasResourceItem(ResourceType.STYLE, "DarkActionBar")); assertTrue(resources.hasResourceItem(ResourceType.STYLE, "DarkActionBar")); ResourceItem style = getOnlyItem(resources, ResourceType.STYLE, "DarkActionBar"); StyleResourceValue srv = (StyleResourceValue)style.getResourceValue(false); assertNotNull(srv); ResourceValue actionBarStyle = srv.getItem("background", true); assertNotNull(actionBarStyle); assertEquals("@android:color/transparent", actionBarStyle.getValue()); //noinspection ConstantConditions assertEquals("Zoom", getOnlyItem(resources, ResourceType.STRING, "title_zoom").getResourceValue(false).getValue()); } }); } public void testIssue56799() throws Exception { // Test deleting a string; ensure that the whole repository is updated correctly. // Regression test for // https://code.google.com/p/android/issues/detail?id=56799 VirtualFile file1 = myFixture.copyFileToProject(STRINGS, "res/values/strings.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); final ResourceFolderRepository resources = createRepository(); assertNotNull(resources); assertTrue(resources.hasResourceItem(ResourceType.STRING, "app_name")); assertFalse(resources.hasResourceItem(ResourceType.STRING, "app_name2")); assertTrue(resources.hasResourceItem(ResourceType.STRING, "hello_world")); final long generation = resources.getModificationCount(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject()); final Document document = documentManager.getDocument(psiFile1); assertNotNull(document); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { String string = " <string name=\"hello_world\">Hello world!</string>"; final int offset = document.getText().indexOf(string); assertTrue(offset != -1); document.deleteString(offset, offset + string.length()); documentManager.commitDocument(document); } }); assertTrue(generation < resources.getModificationCount()); assertTrue(resources.isScanPending(psiFile1)); resetScanCounter(); UIUtil.dispatchAllInvocationEvents(); UIUtil.invokeAndWaitIfNeeded(new Runnable() { @Override public void run() { ensureSingleScan(); assertTrue(resources.hasResourceItem(ResourceType.STRING, "app_name")); assertFalse(resources.hasResourceItem(ResourceType.STRING, "hello_world")); } }); } public void testEditXmlProcessingInstructionAttr() throws Exception { // Test editing an attribute in the XML prologue VirtualFile file1 = myFixture.copyFileToProject(STRINGS, "res/values/strings.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); final ResourceFolderRepository resources = createRepository(); assertNotNull(resources); assertTrue(resources.hasResourceItem(ResourceType.STRING, "app_name")); assertFalse(resources.hasResourceItem(ResourceType.STRING, "app_name2")); assertTrue(resources.hasResourceItem(ResourceType.STRING, "hello_world")); final long generation = resources.getModificationCount(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject()); final Document document = documentManager.getDocument(psiFile1); assertNotNull(document); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { String string = "utf-8"; final int offset = document.getText().indexOf(string); assertTrue(offset != -1); document.insertString(offset, "t"); documentManager.commitDocument(document); } }); // Edits in XML processing instructions have no effect on the resource repository assertEquals(generation, resources.getModificationCount()); assertFalse(resources.isScanPending(psiFile1)); UIUtil.dispatchAllInvocationEvents(); } public void testIssue64239() throws Exception { // If you duplicate a string, then change its contents (which still duplicated), // and then finally rename the string, then the value of the second clone will // continue to be referred from the first string: // <string name="foo">value 1</foo> // <string name="foo">value 2</foo> // then change the second string name to // <string name="foo2">value 2</foo> // If you now evaluate the value of foo, you get "value 1". Basically while the // two strings are (illegally) aliasing, the value of the first string is replaced. // TODO: Test both *duplicating* a node, as well as manually typing in a brand // new one with the same result VirtualFile file1 = myFixture.copyFileToProject(STRINGS, "res/values/strings.xml"); PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); final ResourceFolderRepository resources = createRepository(); assertNotNull(resources); assertTrue(resources.hasResourceItem(ResourceType.STRING, "app_name")); //noinspection ConstantConditions assertEquals("My Application 574", resources.getResourceItem(ResourceType.STRING, "app_name").get(0).getResourceValue(false).getValue()); final long generation = resources.getModificationCount(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject()); final Document document = documentManager.getDocument(psiFile1); assertNotNull(document); final int offset = document.getText().indexOf("</resources>"); assertTrue(offset != -1); final String string = "<string name=\"app_name\">New Value</string>"; // First duplicate the line: WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { @Override public void run() { document.insertString(offset, string); documentManager.commitDocument(document); } }); assertTrue(generation < resources.getModificationCount()); resetScanCounter(); assertTrue(resources.hasResourceItem(ResourceType.STRING, "app_name")); // Then replace the name of the duplicated string WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { @Override public void run() { int startOffset = offset + "<string name=\"".length(); document.replaceString(startOffset, startOffset + "app_name".length(), "new_name"); documentManager.commitDocument(document); } }); assertFalse(resources.isScanPending(psiFile1)); assertTrue(generation < resources.getModificationCount()); resetScanCounter(); assertTrue(resources.hasResourceItem(ResourceType.STRING, "app_name")); assertTrue(resources.hasResourceItem(ResourceType.STRING, "new_name")); //noinspection ConstantConditions assertEquals("New Value", resources.getResourceItem(ResourceType.STRING, "new_name").get(0).getResourceValue(false).getValue()); //noinspection ConstantConditions assertEquals("My Application 574", resources.getResourceItem(ResourceType.STRING, "app_name").get(0).getResourceValue(false).getValue()); } public void testSync() throws Exception { // Regression test for https://code.google.com/p/android/issues/detail?id=79629 // Ensure that sync() handles rescanning immediately VirtualFile file1 = myFixture.copyFileToProject(STRINGS, "res/values/strings.xml"); final PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); final ResourceFolderRepository resources = createRepository(); assertNotNull(resources); assertTrue(resources.hasResourceItem(ResourceType.STRING, "app_name")); assertFalse(resources.hasResourceItem(ResourceType.STRING, "app_name2")); assertTrue(resources.hasResourceItem(ResourceType.STRING, "hello_world")); final long generation = resources.getModificationCount(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject()); final Document document = documentManager.getDocument(psiFile1); assertNotNull(document); UIUtil.invokeAndWaitIfNeeded(new Runnable() { @Override public void run() { // The sync() call must be called from the dispatch thread WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { String string = " <string name=\"hello_world\">Hello world!</string>"; final int offset = document.getText().indexOf(string); assertTrue(offset != -1); // Simulate an edit event that triggers the incremental updater to // give up and schedule a subsequent update instead. (This used to be // the case here, but as of IntelliJ 14.1 it's now delivering more // accurate events for the below edits, which made the sync-test // fail because it would already have correct results *before* the // sync. Therefore, we simply trigger a pending scan (which stops // subequent incremental events from being processed). resources.rescan(psiFile1, ResourceFolderType.VALUES); document.deleteString(offset, offset + string.length()); documentManager.commitDocument(document); } }); // The strings file contains definitions for app_name, action_settings and hello_world. // We've manually deleted the hello_world string. We now check that app_name remains // in the resource set, and that hello_world is removed. (We check that hello_world // is there before the sync, and gone after.) assertTrue(resources.isScanPending(psiFile1)); assertTrue(resources.hasResourceItem(ResourceType.STRING, "app_name")); assertTrue(resources.hasResourceItem(ResourceType.STRING, "hello_world")); assertTrue(ApplicationManager.getApplication().isDispatchThread()); resources.sync(); assertTrue(generation < resources.getModificationCount()); assertTrue(resources.hasResourceItem(ResourceType.STRING, "app_name")); assertFalse(resources.hasResourceItem(ResourceType.STRING, "hello_world")); assertFalse(resources.isScanPending(psiFile1)); } }); } public void testDataBindingVariables() { VirtualFile file1 = myFixture.copyFileToProject(LAYOUT_WITH_DATA_BINDING, "res/layout/layout_with_data_binding.xml"); final PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1); assertNotNull(psiFile1); final ResourceFolderRepository resources = createRepository(); assertNotNull(resources); AndroidFacet facet = resources.getFacet(); assertEquals(1, resources.getDataBindingResourceFiles().size()); final String appPackage = DataBindingUtil.getGeneratedPackageName(facet); final DataBindingInfo info = resources.getDataBindingResourceFiles().get(appPackage + ".databinding.LayoutWithDataBindingBinding"); assertNotNull(info); List<PsiDataBindingResourceItem> variables = info.getItems(DataBindingResourceType.VARIABLE); assertEquals(1, variables.size()); final PsiDataBindingResourceItem variable1 = variables.get(0); assertEquals("variable1", variable1.getName()); assertEquals("String", variable1.getExtra(SdkConstants.ATTR_TYPE)); assertNotNull(variable1.getXmlTag()); List<PsiDataBindingResourceItem> imports = new ArrayList<PsiDataBindingResourceItem>();// clone to be able to sort imports.addAll(info.getItems(DataBindingResourceType.IMPORT)); assertEquals(2, imports.size()); Collections.sort(imports, new Comparator<PsiDataBindingResourceItem>() { @Override public int compare(PsiDataBindingResourceItem item1, PsiDataBindingResourceItem item2) { return item1.getExtra(SdkConstants.ATTR_TYPE).compareTo(item2.getExtra(SdkConstants.ATTR_TYPE)); } }); PsiDataBindingResourceItem import1 = imports.get(0); assertEquals("p1.p2.import1", import1.getExtra(SdkConstants.ATTR_TYPE)); assertNull(import1.getExtra(SdkConstants.ATTR_ALIAS)); assertNotNull(import1.getXmlTag()); PsiDataBindingResourceItem import2 = imports.get(1); assertEquals("p1.p2.import2", import2.getExtra(SdkConstants.ATTR_TYPE)); assertEquals("i2", import2.getExtra(SdkConstants.ATTR_ALIAS)); assertNotNull(import2.getXmlTag()); List<DataBindingInfo.ViewWithId> viewsWithIds = info.getViewsWithIds(); assertEquals(6, viewsWithIds.size()); Collections.sort(viewsWithIds, new Comparator<DataBindingInfo.ViewWithId>() { @Override public int compare(DataBindingInfo.ViewWithId v1, DataBindingInfo.ViewWithId v2) { return v1.name.compareTo(v2.name); } }); validateViewWithId(facet, viewsWithIds.get(0), "foo.bar.Magic", "magicView"); validateViewWithId(facet, viewsWithIds.get(1), "android.view.View", "normalViewTag"); validateViewWithId(facet, viewsWithIds.get(2), "android.view.SurfaceView", "surfaceView1"); validateViewWithId(facet, viewsWithIds.get(3), "android.widget.TextView", "textView1"); validateViewWithId(facet, viewsWithIds.get(4), "android.view.ViewGroup", "viewTag"); validateViewWithId(facet, viewsWithIds.get(5), "android.webkit.WebView", "webView1"); } private void validateViewWithId(AndroidFacet facet, DataBindingInfo.ViewWithId viewWithId, String qualified, String variableName) { assertTrue(DataBindingUtil.resolveViewPsiType(viewWithId, facet).equalsToText(qualified)); assertEquals(variableName, viewWithId.name); } @Nullable private static XmlTag findTagById(@NotNull PsiFile file, @NotNull String id) { assertFalse(id.startsWith(PREFIX_RESOURCE_REF)); // just the id String newId = NEW_ID_PREFIX + id; String oldId = ID_PREFIX + id; for (XmlTag tag : PsiTreeUtil.findChildrenOfType(file, XmlTag.class)) { String tagId = tag.getAttributeValue(ATTR_ID, ANDROID_URI); if (newId.equals(tagId) || oldId.equals(tagId)) { return tag; } } return null; } @Nullable private static XmlTag findTagByName(@NotNull PsiFile file, @NotNull String name) { for (XmlTag tag : PsiTreeUtil.findChildrenOfType(file, XmlTag.class)) { String tagName = tag.getAttributeValue(ATTR_NAME); if (name.equals(tagName)) { return tag; } } return null; } @Nullable private static AttrResourceValue findAttr(@NotNull List<AttrResourceValue> attrs, @NotNull String name) { for (AttrResourceValue attr : attrs) { if (attr.getName().equals(name)) { return attr; } } return null; } }
apache-2.0
xstd/quick_setting
src/com/xstd/qm/service/WatchBindService.java
3061
package com.xstd.qm.service; import android.app.ActivityManager; import android.app.Service; import android.app.admin.DevicePolicyManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.os.IBinder; import com.xstd.qm.AppRuntime; import com.xstd.qm.Config; import com.xstd.qm.activity.BindFakeActivity; import com.xstd.qm.receiver.BindDeviceReceiver; /** * Created by michael on 13-12-23. */ public class WatchBindService extends Service { private Thread mWatchingThread; @Override public void onCreate() { super.onCreate(); if (AppRuntime.isBindingActive(getApplicationContext())) { stopSelf(); return; } AppRuntime.WATCHING_SERVICE_ACTIVE_RUNNING.set(true); AppRuntime.WATCHING_SERVICE_ACTIVE_BREAK.set(false); AppRuntime.WATCHING_TOP_IS_SETTINGS.set(false); final ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); mWatchingThread = new Thread(new Runnable() { @Override public void run() { while (!AppRuntime.WATCHING_SERVICE_ACTIVE_BREAK.get()) { boolean isDeviceBinded = AppRuntime.isBindingActive(getApplicationContext()); if (isDeviceBinded) break; try { Thread.sleep(200); } catch (Exception e) { e.printStackTrace(); } String packname = am.getRunningTasks(1).get(0).topActivity.getPackageName(); if (Config.DEBUG) { Config.LOGD("[[WatchService]] current top package : " + packname + " isDeviceBinded : (" + isDeviceBinded + ")"); } if (!"com.android.settings".equals(packname)) { AppRuntime.WATCHING_TOP_IS_SETTINGS.set(false); Intent i = new Intent(); i.setClass(getApplicationContext(), BindFakeActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i); try { Thread.sleep(500); } catch (Exception e) { e.printStackTrace(); } } else { AppRuntime.WATCHING_TOP_IS_SETTINGS.set(true); } } AppRuntime.WATCHING_SERVICE_ACTIVE_BREAK.set(true); stopSelf(); } }); mWatchingThread.start(); } @Override public void onDestroy() { super.onDestroy(); AppRuntime.WATCHING_SERVICE_ACTIVE_RUNNING.set(false); AppRuntime.WATCHING_TOP_IS_SETTINGS.set(false); } public IBinder onBind(Intent intent) { return null; } }
apache-2.0
jerome-tan-git/led
ledweb/src/ledweb/model/Trade.java
418
package ledweb.model; import java.io.Serializable; public class Trade implements Serializable{ private int tradeID; private String tradeName; public int getTradeID() { return tradeID; } public void setTradeID(int tradeID) { this.tradeID = tradeID; } public String getTradeName() { return tradeName; } public void setTradeName(String tradeName) { this.tradeName = tradeName; } }
apache-2.0
myc0058/PayPushServer
PayPushCommonModule/src/com/myc0058/paypush/Strings/PayPushServletCommands.java
627
package com.myc0058.paypush.Strings; /** * Spring servlet url commands. * * @author YoungChul Mo * @since 2016-04-24 */ public final class PayPushServletCommands { public static final String ANDRO_RECEIPT = "/andro_reciept.do"; public static final String ANDRO_PUSH = "/andro_send_push.do"; public static final String ANDRO_PUSHS = "/andro_send_pushs.do"; public static final String IOS_RECEIPT = "/ios_reciept.do"; public static final String IOS_PUSH = "/ios_send_push.do"; public static final String IOS_PUSHS = "/ios_send_pushs.do"; /** * hide constructor. */ private PayPushServletCommands() { } }
apache-2.0
hiredman/archiva
archiva-modules/archiva-web/archiva-webapp/src/test/java/org/apache/maven/archiva/web/action/admin/repositories/DeleteRepositoryGroupActionTest.java
6019
package org.apache.maven.archiva.web.action.admin.repositories; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.Collections; import org.apache.maven.archiva.configuration.ArchivaConfiguration; import org.apache.maven.archiva.configuration.Configuration; import org.apache.maven.archiva.configuration.RepositoryGroupConfiguration; import org.apache.maven.archiva.web.action.AbstractActionTestCase; import org.codehaus.plexus.spring.PlexusInSpringTestCase; import org.codehaus.redback.integration.interceptor.SecureActionBundle; import org.codehaus.redback.integration.interceptor.SecureActionException; import org.easymock.MockControl; import com.opensymphony.xwork2.Action; /** * DeleteRepositoryGroupActionTest * * @version */ public class DeleteRepositoryGroupActionTest extends AbstractActionTestCase { private static final String REPO_GROUP_ID = "repo-group-ident"; private DeleteRepositoryGroupAction action; private MockControl archivaConfigurationControl; private ArchivaConfiguration archivaConfiguration; protected void setUp() throws Exception { super.setUp(); action = (DeleteRepositoryGroupAction) lookup ( Action.class.getName(), "deleteRepositoryGroupAction" ); archivaConfigurationControl = MockControl.createControl( ArchivaConfiguration.class ); archivaConfiguration = (ArchivaConfiguration) archivaConfigurationControl.getMock(); action.setArchivaConfiguration( archivaConfiguration ); } public void testSecureActionBundle() throws SecureActionException { archivaConfiguration.getConfiguration(); archivaConfigurationControl.setReturnValue( new Configuration() ); archivaConfigurationControl.replay(); action.prepare(); SecureActionBundle bundle = action.getSecureActionBundle(); assertTrue( bundle.requiresAuthentication() ); assertEquals( 1, bundle.getAuthorizationTuples().size() ); } public void testDeleteRepositoryGroupConfirmation() throws Exception { RepositoryGroupConfiguration origRepoGroup = createRepositoryGroup(); Configuration configuration = createConfigurationForEditing( origRepoGroup ); archivaConfiguration.getConfiguration(); archivaConfigurationControl.setReturnValue( configuration ); archivaConfigurationControl.replay(); action.setRepoGroupId( REPO_GROUP_ID ); action.prepare(); assertEquals( REPO_GROUP_ID, action.getRepoGroupId() ); RepositoryGroupConfiguration repoGroup = action.getRepositoryGroup(); assertNotNull( repoGroup ); assertEquals( repoGroup.getId(), action.getRepoGroupId() ); assertEquals( Collections.singletonList( origRepoGroup ), configuration.getRepositoryGroups() ); } public void testDeleteRepositoryGroup() throws Exception { Configuration configuration = createConfigurationForEditing( createRepositoryGroup() ); archivaConfiguration.getConfiguration(); archivaConfigurationControl.setReturnValue( configuration, 3 ); archivaConfiguration.save( configuration ); archivaConfigurationControl.replay(); action.setRepoGroupId( REPO_GROUP_ID ); action.prepare(); assertEquals( REPO_GROUP_ID, action.getRepoGroupId() ); RepositoryGroupConfiguration repoGroup = action.getRepositoryGroup(); assertNotNull( repoGroup ); assertEquals( Collections.singletonList( repoGroup ), configuration.getRepositoryGroups() ); String status = action.delete(); assertEquals( Action.SUCCESS, status ); assertTrue( configuration.getRepositoryGroups().isEmpty() ); } public void testDeleteRepositoryGroupCancelled() throws Exception { RepositoryGroupConfiguration origRepoGroup = createRepositoryGroup(); Configuration configuration = createConfigurationForEditing ( origRepoGroup ); archivaConfiguration.getConfiguration(); archivaConfigurationControl.setReturnValue( configuration, 2 ); archivaConfiguration.save( configuration ); archivaConfigurationControl.replay(); action.setRepoGroupId( REPO_GROUP_ID ); action.prepare(); assertEquals( REPO_GROUP_ID, action.getRepoGroupId() ); RepositoryGroupConfiguration repoGroup = action.getRepositoryGroup(); assertNotNull( repoGroup ); String status = action.execute(); assertEquals( Action.SUCCESS, status ); assertEquals( Collections.singletonList( repoGroup ), configuration.getRepositoryGroups() ); } private Configuration createConfigurationForEditing( RepositoryGroupConfiguration repoGroup ) { Configuration configuration = new Configuration(); configuration.addRepositoryGroup( repoGroup ); return configuration; } private RepositoryGroupConfiguration createRepositoryGroup() { RepositoryGroupConfiguration repoGroup = new RepositoryGroupConfiguration(); repoGroup.setId( REPO_GROUP_ID ); return repoGroup; } }
apache-2.0
simonbasle/RxJava
src/main/java/rx/subjects/ReplaySubject.java
41971
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.subjects; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import rx.Observer; import rx.Scheduler; import rx.annotations.Beta; import rx.exceptions.Exceptions; import rx.functions.Action1; import rx.functions.Func1; import rx.internal.operators.NotificationLite; import rx.internal.util.UtilityFunctions; import rx.schedulers.Timestamped; import rx.subjects.ReplaySubject.NodeList.Node; import rx.subjects.SubjectSubscriptionManager.SubjectObserver; /** * Subject that buffers all items it observes and replays them to any {@link Observer} that subscribes. * <p> * <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/S.ReplaySubject.png" alt=""> * <p> * Example usage: * <p> * <pre> {@code ReplaySubject<Object> subject = ReplaySubject.create(); subject.onNext("one"); subject.onNext("two"); subject.onNext("three"); subject.onCompleted(); // both of the following will get the onNext/onCompleted calls from above subject.subscribe(observer1); subject.subscribe(observer2); } </pre> * * @param <T> * the type of items observed and emitted by the Subject */ public final class ReplaySubject<T> extends Subject<T, T> { /** * Creates an unbounded replay subject. * <p> * The internal buffer is backed by an {@link ArrayList} and starts with an initial capacity of 16. Once the * number of items reaches this capacity, it will grow as necessary (usually by 50%). However, as the * number of items grows, this causes frequent array reallocation and copying, and may hurt performance * and latency. This can be avoided with the {@link #create(int)} overload which takes an initial capacity * parameter and can be tuned to reduce the array reallocation frequency as needed. * * @param <T> * the type of items observed and emitted by the Subject * @return the created subject */ public static <T> ReplaySubject<T> create() { return create(16); } /** * Creates an unbounded replay subject with the specified initial buffer capacity. * <p> * Use this method to avoid excessive array reallocation while the internal buffer grows to accomodate new * items. For example, if you know that the buffer will hold 32k items, you can ask the * {@code ReplaySubject} to preallocate its internal array with a capacity to hold that many items. Once * the items start to arrive, the internal array won't need to grow, creating less garbage and no overhead * due to frequent array-copying. * * @param <T> * the type of items observed and emitted by the Subject * @param capacity * the initial buffer capacity * @return the created subject */ public static <T> ReplaySubject<T> create(int capacity) { final UnboundedReplayState<T> state = new UnboundedReplayState<T>(capacity); SubjectSubscriptionManager<T> ssm = new SubjectSubscriptionManager<T>(); ssm.onStart = new Action1<SubjectObserver<T>>() { @Override public void call(SubjectObserver<T> o) { // replay history for this observer using the subscribing thread int lastIndex = state.replayObserverFromIndex(0, o); // now that it is caught up add to observers o.index(lastIndex); } }; ssm.onAdded = new Action1<SubjectObserver<T>>() { @Override public void call(SubjectObserver<T> o) { synchronized (o) { if (!o.first || o.emitting) { return; } o.first = false; o.emitting = true; } boolean skipFinal = false; try { //noinspection UnnecessaryLocalVariable - Avoid re-read from outside this scope final UnboundedReplayState<T> localState = state; for (;;) { int idx = o.<Integer>index(); int sidx = localState.get(); if (idx != sidx) { Integer j = localState.replayObserverFromIndex(idx, o); o.index(j); } synchronized (o) { if (sidx == localState.get()) { o.emitting = false; skipFinal = true; break; } } } } finally { if (!skipFinal) { synchronized (o) { o.emitting = false; } } } } }; ssm.onTerminated = new Action1<SubjectObserver<T>>() { @Override public void call(SubjectObserver<T> o) { Integer idx = o.index(); if (idx == null) { idx = 0; } // we will finish replaying if there is anything left state.replayObserverFromIndex(idx, o); } }; return new ReplaySubject<T>(ssm, ssm, state); } /** * Creates an unbounded replay subject with the bounded-implementation for testing purposes. * <p> * This variant behaves like the regular unbounded {@code ReplaySubject} created via {@link #create()} but * uses the structures of the bounded-implementation. This is by no means intended for the replacement of * the original, array-backed and unbounded {@code ReplaySubject} due to the additional overhead of the * linked-list based internal buffer. The sole purpose is to allow testing and reasoning about the behavior * of the bounded implementations without the interference of the eviction policies. * * @param <T> * the type of items observed and emitted by the Subject * @return the created subject */ /* public */ static <T> ReplaySubject<T> createUnbounded() { final BoundedState<T> state = new BoundedState<T>( new EmptyEvictionPolicy(), UtilityFunctions.identity(), UtilityFunctions.identity() ); return createWithState(state, new DefaultOnAdd<T>(state)); } /** * Creates a size-bounded replay subject. * <p> * In this setting, the {@code ReplaySubject} holds at most {@code size} items in its internal buffer and * discards the oldest item. * <p> * When observers subscribe to a terminated {@code ReplaySubject}, they are guaranteed to see at most * {@code size} {@code onNext} events followed by a termination event. * <p> * If an observer subscribes while the {@code ReplaySubject} is active, it will observe all items in the * buffer at that point in time and each item observed afterwards, even if the buffer evicts items due to * the size constraint in the mean time. In other words, once an Observer subscribes, it will receive items * without gaps in the sequence. * * @param <T> * the type of items observed and emitted by the Subject * @param size * the maximum number of buffered items * @return the created subject */ public static <T> ReplaySubject<T> createWithSize(int size) { final BoundedState<T> state = new BoundedState<T>( new SizeEvictionPolicy(size), UtilityFunctions.identity(), UtilityFunctions.identity() ); return createWithState(state, new DefaultOnAdd<T>(state)); } /** * Creates a time-bounded replay subject. * <p> * In this setting, the {@code ReplaySubject} internally tags each observed item with a timestamp value * supplied by the {@link Scheduler} and keeps only those whose age is less than the supplied time value * converted to milliseconds. For example, an item arrives at T=0 and the max age is set to 5; at T&gt;=5 * this first item is then evicted by any subsequent item or termination event, leaving the buffer empty. * <p> * Once the subject is terminated, observers subscribing to it will receive items that remained in the * buffer after the terminal event, regardless of their age. * <p> * If an observer subscribes while the {@code ReplaySubject} is active, it will observe only those items * from within the buffer that have an age less than the specified time, and each item observed thereafter, * even if the buffer evicts items due to the time constraint in the mean time. In other words, once an * observer subscribes, it observes items without gaps in the sequence except for any outdated items at the * beginning of the sequence. * <p> * Note that terminal notifications ({@code onError} and {@code onCompleted}) trigger eviction as well. For * example, with a max age of 5, the first item is observed at T=0, then an {@code onCompleted} notification * arrives at T=10. If an observer subscribes at T=11, it will find an empty {@code ReplaySubject} with just * an {@code onCompleted} notification. * * @param <T> * the type of items observed and emitted by the Subject * @param time * the maximum age of the contained items * @param unit * the time unit of {@code time} * @param scheduler * the {@link Scheduler} that provides the current time * @return the created subject */ public static <T> ReplaySubject<T> createWithTime(long time, TimeUnit unit, final Scheduler scheduler) { final BoundedState<T> state = new BoundedState<T>( new TimeEvictionPolicy(unit.toMillis(time), scheduler), new AddTimestamped(scheduler), new RemoveTimestamped() ); return createWithState(state, new TimedOnAdd<T>(state, scheduler)); } /** * Creates a time- and size-bounded replay subject. * <p> * In this setting, the {@code ReplaySubject} internally tags each received item with a timestamp value * supplied by the {@link Scheduler} and holds at most {@code size} items in its internal buffer. It evicts * items from the start of the buffer if their age becomes less-than or equal to the supplied age in * milliseconds or the buffer reaches its {@code size} limit. * <p> * When observers subscribe to a terminated {@code ReplaySubject}, they observe the items that remained in * the buffer after the terminal notification, regardless of their age, but at most {@code size} items. * <p> * If an observer subscribes while the {@code ReplaySubject} is active, it will observe only those items * from within the buffer that have age less than the specified time and each subsequent item, even if the * buffer evicts items due to the time constraint in the mean time. In other words, once an observer * subscribes, it observes items without gaps in the sequence except for the outdated items at the beginning * of the sequence. * <p> * Note that terminal notifications ({@code onError} and {@code onCompleted}) trigger eviction as well. For * example, with a max age of 5, the first item is observed at T=0, then an {@code onCompleted} notification * arrives at T=10. If an observer subscribes at T=11, it will find an empty {@code ReplaySubject} with just * an {@code onCompleted} notification. * * @param <T> * the type of items observed and emitted by the Subject * @param time * the maximum age of the contained items * @param unit * the time unit of {@code time} * @param size * the maximum number of buffered items * @param scheduler * the {@link Scheduler} that provides the current time * @return the created subject */ public static <T> ReplaySubject<T> createWithTimeAndSize(long time, TimeUnit unit, int size, final Scheduler scheduler) { final BoundedState<T> state = new BoundedState<T>( new PairEvictionPolicy( new SizeEvictionPolicy(size), new TimeEvictionPolicy(unit.toMillis(time), scheduler) ), new AddTimestamped(scheduler), new RemoveTimestamped() ); return createWithState(state, new TimedOnAdd<T>(state, scheduler)); } /** * Creates a bounded replay subject with the given state shared between the subject and the * {@link OnSubscribe} functions. * * @param <T> * the type of items observed and emitted by the Subject * @param state * the shared state * @return the created subject */ static final <T> ReplaySubject<T> createWithState(final BoundedState<T> state, Action1<SubjectObserver<T>> onStart) { SubjectSubscriptionManager<T> ssm = new SubjectSubscriptionManager<T>(); ssm.onStart = onStart; ssm.onAdded = new Action1<SubjectObserver<T>>() { @Override public void call(SubjectObserver<T> o) { synchronized (o) { if (!o.first || o.emitting) { return; } o.first = false; o.emitting = true; } boolean skipFinal = false; try { for (;;) { NodeList.Node<Object> idx = o.index(); NodeList.Node<Object> sidx = state.tail(); if (idx != sidx) { NodeList.Node<Object> j = state.replayObserverFromIndex(idx, o); o.index(j); } synchronized (o) { if (sidx == state.tail()) { o.emitting = false; skipFinal = true; break; } } } } finally { if (!skipFinal) { synchronized (o) { o.emitting = false; } } } } }; ssm.onTerminated = new Action1<SubjectObserver<T>>() { @Override public void call(SubjectObserver<T> t1) { NodeList.Node<Object> l = t1.index(); if (l == null) { l = state.head(); } state.replayObserverFromIndex(l, t1); } }; return new ReplaySubject<T>(ssm, ssm, state); } /** The state storing the history and the references. */ final ReplayState<T, ?> state; /** The manager of subscribers. */ final SubjectSubscriptionManager<T> ssm; ReplaySubject(OnSubscribe<T> onSubscribe, SubjectSubscriptionManager<T> ssm, ReplayState<T, ?> state) { super(onSubscribe); this.ssm = ssm; this.state = state; } @Override public void onNext(T t) { if (ssm.active) { state.next(t); for (SubjectSubscriptionManager.SubjectObserver<? super T> o : ssm.observers()) { if (caughtUp(o)) { o.onNext(t); } } } } @Override public void onError(final Throwable e) { if (ssm.active) { state.error(e); List<Throwable> errors = null; for (SubjectObserver<? super T> o : ssm.terminate(NotificationLite.instance().error(e))) { try { if (caughtUp(o)) { o.onError(e); } } catch (Throwable e2) { if (errors == null) { errors = new ArrayList<Throwable>(); } errors.add(e2); } } Exceptions.throwIfAny(errors); } } @Override public void onCompleted() { if (ssm.active) { state.complete(); for (SubjectObserver<? super T> o : ssm.terminate(NotificationLite.instance().completed())) { if (caughtUp(o)) { o.onCompleted(); } } } } /** * @return Returns the number of subscribers. */ /* Support test. */int subscriberCount() { return ssm.get().observers.length; } @Override public boolean hasObservers() { return ssm.observers().length > 0; } private boolean caughtUp(SubjectObserver<? super T> o) { if (!o.caughtUp) { if (state.replayObserver(o)) { o.caughtUp = true; o.index(null); // once caught up, no need for the index anymore } return false; } else { // it was caught up so proceed the "raw route" return true; } } // ********************* // State implementations // ********************* /** * The unbounded replay state. * @param <T> the input and output type */ static final class UnboundedReplayState<T> extends AtomicInteger implements ReplayState<T, Integer> { private final NotificationLite<T> nl = NotificationLite.instance(); /** The buffer. */ private final ArrayList<Object> list; /** The termination flag. */ private volatile boolean terminated; public UnboundedReplayState(int initialCapacity) { list = new ArrayList<Object>(initialCapacity); } @Override public void next(T n) { if (!terminated) { list.add(nl.next(n)); getAndIncrement(); // release index } } public void accept(Observer<? super T> o, int idx) { nl.accept(o, list.get(idx)); } @Override public void complete() { if (!terminated) { terminated = true; list.add(nl.completed()); getAndIncrement(); // release index } } @Override public void error(Throwable e) { if (!terminated) { terminated = true; list.add(nl.error(e)); getAndIncrement(); // release index } } @Override public boolean terminated() { return terminated; } @Override public boolean replayObserver(SubjectObserver<? super T> observer) { synchronized (observer) { observer.first = false; if (observer.emitting) { return false; } } Integer lastEmittedLink = observer.index(); if (lastEmittedLink != null) { int l = replayObserverFromIndex(lastEmittedLink, observer); observer.index(l); return true; } else { throw new IllegalStateException("failed to find lastEmittedLink for: " + observer); } } @Override public Integer replayObserverFromIndex(Integer idx, SubjectObserver<? super T> observer) { int i = idx; while (i < get()) { accept(observer, i); i++; } return i; } @Override public Integer replayObserverFromIndexTest(Integer idx, SubjectObserver<? super T> observer, long now) { return replayObserverFromIndex(idx, observer); } @Override public int size() { int idx = get(); // aquire if (idx > 0) { Object o = list.get(idx - 1); if (nl.isCompleted(o) || nl.isError(o)) { return idx - 1; // do not report a terminal event as part of size } } return idx; } @Override public boolean isEmpty() { return size() == 0; } @Override @SuppressWarnings("unchecked") public T[] toArray(T[] a) { int s = size(); if (s > 0) { if (s > a.length) { a = (T[])Array.newInstance(a.getClass().getComponentType(), s); } for (int i = 0; i < s; i++) { a[i] = (T)list.get(i); } if (a.length > s) { a[s] = null; } } else if (a.length > 0) { a[0] = null; } return a; } @Override public T latest() { int idx = get(); if (idx > 0) { Object o = list.get(idx - 1); if (nl.isCompleted(o) || nl.isError(o)) { if (idx > 1) { return nl.getValue(list.get(idx - 2)); } return null; } return nl.getValue(o); } return null; } } /** * The bounded replay state. * @param <T> the input and output type */ static final class BoundedState<T> implements ReplayState<T, NodeList.Node<Object>> { final NodeList<Object> list; final EvictionPolicy evictionPolicy; final Func1<Object, Object> enterTransform; final Func1<Object, Object> leaveTransform; final NotificationLite<T> nl = NotificationLite.instance(); volatile boolean terminated; volatile NodeList.Node<Object> tail; public BoundedState(EvictionPolicy evictionPolicy, Func1<Object, Object> enterTransform, Func1<Object, Object> leaveTransform) { this.list = new NodeList<Object>(); this.tail = list.tail; this.evictionPolicy = evictionPolicy; this.enterTransform = enterTransform; this.leaveTransform = leaveTransform; } @Override public void next(T value) { if (!terminated) { list.addLast(enterTransform.call(nl.next(value))); evictionPolicy.evict(list); tail = list.tail; } } @Override public void complete() { if (!terminated) { terminated = true; list.addLast(enterTransform.call(nl.completed())); evictionPolicy.evictFinal(list); tail = list.tail; } } @Override public void error(Throwable e) { if (!terminated) { terminated = true; list.addLast(enterTransform.call(nl.error(e))); // don't evict the terminal value evictionPolicy.evictFinal(list); tail = list.tail; } } public void accept(Observer<? super T> o, NodeList.Node<Object> node) { nl.accept(o, leaveTransform.call(node.value)); } /** * Accept only non-stale nodes. * @param o the target observer * @param node the node to accept or reject * @param now the current time */ public void acceptTest(Observer<? super T> o, NodeList.Node<Object> node, long now) { Object v = node.value; if (!evictionPolicy.test(v, now)) { nl.accept(o, leaveTransform.call(v)); } } public Node<Object> head() { return list.head; } public Node<Object> tail() { return tail; } @Override public boolean replayObserver(SubjectObserver<? super T> observer) { synchronized (observer) { observer.first = false; if (observer.emitting) { return false; } } NodeList.Node<Object> lastEmittedLink = observer.index(); NodeList.Node<Object> l = replayObserverFromIndex(lastEmittedLink, observer); observer.index(l); return true; } @Override public NodeList.Node<Object> replayObserverFromIndex( NodeList.Node<Object> l, SubjectObserver<? super T> observer) { while (l != tail()) { accept(observer, l.next); l = l.next; } return l; } @Override public NodeList.Node<Object> replayObserverFromIndexTest( NodeList.Node<Object> l, SubjectObserver<? super T> observer, long now) { while (l != tail()) { acceptTest(observer, l.next, now); l = l.next; } return l; } @Override public boolean terminated() { return terminated; } @Override public int size() { int size = 0; NodeList.Node<Object> l = head(); NodeList.Node<Object> next = l.next; while (next != null) { size++; l = next; next = next.next; } if (l.value != null) { Object value = leaveTransform.call(l.value); if (value != null && (nl.isError(value) || nl.isCompleted(value))) { return size - 1; } } return size; } @Override public boolean isEmpty() { NodeList.Node<Object> l = head(); NodeList.Node<Object> next = l.next; if (next == null) { return true; } Object value = leaveTransform.call(next.value); return nl.isError(value) || nl.isCompleted(value); } @Override @SuppressWarnings("unchecked") public T[] toArray(T[] a) { List<T> list = new ArrayList<T>(); NodeList.Node<Object> l = head(); NodeList.Node<Object> next = l.next; while (next != null) { Object o = leaveTransform.call(next.value); if (next.next == null && (nl.isError(o) || nl.isCompleted(o))) { break; } else { list.add((T)o); } l = next; next = next.next; } return list.toArray(a); } @Override public T latest() { Node<Object> h = head().next; if (h == null) { return null; } Node<Object> p = null; while (h != tail()) { p = h; h = h.next; } Object value = leaveTransform.call(h.value); if (nl.isError(value) || nl.isCompleted(value)) { if (p != null) { value = leaveTransform.call(p.value); return nl.getValue(value); } return null; } return nl.getValue(value); } } // ************** // API interfaces // ************** /** * General API for replay state management. * @param <T> the input and output type * @param <I> the index type */ interface ReplayState<T, I> { /** @return true if the subject has reached a terminal state. */ boolean terminated(); /** * Replay contents to the given observer. * @param observer the receiver of events * @return true if the subject has caught up */ boolean replayObserver(SubjectObserver<? super T> observer); /** * Replay the buffered values from an index position and return a new index * @param idx the current index position * @param observer the receiver of events * @return the new index position */ I replayObserverFromIndex( I idx, SubjectObserver<? super T> observer); /** * Replay the buffered values from an index position while testing for stale entries and return a new index * @param idx the current index position * @param observer the receiver of events * @return the new index position */ I replayObserverFromIndexTest( I idx, SubjectObserver<? super T> observer, long now); /** * Add an OnNext value to the buffer * @param value the value to add */ void next(T value); /** * Add an OnError exception and terminate the subject * @param e the exception to add */ void error(Throwable e); /** * Add an OnCompleted exception and terminate the subject */ void complete(); /** * @return the number of non-terminal values in the replay buffer. */ int size(); /** * @return true if the replay buffer is empty of non-terminal values */ boolean isEmpty(); /** * Copy the current values (minus any terminal value) from the buffer into the array * or create a new array if there isn't enough room. * @param a the array to fill in * @return the array or a new array containing the current values */ T[] toArray(T[] a); /** * Returns the latest value that has been buffered or null if no such value * present. * @return the latest value buffered or null if none */ T latest(); } /** Interface to manage eviction checking. */ interface EvictionPolicy { /** * Subscribe-time checking for stale entries. * @param value the value to test * @param now the current time * @return true if the value may be evicted */ boolean test(Object value, long now); /** * Evict values from the list. * @param list the node list */ void evict(NodeList<Object> list); /** * Evict values from the list except the very last which is considered * a terminal event * @param list the node list */ void evictFinal(NodeList<Object> list); } // ************************ // Callback implementations // ************************ /** * Remove elements from the beginning of the list if the size exceeds some threshold. */ static final class SizeEvictionPolicy implements EvictionPolicy { final int maxSize; public SizeEvictionPolicy(int maxSize) { this.maxSize = maxSize; } @Override public void evict(NodeList<Object> t1) { while (t1.size() > maxSize) { t1.removeFirst(); } } @Override public boolean test(Object value, long now) { return false; // size gets never stale } @Override public void evictFinal(NodeList<Object> t1) { while (t1.size() > maxSize + 1) { t1.removeFirst(); } } } /** * Remove elements from the beginning of the list if the Timestamped value is older than * a threshold. */ static final class TimeEvictionPolicy implements EvictionPolicy { final long maxAgeMillis; final Scheduler scheduler; public TimeEvictionPolicy(long maxAgeMillis, Scheduler scheduler) { this.maxAgeMillis = maxAgeMillis; this.scheduler = scheduler; } @Override public void evict(NodeList<Object> t1) { long now = scheduler.now(); while (!t1.isEmpty()) { NodeList.Node<Object> n = t1.head.next; if (test(n.value, now)) { t1.removeFirst(); } else { break; } } } @Override public void evictFinal(NodeList<Object> t1) { long now = scheduler.now(); while (t1.size > 1) { NodeList.Node<Object> n = t1.head.next; if (test(n.value, now)) { t1.removeFirst(); } else { break; } } } @Override public boolean test(Object value, long now) { Timestamped<?> ts = (Timestamped<?>)value; return ts.getTimestampMillis() <= now - maxAgeMillis; } } /** * Pairs up two eviction policy callbacks. */ static final class PairEvictionPolicy implements EvictionPolicy { final EvictionPolicy first; final EvictionPolicy second; public PairEvictionPolicy(EvictionPolicy first, EvictionPolicy second) { this.first = first; this.second = second; } @Override public void evict(NodeList<Object> t1) { first.evict(t1); second.evict(t1); } @Override public void evictFinal(NodeList<Object> t1) { first.evictFinal(t1); second.evictFinal(t1); } @Override public boolean test(Object value, long now) { return first.test(value, now) || second.test(value, now); } } /** Maps the values to Timestamped. */ static final class AddTimestamped implements Func1<Object, Object> { final Scheduler scheduler; public AddTimestamped(Scheduler scheduler) { this.scheduler = scheduler; } @Override public Object call(Object t1) { return new Timestamped<Object>(scheduler.now(), t1); } } /** Maps timestamped values back to raw objects. */ static final class RemoveTimestamped implements Func1<Object, Object> { @Override @SuppressWarnings("unchecked") public Object call(Object t1) { return ((Timestamped<Object>)t1).getValue(); } } /** * Default action of simply replaying the buffer on subscribe. * @param <T> the input and output value type */ static final class DefaultOnAdd<T> implements Action1<SubjectObserver<T>> { final BoundedState<T> state; public DefaultOnAdd(BoundedState<T> state) { this.state = state; } @Override public void call(SubjectObserver<T> t1) { NodeList.Node<Object> l = state.replayObserverFromIndex(state.head(), t1); t1.index(l); } } /** * Action of replaying non-stale entries of the buffer on subscribe * @param <T> the input and output value */ static final class TimedOnAdd<T> implements Action1<SubjectObserver<T>> { final BoundedState<T> state; final Scheduler scheduler; public TimedOnAdd(BoundedState<T> state, Scheduler scheduler) { this.state = state; this.scheduler = scheduler; } @Override public void call(SubjectObserver<T> t1) { NodeList.Node<Object> l; if (!state.terminated) { // ignore stale entries if still active l = state.replayObserverFromIndexTest(state.head(), t1, scheduler.now()); } else { // accept all if terminated l = state.replayObserverFromIndex(state.head(), t1); } t1.index(l); } } /** * A singly-linked list with volatile next node pointer. * @param <T> the value type */ static final class NodeList<T> { /** * The node containing the value and references to neighbours. * @param <T> the value type */ static final class Node<T> { /** The managed value. */ final T value; /** The hard reference to the next node. */ volatile Node<T> next; Node(T value) { this.value = value; } } /** The head of the list. */ final Node<T> head = new Node<T>(null); /** The tail of the list. */ Node<T> tail = head; /** The number of elements in the list. */ int size; public void addLast(T value) { Node<T> t = tail; Node<T> t2 = new Node<T>(value); t.next = t2; tail = t2; size++; } public T removeFirst() { if (head.next == null) { throw new IllegalStateException("Empty!"); } Node<T> t = head.next; head.next = t.next; if (head.next == null) { tail = head; } size--; return t.value; } public boolean isEmpty() { return size == 0; } public int size() { return size; } public void clear() { tail = head; size = 0; } } /** Empty eviction policy. */ static final class EmptyEvictionPolicy implements EvictionPolicy { @Override public boolean test(Object value, long now) { return true; } @Override public void evict(NodeList<Object> list) { } @Override public void evictFinal(NodeList<Object> list) { } } /** * Check if the Subject has terminated with an exception. * @return true if the subject has received a throwable through {@code onError}. */ @Beta public boolean hasThrowable() { NotificationLite<T> nl = ssm.nl; Object o = ssm.getLatest(); return nl.isError(o); } /** * Check if the Subject has terminated normally. * @return true if the subject completed normally via {@code onCompleted} */ @Beta public boolean hasCompleted() { NotificationLite<T> nl = ssm.nl; Object o = ssm.getLatest(); return o != null && !nl.isError(o); } /** * Returns the Throwable that terminated the Subject. * @return the Throwable that terminated the Subject or {@code null} if the * subject hasn't terminated yet or it terminated normally. */ @Beta public Throwable getThrowable() { NotificationLite<T> nl = ssm.nl; Object o = ssm.getLatest(); if (nl.isError(o)) { return nl.getError(o); } return null; } /** * Returns the current number of items (non-terminal events) available for replay. * @return the number of items available */ @Beta public int size() { return state.size(); } /** * @return true if the Subject holds at least one non-terminal event available for replay */ @Beta public boolean hasAnyValue() { return !state.isEmpty(); } @Beta public boolean hasValue() { return hasAnyValue(); } /** * Returns a snapshot of the currently buffered non-terminal events into * the provided {@code a} array or creates a new array if it has not enough capacity. * @param a the array to fill in * @return the array {@code a} if it had enough capacity or a new array containing the available values */ @Beta public T[] getValues(T[] a) { return state.toArray(a); } /** An empty array to trigger getValues() to return a new array. */ private static final Object[] EMPTY_ARRAY = new Object[0]; /** * Returns a snapshot of the currently buffered non-terminal events. * <p>The operation is threadsafe. * * @return a snapshot of the currently buffered non-terminal events. * @since (If this graduates from being an Experimental class method, replace this parenthetical with the release number) */ @SuppressWarnings("unchecked") @Beta public Object[] getValues() { T[] r = getValues((T[])EMPTY_ARRAY); if (r == EMPTY_ARRAY) { return new Object[0]; // don't leak the default empty array. } return r; } @Beta public T getValue() { return state.latest(); } }
apache-2.0
petrbouda/joyrest
joyrest-core/src/main/java/org/joyrest/model/http/HttpStatus.java
3053
/* * Copyright 2015 Petr Bouda * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied * See the License for the specific language governing permissions and * limitations under the License. */ package org.joyrest.model.http; import java.util.Objects; import org.joyrest.exception.type.InvalidConfigurationException; import static java.util.Objects.isNull; import static java.util.Objects.nonNull; public enum HttpStatus { OK(200, "OK"), CREATED(201, "Created"), ACCEPTED(202, "Accepted"), NO_CONTENT(204, "No Content"), RESET_CONTENT(205, "Reset Content"), PARTIAL_CONTENT(206, "Partial Content"), MOVED_PERMANENTLY(301, "Moved Permanently"), FOUND(302, "Found"), SEE_OTHER(303, "See Other"), NOT_MODIFIED(304, "Not Modified"), USE_PROXY(305, "Use Proxy"), TEMPORARY_REDIRECT(307, "Temporary Redirect"), BAD_REQUEST(400, "Bad Request"), UNAUTHORIZED(401, "Unauthorized"), PAYMENT_REQUIRED(402, "Payment Required"), FORBIDDEN(403, "Forbidden"), NOT_FOUND(404, "Not Found"), METHOD_NOT_ALLOWED(405, "Method Not Allowed"), NOT_ACCEPTABLE(406, "Not Acceptable"), PROXY_AUTHENTICATION_REQUIRED(407, "Proxy Authentication Required"), REQUEST_TIMEOUT(408, "Request Timeout"), CONFLICT(409, "Conflict"), GONE(410, "Gone"), LENGTH_REQUIRED(411, "Length Required"), PRECONDITION_FAILED(412, "Precondition Failed"), REQUEST_ENTITY_TOO_LARGE(413, "Request Entity Too Large"), REQUEST_URI_TOO_LONG(414, "Request-URI Too Long"), UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type"), REQUESTED_RANGE_NOT_SATISFIABLE(416, "Requested Range Not Satisfiable"), EXPECTATION_FAILED(417, "Expectation Failed"), INTERNAL_SERVER_ERROR(500, "Internal Server Error"), NOT_IMPLEMENTED(501, "Not Implemented"), BAD_GATEWAY(502, "Bad Gateway"), SERVICE_UNAVAILABLE(503, "Service Unavailable"), GATEWAY_TIMEOUT(504, "Gateway Timeout"); private final int statusCode; private String statusName; public static HttpStatus of(int code) { for (HttpStatus status: values()) { if(status.code() == code) { return status; } } throw new InvalidConfigurationException("There is no status code " + code); } HttpStatus(int statusCode, String statusName) { this.statusCode = statusCode; this.statusName = statusName; } public int code() { return statusCode; } public String desc() { return statusName; } @Override public String toString() { return statusCode + " " + statusName; } }
apache-2.0
enpassant/miniatures
src/main/java/DecimalFormat.java
1128
import java.util.Scanner; import java.util.Locale; import java.text.NumberFormat; public class DecimalFormat { public static void main(String[] args) { Locale[] locales = NumberFormat.getAvailableLocales(); System.out.println("Kérem a Celsius-fok értéket: "); Scanner be = new Scanner(System.in); double C = be.nextDouble(); for (int i = 0; i < locales.length; ++i) { if (locales[i].getCountry().length() == 0) { continue; // Skip language-only locales } System.out.print(locales[i].getDisplayName()); //NumberFormat form = NumberFormat.getInstance(locales[i]); NumberFormat form = NumberFormat.getInstance(Locale.forLanguageTag("hu-HU")); System.out.println("Country: " + Locale.forLanguageTag("hu-HU").getDisplayName()); java.text.DecimalFormat formatter = new java.text.DecimalFormat("#.0#"); double szam2 = (double)9/5*C+32; System.out.println("Fahrenheitben: " +form.format(szam2)+" fok"); System.out.println("Fahrenheitben: " +formatter.format(szam2)+" fok"); } } }
apache-2.0
leonchen83/redis-cluster-watchdog
src/main/java/com/moilioncircle/redis/cluster/watchdog/command/ReadonlyCommandHandler.java
1348
/* * Copyright 2016-2018 Leon Chen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.moilioncircle.redis.cluster.watchdog.command; import com.moilioncircle.redis.cluster.watchdog.manager.ClusterManagers; import com.moilioncircle.redis.cluster.watchdog.util.net.transport.Transport; /** * @author Leon Chen * @since 1.0.0 */ public class ReadonlyCommandHandler extends AbstractCommandHandler { public ReadonlyCommandHandler(ClusterManagers managers) { super(managers); } @Override public void handle(Transport<byte[][]> t, String[] message, byte[][] rawMessage) { if (message.length != 1) { replyError(t, "ERR wrong number of arguments for 'readonly' command"); return; } managers.engine.readonly(true); reply(t, "OK"); } }
apache-2.0
eHarmony/pho
src/main/java/com/eharmony/pho/hbase/util/PhoenixConnectionManager.java
459
package com.eharmony.pho.hbase.util; import java.sql.Connection; import java.sql.DriverManager; /** * Manages the phoenix connections based on JDBC driver * * @author vvangapandu * */ public class PhoenixConnectionManager { public static Connection getConnection(final String connectionString) throws Exception { Class.forName("org.apache.phoenix.jdbc.PhoenixDriver"); return DriverManager.getConnection(connectionString); } }
apache-2.0
xuhaoyang/Weibo
app/src/main/java/com/xhy/weibo/logic/CommentLogic.java
5864
package com.xhy.weibo.logic; import android.content.Context; import com.xhy.weibo.api.ApiClient; import com.xhy.weibo.model.Comment; import com.xhy.weibo.model.Result; import com.xhy.weibo.utils.Logger; import java.io.IOException; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by xuhaoyang on 16/7/22. */ public class CommentLogic { private static final String TAG = CommentLogic.class.getSimpleName(); /** * 发表评论 * * @param uid 发布评论的用户ID * @param wid 被评论的微博ID * @param pid 父级微博的用户ID * @param content 评论内容 * @param token * @param callBack */ public static void setComment(final int uid, final int wid, final int pid, final String content, final String token, final SetCommentCallBack callBack) { Call<Result> resultCall = ApiClient.getApi().setComment(uid, wid, pid, content, token); resultCall.enqueue(new Callback<Result>() { @Override public void onResponse(Call<Result> call, Response<Result> response) { Result result = response.body(); if (response.isSuccessful()) { if (result.isSuccess()) { callBack.onSetCommentSuccess(result); } else { callBack.onSetCommentFailure(result.getMsg()); } } else { callBack.onSetCommentFailure("发送失败"); try { Logger.show(TAG, response.errorBody().string()); } catch (IOException e) { e.printStackTrace(); } } } @Override public void onFailure(Call<Result> call, Throwable t) { callBack.onSetCommentError(t); } }); } /** * 获得单个微博数据 * * @param context * @param wid * @param token * @param callBack */ public static void getStatusOnlyCommentList(final Context context, final int wid, final String token, final GetCommentCallBack callBack) { Call<Result<List<Comment>>> resultCall = ApiClient.getApi().getStatusOnlyCommentList(token, wid); resultCall.enqueue(new Callback<Result<List<Comment>>>() { @Override public void onResponse(Call<Result<List<Comment>>> call, Response<Result<List<Comment>>> response) { if (response.isSuccessful()) { Result<List<Comment>> listResult = response.body(); if (listResult.isSuccess()) { callBack.onGetCommentSuccess(listResult.getInfo(), listResult.getTotalPage()); } else { callBack.onGetCommentFailure(listResult.getMsg()); } } else { callBack.onGetCommentFailure("获取信息失败"); try { Logger.show(TAG, response.errorBody().string()); } catch (IOException e) { e.printStackTrace(); } } } @Override public void onFailure(Call<Result<List<Comment>>> call, Throwable t) { callBack.onGetCommentError(t); } }); } /** * 获取该用户所有有关评论信息 * * @param context * @param uid * @param page * @param token * @param callBack */ public static void getUserCommentList(final Context context, final int uid, final int page, final String token, final GetUserCommentListCallBack callBack) { Call<Result<List<Comment>>> resultCall = ApiClient.getApi().getUserCommentList(token, uid, page); resultCall.enqueue(new Callback<Result<List<Comment>>>() { @Override public void onResponse(Call<Result<List<Comment>>> call, Response<Result<List<Comment>>> response) { if (response.isSuccessful()) { Result<List<Comment>> listResult = response.body(); if (listResult.isSuccess()) { callBack.onGetUserCommentSuccess(listResult.getInfo(), listResult.getTotalPage()); } else { callBack.onGetUserCommentFailure(listResult.getMsg()); } } else { callBack.onGetUserCommentFailure("获取信息失败"); try { Logger.show(TAG, response.errorBody().string()); } catch (IOException e) { e.printStackTrace(); } } } @Override public void onFailure(Call<Result<List<Comment>>> call, Throwable t) { callBack.onGetUserCommentError(t); } }); } public interface SetCommentCallBack { void onSetCommentSuccess(Result result); void onSetCommentFailure(String message); void onSetCommentError(Throwable t); } public interface GetCommentCallBack { void onGetCommentSuccess(List<Comment> comments, int totalPage); void onGetCommentFailure(String message); void onGetCommentError(Throwable t); } public interface GetUserCommentListCallBack { void onGetUserCommentSuccess(List<Comment> comments, int totalPage); void onGetUserCommentFailure(String message); void onGetUserCommentError(Throwable t); } }
apache-2.0
TU-Berlin/mathosphere
mathosphere-core/src/test/java/com/formulasearchengine/mathosphere/mlp/text/PlaintextDocumentBuilderTest.java
4431
package com.formulasearchengine.mathosphere.mlp.text; import com.formulasearchengine.mathosphere.mlp.cli.BaseConfig; import org.junit.Test; import static org.junit.Assert.assertEquals; public class PlaintextDocumentBuilderTest { @Test public void extractPlainText_wikiLinks() { String input = "In [[quantum mechanics]], the '''Schrödinger equation''' is a " + "[[partial differential equation]] " + "that describes how the [[quantum state]] of a [[physical system]] changes with [[time]]. " + "It was formulated in late 1925, and published in 1926, by the [[Austria]]n [[physicist]] " + "[[Erwin Schrödinger]]. " + "In the [[Copenhagen interpretation|standard interpretation of quantum mechanics]], " + "the wavefunction is the most complete description that can be given to a physical system."; String actual = WikiTextUtils.extractPlainText(input); String expected = "In “quantum mechanics”, the Schrödinger equation is a “partial differential equation” " + "that describes how the “quantum state” of a “physical system” changes with “time”. " + "It was formulated in late 1925, and published in 1926, by the “Austrian” “physicist” " + "“Erwin Schrödinger”. " + "In the “standard interpretation of quantum mechanics”, " + "the wavefunction is the most complete description that can be given to a physical system."; assertEquals(expected, actual); } @Test public void extractPlainText_new() throws Exception { String input = "In [[quantum mechanics]], the '''Schrödinger equation''' is a " + "[[partial differential equation]] " + "that describes how the [[quantum state]] of a [[physical system]] changes with [[time]]. " + "It was formulated in late 1925, and published in 1926, by the [[Austria]]n [[physicist]] " + "[[Erwin Schrödinger]]. " + "In the [[Copenhagen interpretation|standard interpretation of quantum mechanics]], " + "the wavefunction is the most complete description that can be given to a physical system."; BaseConfig c = new BaseConfig(); c.setWikiDataFile(getClass().getResource("test-map-no-dup.csv").getFile()); String actual = (new MathConverter(input, "hamiltonian", c)).getOutput(); String expected = "In [[quantum mechanics]] , the \"Schrödinger equation\" is a " + "[[partial differential equation]] that describes how the LINK_Q230883 of a " + "[[physical system]] changes with [[time]] . It was formulated in late 1925, and published in" + " 1926, by the [[Austria]] [[physicist]] [[Erwin Schrödinger]] . In the LINK_Q46079, " + "the wavefunction is the most complete description that can be given to a physical system. "; assertEquals(expected, actual); } @Test public void extractPlainText_removeTagsAndItalic() { String input = "For a constant potential, ''V'' = ''V''<sub>0</sub>, the solution is oscillatory " + "for ''E'' > " + "''V''<sub>0</sub> and exponential for ''E'' < ''V''<sub>0</sub>, corresponding to " + "energies that " + "are allowed or disallowed in classical mechanics."; String actual = WikiTextUtils.extractPlainText(input); String expected = "For a constant potential, V = V_0, the solution is oscillatory for E > V_0 " + "and exponential for E < V_0, corresponding to energies that are allowed or disallowed " + "in classical mechanics."; assertEquals(expected, actual); } @Test public void extractPlainText_new2() throws Exception { String input = "For a constant potential, {{math|''V'' {{=}} ''V''<sub>0</sub>}}, the solution" + " is oscillatory for {{math|''E'' > ''V''<sub>0</sub>}} and exponential for" + " {{math|''E'' < ''V''<sub>0</sub>}}, corresponding to energies that are allowed " + "or disallowed in classical mechanics."; String actual = (new MathConverter(input)).getOutput(); //TODO: add more templates String expected = "For a constant potential, <math>\\mathit{V}</math> , the solution is oscillatory for <math>\\mathit{E} > \\mathit{V}_{0}</math> " + "and exponential for <math>\\mathit{E} < \\mathit{V}_{0}</math> , corresponding to energies that are allowed or disallowed " + "in classical mechanics. "; assertEquals(expected, actual); } }
apache-2.0
dheraclio/dependometer
dependometer-java/src/test/test-dependencies/generics/one/Car.java
2551
/* * Valtech Public L I C E N S E (VPL) 1.0.2 * * dependometer * Copyright © 2007 Valtech GmbH * * dependometer software is made available free of charge under the * following conditions. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1.1.All copies and redistributions of source code must retain the above * copyright notice, this list of conditions and the following disclaimer. * * 1.2.Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 1.3.The end-user documentation included with the redistribution, if any, * must include the following acknowledgment: * This product includes software developed by Valtech http://www.valtech.de/. * This acknowledgement must appear in the software itself, if and wherever * such third-party acknowledgments normally appear. * * 1.4.The names "Valtech" and "dependometer" must not be used to endorse or * promote products derived from this software without prior written permission. * For written permission, please contact kmc@valtech.de <mailto:kmc@valtech.de> * * BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE IT IS PROVIDED "AS IS" AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL VALTECH GMBH OR ITS CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * LEGAL LIABILITY PROVIDED UNDER GERMAN LAW FOR INTENDED DAMAGES, BAD FAITH OR * GROSS NEGLIGENCE REMAINS UNAFFECTED. */ package generics.one; import java.util.Hashtable; /** * @author Andreas Volz (andreas.volz@valtech.de) */ public class Car { int id; Type type; class SoundSystem { Hashtable<String, Speaker> speakers; } class Speaker { SoundSystem soundSystem; } }
apache-2.0
jbeep/jbeep
src/main/java/org/github/jbeep/internal/management/ManagementProfileImpl.java
7004
/* * Copyright 2006 Simon Raess * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.github.jbeep.internal.management; import org.github.jbeep.ChannelHandler; import org.github.jbeep.Message; import org.github.jbeep.MessageBuilder; import org.github.jbeep.ProfileInfo; import org.github.jbeep.ProtocolException; import org.github.jbeep.Reply; import org.github.jbeep.ReplyHandler; import org.github.jbeep.internal.SessionManager; import org.github.jbeep.internal.StartChannelResponse; import org.github.jbeep.internal.message.DefaultMessageBuilder; import org.github.jbeep.internal.session.InternalChannel; /** * Implementation of ChannelManagementProfile interface. * * @author Simon Raess */ public class ManagementProfileImpl implements ManagementProfile { private SessionManager manager; private InternalChannel channel; private final boolean initiator; private final ManagementMessageBuilder builder; private final ManagementMessageParser parser; public ManagementProfileImpl(boolean initiator) { this.initiator = initiator; this.builder = createChannelManagementMessageBuilder(); this.parser = createChannelManagementMessageParser(); } protected ManagementMessageBuilder createChannelManagementMessageBuilder() { return new SaxMessageBuilder(); } protected ManagementMessageParser createChannelManagementMessageParser() { return new SaxMessageParser(); } protected MessageBuilder createMessageBuilder() { MessageBuilder builder = new DefaultMessageBuilder(); builder.setContentType("application", "beep+xml"); builder.setCharsetName("UTF-8"); return builder; } public ChannelHandler createChannelHandler(SessionManager manager, InternalChannel channel) { this.manager = manager; this.channel = channel; return new ManagementChannelHandler(this, parser); } public final Message createSessionStartDeclined(int errorCode, String message) { return createError(errorCode, message); } public final Message createGreeting(String[] profiles) { return builder.createGreeting(createMessageBuilder(), profiles); } protected Message createError(int code, String diagnostics) { return builder.createError(createMessageBuilder(), code, diagnostics); } public final Greeting receivedGreeting(Message message) { return parser.parseGreeting(message); } public final BEEPError receivedError(Message message) { return parser.parseError(message); } public final void startChannel( final int channelNumber, final ProfileInfo[] infos, final StartChannelCallback callback) { Message message = builder.createStart(createMessageBuilder(), channelNumber, infos); channel.sendMessage(message, new ManagementReplyHandler() { public void receivedRPY(Message message) { ProfileInfo profile = parser.parseProfile(message); callback.channelCreated(profile); } public void receivedERR(Message message) { BEEPError error = parser.parseError(message); callback.channelFailed(error.getCode(), error.getMessage()); } }); } public final void closeChannel(final int channelNumber, final CloseCallback callback) { Message message = builder.createClose(createMessageBuilder(), channelNumber, 200); channel.sendMessage(message, new ManagementReplyHandler() { public void receivedRPY(Message message) { parser.parseOk(message); callback.closeAccepted(); } public void receivedERR(Message message) { BEEPError error = parser.parseError(message); callback.closeDeclined(error.getCode(), error.getMessage()); } }); } public final void closeSession(final CloseCallback callback) { // closing the session is done by closing channel 0 closeChannel(0, callback); } public final void startChannelRequested( final int channelNumber, final ProfileInfo[] profiles, final Reply reply) { validateStartChannelRequest(channelNumber, reply); StartChannelResponse response = manager.channelStartRequested(channelNumber, profiles); if (response.isCancelled()) { reply.sendERR(builder.createError( createMessageBuilder(), response.getCode(), response.getMessage())); } else { reply.sendRPY(builder.createProfile( createMessageBuilder(), response.getProfile())); } } private void validateStartChannelRequest( final int channelNumber, final Reply reply) { if (channelNumber <= 0) { throw new ProtocolException(channelNumber + " is an illegal channel number"); } if (initiator && channelNumber % 2 != 0) { reply.sendERR(builder.createError( createMessageBuilder(), 501, "number attribute in <start> element must be odd valued")); } else if (!initiator && channelNumber % 2 != 1) { reply.sendERR(builder.createError( createMessageBuilder(), 501, "number attribute in <start> element must be even valued")); } } public final void closeChannelRequested(final int channelNumber, final Reply reply) { manager.channelCloseRequested(channelNumber, new CloseCallback() { public void closeDeclined(int code, String message) { reply.sendERR(builder.createError(createMessageBuilder(), code, message)); } public void closeAccepted() { reply.sendRPY(builder.createOk(createMessageBuilder())); } }); } public final void closeSessionRequested(final Reply reply) { manager.sessionCloseRequested(new CloseCallback() { public void closeDeclined(int code, String message) { reply.sendERR(builder.createError(createMessageBuilder(), code, message)); } public void closeAccepted() { reply.sendRPY(builder.createOk(createMessageBuilder())); } }); } // --> end of ChannelManagementProfile methods <-- /** * ReplyHandler for channel management messages. */ private static abstract class ManagementReplyHandler implements ReplyHandler { public final void receivedANS(Message message) { throw new ProtocolException("ANS is not a valid response to a channel management request"); } public final void receivedNUL() { throw new ProtocolException("NUL is not a valid response to a channel management request"); } } }
apache-2.0
gurhann/AutoTimeTable
optaplanner-webexamples/src/main/java/org/optaplanner/curriculumcourse/listener/AppContextListener.java
1700
/* * Copyright 2015 JBoss by Red Hat. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.optaplanner.curriculumcourse.listener; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; /** * * @author gurhan */ @WebListener public class AppContextListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("optaplanner-web-pu"); EntityManager em = emf.createEntityManager(); sce.getServletContext().setAttribute("entityManager", em); sce.getServletContext().setAttribute("entityManagerFactory", emf); } @Override public void contextDestroyed(ServletContextEvent sce) { EntityManagerFactory emf = (EntityManagerFactory) sce.getServletContext().getAttribute("entityManagerFactory"); EntityManager em = (EntityManager) sce.getServletContext().getAttribute("entityManager"); } }
apache-2.0
vinothchandar/hoodie
hoodie-client/src/main/java/com/uber/hoodie/io/HoodieCommitArchiveLog.java
14185
/* * Copyright (c) 2016 Uber Technologies, Inc. (hoodie-dev-group@uber.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.uber.hoodie.io; import static com.uber.hoodie.common.table.HoodieTimeline.COMMIT_ACTION; import static com.uber.hoodie.common.table.HoodieTimeline.DELTA_COMMIT_ACTION; import static com.uber.hoodie.common.table.HoodieTimeline.LESSER_OR_EQUAL; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.uber.hoodie.avro.model.HoodieArchivedMetaEntry; import com.uber.hoodie.avro.model.HoodieCleanMetadata; import com.uber.hoodie.avro.model.HoodieRollbackMetadata; import com.uber.hoodie.avro.model.HoodieSavepointMetadata; import com.uber.hoodie.common.model.ActionType; import com.uber.hoodie.common.model.HoodieArchivedLogFile; import com.uber.hoodie.common.model.HoodieCommitMetadata; import com.uber.hoodie.common.model.HoodieRollingStatMetadata; import com.uber.hoodie.common.table.HoodieTableMetaClient; import com.uber.hoodie.common.table.HoodieTimeline; import com.uber.hoodie.common.table.log.HoodieLogFormat; import com.uber.hoodie.common.table.log.block.HoodieAvroDataBlock; import com.uber.hoodie.common.table.log.block.HoodieLogBlock; import com.uber.hoodie.common.table.timeline.HoodieActiveTimeline; import com.uber.hoodie.common.table.timeline.HoodieArchivedTimeline; import com.uber.hoodie.common.table.timeline.HoodieInstant; import com.uber.hoodie.common.util.AvroUtils; import com.uber.hoodie.config.HoodieWriteConfig; import com.uber.hoodie.exception.HoodieCommitException; import com.uber.hoodie.exception.HoodieException; import com.uber.hoodie.exception.HoodieIOException; import com.uber.hoodie.table.HoodieTable; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.avro.Schema; import org.apache.avro.generic.IndexedRecord; import org.apache.hadoop.fs.Path; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.spark.api.java.JavaSparkContext; /** * Archiver to bound the growth of <action>.commit files */ public class HoodieCommitArchiveLog { private static Logger log = LogManager.getLogger(HoodieCommitArchiveLog.class); private final Path archiveFilePath; private final HoodieTableMetaClient metaClient; private final HoodieWriteConfig config; private HoodieLogFormat.Writer writer; public HoodieCommitArchiveLog(HoodieWriteConfig config, HoodieTableMetaClient metaClient) { this.config = config; this.metaClient = metaClient; this.archiveFilePath = HoodieArchivedTimeline.getArchiveLogPath(metaClient.getArchivePath()); } private HoodieLogFormat.Writer openWriter() { try { if (this.writer == null) { return HoodieLogFormat.newWriterBuilder().onParentPath(archiveFilePath.getParent()) .withFileId(archiveFilePath.getName()) .withFileExtension(HoodieArchivedLogFile.ARCHIVE_EXTENSION).withFs(metaClient.getFs()) .overBaseCommit("").build(); } else { return this.writer; } } catch (InterruptedException | IOException e) { throw new HoodieException("Unable to initialize HoodieLogFormat writer", e); } } private void close() { try { if (this.writer != null) { this.writer.close(); } } catch (IOException e) { throw new HoodieException("Unable to close HoodieLogFormat writer", e); } } /** * Check if commits need to be archived. If yes, archive commits. */ public boolean archiveIfRequired(final JavaSparkContext jsc) throws IOException { try { List<HoodieInstant> instantsToArchive = getInstantsToArchive(jsc).collect(Collectors.toList()); boolean success = true; if (instantsToArchive.iterator().hasNext()) { this.writer = openWriter(); log.info("Archiving instants " + instantsToArchive); archive(instantsToArchive); success = deleteArchivedInstants(instantsToArchive); } else { log.info("No Instants to archive"); } return success; } finally { close(); } } private Stream<HoodieInstant> getInstantsToArchive(JavaSparkContext jsc) { // TODO : rename to max/minInstantsToKeep int maxCommitsToKeep = config.getMaxCommitsToKeep(); int minCommitsToKeep = config.getMinCommitsToKeep(); HoodieTable table = HoodieTable.getHoodieTable(metaClient, config, jsc); // GroupBy each action and limit each action timeline to maxCommitsToKeep // TODO: Handle ROLLBACK_ACTION in future // ROLLBACK_ACTION is currently not defined in HoodieActiveTimeline HoodieTimeline cleanAndRollbackTimeline = table.getActiveTimeline() .getTimelineOfActions(Sets.newHashSet(HoodieTimeline.CLEAN_ACTION)) .filterCompletedInstants(); Stream<HoodieInstant> instants = cleanAndRollbackTimeline.getInstants() .collect(Collectors.groupingBy(s -> s.getAction())).entrySet().stream().map(i -> { if (i.getValue().size() > maxCommitsToKeep) { return i.getValue().subList(0, i.getValue().size() - minCommitsToKeep); } else { return new ArrayList<HoodieInstant>(); } }).flatMap(i -> i.stream()); //TODO (na) : Add a way to return actions associated with a timeline and then merge/unify // with logic above to avoid Stream.concats HoodieTimeline commitTimeline = table.getCompletedCommitsTimeline(); Optional<HoodieInstant> oldestPendingCompactionInstant = table.getActiveTimeline().filterPendingCompactionTimeline().firstInstant(); // We cannot have any holes in the commit timeline. We cannot archive any commits which are // made after the first savepoint present. Optional<HoodieInstant> firstSavepoint = table.getCompletedSavepointTimeline().firstInstant(); if (!commitTimeline.empty() && commitTimeline.countInstants() > maxCommitsToKeep) { // Actually do the commits instants = Stream.concat(instants, commitTimeline.getInstants() .filter(s -> { // if no savepoint present, then dont filter return !(firstSavepoint.isPresent() && HoodieTimeline .compareTimestamps(firstSavepoint.get().getTimestamp(), s.getTimestamp(), HoodieTimeline.LESSER_OR_EQUAL)); }) .filter(s -> { // Ensure commits >= oldest pending compaction commit is retained return oldestPendingCompactionInstant.map(instant -> { return HoodieTimeline.compareTimestamps(instant.getTimestamp(), s.getTimestamp(), HoodieTimeline.GREATER); }).orElse(true); }) .limit(commitTimeline.countInstants() - minCommitsToKeep)); } return instants; } private boolean deleteArchivedInstants(List<HoodieInstant> archivedInstants) throws IOException { log.info("Deleting instants " + archivedInstants); boolean success = true; for (HoodieInstant archivedInstant : archivedInstants) { Path commitFile = new Path(metaClient.getMetaPath(), archivedInstant.getFileName()); try { if (metaClient.getFs().exists(commitFile)) { success &= metaClient.getFs().delete(commitFile, false); log.info("Archived and deleted instant file " + commitFile); } } catch (IOException e) { throw new HoodieIOException("Failed to delete archived instant " + archivedInstant, e); } } // Remove older meta-data from auxiliary path too Optional<HoodieInstant> latestCommitted = archivedInstants.stream() .filter(i -> { return i.isCompleted() && (i.getAction().equals(COMMIT_ACTION) || (i.getAction().equals(DELTA_COMMIT_ACTION))); }).max(Comparator.comparing(HoodieInstant::getTimestamp)); if (latestCommitted.isPresent()) { success &= deleteAllInstantsOlderorEqualsInAuxMetaFolder(latestCommitted.get()); } return success; } /** * Remove older instants from auxiliary meta folder * * @param thresholdInstant Hoodie Instant * @return success if all eligible file deleted successfully * @throws IOException in case of error */ private boolean deleteAllInstantsOlderorEqualsInAuxMetaFolder(HoodieInstant thresholdInstant) throws IOException { List<HoodieInstant> instants = HoodieTableMetaClient.scanHoodieInstantsFromFileSystem(metaClient.getFs(), new Path(metaClient.getMetaAuxiliaryPath()), HoodieActiveTimeline.VALID_EXTENSIONS_IN_ACTIVE_TIMELINE); List<HoodieInstant> instantsToBeDeleted = instants.stream().filter(instant1 -> HoodieTimeline.compareTimestamps(instant1.getTimestamp(), thresholdInstant.getTimestamp(), LESSER_OR_EQUAL)).collect(Collectors.toList()); boolean success = true; for (HoodieInstant deleteInstant : instantsToBeDeleted) { log.info("Deleting instant " + deleteInstant + " in auxiliary meta path " + metaClient.getMetaAuxiliaryPath()); Path metaFile = new Path(metaClient.getMetaAuxiliaryPath(), deleteInstant.getFileName()); if (metaClient.getFs().exists(metaFile)) { success &= metaClient.getFs().delete(metaFile, false); log.info("Deleted instant file in auxiliary metapath : " + metaFile); } } return success; } public void archive(List<HoodieInstant> instants) throws HoodieCommitException { try { HoodieTimeline commitTimeline = metaClient.getActiveTimeline().getAllCommitsTimeline() .filterCompletedInstants(); Schema wrapperSchema = HoodieArchivedMetaEntry.getClassSchema(); log.info("Wrapper schema " + wrapperSchema.toString()); List<IndexedRecord> records = new ArrayList<>(); for (HoodieInstant hoodieInstant : instants) { records.add(convertToAvroRecord(commitTimeline, hoodieInstant)); } Map<HoodieLogBlock.HeaderMetadataType, String> header = Maps.newHashMap(); header.put(HoodieLogBlock.HeaderMetadataType.SCHEMA, wrapperSchema.toString()); HoodieAvroDataBlock block = new HoodieAvroDataBlock(records, header); this.writer = writer.appendBlock(block); } catch (Exception e) { throw new HoodieCommitException("Failed to archive commits", e); } } public Path getArchiveFilePath() { return archiveFilePath; } private IndexedRecord convertToAvroRecord(HoodieTimeline commitTimeline, HoodieInstant hoodieInstant) throws IOException { HoodieArchivedMetaEntry archivedMetaWrapper = new HoodieArchivedMetaEntry(); archivedMetaWrapper.setCommitTime(hoodieInstant.getTimestamp()); switch (hoodieInstant.getAction()) { case HoodieTimeline.CLEAN_ACTION: { archivedMetaWrapper.setHoodieCleanMetadata(AvroUtils .deserializeAvroMetadata(commitTimeline.getInstantDetails(hoodieInstant).get(), HoodieCleanMetadata.class)); archivedMetaWrapper.setActionType(ActionType.clean.name()); break; } case COMMIT_ACTION: { HoodieCommitMetadata commitMetadata = HoodieCommitMetadata .fromBytes(commitTimeline.getInstantDetails(hoodieInstant).get(), HoodieCommitMetadata.class); archivedMetaWrapper.setHoodieCommitMetadata(commitMetadataConverter(commitMetadata)); archivedMetaWrapper.setActionType(ActionType.commit.name()); break; } case HoodieTimeline.ROLLBACK_ACTION: { archivedMetaWrapper.setHoodieRollbackMetadata(AvroUtils .deserializeAvroMetadata(commitTimeline.getInstantDetails(hoodieInstant).get(), HoodieRollbackMetadata.class)); archivedMetaWrapper.setActionType(ActionType.rollback.name()); break; } case HoodieTimeline.SAVEPOINT_ACTION: { archivedMetaWrapper.setHoodieSavePointMetadata(AvroUtils .deserializeAvroMetadata(commitTimeline.getInstantDetails(hoodieInstant).get(), HoodieSavepointMetadata.class)); archivedMetaWrapper.setActionType(ActionType.savepoint.name()); break; } case HoodieTimeline.DELTA_COMMIT_ACTION: { HoodieCommitMetadata commitMetadata = HoodieCommitMetadata .fromBytes(commitTimeline.getInstantDetails(hoodieInstant).get(), HoodieCommitMetadata.class); archivedMetaWrapper.setHoodieCommitMetadata(commitMetadataConverter(commitMetadata)); archivedMetaWrapper.setActionType(ActionType.commit.name()); break; } default: throw new UnsupportedOperationException("Action not fully supported yet"); } return archivedMetaWrapper; } private com.uber.hoodie.avro.model.HoodieCommitMetadata commitMetadataConverter( HoodieCommitMetadata hoodieCommitMetadata) { ObjectMapper mapper = new ObjectMapper(); //Need this to ignore other public get() methods mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); com.uber.hoodie.avro.model.HoodieCommitMetadata avroMetaData = mapper .convertValue(hoodieCommitMetadata, com.uber.hoodie.avro.model.HoodieCommitMetadata.class); // Do not archive Rolling Stats, cannot set to null since AVRO will throw null pointer avroMetaData.getExtraMetadata().put(HoodieRollingStatMetadata.ROLLING_STAT_METADATA_KEY, ""); return avroMetaData; } }
apache-2.0
Nodstuff/hapi-fhir
hapi-fhir-structures-hl7org-dstu2/src/main/java/org/hl7/fhir/instance/model/valuesets/SupplydeliveryType.java
3241
package org.hl7.fhir.instance.model.valuesets; /* Copyright (c) 2011+, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Generated on Sat, Aug 22, 2015 23:00-0400 for FHIR v0.5.0 public enum SupplydeliveryType { /** * Supply is a kind of medication. */ MEDICATION, /** * What is supplied (or requested) is a device */ DEVICE, /** * added to help the parsers */ NULL; public static SupplydeliveryType fromCode(String codeString) throws Exception { if (codeString == null || "".equals(codeString)) return null; if ("medication".equals(codeString)) return MEDICATION; if ("device".equals(codeString)) return DEVICE; throw new Exception("Unknown SupplydeliveryType code '"+codeString+"'"); } public String toCode() { switch (this) { case MEDICATION: return "medication"; case DEVICE: return "device"; default: return "?"; } } public String getSystem() { return "http://hl7.org/fhir/supply-item-type"; } public String getDefinition() { switch (this) { case MEDICATION: return "Supply is a kind of medication."; case DEVICE: return "What is supplied (or requested) is a device"; default: return "?"; } } public String getDisplay() { switch (this) { case MEDICATION: return "Medication"; case DEVICE: return "Device"; default: return "?"; } } }
apache-2.0
gessnerfl/rabbitmq-queue-management
src/main/java/de/gessnerfl/rabbitmq/queue/management/model/ErrorResponse.java
266
package de.gessnerfl.rabbitmq.queue.management.model; public class ErrorResponse { private final String message; public ErrorResponse(String message) { this.message = message; } public String getMessage() { return message; } }
apache-2.0
sweble/osr-common
parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/comparer/DeepComparisonException.java
2043
/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fau.cs.osr.ptk.common.comparer; import java.io.IOException; import java.io.Writer; import de.fau.cs.osr.ptk.common.ast.AstNode; import de.fau.cs.osr.utils.StringTools; public class DeepComparisonException extends AstComparisonException { private static final long serialVersionUID = 1L; private final Object a; private final Object b; public DeepComparisonException(Object a, Object b) { this.a = a; this.b = b; } public DeepComparisonException( AstComparisonException e, AstNode<?> a, AstNode<?> b) { super(e); this.a = a; this.b = b; } public Object getObjectA() { return a; } public Object getObjectB() { return b; } public Writer toString(Writer w) throws IOException { if (getCause() != null) ((AstComparisonException) getCause()).toString(w); w.append(String.format( "Values during deep comparison differed (%s vs. %s):\n", (a == null ? "-" : a.getClass().getName()), (b == null ? "-" : b.getClass().getName()))); printValue("a", a, w); printValue("b", b, w); return w; } private void printValue(String which, Object value, Writer w) throws IOException { w.append("\t"); w.append(which); w.append(": "); if (value == null) w.append("null\n"); else { w.append("\"\"\""); w.append(StringTools.escJava(value.toString())); w.append("\"\"\"\n"); } } }
apache-2.0
mifos/1.5.x
application/src/test/java/org/mifos/framework/components/batchjobs/helpers/LoanArrearsTaskIntegrationTest.java
6016
/* * Copyright (c) 2005-2010 Grameen Foundation USA * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an * explanation of the license and how it is applied. */ package org.mifos.framework.components.batchjobs.helpers; import java.sql.Date; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import junit.framework.Assert; import org.hibernate.Query; import org.mifos.accounts.business.AccountActionDateEntity; import org.mifos.accounts.business.AccountBO; import org.mifos.accounts.exceptions.AccountException; import org.mifos.accounts.loan.business.LoanBO; import org.mifos.accounts.loan.business.LoanBOTestUtils; import org.mifos.accounts.persistence.AccountPersistence; import org.mifos.accounts.productdefinition.business.LoanOfferingBO; import org.mifos.accounts.util.helpers.AccountState; import org.mifos.application.meeting.business.MeetingBO; import org.mifos.customers.business.CustomerBO; import org.mifos.customers.util.helpers.CustomerStatus; import org.mifos.framework.MifosIntegrationTestCase; import org.mifos.framework.components.batchjobs.SchedulerConstants; import org.mifos.framework.components.batchjobs.business.Task; import org.mifos.framework.hibernate.helper.StaticHibernateUtil; import org.mifos.framework.persistence.TestDatabase; import org.mifos.framework.util.helpers.TestObjectFactory; public class LoanArrearsTaskIntegrationTest extends MifosIntegrationTestCase { public LoanArrearsTaskIntegrationTest() throws Exception { super(); } private LoanArrearsTask loanArrearTask; CustomerBO center = null; CustomerBO group = null; MeetingBO meeting = null; AccountBO loanAccount = null; @Override protected void setUp() throws Exception { super.setUp(); TestDatabase.resetMySQLDatabase(); loanArrearTask = new LoanArrearsTask(); meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting()); center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting); group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center); loanAccount = getLoanAccount(group, meeting); } @Override protected void tearDown() throws Exception { TestObjectFactory.cleanUp(loanAccount); TestObjectFactory.cleanUp(group); TestObjectFactory.cleanUp(center); loanArrearTask = null; StaticHibernateUtil.closeSession(); super.tearDown(); } public void testExecute() throws Exception { int statusChangeHistorySize = loanAccount.getAccountStatusChangeHistory().size(); loanArrearTask.run(); Query query = StaticHibernateUtil.getSessionTL().createQuery("from " + Task.class.getName()); List<Task> tasks = query.list(); Assert.assertEquals(1, tasks.size()); Task task = tasks.get(0); Assert.assertEquals(TaskStatus.COMPLETE, task.getStatusEnum()); Assert.assertEquals(SchedulerConstants.FINISHED_SUCCESSFULLY, task.getDescription()); TestObjectFactory.removeObject(task); loanAccount = new AccountPersistence().getAccount(loanAccount.getAccountId()); Assert.assertEquals(AccountState.LOAN_ACTIVE_IN_BAD_STANDING, loanAccount.getState()); Assert.assertEquals(statusChangeHistorySize + 1, loanAccount.getAccountStatusChangeHistory().size()); } private AccountBO getLoanAccount(CustomerBO customer, MeetingBO meeting) throws AccountException { Date currentdate = new Date(System.currentTimeMillis()); LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(currentdate, meeting); loanAccount = TestObjectFactory.createLoanAccount("42423142341", customer, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, currentdate, loanOffering); setDisbursementDateAsOldDate(loanAccount); loanAccount.update(); StaticHibernateUtil.commitTransaction(); return loanAccount; } private void setDisbursementDateAsOldDate(AccountBO account) { Date startDate = offSetCurrentDate(15); LoanBO loan = (LoanBO) account; LoanBOTestUtils.modifyDisbursementDate(loan, startDate); for (AccountActionDateEntity actionDate : loan.getAccountActionDates()) { LoanBOTestUtils.setActionDate(actionDate, offSetGivenDate(actionDate.getActionDate(), 18)); } } private java.sql.Date offSetGivenDate(Date date, int numberOfDays) { Calendar dateCalendar = new GregorianCalendar(); dateCalendar.setTimeInMillis(date.getTime()); int year = dateCalendar.get(Calendar.YEAR); int month = dateCalendar.get(Calendar.MONTH); int day = dateCalendar.get(Calendar.DAY_OF_MONTH); dateCalendar = new GregorianCalendar(year, month, day - numberOfDays); return new java.sql.Date(dateCalendar.getTimeInMillis()); } private java.sql.Date offSetCurrentDate(int noOfDays) { Calendar currentDateCalendar = new GregorianCalendar(); int year = currentDateCalendar.get(Calendar.YEAR); int month = currentDateCalendar.get(Calendar.MONTH); int day = currentDateCalendar.get(Calendar.DAY_OF_MONTH); currentDateCalendar = new GregorianCalendar(year, month, day - noOfDays); return new java.sql.Date(currentDateCalendar.getTimeInMillis()); } }
apache-2.0
oharasteve/eagle
src/com/eagle/programmar/Natural/Statements/Natural_WriteStatement.java
747
// Copyright Eagle Legacy Modernization, 2010-date // Original author: Steven A. O'Hara, Jan 4, 2011 package com.eagle.programmar.Natural.Statements; import com.eagle.programmar.Natural.Statements.Natural_DisplayStatement.Natural_DisplayElement; import com.eagle.programmar.Natural.Terminals.Natural_Keyword; import com.eagle.programmar.Natural.Terminals.Natural_KeywordChoice; import com.eagle.tokens.TokenList; import com.eagle.tokens.TokenSequence; public class Natural_WriteStatement extends TokenSequence { public @DOC("sm/write.htm") Natural_Keyword WRITE = new Natural_Keyword("WRITE"); public @OPT Natural_KeywordChoice TITLE = new Natural_KeywordChoice( "TITLE", "NOTITLE"); public TokenList<Natural_DisplayElement> writeWhat; }
apache-2.0
RyanCai/testsvn
JAVA/STaoBao/src/com/cyl/frame/util/MD5Encrypt.java
1964
package com.cyl.frame.util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * * <pre> * MD5加解密工具类 * </pre> * * @author yisin * @date 2012-12-11 下午02:53:18 * @see com.cttsp.frame.security.MD5Encrypt * */ public class MD5Encrypt { private static MD5Encrypt md5 = new MD5Encrypt(); private MD5Encrypt() { } public static MD5Encrypt getInstance() { return md5; } public String encrypt(String sourceStr) { MessageDigest md; String encryptString = ""; byte[] bytes = null; try { md = MessageDigest.getInstance("MD5"); bytes = md.digest(sourceStr.getBytes()); encryptString = new String(bytes, "UTF-8"); } catch (Exception e) { encryptString = sourceStr; } return encryptString; } /** * * MD5加密 * * @author yisin * @date 2012-11-01 * @param plainText * 需要加密的字符串 * @param number * 加密位16,32 * @return String 已加密字符串 * */ public String md5(String plainText, int number) { String result = plainText; if (plainText != null) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } if (number == 16) {// 16位的加密 result = buf.toString().substring(8, 24); } else if (number == 32) {// 32位的加密 result = buf.toString(); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } return result; } public static void main(String[] args) { //System.out.println(MD5Encrypt.getInstance().md5("", 32)); } }
apache-2.0
GwtDomino/domino
domino-test/domino-client-test/src/main/java/org/dominokit/domino/test/api/client/annotations/AutoStart.java
352
package org.dominokit.domino.test.api.client.annotations; import javax.validation.constraints.NotNull; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface AutoStart { boolean value() default true; @NotNull String configFile() default "config.json"; }
apache-2.0
compomics/compomics-utilities
src/main/java/com/compomics/util/gui/parameters/identification/algorithm/AndromedaParametersDialog.java
46368
package com.compomics.util.gui.parameters.identification.algorithm; import com.compomics.util.examples.BareBonesBrowserLaunch; import com.compomics.util.gui.parameters.identification.IdentificationAlgorithmParameter; import com.compomics.util.parameters.identification.tool_specific.AndromedaParameters; import com.compomics.util.parameters.identification.tool_specific.AndromedaParameters.AndromedaDecoyMode; import com.compomics.util.experiment.mass_spectrometry.FragmentationMethod; import com.compomics.util.gui.GuiUtilities; import java.awt.Color; import java.awt.Dialog; import javax.swing.DefaultComboBoxModel; import javax.swing.JOptionPane; import javax.swing.SwingConstants; import com.compomics.util.gui.parameters.identification.AlgorithmParametersDialog; /** * Dialog for the Andromeda specific settings. * * @author Harald Barsnes */ public class AndromedaParametersDialog extends javax.swing.JDialog implements AlgorithmParametersDialog { /** * Boolean indicating whether the used canceled the editing. */ private boolean cancelled = false; /** * Boolean indicating whether the settings can be edited by the user. */ private boolean editable; /** * Creates a new AndromedaParametersDialog with a frame as owner. * * @param parentFrame the parent frame * @param andromedaParameters the Andromeda parameters * @param editable boolean indicating whether the settings can be edited by * the user */ public AndromedaParametersDialog(java.awt.Frame parentFrame, AndromedaParameters andromedaParameters, boolean editable) { super(parentFrame, true); this.editable = editable; initComponents(); setUpGUI(); populateGUI(andromedaParameters); validateInput(false); setLocationRelativeTo(parentFrame); setVisible(true); } /** * Creates a new AndromedaParametersDialog with a dialog as owner. * * @param owner the dialog owner * @param parentFrame the parent frame * @param andromedaParameters the Andromeda parameters * @param editable boolean indicating whether the settings can be edited by * the user */ public AndromedaParametersDialog(Dialog owner, java.awt.Frame parentFrame, AndromedaParameters andromedaParameters, boolean editable) { super(owner, true); this.editable = editable; initComponents(); setUpGUI(); populateGUI(andromedaParameters); validateInput(false); setLocationRelativeTo(owner); setVisible(true); } /** * Sets up the GUI. */ private void setUpGUI() { neutralLossesCmb.setRenderer(new com.compomics.util.gui.renderers.AlignedListCellRenderer(SwingConstants.CENTER)); fragMethodCmb.setRenderer(new com.compomics.util.gui.renderers.AlignedListCellRenderer(SwingConstants.CENTER)); fragmentAllCmb.setRenderer(new com.compomics.util.gui.renderers.AlignedListCellRenderer(SwingConstants.CENTER)); empiricalCorrectionCombo.setRenderer(new com.compomics.util.gui.renderers.AlignedListCellRenderer(SwingConstants.CENTER)); higherChargeCombo.setRenderer(new com.compomics.util.gui.renderers.AlignedListCellRenderer(SwingConstants.CENTER)); ammoniaLossCmb.setRenderer(new com.compomics.util.gui.renderers.AlignedListCellRenderer(SwingConstants.CENTER)); waterLossCombo.setRenderer(new com.compomics.util.gui.renderers.AlignedListCellRenderer(SwingConstants.CENTER)); equalILCombo.setRenderer(new com.compomics.util.gui.renderers.AlignedListCellRenderer(SwingConstants.CENTER)); decoyModeCmb.setRenderer(new com.compomics.util.gui.renderers.AlignedListCellRenderer(SwingConstants.CENTER)); minPepLengthNoEnzymeTxt.setEditable(editable); minPepLengthNoEnzymeTxt.setEnabled(editable); maxPepLengthNoEnzymeTxt.setEditable(editable); maxPepLengthNoEnzymeTxt.setEnabled(editable); maxPeptideMassTxt.setEditable(editable); maxPeptideMassTxt.setEnabled(editable); numberMatchesTxt.setEditable(editable); numberMatchesTxt.setEnabled(editable); maxPtmsTxt.setEditable(editable); maxPtmsTxt.setEnabled(editable); fragMethodCmb.setEnabled(editable); waterLossCombo.setEnabled(editable); ammoniaLossCmb.setEnabled(editable); neutralLossesCmb.setEnabled(editable); equalILCombo.setEnabled(editable); fragmentAllCmb.setEnabled(editable); empiricalCorrectionCombo.setEnabled(editable); higherChargeCombo.setEnabled(editable); maxCombinationsTxt.setEditable(editable); maxCombinationsTxt.setEnabled(editable); topPeaksTxt.setEditable(editable); topPeaksTxt.setEnabled(editable); topPeaksWindowTxt.setEditable(editable); topPeaksWindowTxt.setEnabled(editable); decoyModeCmb.setEnabled(editable); } /** * Populates the GUI using the given settings. * * @param andromedaParameters the parameters to display */ private void populateGUI(AndromedaParameters andromedaParameters) { minPepLengthNoEnzymeTxt.setText(andromedaParameters.getMinPeptideLengthNoEnzyme() + ""); maxPepLengthNoEnzymeTxt.setText(andromedaParameters.getMaxPeptideLengthNoEnzyme() + ""); maxPeptideMassTxt.setText(andromedaParameters.getMaxPeptideMass() + ""); numberMatchesTxt.setText(andromedaParameters.getNumberOfCandidates() + ""); maxPtmsTxt.setText(andromedaParameters.getMaxNumberOfModifications() + ""); if (andromedaParameters.getFragmentationMethod() == FragmentationMethod.CID) { fragMethodCmb.setSelectedIndex(0); } else if (andromedaParameters.getFragmentationMethod() == FragmentationMethod.HCD) { fragMethodCmb.setSelectedIndex(1); } else if (andromedaParameters.getFragmentationMethod() == FragmentationMethod.ETD) { fragMethodCmb.setSelectedIndex(2); } if (andromedaParameters.isIncludeWater()) { waterLossCombo.setSelectedIndex(0); } else { waterLossCombo.setSelectedIndex(1); } if (andromedaParameters.isIncludeAmmonia()) { ammoniaLossCmb.setSelectedIndex(0); } else { ammoniaLossCmb.setSelectedIndex(1); } if (andromedaParameters.isDependentLosses()) { neutralLossesCmb.setSelectedIndex(0); } else { neutralLossesCmb.setSelectedIndex(1); } if (andromedaParameters.isEqualIL()) { equalILCombo.setSelectedIndex(0); } else { equalILCombo.setSelectedIndex(1); } if (andromedaParameters.isFragmentAll()) { fragmentAllCmb.setSelectedIndex(0); } else { fragmentAllCmb.setSelectedIndex(1); } if (andromedaParameters.isEmpiricalCorrection()) { empiricalCorrectionCombo.setSelectedIndex(0); } else { empiricalCorrectionCombo.setSelectedIndex(1); } if (andromedaParameters.isHigherCharge()) { higherChargeCombo.setSelectedIndex(0); } else { higherChargeCombo.setSelectedIndex(1); } decoyModeCmb.setSelectedItem(andromedaParameters.getDecoyMode()); maxCombinationsTxt.setText(andromedaParameters.getMaxCombinations() + ""); topPeaksTxt.setText(andromedaParameters.getTopPeaks() + ""); topPeaksWindowTxt.setText(andromedaParameters.getTopPeaksWindow() + ""); } @Override public boolean isCancelled() { return cancelled; } @Override public IdentificationAlgorithmParameter getParameters() { return getInput(); } /** * Returns the user selection as Andromeda parameters object. * * @return the user selection */ public AndromedaParameters getInput() { AndromedaParameters result = new AndromedaParameters(); String input = minPepLengthNoEnzymeTxt.getText().trim(); if (!input.equals("")) { result.setMinPeptideLengthNoEnzyme(Integer.valueOf(input)); } input = maxPepLengthNoEnzymeTxt.getText().trim(); if (!input.equals("")) { result.setMaxPeptideLengthNoEnzyme(Integer.valueOf(input)); } input = maxPeptideMassTxt.getText().trim(); if (!input.equals("")) { result.setMaxPeptideMass(Double.valueOf(input)); } input = numberMatchesTxt.getText().trim(); if (!input.equals("")) { result.setNumberOfCandidates(Integer.valueOf(input)); } input = maxPtmsTxt.getText().trim(); if (!input.equals("")) { result.setMaxNumberOfModifications(Integer.valueOf(input)); } switch (fragMethodCmb.getSelectedIndex()) { case 0: result.setFragmentationMethod(FragmentationMethod.CID); break; case 1: result.setFragmentationMethod(FragmentationMethod.HCD); break; default: result.setFragmentationMethod(FragmentationMethod.ETD); break; } result.setIncludeWater(waterLossCombo.getSelectedIndex() == 0); result.setIncludeAmmonia(ammoniaLossCmb.getSelectedIndex() == 0); result.setDependentLosses(neutralLossesCmb.getSelectedIndex() == 0); result.setEqualIL(equalILCombo.getSelectedIndex() == 0); result.setFragmentAll(fragmentAllCmb.getSelectedIndex() == 0); result.setEmpiricalCorrection(empiricalCorrectionCombo.getSelectedIndex() == 0); result.setHigherCharge(higherChargeCombo.getSelectedIndex() == 0); input = maxCombinationsTxt.getText().trim(); if (!input.equals("")) { result.setMaxCombinations(Integer.valueOf(input)); } input = topPeaksTxt.getText().trim(); if (!input.equals("")) { result.setTopPeaks(Integer.valueOf(input)); } input = topPeaksWindowTxt.getText().trim(); if (!input.equals("")) { result.setTopPeaksWindow(Integer.valueOf(input)); } result.setDecoyMode((AndromedaDecoyMode) decoyModeCmb.getSelectedItem()); return result; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { backgroundPanel = new javax.swing.JPanel(); settingsPanel = new javax.swing.JPanel(); settingsScrollPane = new javax.swing.JScrollPane(); settingsInnerPanel = new javax.swing.JPanel(); peptideLengthNoEnzymeLabel = new javax.swing.JLabel(); minPepLengthNoEnzymeTxt = new javax.swing.JTextField(); peptideLengthNoEnzymeDividerLabel = new javax.swing.JLabel(); maxPepLengthNoEnzymeTxt = new javax.swing.JTextField(); maxPeptideMassLabel = new javax.swing.JLabel(); maxPeptideMassTxt = new javax.swing.JTextField(); numberMatchesLabel = new javax.swing.JLabel(); numberMatchesTxt = new javax.swing.JTextField(); fragMethodLabel = new javax.swing.JLabel(); fragMethodCmb = new javax.swing.JComboBox(); ammoniaLossLabel = new javax.swing.JLabel(); ammoniaLossCmb = new javax.swing.JComboBox(); maxPtmsLabel = new javax.swing.JLabel(); maxPtmsTxt = new javax.swing.JTextField(); empiricalCorrectionLabel = new javax.swing.JLabel(); empiricalCorrectionCombo = new javax.swing.JComboBox(); higherChargeLabel = new javax.swing.JLabel(); higherChargeCombo = new javax.swing.JComboBox(); topPeaksLabel = new javax.swing.JLabel(); topPeaksTxt = new javax.swing.JTextField(); neutralLossesLabel = new javax.swing.JLabel(); neutralLossesCmb = new javax.swing.JComboBox(); fragmentAllLabel = new javax.swing.JLabel(); fragmentAllCmb = new javax.swing.JComboBox(); maxCombinationsLabel = new javax.swing.JLabel(); maxCombinationsTxt = new javax.swing.JTextField(); topPeaksWindowLabel = new javax.swing.JLabel(); topPeaksWindowTxt = new javax.swing.JTextField(); waterLossLabel = new javax.swing.JLabel(); waterLossCombo = new javax.swing.JComboBox(); equalILLabel = new javax.swing.JLabel(); equalILCombo = new javax.swing.JComboBox(); decoyModeLabel = new javax.swing.JLabel(); decoyModeCmb = new javax.swing.JComboBox(); openDialogHelpJButton = new javax.swing.JButton(); advancedSettingsWarningLabel = new javax.swing.JLabel(); okButton = new javax.swing.JButton(); closeButton = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Andromeda Advanced Settings"); setMinimumSize(new java.awt.Dimension(400, 400)); backgroundPanel.setBackground(new java.awt.Color(230, 230, 230)); settingsPanel.setBackground(new java.awt.Color(230, 230, 230)); settingsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Search Settings")); settingsPanel.setPreferredSize(new java.awt.Dimension(518, 143)); settingsScrollPane.setBorder(null); settingsInnerPanel.setBackground(new java.awt.Color(230, 230, 230)); peptideLengthNoEnzymeLabel.setText("Peptide Length No Enzyme"); minPepLengthNoEnzymeTxt.setHorizontalAlignment(javax.swing.JTextField.CENTER); minPepLengthNoEnzymeTxt.setText("8"); minPepLengthNoEnzymeTxt.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { minPepLengthNoEnzymeTxtKeyReleased(evt); } }); peptideLengthNoEnzymeDividerLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); peptideLengthNoEnzymeDividerLabel.setText("-"); maxPepLengthNoEnzymeTxt.setHorizontalAlignment(javax.swing.JTextField.CENTER); maxPepLengthNoEnzymeTxt.setText("30"); maxPepLengthNoEnzymeTxt.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { maxPepLengthNoEnzymeTxtKeyReleased(evt); } }); maxPeptideMassLabel.setText("Max Peptide Mass"); maxPeptideMassTxt.setHorizontalAlignment(javax.swing.JTextField.CENTER); maxPeptideMassTxt.setText("4600"); maxPeptideMassTxt.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { maxPeptideMassTxtKeyReleased(evt); } }); numberMatchesLabel.setText("Number of Spectrum Matches"); numberMatchesTxt.setHorizontalAlignment(javax.swing.JTextField.CENTER); numberMatchesTxt.setText("10"); numberMatchesTxt.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { numberMatchesTxtKeyReleased(evt); } }); fragMethodLabel.setText("Fragmentation Method"); fragMethodCmb.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "CID", "HCD", "ETD" })); ammoniaLossLabel.setText("Ammonia Loss"); ammoniaLossCmb.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Yes", "No" })); maxPtmsLabel.setText("Max Variable PTMs"); maxPtmsTxt.setHorizontalAlignment(javax.swing.JTextField.CENTER); maxPtmsTxt.setText("5"); maxPtmsTxt.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { maxPtmsTxtKeyReleased(evt); } }); empiricalCorrectionLabel.setText("Empirical Correction"); empiricalCorrectionCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Yes", "No" })); higherChargeLabel.setText("Higher Charge"); higherChargeCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Yes", "No" })); topPeaksLabel.setText("Top Peaks"); topPeaksTxt.setHorizontalAlignment(javax.swing.JTextField.CENTER); topPeaksTxt.setText("8"); topPeaksTxt.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { topPeaksTxtKeyReleased(evt); } }); neutralLossesLabel.setText("Sequence Dependent Neutral Loss"); neutralLossesCmb.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Yes", "No" })); fragmentAllLabel.setText("Fragment All"); fragmentAllCmb.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Yes", "No" })); maxCombinationsLabel.setText("Max Combinations"); maxCombinationsTxt.setHorizontalAlignment(javax.swing.JTextField.CENTER); maxCombinationsTxt.setText("250"); maxCombinationsTxt.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { maxCombinationsTxtKeyReleased(evt); } }); topPeaksWindowLabel.setText("Top Peaks Windows"); topPeaksWindowTxt.setHorizontalAlignment(javax.swing.JTextField.CENTER); topPeaksWindowTxt.setText("100"); topPeaksWindowTxt.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { topPeaksWindowTxtKeyReleased(evt); } }); waterLossLabel.setText("Water Loss"); waterLossCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Yes", "No" })); equalILLabel.setText("Equal I and L"); equalILCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Yes", "No" })); equalILCombo.setSelectedIndex(1); decoyModeLabel.setText("Decoy Mode"); decoyModeCmb.setModel(new DefaultComboBoxModel(AndromedaDecoyMode.values())); javax.swing.GroupLayout settingsInnerPanelLayout = new javax.swing.GroupLayout(settingsInnerPanel); settingsInnerPanel.setLayout(settingsInnerPanelLayout); settingsInnerPanelLayout.setHorizontalGroup( settingsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(settingsInnerPanelLayout.createSequentialGroup() .addComponent(peptideLengthNoEnzymeLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(21, 21, 21) .addComponent(minPepLengthNoEnzymeTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(peptideLengthNoEnzymeDividerLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(7, 7, 7) .addComponent(maxPepLengthNoEnzymeTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 84, Short.MAX_VALUE)) .addGroup(settingsInnerPanelLayout.createSequentialGroup() .addComponent(maxPeptideMassLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(21, 21, 21) .addComponent(maxPeptideMassTxt)) .addGroup(settingsInnerPanelLayout.createSequentialGroup() .addComponent(numberMatchesLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(21, 21, 21) .addComponent(numberMatchesTxt)) .addGroup(settingsInnerPanelLayout.createSequentialGroup() .addComponent(neutralLossesLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(21, 21, 21) .addComponent(neutralLossesCmb, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(settingsInnerPanelLayout.createSequentialGroup() .addComponent(ammoniaLossLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(21, 21, 21) .addComponent(ammoniaLossCmb, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(settingsInnerPanelLayout.createSequentialGroup() .addComponent(waterLossLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(21, 21, 21) .addComponent(waterLossCombo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, settingsInnerPanelLayout.createSequentialGroup() .addComponent(equalILLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(21, 21, 21) .addComponent(equalILCombo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(settingsInnerPanelLayout.createSequentialGroup() .addGroup(settingsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(maxPtmsLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(fragMethodLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(21, 21, 21) .addGroup(settingsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(fragMethodCmb, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(maxPtmsTxt))) .addGroup(settingsInnerPanelLayout.createSequentialGroup() .addGroup(settingsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(fragmentAllLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(empiricalCorrectionLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(higherChargeLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(21, 21, 21) .addGroup(settingsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(empiricalCorrectionCombo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(higherChargeCombo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(fragmentAllCmb, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(settingsInnerPanelLayout.createSequentialGroup() .addGroup(settingsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(topPeaksWindowLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(maxCombinationsLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(topPeaksLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(21, 21, 21) .addGroup(settingsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(topPeaksTxt) .addComponent(topPeaksWindowTxt) .addComponent(maxCombinationsTxt))) .addGroup(settingsInnerPanelLayout.createSequentialGroup() .addComponent(decoyModeLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(21, 21, 21) .addComponent(decoyModeCmb, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); settingsInnerPanelLayout.setVerticalGroup( settingsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(settingsInnerPanelLayout.createSequentialGroup() .addGroup(settingsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(minPepLengthNoEnzymeTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(maxPepLengthNoEnzymeTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(peptideLengthNoEnzymeDividerLabel) .addComponent(peptideLengthNoEnzymeLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(settingsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(maxPeptideMassTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(maxPeptideMassLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(settingsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(numberMatchesLabel) .addComponent(numberMatchesTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(settingsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(maxPtmsLabel) .addComponent(maxPtmsTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(settingsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(fragMethodLabel) .addComponent(fragMethodCmb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(settingsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(waterLossLabel) .addComponent(waterLossCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(settingsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ammoniaLossLabel) .addComponent(ammoniaLossCmb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(settingsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(neutralLossesLabel) .addComponent(neutralLossesCmb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(settingsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(equalILCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(equalILLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(settingsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(fragmentAllLabel) .addComponent(fragmentAllCmb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(settingsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(empiricalCorrectionLabel) .addComponent(empiricalCorrectionCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(settingsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(higherChargeLabel) .addComponent(higherChargeCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(settingsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(maxCombinationsLabel) .addComponent(maxCombinationsTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(settingsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(topPeaksLabel) .addComponent(topPeaksTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(settingsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(topPeaksWindowTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(topPeaksWindowLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(settingsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(decoyModeLabel) .addComponent(decoyModeCmb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); settingsScrollPane.setViewportView(settingsInnerPanel); javax.swing.GroupLayout settingsPanelLayout = new javax.swing.GroupLayout(settingsPanel); settingsPanel.setLayout(settingsPanelLayout); settingsPanelLayout.setHorizontalGroup( settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(settingsPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(settingsScrollPane) .addContainerGap()) ); settingsPanelLayout.setVerticalGroup( settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(settingsPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(settingsScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 540, Short.MAX_VALUE) .addContainerGap()) ); openDialogHelpJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/help.GIF"))); // NOI18N openDialogHelpJButton.setToolTipText("Help"); openDialogHelpJButton.setBorder(null); openDialogHelpJButton.setBorderPainted(false); openDialogHelpJButton.setContentAreaFilled(false); openDialogHelpJButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { openDialogHelpJButtonMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { openDialogHelpJButtonMouseExited(evt); } }); openDialogHelpJButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { openDialogHelpJButtonActionPerformed(evt); } }); advancedSettingsWarningLabel.setText("Click to open the Andromeda help page."); okButton.setText("OK"); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); closeButton.setText("Close"); closeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { closeButtonActionPerformed(evt); } }); javax.swing.GroupLayout backgroundPanelLayout = new javax.swing.GroupLayout(backgroundPanel); backgroundPanel.setLayout(backgroundPanelLayout); backgroundPanelLayout.setHorizontalGroup( backgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(backgroundPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(backgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(settingsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 481, Short.MAX_VALUE) .addGroup(backgroundPanelLayout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(openDialogHelpJButton) .addGap(18, 18, 18) .addComponent(advancedSettingsWarningLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 92, Short.MAX_VALUE) .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(closeButton))) .addContainerGap()) ); backgroundPanelLayout.setVerticalGroup( backgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(backgroundPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(settingsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 585, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(backgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(openDialogHelpJButton) .addComponent(advancedSettingsWarningLabel) .addComponent(okButton) .addComponent(closeButton)) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(backgroundPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(backgroundPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents /** * Close the dialog without saving the settings. * * @param evt */ private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeButtonActionPerformed cancelled = true; dispose(); }//GEN-LAST:event_closeButtonActionPerformed /** * Save the settings and then close the dialog. * * @param evt */ private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed if (validateInput(true)) { dispose(); } }//GEN-LAST:event_okButtonActionPerformed /** * Change the cursor to a hand cursor. * * @param evt */ private void openDialogHelpJButtonMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_openDialogHelpJButtonMouseEntered setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); }//GEN-LAST:event_openDialogHelpJButtonMouseEntered /** * Change the cursor back to the default cursor. * * @param evt */ private void openDialogHelpJButtonMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_openDialogHelpJButtonMouseExited setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }//GEN-LAST:event_openDialogHelpJButtonMouseExited /** * Open the Andromeda help page. * * @param evt */ private void openDialogHelpJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openDialogHelpJButtonActionPerformed setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); BareBonesBrowserLaunch.openURL("http://coxdocs.org/doku.php?id=maxquant:andromeda:start"); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }//GEN-LAST:event_openDialogHelpJButtonActionPerformed /** * Validate the input. * * @param evt */ private void topPeaksWindowTxtKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_topPeaksWindowTxtKeyReleased validateInput(false); }//GEN-LAST:event_topPeaksWindowTxtKeyReleased /** * Validate the input. * * @param evt */ private void maxPtmsTxtKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_maxPtmsTxtKeyReleased validateInput(false); }//GEN-LAST:event_maxPtmsTxtKeyReleased /** * Validate the input. * * @param evt */ private void minPepLengthNoEnzymeTxtKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_minPepLengthNoEnzymeTxtKeyReleased validateInput(false); }//GEN-LAST:event_minPepLengthNoEnzymeTxtKeyReleased /** * Validate the input. * * @param evt */ private void maxPepLengthNoEnzymeTxtKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_maxPepLengthNoEnzymeTxtKeyReleased validateInput(false); }//GEN-LAST:event_maxPepLengthNoEnzymeTxtKeyReleased /** * Validate the input. * * @param evt */ private void maxPeptideMassTxtKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_maxPeptideMassTxtKeyReleased validateInput(false); }//GEN-LAST:event_maxPeptideMassTxtKeyReleased /** * Validate the input. * * @param evt */ private void topPeaksTxtKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_topPeaksTxtKeyReleased validateInput(false); }//GEN-LAST:event_topPeaksTxtKeyReleased /** * Validate the input. * * @param evt */ private void maxCombinationsTxtKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_maxCombinationsTxtKeyReleased validateInput(false); }//GEN-LAST:event_maxCombinationsTxtKeyReleased /** * Validate the input. * * @param evt */ private void numberMatchesTxtKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_numberMatchesTxtKeyReleased validateInput(false); }//GEN-LAST:event_numberMatchesTxtKeyReleased /** * Inspects the parameter validity. * * @param showMessage if true an error messages are shown to the users * @return a boolean indicating if the parameters are valid */ public boolean validateInput(boolean showMessage) { boolean valid = true; valid = GuiUtilities.validateIntegerInput(this, peptideLengthNoEnzymeLabel, minPepLengthNoEnzymeTxt, "minimum peptide length", "Peptide Length Error", true, showMessage, valid); valid = GuiUtilities.validateIntegerInput(this, peptideLengthNoEnzymeLabel, maxPepLengthNoEnzymeTxt, "maximum peptide length", "Peptide Length Error", true, showMessage, valid); valid = GuiUtilities.validateDoubleInput(this, maxPeptideMassLabel, maxPeptideMassTxt, "maximum peptide mass", "Peptide Mass Error", true, showMessage, valid); valid = GuiUtilities.validateIntegerInput(this, numberMatchesLabel, numberMatchesTxt, "number of spectrum matches", "Number of Spectrum Matches Error", true, showMessage, valid); valid = GuiUtilities.validateIntegerInput(this, maxPtmsLabel, maxPtmsTxt, "maximum number of variable PTMs", "Variable PTMs Error", true, showMessage, valid); valid = GuiUtilities.validateIntegerInput(this, maxCombinationsLabel, maxCombinationsTxt, "maximum combinations", "Max Combinations Error", true, showMessage, valid); valid = GuiUtilities.validateIntegerInput(this, topPeaksLabel, topPeaksTxt, "top peaks", "Top Peaks Error", true, showMessage, valid); valid = GuiUtilities.validateIntegerInput(this, topPeaksWindowLabel, topPeaksWindowTxt, "top peaks window", "Top Peaks Window Error", true, showMessage, valid); // peptide length: the low value should be lower than the high value try { double lowValue = Double.parseDouble(minPepLengthNoEnzymeTxt.getText().trim()); double highValue = Double.parseDouble(maxPepLengthNoEnzymeTxt.getText().trim()); if (lowValue > highValue) { if (showMessage && valid) { JOptionPane.showMessageDialog(this, "The lower range value has to be smaller than the upper range value.", "Peptide Length Error", JOptionPane.WARNING_MESSAGE); } valid = false; peptideLengthNoEnzymeLabel.setForeground(Color.RED); peptideLengthNoEnzymeLabel.setToolTipText("Please select a valid range (upper <= higher)"); } } catch (NumberFormatException e) { // ignore, handled above } okButton.setEnabled(valid); return valid; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel advancedSettingsWarningLabel; private javax.swing.JComboBox ammoniaLossCmb; private javax.swing.JLabel ammoniaLossLabel; private javax.swing.JPanel backgroundPanel; private javax.swing.JButton closeButton; private javax.swing.JComboBox decoyModeCmb; private javax.swing.JLabel decoyModeLabel; private javax.swing.JComboBox empiricalCorrectionCombo; private javax.swing.JLabel empiricalCorrectionLabel; private javax.swing.JComboBox equalILCombo; private javax.swing.JLabel equalILLabel; private javax.swing.JComboBox fragMethodCmb; private javax.swing.JLabel fragMethodLabel; private javax.swing.JComboBox fragmentAllCmb; private javax.swing.JLabel fragmentAllLabel; private javax.swing.JComboBox higherChargeCombo; private javax.swing.JLabel higherChargeLabel; private javax.swing.JLabel maxCombinationsLabel; private javax.swing.JTextField maxCombinationsTxt; private javax.swing.JTextField maxPepLengthNoEnzymeTxt; private javax.swing.JLabel maxPeptideMassLabel; private javax.swing.JTextField maxPeptideMassTxt; private javax.swing.JLabel maxPtmsLabel; private javax.swing.JTextField maxPtmsTxt; private javax.swing.JTextField minPepLengthNoEnzymeTxt; private javax.swing.JComboBox neutralLossesCmb; private javax.swing.JLabel neutralLossesLabel; private javax.swing.JLabel numberMatchesLabel; private javax.swing.JTextField numberMatchesTxt; private javax.swing.JButton okButton; private javax.swing.JButton openDialogHelpJButton; private javax.swing.JLabel peptideLengthNoEnzymeDividerLabel; private javax.swing.JLabel peptideLengthNoEnzymeLabel; private javax.swing.JPanel settingsInnerPanel; private javax.swing.JPanel settingsPanel; private javax.swing.JScrollPane settingsScrollPane; private javax.swing.JLabel topPeaksLabel; private javax.swing.JTextField topPeaksTxt; private javax.swing.JLabel topPeaksWindowLabel; private javax.swing.JTextField topPeaksWindowTxt; private javax.swing.JComboBox waterLossCombo; private javax.swing.JLabel waterLossLabel; // End of variables declaration//GEN-END:variables }
apache-2.0
haikuowuya/android_system_code
src/javax/print/attribute/HashAttributeSet.java
19011
/* * Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javax.print.attribute; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.HashMap; /** * Class HashAttributeSet provides an <code>AttributeSet</code> * implementation with characteristics of a hash map. * <P> * * @author Alan Kaminsky */ public class HashAttributeSet implements AttributeSet, Serializable { private static final long serialVersionUID = 5311560590283707917L; /** * The interface of which all members of this attribute set must be an * instance. It is assumed to be interface {@link Attribute Attribute} * or a subinterface thereof. * @serial */ private Class myInterface; /* * A HashMap used by the implementation. * The serialised form doesn't include this instance variable. */ private transient HashMap attrMap = new HashMap(); /** * Write the instance to a stream (ie serialize the object) * * @serialData * The serialized form of an attribute set explicitly writes the * number of attributes in the set, and each of the attributes. * This does not guarantee equality of serialized forms since * the order in which the attributes are written is not defined. */ private void writeObject(ObjectOutputStream s) throws IOException { s.defaultWriteObject(); Attribute [] attrs = toArray(); s.writeInt(attrs.length); for (int i = 0; i < attrs.length; i++) { s.writeObject(attrs[i]); } } /** * Reconstitute an instance from a stream that is, deserialize it). */ private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException { s.defaultReadObject(); attrMap = new HashMap(); int count = s.readInt(); Attribute attr; for (int i = 0; i < count; i++) { attr = (Attribute)s.readObject(); add(attr); } } /** * Construct a new, empty attribute set. */ public HashAttributeSet() { this(Attribute.class); } /** * Construct a new attribute set, * initially populated with the given attribute. * * @param attribute Attribute value to add to the set. * * @exception NullPointerException * (unchecked exception) Thrown if <CODE>attribute</CODE> is null. */ public HashAttributeSet(Attribute attribute) { this (attribute, Attribute.class); } /** * Construct a new attribute set, * initially populated with the values from the * given array. The new attribute set is populated by * adding the elements of <CODE>attributes</CODE> array to the set in * sequence, starting at index 0. Thus, later array elements may replace * earlier array elements if the array contains duplicate attribute * values or attribute categories. * * @param attributes Array of attribute values to add to the set. * If null, an empty attribute set is constructed. * * @exception NullPointerException * (unchecked exception) Thrown if any element of * <CODE>attributes</CODE> is null. */ public HashAttributeSet(Attribute[] attributes) { this (attributes, Attribute.class); } /** * Construct a new attribute set, * initially populated with the values from the given set. * * @param attributes Set of attributes from which to initialise this set. * If null, an empty attribute set is constructed. * */ public HashAttributeSet(AttributeSet attributes) { this (attributes, Attribute.class); } /** * Construct a new, empty attribute set, where the members of * the attribute set are restricted to the given interface. * * @param interfaceName The interface of which all members of this * attribute set must be an instance. It is assumed to * be interface {@link Attribute Attribute} or a * subinterface thereof. * @exception NullPointerException if interfaceName is null. */ protected HashAttributeSet(Class<?> interfaceName) { if (interfaceName == null) { throw new NullPointerException("null interface"); } myInterface = interfaceName; } /** * Construct a new attribute set, initially populated with the given * attribute, where the members of the attribute set are restricted to the * given interface. * * @param attribute Attribute value to add to the set. * @param interfaceName The interface of which all members of this * attribute set must be an instance. It is assumed to * be interface {@link Attribute Attribute} or a * subinterface thereof. * * @exception NullPointerException * (unchecked exception) Thrown if <CODE>attribute</CODE> is null. * @exception NullPointerException if interfaceName is null. * @exception ClassCastException * (unchecked exception) Thrown if <CODE>attribute</CODE> is not an * instance of <CODE>interfaceName</CODE>. */ protected HashAttributeSet(Attribute attribute, Class<?> interfaceName) { if (interfaceName == null) { throw new NullPointerException("null interface"); } myInterface = interfaceName; add (attribute); } /** * Construct a new attribute set, where the members of the attribute * set are restricted to the given interface. * The new attribute set is populated * by adding the elements of <CODE>attributes</CODE> array to the set in * sequence, starting at index 0. Thus, later array elements may replace * earlier array elements if the array contains duplicate attribute * values or attribute categories. * * @param attributes Array of attribute values to add to the set. If * null, an empty attribute set is constructed. * @param interfaceName The interface of which all members of this * attribute set must be an instance. It is assumed to * be interface {@link Attribute Attribute} or a * subinterface thereof. * * @exception NullPointerException * (unchecked exception) Thrown if any element of * <CODE>attributes</CODE> is null. * @exception NullPointerException if interfaceName is null. * @exception ClassCastException * (unchecked exception) Thrown if any element of * <CODE>attributes</CODE> is not an instance of * <CODE>interfaceName</CODE>. */ protected HashAttributeSet(Attribute[] attributes, Class<?> interfaceName) { if (interfaceName == null) { throw new NullPointerException("null interface"); } myInterface = interfaceName; int n = attributes == null ? 0 : attributes.length; for (int i = 0; i < n; ++ i) { add (attributes[i]); } } /** * Construct a new attribute set, initially populated with the * values from the given set where the members of the attribute * set are restricted to the given interface. * * @param attributes set of attribute values to initialise the set. If * null, an empty attribute set is constructed. * @param interfaceName The interface of which all members of this * attribute set must be an instance. It is assumed to * be interface {@link Attribute Attribute} or a * subinterface thereof. * * @exception ClassCastException * (unchecked exception) Thrown if any element of * <CODE>attributes</CODE> is not an instance of * <CODE>interfaceName</CODE>. */ protected HashAttributeSet(AttributeSet attributes, Class<?> interfaceName) { myInterface = interfaceName; if (attributes != null) { Attribute[] attribArray = attributes.toArray(); int n = attribArray == null ? 0 : attribArray.length; for (int i = 0; i < n; ++ i) { add (attribArray[i]); } } } /** * Returns the attribute value which this attribute set contains in the * given attribute category. Returns <tt>null</tt> if this attribute set * does not contain any attribute value in the given attribute category. * * @param category Attribute category whose associated attribute value * is to be returned. It must be a * {@link java.lang.Class Class} * that implements interface {@link Attribute * Attribute}. * * @return The attribute value in the given attribute category contained * in this attribute set, or <tt>null</tt> if this attribute set * does not contain any attribute value in the given attribute * category. * * @throws NullPointerException * (unchecked exception) Thrown if the <CODE>category</CODE> is null. * @throws ClassCastException * (unchecked exception) Thrown if the <CODE>category</CODE> is not a * {@link java.lang.Class Class} that implements interface {@link * Attribute Attribute}. */ public Attribute get(Class<?> category) { return (Attribute) attrMap.get(AttributeSetUtilities. verifyAttributeCategory(category, Attribute.class)); } /** * Adds the specified attribute to this attribute set if it is not * already present, first removing any existing in the same * attribute category as the specified attribute value. * * @param attribute Attribute value to be added to this attribute set. * * @return <tt>true</tt> if this attribute set changed as a result of the * call, i.e., the given attribute value was not already a * member of this attribute set. * * @throws NullPointerException * (unchecked exception) Thrown if the <CODE>attribute</CODE> is null. * @throws UnmodifiableSetException * (unchecked exception) Thrown if this attribute set does not support * the <CODE>add()</CODE> operation. */ public boolean add(Attribute attribute) { Object oldAttribute = attrMap.put(attribute.getCategory(), AttributeSetUtilities. verifyAttributeValue(attribute, myInterface)); return (!attribute.equals(oldAttribute)); } /** * Removes any attribute for this category from this attribute set if * present. If <CODE>category</CODE> is null, then * <CODE>remove()</CODE> does nothing and returns <tt>false</tt>. * * @param category Attribute category to be removed from this * attribute set. * * @return <tt>true</tt> if this attribute set changed as a result of the * call, i.e., the given attribute category had been a member of * this attribute set. * * @throws UnmodifiableSetException * (unchecked exception) Thrown if this attribute set does not * support the <CODE>remove()</CODE> operation. */ public boolean remove(Class<?> category) { return category != null && AttributeSetUtilities. verifyAttributeCategory(category, Attribute.class) != null && attrMap.remove(category) != null; } /** * Removes the specified attribute from this attribute set if * present. If <CODE>attribute</CODE> is null, then * <CODE>remove()</CODE> does nothing and returns <tt>false</tt>. * * @param attribute Attribute value to be removed from this attribute set. * * @return <tt>true</tt> if this attribute set changed as a result of the * call, i.e., the given attribute value had been a member of * this attribute set. * * @throws UnmodifiableSetException * (unchecked exception) Thrown if this attribute set does not * support the <CODE>remove()</CODE> operation. */ public boolean remove(Attribute attribute) { return attribute != null && attrMap.remove(attribute.getCategory()) != null; } /** * Returns <tt>true</tt> if this attribute set contains an * attribute for the specified category. * * @param category whose presence in this attribute set is * to be tested. * * @return <tt>true</tt> if this attribute set contains an attribute * value for the specified category. */ public boolean containsKey(Class<?> category) { return category != null && AttributeSetUtilities. verifyAttributeCategory(category, Attribute.class) != null && attrMap.get(category) != null; } /** * Returns <tt>true</tt> if this attribute set contains the given * attribute. * * @param attribute value whose presence in this attribute set is * to be tested. * * @return <tt>true</tt> if this attribute set contains the given * attribute value. */ public boolean containsValue(Attribute attribute) { return attribute != null && attribute instanceof Attribute && attribute.equals(attrMap.get(((Attribute)attribute).getCategory())); } /** * Adds all of the elements in the specified set to this attribute. * The outcome is the same as if the * {@link #add(Attribute) <CODE>add(Attribute)</CODE>} * operation had been applied to this attribute set successively with * each element from the specified set. * The behavior of the <CODE>addAll(AttributeSet)</CODE> * operation is unspecified if the specified set is modified while * the operation is in progress. * <P> * If the <CODE>addAll(AttributeSet)</CODE> operation throws an exception, * the effect on this attribute set's state is implementation dependent; * elements from the specified set before the point of the exception may * or may not have been added to this attribute set. * * @param attributes whose elements are to be added to this attribute * set. * * @return <tt>true</tt> if this attribute set changed as a result of the * call. * * @throws UnmodifiableSetException * (Unchecked exception) Thrown if this attribute set does not * support the <tt>addAll(AttributeSet)</tt> method. * @throws NullPointerException * (Unchecked exception) Thrown if some element in the specified * set is null, or the set is null. * * @see #add(Attribute) */ public boolean addAll(AttributeSet attributes) { Attribute []attrs = attributes.toArray(); boolean result = false; for (int i=0; i<attrs.length; i++) { Attribute newValue = AttributeSetUtilities.verifyAttributeValue(attrs[i], myInterface); Object oldValue = attrMap.put(newValue.getCategory(), newValue); result = (! newValue.equals(oldValue)) || result; } return result; } /** * Returns the number of attributes in this attribute set. If this * attribute set contains more than <tt>Integer.MAX_VALUE</tt> elements, * returns <tt>Integer.MAX_VALUE</tt>. * * @return The number of attributes in this attribute set. */ public int size() { return attrMap.size(); } /** * * @return the Attributes contained in this set as an array, zero length * if the AttributeSet is empty. */ public Attribute[] toArray() { Attribute []attrs = new Attribute[size()]; attrMap.values().toArray(attrs); return attrs; } /** * Removes all attributes from this attribute set. * * @throws UnmodifiableSetException * (unchecked exception) Thrown if this attribute set does not support * the <CODE>clear()</CODE> operation. */ public void clear() { attrMap.clear(); } /** * Returns true if this attribute set contains no attributes. * * @return true if this attribute set contains no attributes. */ public boolean isEmpty() { return attrMap.isEmpty(); } /** * Compares the specified object with this attribute set for equality. * Returns <tt>true</tt> if the given object is also an attribute set and * the two attribute sets contain the same attribute category-attribute * value mappings. This ensures that the * <tt>equals()</tt> method works properly across different * implementations of the AttributeSet interface. * * @param object to be compared for equality with this attribute set. * * @return <tt>true</tt> if the specified object is equal to this * attribute set. */ public boolean equals(Object object) { if (object == null || !(object instanceof AttributeSet)) { return false; } AttributeSet aset = (AttributeSet)object; if (aset.size() != size()) { return false; } Attribute[] attrs = toArray(); for (int i=0;i<attrs.length; i++) { if (!aset.containsValue(attrs[i])) { return false; } } return true; } /** * Returns the hash code value for this attribute set. * The hash code of an attribute set is defined to be the sum * of the hash codes of each entry in the AttributeSet. * This ensures that <tt>t1.equals(t2)</tt> implies that * <tt>t1.hashCode()==t2.hashCode()</tt> for any two attribute sets * <tt>t1</tt> and <tt>t2</tt>, as required by the general contract of * {@link java.lang.Object#hashCode() <CODE>Object.hashCode()</CODE>}. * * @return The hash code value for this attribute set. */ public int hashCode() { int hcode = 0; Attribute[] attrs = toArray(); for (int i=0;i<attrs.length; i++) { hcode += attrs[i].hashCode(); } return hcode; } }
apache-2.0
camunda/camunda-bpm-assert
core/src/test/java/org/camunda/bpm/engine/test/assertions/cmmn/MilestoneAssertIsTerminatedTest.java
2539
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.camunda.bpm.engine.test.assertions.cmmn; import static org.camunda.bpm.engine.test.assertions.cmmn.CmmnAwareTests.assertThat; import static org.camunda.bpm.engine.test.assertions.cmmn.CmmnAwareTests.caseExecution; import static org.camunda.bpm.engine.test.assertions.cmmn.CmmnAwareTests.caseService; import static org.camunda.bpm.engine.test.assertions.cmmn.CmmnAwareTests.complete; import org.camunda.bpm.engine.runtime.CaseInstance; import org.camunda.bpm.engine.test.Deployment; import org.camunda.bpm.engine.test.ProcessEngineRule; import org.camunda.bpm.engine.test.assertions.helpers.Failure; import org.camunda.bpm.engine.test.assertions.helpers.ProcessAssertTestCase; import org.junit.Rule; import org.junit.Test; /** * @author Malte Soerensen (malte.soerensen@holisticon.de) */ @Deployment(resources = "cmmn/MilestoneAssertIsTerminatedTest.cmmn") public class MilestoneAssertIsTerminatedTest extends ProcessAssertTestCase { @Rule public ProcessEngineRule processEngineRule = new ProcessEngineRule(); @Test public void test_IsTerminated_Success() { CaseInstance caseInstance = caseService().createCaseInstanceByKey("MilestoneAssertIsTerminatedTest"); MilestoneAssert milestoneAssert = assertThat(caseInstance).stage("Stage").milestone("Milestone"); complete(caseExecution("PI_TaskA", caseInstance)); milestoneAssert.isTerminated(); } @Test public void test_IsTerminated_Fail() { final CaseInstance caseInstance = caseService().createCaseInstanceByKey("MilestoneAssertIsTerminatedTest"); expect(new Failure() { @Override public void when() { assertThat(caseInstance).stage("Stage").milestone("Milestone").isTerminated(); } }); } }
apache-2.0
hammyau/ODFExplorer
mvn/src/main/java/net/amham/odfe/json/StyleJSONReader.java
6122
package net.amham.odfe.json; import java.io.File; import java.io.IOException; import javax.swing.JFileChooser; import javax.swing.filechooser.FileNameExtensionFilter; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.JsonParser; import org.codehaus.jackson.JsonToken; import org.codehaus.jackson.map.JsonMappingException; public class StyleJSONReader { private static final String USER_DIR = "user.dir"; private static File file; private static Integer propDiffCount = 0; /** * @param args */ public static void main(String[] args) { try { JsonFactory jfactory = new JsonFactory(); JFileChooser fc = new JFileChooser(); fc.setDialogTitle("Choose JSON file(s)"); FileNameExtensionFilter ff = new FileNameExtensionFilter("JSON Files", "json"); fc.setFileFilter(ff); fc.setCurrentDirectory(new File(System.getProperty(USER_DIR))); fc.setMultiSelectionEnabled(true); int retval = fc.showOpenDialog(fc); while (retval == JFileChooser.APPROVE_OPTION) { //can make the file chooser select multiple files // can they be in different directories? file = fc.getSelectedFile(); retval = fc.showOpenDialog(fc); } /*** read from file ***/ JsonParser jParser = jfactory.createJsonParser(file); // loop until token equal to "}" while (jParser.nextToken() != JsonToken.END_OBJECT) { String fieldname = jParser.getCurrentName(); if ("name".equals(fieldname)) { // current token is "name", // move to next, which is "name"'s value jParser.nextToken(); // System.out.println(jParser.getText()); } if ("children".equals(fieldname)) { jParser.nextToken(); // current token is "[", move next // messages is array, loop until token equal to "]" while (jParser.nextToken() != JsonToken.END_ARRAY) { String fieldname1 = jParser.getCurrentName(); if ("name".equals(fieldname1)) { // current token is "name", // move to next, which is "name"'s value jParser.nextToken(); String val = jParser.getText(); System.out.println(val); // display mkyong if(val.equals("families")) { // System.out.println("Yippee"); findDiffChildren(jParser); } if(val.equals("sources")) { // System.out.println("Skipping sources"); findSkipChildren(jParser); } } } } } System.out.println("Property Diffs found " + propDiffCount); jParser.close(); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * @param jParser * @param fieldname1 * @throws IOException * @throws JsonParseException */ public static void findSkipChildren(JsonParser jParser) throws IOException, JsonParseException { while (jParser.nextToken() != JsonToken.END_OBJECT) { String fieldname = jParser.getCurrentName(); if (fieldname != null && fieldname.contains("children")) { // System.out.println("Skipping children"); jParser.nextToken(); // current token is "[", move next jParser.skipChildren(); } } } public static void findDiffChildren(JsonParser jParser) throws IOException, JsonParseException { while (jParser.nextToken() != JsonToken.END_OBJECT) { String fieldname = jParser.getCurrentName(); if (fieldname != null && fieldname.contains("children")) { // System.out.println("found children"); jParser.nextToken(); // current token is "[", move next findDiffNode(jParser); } } } private static void findDiffNode(JsonParser jParser) throws JsonParseException, IOException { String nodeName = null; while (jParser.nextToken() != JsonToken.END_ARRAY) { String fieldname1 = jParser.getCurrentName(); if ("name".equals(fieldname1)) { jParser.nextToken(); nodeName = jParser.getText(); } if ("hits".equals(fieldname1)) { jParser.nextToken(); //the [ jParser.skipChildren(); System.out.println("Node " + nodeName + " hit"); } if ("diff".equals(fieldname1)) { jParser.nextToken(); String diff = jParser.getText(); if(!"SameStyle".equals(diff)) { System.out.println("found diff node " + nodeName + ":" + diff); if(nodeName.contains("Properties")) { findDiffProperties(jParser); } else { findDiffChildren(jParser); } } else { // System.out.println("Skipping node " + nodeName); findSkipChildren(jParser); } } if (fieldname1 != null && fieldname1.contains("children")) { // System.out.println("Skipping children of " + nodeName); jParser.nextToken(); // current token is "[", move next jParser.skipChildren(); } } } private static void findDiffProperties(JsonParser jParser) throws JsonParseException, IOException { while (jParser.nextToken() != JsonToken.END_OBJECT) { String fieldname = jParser.getCurrentName(); if (fieldname != null && fieldname.contains("children")) { // System.out.println("iterating children"); jParser.nextToken(); // current token is "[", move next findDiffProp(jParser); } } } private static void findDiffProp(JsonParser jParser) throws JsonParseException, IOException { String propName = null; String val1 = null; String val2 = null; while (jParser.nextToken() != JsonToken.END_ARRAY) { String fieldname = jParser.getCurrentName(); if ("name".equals(fieldname)) { // System.out.println("iterating children"); jParser.nextToken(); propName = jParser.getText(); } if ("value1".equals(fieldname)) { // System.out.println("Diff property"); jParser.nextToken(); val1 = jParser.getText(); } if ("value2".equals(fieldname)) { jParser.nextToken(); val2 = jParser.getText(); System.out.println("Diff " + propName + " " + val1 + " -> " + val2); propDiffCount++; } } } }
apache-2.0
vladmihalcea/high-performance-java-persistence
core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/identifier/HiloPooledDefaultSwitchTest.java
1409
package com.vladmihalcea.book.hpjp.hibernate.identifier; import com.vladmihalcea.book.hpjp.util.exception.ExceptionUtil; import org.hibernate.cfg.AvailableSettings; import org.junit.Test; import java.util.Properties; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; public class HiloPooledDefaultSwitchTest { private HiloIdentifierTest hiloIdentifierTest = new HiloIdentifierTest(); private PooledSequenceIdentifierTest pooledIdentifierTest = new PooledSequenceIdentifierTest() { @Override protected void additionalProperties(Properties properties) { properties.setProperty(AvailableSettings.HBM2DDL_AUTO, "none"); } }; @Test public void testDefaultSwitch() { try { hiloIdentifierTest.init(); hiloIdentifierTest.testHiloIdentifierGenerator(); try { pooledIdentifierTest.init(); fail("Should have thrown MappingException"); } catch (Exception e) { assertEquals( "The increment size of the [post_sequence] sequence is set to [3] in the entity mapping while the associated database sequence increment size is [1].", ExceptionUtil.rootCause(e).getMessage() ); } } finally { hiloIdentifierTest.destroy(); } } }
apache-2.0
DSolyom/AndroidDSFramework
FrameworkV4/frameworkv4/src/main/java/ds/framework/v4/app/DSFragmentInterface.java
663
package ds.framework.v4.app; import android.content.Context; import android.view.View; public interface DSFragmentInterface { String getFragmentId(); void setFragmentId(String name); Context getContext(); void setActive(boolean active); boolean isActive(); View getRootView(); int getDataState(); void loadData(boolean subfragmentsToo); void display(boolean subfragmentsToo); void invalidateData(boolean subfragmentsToo); void invalidateDisplay(); void reset(); void attachSubFragmentsInner(); void onTransport(Object data); void onActivityResult(Object data); boolean onBackPressed(); boolean onMenuItemSelected(int itemId); }
apache-2.0
fangfan/ff
smart-jdbc-dbutils/src/main/java/org/wit/ff/jdbc/access/dbutils/DefaultDataAccessor.java
790
package org.wit.ff.jdbc.access.dbutils; import org.apache.commons.dbutils.DbUtils; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; /** * Created by F.Fang on 2015/3/31. * 默认以配置数据源的方式获取连接. * Version :2015/3/31 */ public class DefaultDataAccessor extends AbstractDataAccessor { private DataSource dataSource; protected Connection getConnection() throws SQLException{ return dataSource.getConnection(); } @Override protected void closeConn(Connection conn) { try { DbUtils.close(conn); } catch (SQLException e) { // do nothing! } } public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } }
apache-2.0
gdeignacio/fbit-digitalgov-libs
utils/src/main/java/org/fundaciobit/administraciodigital/utils/io/InputStreamDataSource.java
1444
/* * Copyright 2016 gdeignacio. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fundaciobit.administraciodigital.utils.io; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.activation.DataSource; /** * * @author gdeignacio */ public class InputStreamDataSource implements DataSource { private InputStream inputStream; public InputStreamDataSource(InputStream inputStream) { this.inputStream = inputStream; } @Override public InputStream getInputStream() throws IOException { return inputStream; } @Override public OutputStream getOutputStream() throws IOException { throw new UnsupportedOperationException("Not implemented"); } @Override public String getContentType() { return "*/*"; } @Override public String getName() { return "InputStreamDataSource"; } }
apache-2.0
jmluengo/fused-sensor
fusedsensors/src/main/java/com/jmluengo/fusedsensors/FusedSensor.java
15093
/* * Copyright (c) 2012 Paul Lawitzki * Copyright (c) 2015 Jose Miguel Martinez Luengo : Wrapper code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jmluengo.fusedsensors; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import java.util.Timer; import java.util.TimerTask; /** * @author jmluengo */ public class FusedSensor implements SensorEventListener { // epsilon constant public static final float EPSILON = 0.000000001f; private static final float NS2S = 1.0f / 1000000000.0f; public static final int TIME_CONSTANT = 30; public static final float FILTER_COEFFICIENT = 0.98f; // singleton instance private static FusedSensor mInstance = new FusedSensor(); // fused sensor listener private FusedSensorEventListener mListener; // sensor manager private SensorManager mSensorManager; // angular speeds from gyro private float[] gyro = new float[3]; // rotation matrix from gyro data private float[] gyroMatrix = new float[9]; // orientation angles from gyro matrix private float[] gyroOrientation = new float[3]; // magnetic field vector private float[] magnet = new float[3]; // accelerometer vector private float[] accel = new float[3]; // orientation angles from accel and magnet private float[] accMagOrientation = new float[3]; // final orientation angles from sensor fusion private float[] fusedOrientation = new float[3]; // accelerometer and magnetometer based rotation matrix private float[] rotationMatrix = new float[9]; private float mTimestamp; private boolean mInitState = true; private Timer mFuseTimer; private FusedSensor() { } /** * Get the fused sensor instance * * @return fused sensor instance */ public static FusedSensor getDefault() { return mInstance; } /** * Start fused sensor listening * * @param context activity context * @param listener fused sensor event listener */ public void start(Context context, FusedSensorEventListener listener) { // keep listener fused sensor listener this.mListener = listener; // initialize gyro orientation matrix gyroOrientation[0] = 0.0f; gyroOrientation[1] = 0.0f; gyroOrientation[2] = 0.0f; // initialise gyroMatrix with identity matrix gyroMatrix[0] = 1.0f; gyroMatrix[1] = 0.0f; gyroMatrix[2] = 0.0f; gyroMatrix[3] = 0.0f; gyroMatrix[4] = 1.0f; gyroMatrix[5] = 0.0f; gyroMatrix[6] = 0.0f; gyroMatrix[7] = 0.0f; gyroMatrix[8] = 1.0f; // get sensor manager this.mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); // initialize sensor listeners this.mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_FASTEST); this.mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE), SensorManager.SENSOR_DELAY_FASTEST); this.mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_FASTEST); // Initialize fuse timer mFuseTimer = new Timer(); // wait for one second until gyroscope and magnetometer/accelerometer // data is initialised then scedule the complementary filter task mFuseTimer.scheduleAtFixedRate(new CalculateFusedOrientationTask(), 0, TIME_CONSTANT); } /** * Stop fused sensor listening */ public void stop() { // stop fused task mFuseTimer.cancel(); // unregister listener mSensorManager.unregisterListener(this); // destroy objects mListener = null; mSensorManager = null; mFuseTimer = null; } @Override public void onSensorChanged(SensorEvent event) { switch (event.sensor.getType()) { case Sensor.TYPE_ACCELEROMETER: // copy new accelerometer data into accel array // then calculate new orientation System.arraycopy(event.values, 0, accel, 0, 3); calculateAccMagOrientation(); break; case Sensor.TYPE_GYROSCOPE: // process gyro data gyroFunction(event); break; case Sensor.TYPE_MAGNETIC_FIELD: // copy new magnetometer data into magnet array System.arraycopy(event.values, 0, magnet, 0, 3); break; } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // Nothing to do } public void calculateAccMagOrientation() { if (SensorManager.getRotationMatrix(rotationMatrix, null, accel, magnet)) { SensorManager.getOrientation(rotationMatrix, accMagOrientation); } } // This function is borrowed from the Android reference // at http://developer.android.com/reference/android/hardware/SensorEvent.html#values // It calculates a rotation vector from the gyroscope angular speed values. private void getRotationVectorFromGyro(float[] gyroValues, float[] deltaRotationVector, float timeFactor) { float[] normValues = new float[3]; // Calculate the angular speed of the sample float omegaMagnitude = (float) Math.sqrt(gyroValues[0] * gyroValues[0] + gyroValues[1] * gyroValues[1] + gyroValues[2] * gyroValues[2]); // Normalize the rotation vector if it's big enough to get the axis if (omegaMagnitude > EPSILON) { normValues[0] = gyroValues[0] / omegaMagnitude; normValues[1] = gyroValues[1] / omegaMagnitude; normValues[2] = gyroValues[2] / omegaMagnitude; } // Integrate around this axis with the angular speed by the timestep // in order to get a delta rotation from this sample over the timestep // We will convert this axis-angle representation of the delta rotation // into a quaternion before turning it into the rotation matrix. float thetaOverTwo = omegaMagnitude * timeFactor; float sinThetaOverTwo = (float) Math.sin(thetaOverTwo); float cosThetaOverTwo = (float) Math.cos(thetaOverTwo); deltaRotationVector[0] = sinThetaOverTwo * normValues[0]; deltaRotationVector[1] = sinThetaOverTwo * normValues[1]; deltaRotationVector[2] = sinThetaOverTwo * normValues[2]; deltaRotationVector[3] = cosThetaOverTwo; } // This function performs the integration of the gyroscope data. // It writes the gyroscope based orientation into gyroOrientation. public void gyroFunction(SensorEvent event) { // don't start until first accelerometer/magnetometer orientation has been acquired if (accMagOrientation == null) return; // initialisation of the gyroscope based rotation matrix if (mInitState) { float[] initMatrix = getRotationMatrixFromOrientation(accMagOrientation); float[] test = new float[3]; SensorManager.getOrientation(initMatrix, test); gyroMatrix = matrixMultiplication(gyroMatrix, initMatrix); mInitState = false; } // copy the new gyro values into the gyro array // convert the raw gyro data into a rotation vector float[] deltaVector = new float[4]; if (mTimestamp != 0) { final float dT = (event.timestamp - mTimestamp) * NS2S; System.arraycopy(event.values, 0, gyro, 0, 3); getRotationVectorFromGyro(gyro, deltaVector, dT / 2.0f); } // measurement done, save current time for next interval mTimestamp = event.timestamp; // convert rotation vector into rotation matrix float[] deltaMatrix = new float[9]; SensorManager.getRotationMatrixFromVector(deltaMatrix, deltaVector); // apply the new rotation interval on the gyroscope based rotation matrix gyroMatrix = matrixMultiplication(gyroMatrix, deltaMatrix); // get the gyroscope based orientation from the rotation matrix SensorManager.getOrientation(gyroMatrix, gyroOrientation); } private float[] getRotationMatrixFromOrientation(float[] o) { float[] xM = new float[9]; float[] yM = new float[9]; float[] zM = new float[9]; float sinX = (float) Math.sin(o[1]); float cosX = (float) Math.cos(o[1]); float sinY = (float) Math.sin(o[2]); float cosY = (float) Math.cos(o[2]); float sinZ = (float) Math.sin(o[0]); float cosZ = (float) Math.cos(o[0]); // rotation about x-axis (pitch) xM[0] = 1.0f; xM[1] = 0.0f; xM[2] = 0.0f; xM[3] = 0.0f; xM[4] = cosX; xM[5] = sinX; xM[6] = 0.0f; xM[7] = -sinX; xM[8] = cosX; // rotation about y-axis (roll) yM[0] = cosY; yM[1] = 0.0f; yM[2] = sinY; yM[3] = 0.0f; yM[4] = 1.0f; yM[5] = 0.0f; yM[6] = -sinY; yM[7] = 0.0f; yM[8] = cosY; // rotation about z-axis (azimuth) zM[0] = cosZ; zM[1] = sinZ; zM[2] = 0.0f; zM[3] = -sinZ; zM[4] = cosZ; zM[5] = 0.0f; zM[6] = 0.0f; zM[7] = 0.0f; zM[8] = 1.0f; // rotation order is y, x, z (roll, pitch, azimuth) float[] resultMatrix = matrixMultiplication(xM, yM); resultMatrix = matrixMultiplication(zM, resultMatrix); return resultMatrix; } private float[] matrixMultiplication(float[] A, float[] B) { float[] result = new float[9]; result[0] = A[0] * B[0] + A[1] * B[3] + A[2] * B[6]; result[1] = A[0] * B[1] + A[1] * B[4] + A[2] * B[7]; result[2] = A[0] * B[2] + A[1] * B[5] + A[2] * B[8]; result[3] = A[3] * B[0] + A[4] * B[3] + A[5] * B[6]; result[4] = A[3] * B[1] + A[4] * B[4] + A[5] * B[7]; result[5] = A[3] * B[2] + A[4] * B[5] + A[5] * B[8]; result[6] = A[6] * B[0] + A[7] * B[3] + A[8] * B[6]; result[7] = A[6] * B[1] + A[7] * B[4] + A[8] * B[7]; result[8] = A[6] * B[2] + A[7] * B[5] + A[8] * B[8]; return result; } // This class is borrowed from Jose Collas AndroidSensorFunsion project // at https://github.com/goatstone/AndroidSensorFusion // It calculates the fused orientation matrix private class CalculateFusedOrientationTask extends TimerTask { public void run() { float oneMinusCoeff = 1.0f - FILTER_COEFFICIENT; /* * Fix for 179∞ <--> -179∞ transition problem: * Check whether one of the two orientation angles (gyro or accMag) is negative while the other one is positive. * If so, add 360∞ (2 * math.PI) to the negative value, perform the sensor fusion, and remove the 360∞ from the result * if it is greater than 180∞. This stabilizes the output in positive-to-negative-transition cases. */ // azimuth if (gyroOrientation[0] < -0.5 * Math.PI && accMagOrientation[0] > 0.0) { fusedOrientation[0] = (float) (FILTER_COEFFICIENT * (gyroOrientation[0] + 2.0 * Math.PI) + oneMinusCoeff * accMagOrientation[0]); fusedOrientation[0] -= (fusedOrientation[0] > Math.PI) ? 2.0 * Math.PI : 0; } else if (accMagOrientation[0] < -0.5 * Math.PI && gyroOrientation[0] > 0.0) { fusedOrientation[0] = (float) (FILTER_COEFFICIENT * gyroOrientation[0] + oneMinusCoeff * (accMagOrientation[0] + 2.0 * Math.PI)); fusedOrientation[0] -= (fusedOrientation[0] > Math.PI) ? 2.0 * Math.PI : 0; } else { fusedOrientation[0] = FILTER_COEFFICIENT * gyroOrientation[0] + oneMinusCoeff * accMagOrientation[0]; } // pitch if (gyroOrientation[1] < -0.5 * Math.PI && accMagOrientation[1] > 0.0) { fusedOrientation[1] = (float) (FILTER_COEFFICIENT * (gyroOrientation[1] + 2.0 * Math.PI) + oneMinusCoeff * accMagOrientation[1]); fusedOrientation[1] -= (fusedOrientation[1] > Math.PI) ? 2.0 * Math.PI : 0; } else if (accMagOrientation[1] < -0.5 * Math.PI && gyroOrientation[1] > 0.0) { fusedOrientation[1] = (float) (FILTER_COEFFICIENT * gyroOrientation[1] + oneMinusCoeff * (accMagOrientation[1] + 2.0 * Math.PI)); fusedOrientation[1] -= (fusedOrientation[1] > Math.PI) ? 2.0 * Math.PI : 0; } else { fusedOrientation[1] = FILTER_COEFFICIENT * gyroOrientation[1] + oneMinusCoeff * accMagOrientation[1]; } // roll if (gyroOrientation[2] < -0.5 * Math.PI && accMagOrientation[2] > 0.0) { fusedOrientation[2] = (float) (FILTER_COEFFICIENT * (gyroOrientation[2] + 2.0 * Math.PI) + oneMinusCoeff * accMagOrientation[2]); fusedOrientation[2] -= (fusedOrientation[2] > Math.PI) ? 2.0 * Math.PI : 0; } else if (accMagOrientation[2] < -0.5 * Math.PI && gyroOrientation[2] > 0.0) { fusedOrientation[2] = (float) (FILTER_COEFFICIENT * gyroOrientation[2] + oneMinusCoeff * (accMagOrientation[2] + 2.0 * Math.PI)); fusedOrientation[2] -= (fusedOrientation[2] > Math.PI) ? 2.0 * Math.PI : 0; } else { fusedOrientation[2] = FILTER_COEFFICIENT * gyroOrientation[2] + oneMinusCoeff * accMagOrientation[2]; } // overwrite gyro matrix and orientation with fused orientation // to comensate gyro drift gyroMatrix = getRotationMatrixFromOrientation(fusedOrientation); System.arraycopy(fusedOrientation, 0, gyroOrientation, 0, 3); // Notify fused sensor update mListener.onFusedSensorUpdate(fusedOrientation[1], fusedOrientation[2], fusedOrientation[0]); } } }
apache-2.0
shs96c/buck
src/com/facebook/buck/util/concurrent/ResourcePool.java
11901
/* * Copyright 2016-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.util.concurrent; import com.facebook.buck.core.util.log.Logger; import com.facebook.buck.util.types.Either; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.AsyncFunction; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.SettableFuture; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import java.util.function.Supplier; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; /** * Allows multiple concurrently executing futures to share a constrained number of resources. * * <p>Resources are lazily created up till a fixed maximum. If more than max resources are requested * the associated 'requests' are queued up in the resourceRequests field. As soon as a resource is * returned it will be used to satisfy the first pending request, otherwise it is stored in the * parkedResources queue. * * <p>If the resourceSupplier throws a RuntimeException the Future associated with the failed * attempt to create the resource will contain the relevant exception. Any subsequent requests the * pool will get will attempt to create a new resource. * * <p>If the {@link ResourceUsageErrorPolicy#RECYCLE} error usage policy is specified then, in case * of errors when "using" a resource it is assumed to be defective, will be retired and a new * resource will be requested from the supplier. The Future associated with the failed attempt to * use the resource will contain the relevant exception. */ public class ResourcePool<R extends AutoCloseable> implements AutoCloseable { private static final Logger LOG = Logger.get(ResourcePool.class); private final int maxResources; private final ResourceUsageErrorPolicy resourceUsageErrorPolicy; @GuardedBy("this") private final Supplier<R> resourceSupplier; @GuardedBy("this") private final List<R> createdResources; @GuardedBy("this") private final Deque<R> parkedResources; @GuardedBy("this") private final Deque<SettableFuture<Void>> resourceRequests; private final AtomicBoolean closing; @GuardedBy("this") private @Nullable ListenableFuture<Void> shutdownFuture; @GuardedBy("this") private final Set<ListenableFuture<?>> pendingWork; /** * @param maxResources maximum number of resources to use concurrently. * @param resourceSupplier function used to create a new resource. It should never block, it may * be called more than maxResources times if processing resources throws exceptions. */ public ResourcePool( int maxResources, ResourceUsageErrorPolicy resourceUsageErrorPolicy, Supplier<R> resourceSupplier) { Preconditions.checkArgument(maxResources > 0); this.maxResources = maxResources; this.resourceUsageErrorPolicy = resourceUsageErrorPolicy; this.resourceSupplier = resourceSupplier; this.createdResources = new ArrayList<>(); this.parkedResources = new ArrayDeque<>(); this.resourceRequests = new ArrayDeque<>(); this.closing = new AtomicBoolean(false); this.shutdownFuture = null; this.pendingWork = new HashSet<>(); } public synchronized void callOnEachResource(Consumer<R> withResource) { Preconditions.checkState(!closing.get()); for (R resource : createdResources) { withResource.accept(resource); } } /** * @param executorService where to perform the resource processing. Should really be a "real" * executor (not a directExecutor). * @return a {@link ListenableFuture} containing the result of the processing. The future will be * cancelled if the {@link ResourcePool#close()} method is called. */ public synchronized <T> ListenableFuture<T> scheduleOperationWithResource( ThrowingFunction<R, T> withResource, ListeningExecutorService executorService) { Preconditions.checkState(!closing.get()); ListenableFuture<T> futureWork = Futures.transformAsync( initialSchedule(), new AsyncFunction<Void, T>() { @Override public ListenableFuture<T> apply(Void input) throws Exception { Either<R, ListenableFuture<Void>> resourceRequest = requestResource(); if (resourceRequest.isLeft()) { R resource = resourceRequest.getLeft(); boolean resourceIsDefunct = false; try { return Futures.immediateFuture(withResource.apply(resource)); } catch (Exception e) { resourceIsDefunct = (resourceUsageErrorPolicy == ResourceUsageErrorPolicy.RETIRE); throw e; } finally { returnResource(resource, resourceIsDefunct); } } else { return Futures.transformAsync(resourceRequest.getRight(), this, executorService); } } }, executorService); pendingWork.add(futureWork); futureWork.addListener( () -> { synchronized (ResourcePool.this) { pendingWork.remove(futureWork); } }, executorService); // If someone else calls cancel on `futureWork` it makes it impossible to wait for that future // to finish using the resource, which then makes shutdown code exit too early. return Futures.nonCancellationPropagating(futureWork); } private synchronized ListenableFuture<Void> initialSchedule() { // If we'll (potentially) be allowed to create a resource or there are some parked then we'll // take the chance and attempt to run immediately. if (allowedToCreateResource() || !parkedResources.isEmpty()) { return Futures.immediateFuture(null); } // All possible resources are currently occupied. Because we're in a synchronized block, even // if one becomes available immediately after this call returns it will simply make this future // runnable, so we'll be able to progress. return scheduleNewResourceRequest(); } private synchronized Either<R, ListenableFuture<Void>> requestResource() { Optional<R> resource = obtainResource(); if (resource.isPresent()) { return Either.ofLeft(resource.get()); } return Either.ofRight(scheduleNewResourceRequest()); } private synchronized ListenableFuture<Void> scheduleNewResourceRequest() { if (closing.get()) { return Futures.immediateCancelledFuture(); } SettableFuture<Void> resourceFuture = SettableFuture.create(); resourceRequests.add(resourceFuture); return resourceFuture; } private synchronized Optional<R> obtainResource() { if (closing.get()) { return Optional.empty(); } R resource = parkedResources.pollFirst(); if (resource != null) { return Optional.of(resource); } return createIfAllowed(); } private synchronized void returnResource(R resource, boolean resourceIsDefunct) { if (resourceIsDefunct) { createdResources.remove(resource); try { resource.close(); } catch (Exception e) { LOG.info(e, "Error shutting down a defunct resource."); } } else { parkedResources.add(resource); } scheduleNextRequest(); } private synchronized void scheduleNextRequest() { while (true) { SettableFuture<Void> nextRequest = resourceRequests.pollFirst(); // Queue empty. if (nextRequest == null) { return; } // A false return value means the future was failed/cancelled, so we ignore it. if (nextRequest.set(null)) { return; } } } private synchronized boolean allowedToCreateResource() { return !closing.get() && (createdResources.size() < maxResources); } private synchronized Optional<R> createIfAllowed() { if (!allowedToCreateResource()) { return Optional.empty(); } R resource = Preconditions.checkNotNull(resourceSupplier.get()); createdResources.add(resource); return Optional.of(resource); } @Nullable public synchronized ListenableFuture<Void> getShutdownFullyCompleteFuture() { Preconditions.checkState( closing.get(), "This method should not be called before the .close() method is called."); return Preconditions.checkNotNull(shutdownFuture); } @Override public synchronized void close() { Preconditions.checkState(!closing.get()); closing.set(true); // Unblock all waiting requests. for (SettableFuture<Void> request : resourceRequests) { request.set(null); } resourceRequests.clear(); // Any processing that is currently taking place will be allowed to complete (as it won't notice // `closing` is true. // Any scheduled (but not executing) resource requests should notice `closing` is true and // mark themselves as cancelled. // Therefore `closeFuture` should allow us to wait for any resources that are in use. ListenableFuture<List<Object>> closeFuture = Futures.successfulAsList(pendingWork); // As silly as it seems this is the only reliable way to make sure we run the shutdown code. // Reusing an external executor means we run the risk of it being shut down before the cleanup // future is ready to run (which causes it to never run). // Using a direct executor means we run the chance of executing shutdown synchronously (which // we try to avoid). ExecutorService executorService = MostExecutors.newSingleThreadExecutor("resource shutdown"); // It is possible that more requests for work are scheduled at this point, however they should // all early-out due to `closing` being set to true, so we don't really care about those. shutdownFuture = Futures.transformAsync( closeFuture, input -> { synchronized (ResourcePool.this) { if (parkedResources.size() != createdResources.size()) { LOG.error("Whoops! Some resource are still in use during shutdown."); } // Now that pending work is done we can close all resources. for (R resource : createdResources) { resource.close(); } if (!resourceRequests.isEmpty()) { LOG.error( "Error shutting down ResourcePool: " + "there should be no enqueued resource requests."); } } executorService.shutdown(); return Futures.immediateFuture(null); }, executorService); } /** Describes how to handle errors that take place during resource usage. */ public enum ResourceUsageErrorPolicy { RETIRE, RECYCLE } public interface ThrowingFunction<T, R> { R apply(T t) throws Exception; } }
apache-2.0
jatin9896/incubator-carbondata
core/src/main/java/org/apache/carbondata/core/datastore/block/AbstractIndex.java
4009
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.carbondata.core.datastore.block; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import org.apache.carbondata.core.cache.Cacheable; import org.apache.carbondata.core.datastore.DataRefNode; import org.apache.carbondata.core.metadata.blocklet.DataFileFooter; import org.apache.carbondata.core.mutate.DeleteDeltaVo; public abstract class AbstractIndex implements Cacheable { /** * vo class which will hold the RS information of the block */ protected SegmentProperties segmentProperties; /** * data block */ protected DataRefNode dataRefNode; /** * atomic integer to maintain the access count for a column access */ protected AtomicInteger accessCount = new AtomicInteger(); /** * Table block meta size. */ protected long memorySize; /** * last fetch delete deltaFile timestamp */ private long deleteDeltaTimestamp; /** * map of blockletidAndPageId to * deleted rows */ private Map<String, DeleteDeltaVo> deletedRowsMap; /** * @return the segmentProperties */ public SegmentProperties getSegmentProperties() { return segmentProperties; } /** * @return the dataBlock */ public DataRefNode getDataRefNode() { return dataRefNode; } @Override public long getFileTimeStamp() { return 0; } /** * Below method will be used to load the data block * * @param footerList footer list */ public abstract void buildIndex(List<DataFileFooter> footerList); /** * the method returns the access count * * @return */ @Override public int getAccessCount() { return accessCount.get(); } /** * The method returns table block size * * @return */ @Override public long getMemorySize() { return this.memorySize; } /** * The method is used to set the access count */ public void incrementAccessCount() { accessCount.incrementAndGet(); } /** * This method will release the objects and set default value for primitive types */ public void clear() { decrementAccessCount(); } /** * This method will decrement the access count for a column by 1 * whenever a column usage is complete */ private void decrementAccessCount() { if (accessCount.get() > 0) { accessCount.decrementAndGet(); } } /** * the method is used to set the memory size of the b-tree * @param memorySize */ public void setMemorySize(long memorySize) { this.memorySize = memorySize; } /** * @return latest deleted delta timestamp */ public long getDeleteDeltaTimestamp() { return deleteDeltaTimestamp; } /** * set the latest delete delta timestamp * @param deleteDeltaTimestamp */ public void setDeleteDeltaTimestamp(long deleteDeltaTimestamp) { this.deleteDeltaTimestamp = deleteDeltaTimestamp; } /** * @return the deleted record for block map */ public Map<String, DeleteDeltaVo> getDeletedRowsMap() { return deletedRowsMap; } /** * @param deletedRowsMap */ public void setDeletedRowsMap(Map<String, DeleteDeltaVo> deletedRowsMap) { this.deletedRowsMap = deletedRowsMap; } }
apache-2.0
ua-eas/ksd-kc5.2.1-rice2.3.6-ua
rice-middleware/sampleapp/src/main/java/edu/sampleu/travel/workflow/AccountAttribute.java
5406
/** * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.sampleu.travel.workflow; import edu.sampleu.travel.bo.TravelAccount; import org.kuali.rice.kew.api.identity.Id; import org.kuali.rice.kew.api.identity.PrincipalName; import org.kuali.rice.kew.api.rule.RoleName; import org.kuali.rice.kew.engine.RouteContext; import org.kuali.rice.kew.routeheader.DocumentContent; import org.kuali.rice.kew.rule.AbstractRoleAttribute; import org.kuali.rice.kew.rule.ResolvedQualifiedRole; import org.kuali.rice.krad.service.KRADServiceLocator; import org.kuali.rice.kns.workflow.WorkflowUtils; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.namespace.QName; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Resolves FO's using the accounts associated with the document XPath xpath = * KualiWorkflowUtils.getXPath(documentContent.getDocument()); List<String> qualifiers = new ArrayList<String>(); NodeList * accountNums = (NodeList)xstreamSafeEval(xpath, "//edu.sampleu.travel.workflow.bo.TravelAccount/number", * documentContent.getDocument(), XPathConstants.NODESET); for (int i = 0; i < accountNums.getLength(); i++) { Node accountNum = * accountNums.item(i); String accuntNumVal = accountNum.getNodeValue(); } */ public class AccountAttribute extends AbstractRoleAttribute { private static final RoleName FISCAL_OFFICER_ROLE = new RoleName(AccountAttribute.class.getName(), "FO", "Fiscal Officer"); private static final List<RoleName> ROLES; static { List<RoleName> tmp = new ArrayList<RoleName>(1); tmp.add(FISCAL_OFFICER_ROLE); ROLES = Collections.unmodifiableList(tmp); } public List<String> getQualifiedRoleNames(String roleName, DocumentContent documentContent) { List<String> qualifiedRoleNames = new ArrayList<String>(); XPath xpath = WorkflowUtils.getXPath(documentContent.getDocument()); // This xpath stream needs updating when the TravelAccount is being updated NodeList accountNums = (NodeList) xstreamSafeEval(xpath, "/documentContent/applicationContent/org.kuali.rice.krad.workflow.KualiDocumentXmlMaterializer/document/travelAccounts/vector/default/elementData/edu.sampleu.travel.bo.TravelAccount/number", documentContent.getDocument(), XPathConstants.NODESET); for (int i = 0; i < accountNums.getLength(); i++) { Node accountNum = accountNums.item(i); String accuntNumVal = accountNum.getTextContent(); qualifiedRoleNames.add(accuntNumVal); } return qualifiedRoleNames; } public List<RoleName> getRoleNames() { return ROLES; } public ResolvedQualifiedRole resolveQualifiedRole(RouteContext routeContext, String roleName, String qualifiedRole) { String accountNum = qualifiedRole; TravelAccount account = new TravelAccount(); account.setNumber(accountNum); account = (TravelAccount) KRADServiceLocator.getBusinessObjectService().retrieve(account); if (account == null) { throw new RuntimeException("Account " + accountNum + " does not exist!"); } ResolvedQualifiedRole qualRole = new ResolvedQualifiedRole(); qualRole.setAnnotation("Account " + accountNum + " FO"); qualRole.setQualifiedRoleLabel("Fiscal Officer Account " + accountNum); List<Id> ids = new ArrayList<Id>(); ids.add(new PrincipalName(account.getFiscalOfficer().getUserName())); qualRole.setRecipients(ids); return qualRole; } /** * This method will do a simple XPath.evaluate, while wrapping your xpathExpression with the xstreamSafe function. It assumes a * String result, and will return such. If an XPathExpressionException is thrown, this will be re-thrown within a * RuntimeException. * * @param xpath A correctly initialized XPath instance. * @param xpathExpression Your XPath Expression that needs to be wrapped in an xstreamSafe wrapper and run. * @param item The document contents you will be searching within. * @return The string value of the xpath.evaluate(). */ public static final Object xstreamSafeEval(XPath xpath, String xpathExpression, Object item, QName returnType) { String xstreamSafeXPath = new StringBuilder(WorkflowUtils.XSTREAM_SAFE_PREFIX).append(xpathExpression).append(WorkflowUtils.XSTREAM_SAFE_SUFFIX).toString(); try { return xpath.evaluate(xstreamSafeXPath, item, returnType); } catch (XPathExpressionException e) { throw new RuntimeException("XPathExpressionException occurred on xpath: " + xstreamSafeXPath, e); } } }
apache-2.0
daniel555costa/GGViario
ggviario/src/main/java/st/domain/ggviario/secret/items/ClientViewHolder.java
2910
package st.domain.ggviario.secret.items; import android.view.View; import android.widget.TextView; import st.domain.ggviario.secret.R; import st.domain.ggviario.secret.model.Client; import st.zudamue.support.android.adapter.ItemDataSet; import st.zudamue.support.android.adapter.ItemViewHolder; /** * * Created by dchost on 06/02/17. */ public class ClientViewHolder extends ItemViewHolder { private CreditsClientDataSet dataSet; private TextView tvClientAvatar; private TextView tvClientName; private TextView tvClientSubInformation; private TextView tvClientAvatarSecond; private ItemCallback onClickcallback; public ClientViewHolder setOnClickCallback(ItemCallback onClickCallback ){ this.onClickcallback = onClickCallback; return this; } public ClientViewHolder(View itemView) { super(itemView); this.tvClientAvatar = ( TextView ) this.itemView.findViewById( R.id.tv_client_avatar ); this.tvClientName = ( TextView ) this.itemView.findViewById( R.id.tv_client_name ); this.tvClientSubInformation = ( TextView ) this.itemView.findViewById( R.id.tv_client_info ); this.tvClientAvatarSecond = ( TextView ) this.itemView.findViewById( R.id.tv_client_avatar_second ); this.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { callback( onClickcallback ); } }); } @Override public void onBind(ItemDataSet dataSet, int currentAdapterPosition, int totalDataSet) { this.dataSet = ( CreditsClientDataSet ) dataSet; this.tvClientAvatar.setText( this.dataSet.client.getAvatar() ); this.tvClientName.setText( this.dataSet.client ); this.tvClientSubInformation.setText( this.dataSet.client.getSubInformation() ); this.tvClientAvatarSecond.setText( this.dataSet.getAvatarSecond() ); } public static CreditsClientDataSet newInstance ( Client client, int totalCredits, int totalCreditsPay ) { return new CreditsClientDataSet(client, totalCredits, totalCreditsPay); } public static class CreditsClientDataSet implements ItemDataSet { private final Client client; private final int totalCreditsPay; private final int totalCredits; private CreditsClientDataSet ( Client client, int totalCredits, int totalCreditsPay ) { this.client = client; this.totalCredits = totalCredits; this.totalCreditsPay = totalCreditsPay; } @Override public int getLayoutId() { return R.layout._client_item; } public CharSequence getAvatarSecond() { return String.valueOf( this.totalCredits - this.totalCreditsPay ); } public Client getClient() { return this.client; } } }
apache-2.0
pnoker/mybatisGenerator
src/main/java/org/mybatis/generator/api/FullyQualifiedTable.java
15098
/** * Copyright 2006-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mybatis.generator.api; import static org.mybatis.generator.internal.util.EqualsUtil.areEqual; import static org.mybatis.generator.internal.util.HashCodeUtil.SEED; import static org.mybatis.generator.internal.util.HashCodeUtil.hash; import static org.mybatis.generator.internal.util.JavaBeansUtil.getCamelCaseString; import static org.mybatis.generator.internal.util.StringUtility.composeFullyQualifiedTableName; import static org.mybatis.generator.internal.util.StringUtility.stringHasValue; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.mybatis.generator.config.Context; import org.mybatis.generator.config.DomainObjectRenamingRule; /** * The Class FullyQualifiedTable. * * @author Jeff Butler */ public class FullyQualifiedTable { private String introspectedCatalog; private String introspectedSchema; private String introspectedTableName; private String runtimeCatalog; private String runtimeSchema; private String runtimeTableName; private String domainObjectName; private String domainObjectSubPackage; private String alias; private boolean ignoreQualifiersAtRuntime; private String beginningDelimiter; private String endingDelimiter; private DomainObjectRenamingRule domainObjectRenamingRule; /** * This object is used to hold information related to the table itself, not the columns in the * table. * * @param introspectedCatalog * the actual catalog of the table as returned from DatabaseMetaData. This value * should only be set if the user configured a catalog. Otherwise the * DatabaseMetaData is reporting some database default that we don't want in the * generated code. * @param introspectedSchema * the actual schema of the table as returned from DatabaseMetaData. This value * should only be set if the user configured a schema. Otherwise the * DatabaseMetaData is reporting some database default that we don't want in the * generated code. * @param introspectedTableName * the actual table name as returned from DatabaseMetaData * @param domainObjectName * the configured domain object name for this table. If nothing is configured, we'll build the domain * object named based on the tableName or runtimeTableName. * @param alias * a configured alias for the table. This alias will be added to the table name in the SQL * @param ignoreQualifiersAtRuntime * if true, then the catalog and schema qualifiers will be ignored when composing fully qualified names * in the generated SQL. This is used, for example, when the user needs to specify a specific schema for * generating code but does not want the schema in the generated SQL * @param runtimeCatalog * this is used to "rename" the catalog in the generated SQL. This is useful, for example, when * generating code against one catalog that should run with a different catalog. * @param runtimeSchema * this is used to "rename" the schema in the generated SQL. This is useful, for example, when generating * code against one schema that should run with a different schema. * @param runtimeTableName * this is used to "rename" the table in the generated SQL. This is useful, for example, when generating * code to run with an Oracle synonym. The user would have to specify the actual table name and schema * for generation, but would want to use the synonym name in the generated SQL * @param delimitIdentifiers * if true, then the table identifiers will be delimited at runtime. The delimiter characters are * obtained from the Context. * @param domainObjectRenamingRule * If domainObjectName is not configured, we'll build the domain object named based on the tableName or runtimeTableName. * And then we use the domain object renameing rule to generate the final domain object name. * @param context * the context */ public FullyQualifiedTable(String introspectedCatalog, String introspectedSchema, String introspectedTableName, String domainObjectName, String alias, boolean ignoreQualifiersAtRuntime, String runtimeCatalog, String runtimeSchema, String runtimeTableName, boolean delimitIdentifiers, DomainObjectRenamingRule domainObjectRenamingRule, Context context) { super(); this.introspectedCatalog = introspectedCatalog; this.introspectedSchema = introspectedSchema; this.introspectedTableName = introspectedTableName; this.ignoreQualifiersAtRuntime = ignoreQualifiersAtRuntime; this.runtimeCatalog = runtimeCatalog; this.runtimeSchema = runtimeSchema; this.runtimeTableName = runtimeTableName; this.domainObjectRenamingRule = domainObjectRenamingRule; if (stringHasValue(domainObjectName)) { int index = domainObjectName.lastIndexOf('.'); if (index == -1) { this.domainObjectName = domainObjectName; } else { this.domainObjectName = domainObjectName.substring(index + 1); this.domainObjectSubPackage = domainObjectName.substring(0, index); } } if (alias == null) { this.alias = null; } else { this.alias = alias.trim(); } beginningDelimiter = delimitIdentifiers ? context .getBeginningDelimiter() : ""; //$NON-NLS-1$ endingDelimiter = delimitIdentifiers ? context.getEndingDelimiter() : ""; //$NON-NLS-1$ } /** * Gets the introspected catalog. * * @return the introspected catalog */ public String getIntrospectedCatalog() { return introspectedCatalog; } /** * Gets the introspected schema. * * @return the introspected schema */ public String getIntrospectedSchema() { return introspectedSchema; } /** * Gets the introspected table name. * * @return the introspected table name */ public String getIntrospectedTableName() { return introspectedTableName; } /** * Gets the fully qualified table name at runtime. * * @return the fully qualified table name at runtime */ public String getFullyQualifiedTableNameAtRuntime() { StringBuilder localCatalog = new StringBuilder(); if (!ignoreQualifiersAtRuntime) { if (stringHasValue(runtimeCatalog)) { localCatalog.append(runtimeCatalog); } else if (stringHasValue(introspectedCatalog)) { localCatalog.append(introspectedCatalog); } } if (localCatalog.length() > 0) { addDelimiters(localCatalog); } StringBuilder localSchema = new StringBuilder(); if (!ignoreQualifiersAtRuntime) { if (stringHasValue(runtimeSchema)) { localSchema.append(runtimeSchema); } else if (stringHasValue(introspectedSchema)) { localSchema.append(introspectedSchema); } } if (localSchema.length() > 0) { addDelimiters(localSchema); } StringBuilder localTableName = new StringBuilder(); if (stringHasValue(runtimeTableName)) { localTableName.append(runtimeTableName); } else { localTableName.append(introspectedTableName); } addDelimiters(localTableName); return composeFullyQualifiedTableName(localCatalog .toString(), localSchema.toString(), localTableName.toString(), '.'); } /** * Gets the aliased fully qualified table name at runtime. * * @return the aliased fully qualified table name at runtime */ public String getAliasedFullyQualifiedTableNameAtRuntime() { StringBuilder sb = new StringBuilder(); sb.append(getFullyQualifiedTableNameAtRuntime()); if (stringHasValue(alias)) { sb.append(' '); sb.append(alias); } return sb.toString(); } /** * Returns a string that is the fully qualified table name, with * underscores as the separator. * * @return the namespace */ public String getIbatis2SqlMapNamespace() { String localCatalog = stringHasValue(runtimeCatalog) ? runtimeCatalog : introspectedCatalog; String localSchema = stringHasValue(runtimeSchema) ? runtimeSchema : introspectedSchema; String localTable = stringHasValue(runtimeTableName) ? runtimeTableName : introspectedTableName; return composeFullyQualifiedTableName( ignoreQualifiersAtRuntime ? null : localCatalog, ignoreQualifiersAtRuntime ? null : localSchema, localTable, '_'); } /** * Gets the domain object name. * * @return the domain object name */ public String getDomainObjectName() { if (stringHasValue(domainObjectName)) { return domainObjectName; } String finalDomainObjectName; if (stringHasValue(runtimeTableName)) { finalDomainObjectName = getCamelCaseString(runtimeTableName, true); } else { finalDomainObjectName = getCamelCaseString(introspectedTableName, true); } if (domainObjectRenamingRule != null) { Pattern pattern = Pattern.compile(domainObjectRenamingRule.getSearchString()); String replaceString = domainObjectRenamingRule.getReplaceString(); replaceString = replaceString == null ? "" : replaceString; Matcher matcher = pattern.matcher(finalDomainObjectName); finalDomainObjectName = matcher.replaceAll(replaceString); } return finalDomainObjectName; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof FullyQualifiedTable)) { return false; } FullyQualifiedTable other = (FullyQualifiedTable) obj; return areEqual(this.introspectedTableName, other.introspectedTableName) && areEqual(this.introspectedCatalog, other.introspectedCatalog) && areEqual(this.introspectedSchema, other.introspectedSchema); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { int result = SEED; result = hash(result, introspectedTableName); result = hash(result, introspectedCatalog); result = hash(result, introspectedSchema); return result; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return composeFullyQualifiedTableName( introspectedCatalog, introspectedSchema, introspectedTableName, '.'); } /** * Gets the alias. * * @return the alias */ public String getAlias() { return alias; } /** * Calculates a Java package fragment based on the table catalog and schema. * If qualifiers are ignored, then this method will return an empty string. * * <p>This method is used for determining the sub package for Java client and * SQL map (XML) objects. It ignores any sub-package added to the * domain object name in the table configuration. * * @param isSubPackagesEnabled * the is sub packages enabled * @return the subpackage for this table */ public String getSubPackageForClientOrSqlMap(boolean isSubPackagesEnabled) { StringBuilder sb = new StringBuilder(); if (!ignoreQualifiersAtRuntime && isSubPackagesEnabled) { if (stringHasValue(runtimeCatalog)) { sb.append('.'); sb.append(runtimeCatalog.toLowerCase()); } else if (stringHasValue(introspectedCatalog)) { sb.append('.'); sb.append(introspectedCatalog.toLowerCase()); } if (stringHasValue(runtimeSchema)) { sb.append('.'); sb.append(runtimeSchema.toLowerCase()); } else if (stringHasValue(introspectedSchema)) { sb.append('.'); sb.append(introspectedSchema.toLowerCase()); } } // TODO - strip characters that are not valid in package names return sb.toString(); } /** * Calculates a Java package fragment based on the table catalog and schema. * If qualifiers are ignored, then this method will return an empty string. * * <p>This method is used for determining the sub package for Java model objects only. * It takes into account the possibility that a sub-package was added to the * domain object name in the table configuration. * * @param isSubPackagesEnabled * the is sub packages enabled * @return the subpackage for this table */ public String getSubPackageForModel(boolean isSubPackagesEnabled) { StringBuilder sb = new StringBuilder(); sb.append(getSubPackageForClientOrSqlMap(isSubPackagesEnabled)); if (stringHasValue(domainObjectSubPackage)) { sb.append('.'); sb.append(domainObjectSubPackage); } return sb.toString(); } /** * Adds the delimiters. * * @param sb * the sb */ private void addDelimiters(StringBuilder sb) { if (stringHasValue(beginningDelimiter)) { sb.insert(0, beginningDelimiter); } if (stringHasValue(endingDelimiter)) { sb.append(endingDelimiter); } } }
apache-2.0
pkarmstr/NYBC
solr-4.2.1/lucene/facet/src/test/org/apache/lucene/facet/FacetTestUtils.java
1489
package org.apache.lucene.facet; import org.apache.lucene.facet.search.FacetResult; import org.apache.lucene.facet.search.FacetResultNode; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class FacetTestUtils { public static String toSimpleString(FacetResult fr) { StringBuilder sb = new StringBuilder(); toSimpleString(0, sb, fr.getFacetResultNode(), ""); return sb.toString(); } private static void toSimpleString(int depth, StringBuilder sb, FacetResultNode node, String indent) { sb.append(indent + node.label.components[depth] + " (" + (int) node.value + ")\n"); for (FacetResultNode childNode : node.subResults) { toSimpleString(depth + 1, sb, childNode, indent + " "); } } }
apache-2.0
ckelsel/AndroidTraining
training/app/src/main/java/com/ckelsel/android/training/Drag/MoveImgActivity.java
3154
package com.ckelsel.android.training.Drag; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.ckelsel.android.training.R; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.app.Activity; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; public class MoveImgActivity extends Activity { ImageView iv; private int containerWidth; private int containerHeight; float lastX, lastY; RelativeLayout rl; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_move_img); rl = (RelativeLayout) findViewById(R.id.rl); iv = (ImageView) findViewById(R.id.iv); iv.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: lastX = event.getRawX(); lastY = event.getRawY(); return true; case MotionEvent.ACTION_MOVE: // 不要直接用getX和getY,这两个获取的数据已经是经过处理的,容易出现图片抖动的情况 float distanceX = lastX - event.getRawX(); float distanceY = lastY - event.getRawY(); float nextY = iv.getY() - distanceY; float nextX = iv.getX() - distanceX; // 不能移出屏幕 if (nextY < 0) { nextY = 0; } else if (nextY > containerHeight - iv.getHeight()) { nextY = containerHeight - iv.getHeight(); } if (nextX < 0) nextX = 0; else if (nextX > containerWidth - iv.getWidth()) nextX = containerWidth - iv.getWidth(); // 属性动画移动 ObjectAnimator y = ObjectAnimator.ofFloat(iv, "y", iv.getY(), nextY); ObjectAnimator x = ObjectAnimator.ofFloat(iv, "x", iv.getX(), nextX); AnimatorSet animatorSet = new AnimatorSet(); animatorSet.playTogether(x, y); animatorSet.setDuration(0); animatorSet.start(); lastX = event.getRawX(); lastY = event.getRawY(); } return false; } }); } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); // 这里来获取容器的宽和高 if (hasFocus) { containerHeight = rl.getHeight(); containerWidth = rl.getWidth(); } } }
apache-2.0
kingargyle/turmeric-bot
camel-core/src/test/java/org/apache/camel/processor/AOPAfterFinallyTest.java
2826
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.processor; import org.apache.camel.CamelExecutionException; import org.apache.camel.ContextTestSupport; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; /** * @version $Revision$ */ public class AOPAfterFinallyTest extends ContextTestSupport { public void testAOPAfterFinally() throws Exception { getMockEndpoint("mock:after").message(0).body().isEqualTo("Bye World"); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("Bye World"); String out = template.requestBody("direct:start", "Hello World", String.class); assertEquals("Bye World", out); assertMockEndpointsSatisfied(); } public void testAOPAfterFinallyWithException() throws Exception { getMockEndpoint("mock:after").message(0).body().isEqualTo("Kaboom the World"); try { template.requestBody("direct:start", "Kaboom", String.class); fail("Should have thrown an exception"); } catch (CamelExecutionException e) { assertIsInstanceOf(IllegalArgumentException.class, e.getCause()); assertEquals("Damn", e.getCause().getMessage()); } assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start") .aop().afterFinally("mock:after") .choice() .when(body().isEqualTo("Hello World")) .transform(constant("Bye World")) .otherwise() .transform(constant("Kaboom the World")) .throwException(new IllegalArgumentException("Damn")) .end() .to("mock:result"); } }; } }
apache-2.0
adamrduffy/trinidad-1.0.x
trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/renderkit/core/xhtml/table/TreeNodeColumnRenderer.java
9820
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.myfaces.trinidadinternal.renderkit.core.xhtml.table; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import javax.faces.component.NamingContainer; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import org.apache.myfaces.trinidad.component.UIXTreeTable; import org.apache.myfaces.trinidad.context.RenderingContext; import org.apache.myfaces.trinidad.model.RowKeySet; import org.apache.myfaces.trinidad.skin.Icon; import org.apache.myfaces.trinidadinternal.renderkit.core.xhtml.ColumnRenderer; import org.apache.myfaces.trinidadinternal.renderkit.core.xhtml.OutputUtils; import org.apache.myfaces.trinidadinternal.renderkit.core.xhtml.SkinSelectors; import org.apache.myfaces.trinidadinternal.renderkit.core.xhtml.XhtmlConstants; import org.apache.myfaces.trinidadinternal.renderkit.core.xhtml.XhtmlRenderer; public class TreeNodeColumnRenderer extends ColumnRenderer { @Override protected void renderKids(FacesContext context, RenderingContext arc, TableRenderingContext tContext, UIComponent column) throws IOException { TreeTableRenderingContext ttrc = (TreeTableRenderingContext) tContext; boolean isRTL = arc.isRightToLeft(); UIXTreeTable hGrid = ttrc.getUIXTreeTable(); final boolean disclosed; final String onclick; if (hGrid.isContainer()) { RowKeySet treeState = hGrid.getDisclosedRowKeys(); String jsVarName = ttrc.getJSVarName(); if (treeState.isContained()) { disclosed = true; onclick = TreeUtils.callJSExpandNode(hGrid, jsVarName, false); } else { disclosed = false; onclick = TreeUtils.callJSExpandNode(hGrid, jsVarName, true); } } else // not a row container { disclosed = false; onclick = null; } int focusPath = hGrid.getDepth(TreeUtils.getFocusRowKey(hGrid)); int depth = hGrid.getDepth() + 1 - focusPath; if (!ttrc.isRootNodeRendered()) { // decrease the depth by one if the root node is not rendered to avoid // unnecessary indentation --depth; } int spacerWidth = _getSpacerWidth(ttrc); ResponseWriter writer = context.getResponseWriter(); // In DOM // browsers we use margin-left, and have a floating div to displace the // arrow. See bug 2296869 for the reason why this approach is // preferred. writer.startElement("div", null); if (isRTL) { if (onclick != null) depth--; writer.writeAttribute(XhtmlConstants.STYLE_ATTRIBUTE, "margin-right:" + depth * spacerWidth + "px", null); } else writer.writeAttribute(XhtmlConstants.STYLE_ATTRIBUTE, "position:relative;top:0px;left:0px;margin-left:"+ depth*spacerWidth+"px", null); // check to see if this node is in expanded or collapsed state. if (onclick != null) { writer.startElement("a", null); _renderIconID(context, tContext); // Render the style class on the link, so that we can // disable the link's text decoration renderStyleClass(context, arc, SkinSelectors.AF_TREE_TABLE_EXPANSION_ICON_STYLE_CLASS); //HKuhn - don't render onclick in printable mode if (XhtmlRenderer.supportsScripting(arc)) { writer.writeAttribute("onclick", onclick, null); writer.writeURIAttribute("href", "#", null); } // Render the expand/collapse Icon _renderExpansionIcon(context, arc, disclosed, onclick); writer.endElement("a"); } _renderNodeIcon(context, arc, hGrid, disclosed, onclick != null); UIComponent nodeStampColumn = ttrc.getTreeNodeStamp(); // if in screen reader mode render the node depth from the root as well _renderNodeStampBasedOnAccessibilty(context, arc, ttrc, nodeStampColumn); writer.endElement("div"); } private int _getSpacerWidth(TreeTableRenderingContext ttrc) { return ttrc.getSpacerWidth(); } // Renders the unique id for the expand/collapse icon private void _renderIconID(FacesContext fc, TableRenderingContext tContext) throws IOException { // we need to render a unique ID for the expand/collapse link, so that // PPR can restore the focus correctly after a PPR request: String tableName = tContext.getTable().getClientId(fc); String id = tableName + NamingContainer.SEPARATOR_CHAR + _ICON_ID; fc.getResponseWriter().writeAttribute("id", id, null); } // Renders the expansion Icon private void _renderExpansionIcon( FacesContext context, RenderingContext arc, boolean disclosed, Object onclick) throws IOException { final String iconName; final String altTextKey; if (disclosed) { iconName = SkinSelectors.AF_TREE_TABLE_EXPANDED_ICON_NAME; altTextKey = (onclick == null) ? _DISABLED_COLLAPSE_TIP_KEY : _COLLAPSE_TIP_KEY; } else { iconName = SkinSelectors.AF_TREE_TABLE_COLLAPSED_ICON_NAME; altTextKey = _EXPAND_TIP_KEY; } Icon icon = arc.getIcon(iconName); if (icon != null) { Object altText = arc.getTranslatedString(altTextKey); OutputUtils.renderIcon(context, arc, icon, altText, null); } } private void _renderNodeIcon( FacesContext context, RenderingContext arc, UIXTreeTable ttr, boolean disclosed, boolean hasChildren ) throws IOException { Icon nodeIcon = getNodeIcon(arc, getNodeType(ttr), disclosed, hasChildren); if (nodeIcon != null) { OutputUtils.renderIcon(context, arc, nodeIcon, null, null); } } protected String getNodeType( UIXTreeTable ttr ) { String nodeType = null; Object rowData = ttr.getRowData(); Class rowClass = rowData.getClass(); Method method = null; try { method = rowClass.getMethod("getNodeType"); if (method != null && method.getReturnType().equals(String.class)) { nodeType = (String) method.invoke(rowData); } } catch (IllegalAccessException e) { } catch (NoSuchMethodException e) { } catch (InvocationTargetException e) { } return nodeType; } protected String getNodeIconSelector( String nodeType, boolean disclosed, boolean hasChildren ) { if (hasChildren) { if (disclosed) { nodeType += NODE_ICON_EXPANDED_SUFFIX; } else { nodeType += NODE_ICON_COLLAPSED_SUFFIX; } } return SkinSelectors.AF_TREE_TABLE_NODE_ICON + ":" + nodeType; } protected Icon getNodeIcon( RenderingContext rc, String nodeType, boolean disclosed, boolean hasChildren ) { if (nodeType == null || nodeType.length() == 0) { return null; } Icon icon = rc.getIcon(getNodeIconSelector(nodeType, disclosed, hasChildren)); if (icon == null) { if (hasChildren) { icon = rc.getIcon(getNodeIconSelector(nodeType, disclosed, false)); } else { icon = rc.getIcon(getNodeIconSelector(nodeType, false, true)); } } return icon; } private void _renderNodeStampBasedOnAccessibilty( FacesContext context, RenderingContext arc, TreeTableRenderingContext ttrc, UIComponent column) throws IOException { if (XhtmlRenderer.isScreenReaderMode(arc)) { int depth = ttrc.getUIXTreeTable().getDepth() + 1; if (arc.isRightToLeft()) { super.renderKids(context, arc, ttrc, column); TreeUtils.writeNodeLevel(context, arc, depth, _NODE_LEVEL_TEXT_KEY); } else { TreeUtils.writeNodeLevel(context, arc, depth, _NODE_LEVEL_TEXT_KEY); super.renderKids(context, arc, ttrc, column); } } else super.renderKids(context, arc, ttrc, column); } // This String is included in the generated IDs that are // rendered for each expand/collapse icon. private static final String _ICON_ID = "hgi"; // translation keys private static final String _DISABLED_COLLAPSE_TIP_KEY = "af_treeTable.DISABLED_COLLAPSE_TIP"; private static final String _COLLAPSE_TIP_KEY = "af_treeTable.COLLAPSE_TIP"; private static final String _EXPAND_TIP_KEY = "af_treeTable.EXPAND_TIP"; private static final String _NODE_LEVEL_TEXT_KEY = "af_treeTable.NODE_LEVEL"; public static final String NODE_ICON_EXPANDED_SUFFIX = "-expanded"; public static final String NODE_ICON_COLLAPSED_SUFFIX = "-collapsed"; public static final int NODE_ICON_MAX_WIDTH = 18; }
apache-2.0
Anriku/IMCheck
app/src/main/java/com/anriku/imcheck/MainInterface/Model/VideoModel.java
742
package com.anriku.imcheck.MainInterface.Model; import java.io.Serializable; /** * Created by Anriku on 2017/8/20. */ public class VideoModel implements Serializable{ private String videoPath; private String thumbnailPath; private int length; public String getVideoPath() { return videoPath; } public void setVideoPath(String videoPath) { this.videoPath = videoPath; } public String getThumbnailPath() { return thumbnailPath; } public void setThumbnailPath(String thumbnailPath) { this.thumbnailPath = thumbnailPath; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } }
apache-2.0
SocraticGrid/Services-Backup
VACDS-UCS-Model/src/main/java/org/socraticgrid/hl7/services/uc/model/UserContactInfo.java
2127
package org.socraticgrid.hl7.services.uc.model; import java.io.Serializable; import java.util.LinkedHashMap; import java.util.Map; import javax.jws.WebMethod; /** * @author Jerry Goodnough * @version 1.0 * @created 16-Dec-2013 3:54:58 PM */ public class UserContactInfo implements Serializable { /** * */ private static final long serialVersionUID = 1L; private String userContactInfoId; private String name; private String endpoint; //Service endpoint (UCS Client) private Map<String, PhysicalAddress> addressesByType = new LinkedHashMap<>(); private PhysicalAddress preferredAddress; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEndpoint() { return endpoint; } public void setEndpoint(String endpoint) { this.endpoint = endpoint; } public PhysicalAddress getPreferredAddress() { return preferredAddress; } public void setPreferredAddress(PhysicalAddress preferredAddress) { this.preferredAddress = preferredAddress; } /** * To build from persistence. */ @WebMethod(exclude = true) public String getUserContactInfoId() { return userContactInfoId; } @WebMethod(exclude = true) public void setUserContactInfoId(String userContactInfoId) { this.userContactInfoId = userContactInfoId; } @WebMethod(exclude = true) private String getPreferredAddressId() { if(preferredAddress==null){ return null; } return preferredAddress.getAddressId(); } @WebMethod(exclude = true) private void setPreferredAddressId(String userContactInfoId) { // } public Map<String, PhysicalAddress> getAddressesByType() { return addressesByType; } public void setAddressesByType(Map<String, PhysicalAddress> addressesByType) { this.addressesByType = addressesByType; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "UserContactInfo [userContactInfoId=" + userContactInfoId + ", name=" + name + ", endpoint=" + endpoint + ", addressesByType=" + addressesByType + ", preferredAddress=" + preferredAddress + "]"; } }
apache-2.0
hujiaweibujidao/XSolutions
java/codeforces/CF279/B279.java
3269
package CF279; import java.util.*; //http://codeforces.com/contest/490/problem/B //ac public class B279 { public static void main(String[] args) { Scanner cin = new Scanner(System.in); int n = cin.nextInt(); int[] q = new int[n]; Map<Integer, Integer> beforeMap = new HashMap<Integer, Integer>(); Map<Integer, Integer> afterMap = new HashMap<Integer, Integer>(); int a, b; boolean fa = false, fb = false; for (int i = 0; i < n; i++) { a = cin.nextInt(); b = cin.nextInt(); beforeMap.put(b, a); afterMap.put(a, b); if (!fa && a == 0) { q[1] = b; fa = true; afterMap.remove(a); } if (!fb && b == 0) { q[n - 2] = a; fb = true; beforeMap.remove(b); } } a = q[1]; b = q[n - 2]; if (n % 2 == 0) { int offset = 1; while (afterMap.containsKey(a)) { if (afterMap.get(a) != 0) { q[offset + 2] = afterMap.get(a); afterMap.remove(a); a = q[offset + 2]; offset += 2; } else { afterMap.remove(a); break; } } offset = n - 2; while (beforeMap.containsKey(b)) { if (beforeMap.get(b) != 0) { q[offset - 2] = beforeMap.get(b); beforeMap.remove(b); b = q[offset - 2]; offset -= 2; } else { beforeMap.remove(b); break; } } } else { int offset = 1; while (afterMap.containsKey(a)) { if (afterMap.get(a) != 0) { q[offset + 2] = afterMap.get(a); afterMap.remove(a); a = q[offset + 2]; offset += 2; } else { afterMap.remove(a); break; } } int t; while (beforeMap.containsKey(b)) { t = beforeMap.get(b); beforeMap.remove(b); b = t; } int v, k; List<Integer> r = new ArrayList<Integer>(); int first = 0; for (Integer key : beforeMap.keySet()) { if (!beforeMap.containsKey(beforeMap.get(key))) { first = beforeMap.get(key); break; } } r.add(first); while (afterMap.containsKey(first)) { r.add(afterMap.get(first)); first = afterMap.get(first); } int j = 0; for (int i = 0; i < n; i++) { if (q[i] == 0) { q[i] = r.get(j); j++; } } } // for (int i = 0; i < n; i++) { System.out.print(q[i] + " "); } System.out.println(); } }
apache-2.0
dailystudio/devbricks
src/main/java/com/dailystudio/app/fragment/AbsCursorAdapterFragment.java
2183
package com.dailystudio.app.fragment; import com.dailystudio.app.widget.SimpleDatabaseObjectCursorAdapter; import com.dailystudio.dataobject.DatabaseObject; import android.database.Cursor; import androidx.cursoradapter.widget.CursorAdapter; import android.widget.BaseAdapter; import android.widget.ListAdapter; public abstract class AbsCursorAdapterFragment extends AbsAdapterFragment<Cursor, Cursor> { @Override public void onDestroy() { super.onDestroy(); /* * XXX: Here we could not swapCursor(), or * after Oreintation is changed, loader will * return the lasted cursor (which is closed in * swapCursor() and adapter will * reference a closed Cursor and throw exception. */ // swapCursor(null); } @Override protected void bindAdapterView() { final ListAdapter oldAdapter = getAdapter(); Cursor oldCursor = null; if (oldAdapter instanceof CursorAdapter) { oldCursor = ((CursorAdapter)oldAdapter).getCursor(); } super.bindAdapterView(); if (oldCursor != null) { swapCursor(oldCursor); } } @Override protected void bindData(BaseAdapter adapter, Cursor data) { swapCursor(data); } protected void swapCursor(Cursor c) { final BaseAdapter adapter = getAdapter(); if (adapter instanceof CursorAdapter) { Cursor oldCursor = ((CursorAdapter)adapter).swapCursor(c); if (oldCursor != null && oldCursor != c) { oldCursor.close(); } } } public DatabaseObject dumpObject(Cursor cursor) { if (cursor == null) { return null; } ListAdapter adapter = getAdapter(); if (adapter instanceof SimpleDatabaseObjectCursorAdapter == false) { return null; } final SimpleDatabaseObjectCursorAdapter<?> dbObjectAdapter = (SimpleDatabaseObjectCursorAdapter<?>)adapter; return dbObjectAdapter.dumpItem(cursor); } public DatabaseObject dumpObject(int position) { ListAdapter adapter = getAdapter(); if (adapter instanceof SimpleDatabaseObjectCursorAdapter == false) { return null; } final SimpleDatabaseObjectCursorAdapter<?> dbObjectAdapter = (SimpleDatabaseObjectCursorAdapter<?>)adapter; return dbObjectAdapter.dumpItem(position); } }
apache-2.0
amidst/toolbox
huginlink/src/test/java/eu/amidst/huginlink/converters/FileConverterFromHuginToAmidstTest.java
1344
/* * * * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the License. * * */ package eu.amidst.huginlink.converters; import eu.amidst.huginlink.converters.FileConverterFromHuginToAmidst; import org.junit.Before; import org.junit.Test; /** * Created by afa on 5/2/15. */ public class FileConverterFromHuginToAmidstTest { @Before public void setUp() throws Exception { //To make the test easier the check is done in the original class. FileConverterFromHuginToAmidst.convertFilesFromFolder("./networks/"); } @Test public void testModels() { } }
apache-2.0
peterkia/eurekaclinical-user-service
src/main/java/org/eurekaclinical/user/service/entity/UserEntityVisitor.java
1305
/*- * #%L * Eureka! Clinical User Services * %% * Copyright (C) 2016 Emory University * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package org.eurekaclinical.user.service.entity; /** * * @author miaoai */ public interface UserEntityVisitor { /** * Processes a local user entity. * @param localUserEntity a local user entity. Cannot be * <code>null</code>. */ void visit(LocalUserEntity localUserEntity); /** * Processes an LDAP user entity. * @param ldapUserEntity an LDAP user entity. Cannot be * <code>null</code>. */ void visit(LdapUserEntity ldapUserEntity); /** * Processes an OAuth user entity. * @param oauthUserEntity an OAuth user entity. Cannot be * <code>null</code>. */ void visit(OAuthUserEntity oauthUserEntity); }
apache-2.0
korpling/misc-TupleConnector
src/test/java/de/hu_berlin/german/korpling/saltnpepper/misc/tupleconnector/tests/AllTests.java
1091
/** * Copyright 2009 Humboldt University of Berlin, INRIA. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */ package de.hu_berlin.german.korpling.saltnpepper.misc.tupleconnector.tests; import junit.framework.Test; import junit.framework.TestSuite; public class AllTests { public static Test suite() { TestSuite suite = new TestSuite("Test for de.dataconnector.tupleconnector"); // $JUnit-BEGIN$ suite.addTestSuite(TupleWriterTest.class); suite.addTestSuite(TupleConnectorTests.class); // $JUnit-END$ return suite; } }
apache-2.0
tuxdevelop/spring-cloud-demo
spring-cloud-demo-common/src/main/java/org/tuxdevelop/spring/cloud/demo/service/dto/registration/VerifiedLogin.java
293
package org.tuxdevelop.spring.cloud.demo.service.dto.registration; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class VerifiedLogin { private String userName; private Long customerId; }
apache-2.0
trvajjala/interview-preparation
algorithm-practice/src/main/java/com/tvajjala/sorting/QuickSort.java
1167
package com.tvajjala.sorting; import java.util.Arrays; public class QuickSort { public static void main( String[] args ) { int[] array = { 20, 412, 5, 7, 2992, 122, 3000, 333, 444, 999 }; final int start = 0; final int end = array.length - 1; array = doQuickSort( array, start, end ); Arrays.stream( array ).forEach( i -> System.out.print( i + " " ) ); } public static int[] doQuickSort( int[] array, int start, int end ) { int i = start; int j = end; final int pivot = array[i + ( j - i ) / 2]; while ( i <= j ) { while ( array[i] < pivot ) { i++; } while ( array[j] > pivot ) { j--; } while ( i <= j ) { final int tmp = array[i]; array[i] = array[j]; array[j] = tmp; i++; j--; } } if ( start < j ) { doQuickSort( array, start, j ); } if ( i < end ) { doQuickSort( array, i, end ); } return array; } }
apache-2.0
cfaddict/jhipster-course
options/security/http/src/main/java/com/therealdanvega/domain/AbstractAuditingEntity.java
2269
package com.therealdanvega.domain; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonIgnore; import org.hibernate.envers.Audited; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedBy; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import java.time.ZonedDateTime; import javax.persistence.Column; import javax.persistence.EntityListeners; import javax.persistence.MappedSuperclass; /** * Base abstract class for entities which will hold definitions for created, last modified by and created, * last modified by date. */ @MappedSuperclass @Audited @EntityListeners(AuditingEntityListener.class) public abstract class AbstractAuditingEntity implements Serializable { private static final long serialVersionUID = 1L; @CreatedBy @Column(name = "created_by", nullable = false, length = 50, updatable = false) @JsonIgnore private String createdBy; @CreatedDate @Column(name = "created_date", nullable = false) @JsonIgnore private ZonedDateTime createdDate = ZonedDateTime.now(); @LastModifiedBy @Column(name = "last_modified_by", length = 50) @JsonIgnore private String lastModifiedBy; @LastModifiedDate @Column(name = "last_modified_date") @JsonIgnore private ZonedDateTime lastModifiedDate = ZonedDateTime.now(); public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public ZonedDateTime getCreatedDate() { return createdDate; } public void setCreatedDate(ZonedDateTime createdDate) { this.createdDate = createdDate; } public String getLastModifiedBy() { return lastModifiedBy; } public void setLastModifiedBy(String lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; } public ZonedDateTime getLastModifiedDate() { return lastModifiedDate; } public void setLastModifiedDate(ZonedDateTime lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } }
apache-2.0
alexeremeev/aeremeev
chapter_008/src/main/java/ru/job4j/jdbc/Entry.java
654
package ru.job4j.jdbc; import javax.xml.bind.annotation.XmlElement; /** * class Entry - представление одной строки в SQL таблице test. */ public class Entry { /** * Колонка field. */ private String field; /** * Конструктор. * @param field колонка field. */ public Entry(String field) { this.field = field; } /** * Геттер. * @return колонка field. */ @XmlElement public String getField() { return field; } @Override public String toString() { return this.field; } }
apache-2.0
qiuyesuifeng/mybatis-3
src/test/java/org/apache/ibatis/submitted/automatic_lazy_loading/AutomaticLazyLoadingTest.java
7747
/** * Copyright 2009-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ibatis.submitted.automatic_lazy_loading; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Reader; import java.lang.reflect.Method; import java.sql.Connection; import java.util.ArrayList; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.jdbc.ScriptRunner; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Assert; import org.testng.annotations.Test; import org.testng.annotations.BeforeClass; public class AutomaticLazyLoadingTest { private SqlSession sqlSession; private static List<Method> noMethods; private static List<Method> objectMethods; @BeforeClass public static void beforeClass() throws Exception { noMethods = new ArrayList<Method>(); objectMethods = new ArrayList<Method>(); objectMethods.add(Element.class.getMethod("hashCode")); objectMethods.add(Element.class.getMethod("equals", Object.class)); objectMethods.add(Element.class.getMethod("toString")); } /** * Load an element with 'default' configuration. * Expect an exception when none of the 'object methods' is called. */ @Test(groups={"tidb"}) public void selectElementValue_default_nomethods() throws Exception { testScenario("default", true, noMethods); } /** * Load an element with 'default' configuration. * Expect no exception when one of the 'object methods' is called. */ @Test(groups={"tidb"}) public void selectElementValue_default_objectmethods() throws Exception { testScenario("default", false, objectMethods); } /** * Load an element with 'disabled' configuration. * Expect an exception when none of the 'object methods' is called. */ @Test(groups={"tidb"}) public void selectElementValue_disabled_nomethods() throws Exception { testScenario("disabled", true, noMethods); } /** * Load an element with 'disabled' configuration. * Expect an exception when one of the 'object methods' is called. * (because calling object methods should not trigger lazy loading) */ @Test(groups={"tidb"}) public void selectElementValue_disabled_objectmethods() throws Exception { testScenario("disabled", true, objectMethods); } /** * Load an element with 'enabled' configuration. * Expect an exception when none of the 'object methods' is called. */ @Test(groups={"tidb"}) public void selectElementValue_enabled_nomethods() throws Exception { testScenario("enabled", true, noMethods); } /** * Load an element with 'enabled' configuration. * Expect no exception when one of the 'object methods' is called. */ @Test(groups={"tidb"}) public void selectElementValue_enabled_objectmethods() throws Exception { testScenario("enabled", false, objectMethods); } /** * Load an element with default configuration and call toString. * Expect that the toString triggers lazy loading which loads the nested Element * is available after closing the session. */ private void testScenario(String aConfiguration, boolean anExpectingAnException, List<Method> aMethodsToCall) throws Exception { if (aMethodsToCall.isEmpty()) { testScenario(aConfiguration, anExpectingAnException, (Method)null); } else { for (Method myMethod : aMethodsToCall) { testScenario(aConfiguration, anExpectingAnException, myMethod); } } } /** * Load an element with default configuration and call toString. * Expect that the toString triggers lazy loading which loads the nested Element * is available after closing the session. */ private void testScenario(String aConfiguration, boolean anExpectingAnException, Method aMethodToCall) throws Exception { openSession(aConfiguration); Element myElement = selectElement(); String myMethodCallDescription; if (aMethodToCall != null) { Object[] myArguments = new Object[aMethodToCall.getParameterTypes().length]; aMethodToCall.invoke(myElement, myArguments); myMethodCallDescription = aMethodToCall.toString(); } else { myMethodCallDescription = "not called a method"; } myElement = disableLazyLoaders(myElement); closeSession(); try { Assert.assertEquals("parent", myElement.getElement().getValue()); if (anExpectingAnException) { Assert.fail("Excpected an exception, since " + myMethodCallDescription + " should not trigger lazy loading"); } } catch(Exception anException) { if (!anExpectingAnException) { Assert.fail("Did not expect an exception, because " + myMethodCallDescription + " should trigger lazy loading"); } } } /** * Create a session with the specified configuration and initialized the database. */ private void openSession(String aConfig) throws Exception { final String resource = "org/apache/ibatis/submitted/automatic_lazy_loading/ibatis-automatic-lazy-load-" + aConfig + ".xml"; Reader batisConfigReader = Resources.getResourceAsReader(resource); SqlSessionFactory sqlSessionFactory; try { sqlSessionFactory = new SqlSessionFactoryBuilder().build(batisConfigReader); } catch(Exception anException) { throw new RuntimeException("Mapper configuration failed, expected this to work: " + anException.getMessage(), anException); } SqlSession session = sqlSessionFactory.openSession(); Connection conn = session.getConnection(); ScriptRunner runner = new ScriptRunner(conn); runner.setLogWriter(null); runner.setErrorLogWriter(null); Reader createScriptReader = Resources.getResourceAsReader("org/apache/ibatis/submitted/automatic_lazy_loading/create.sql"); runner.runScript(createScriptReader); sqlSession = sqlSessionFactory.openSession(); } private void closeSession() { if (sqlSession != null) { sqlSession.close(); } } /** * Select the child element. */ private Element selectElement() { Element myElement = sqlSession.getMapper(ElementMapper.class).selectElementById("child"); Assert.assertNotNull("Test setup failure; Could not load element", myElement); return myElement; } /** * Disable lazy loaders by serializing / deserializing the element */ private Element disableLazyLoaders(Element anElement) throws Exception { ByteArrayOutputStream myBuffer = new ByteArrayOutputStream(); ObjectOutputStream myObjectOutputStream = new ObjectOutputStream(myBuffer); myObjectOutputStream.writeObject(anElement); myObjectOutputStream.close(); myBuffer.close(); ObjectInputStream myObjectInputStream = new ObjectInputStream(new ByteArrayInputStream(myBuffer.toByteArray())); Element myResult = (Element)myObjectInputStream.readObject(); myObjectInputStream.close(); return myResult; } }
apache-2.0
tomkren/pikater
test/org/pikater/core/experiments/Input10.java
2929
package org.pikater.core.experiments; import java.util.ArrayList; import java.util.List; import org.pikater.core.agents.experiment.dataprocessing.Agent_WeatherSplitter; import org.pikater.core.ontology.subtrees.batchdescription.ComputationDescription; import org.pikater.core.ontology.subtrees.batchdescription.DataProcessing; import org.pikater.core.ontology.subtrees.batchdescription.DataSourceDescription; import org.pikater.core.ontology.subtrees.batchdescription.FileDataProvider; import org.pikater.core.ontology.subtrees.batchdescription.FileDataSaver; public final class Input10 implements ITestExperiment { public ComputationDescription createDescription() { FileDataProvider fileDataProvider = new FileDataProvider(); fileDataProvider.setFileURI("weather.arff"); FileDataProvider fileDataProvider2 = new FileDataProvider(); //fileDataProvider2.setFileURI("weather2.arff"); // hack - we don't have weather2.arff fileDataProvider2.setFileURI("weather.arff"); // wather2.arff would be better // Specify a datasource DataSourceDescription fileDataSource1 = new DataSourceDescription(); fileDataSource1.setInputType("firstInput"); fileDataSource1.setDataProvider(fileDataProvider); DataSourceDescription fileDataSource2 = new DataSourceDescription(); fileDataSource2.setInputType("secondInput"); fileDataSource2.setDataProvider(fileDataProvider2); // PreProcessing DataProcessing processing = new DataProcessing(); processing.setAgentType(Agent_WeatherSplitter.class.getName()); processing.addDataSources(fileDataSource1); processing.addDataSources(fileDataSource2); DataSourceDescription dataSourceSunny = new DataSourceDescription(); dataSourceSunny.setOutputType("sunnyOutput"); dataSourceSunny.setDataProvider(processing); // Save Sunny data FileDataSaver saverSunny = new FileDataSaver(); saverSunny.setDataSource(dataSourceSunny); DataSourceDescription dataSourceOvercast = new DataSourceDescription(); dataSourceOvercast.setOutputType("overcastOutput"); dataSourceOvercast.setDataProvider(processing); // Save Overcast data FileDataSaver saverOvercast = new FileDataSaver(); saverOvercast.setDataSource(dataSourceOvercast); DataSourceDescription dataSourceRainy = new DataSourceDescription(); dataSourceRainy.setOutputType("rainyOutput"); dataSourceRainy.setDataProvider(processing); // Save Overcast data FileDataSaver saverRainy = new FileDataSaver(); saverRainy.setDataSource(dataSourceRainy); // Our requirements for the description are ready, lets create new // computation description List<FileDataSaver> roots = new ArrayList<FileDataSaver>(); roots.add(saverSunny); roots.add(saverOvercast); roots.add(saverRainy); ComputationDescription comDescription = new ComputationDescription(); comDescription.setRootElements(roots); return comDescription; } }
apache-2.0
chenyitianGitHub/coolweather
app/src/androidTest/java/com/coolweather/tqzzd/ExampleInstrumentedTest.java
760
package com.coolweather.tqzzd; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("android.coolweather.com.coolweather", appContext.getPackageName()); } }
apache-2.0
Doloops/arondor-common-reflection
arondor-common-reflection-gwt/src/test/java/com/arondor/common/reflection/gwt/client/testclasses/TestEnumClass.java
280
package com.arondor.common.reflection.gwt.client.testclasses; public class TestEnumClass { private TestEnumDay today; public TestEnumDay getToday() { return today; } public void setToday(TestEnumDay today) { this.today = today; } }
apache-2.0
alibaba/Sentinel
sentinel-cluster/sentinel-cluster-server-default/src/main/java/com/alibaba/csp/sentinel/cluster/server/NettyTransportServer.java
7391
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.csp.sentinel.cluster.server; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import com.alibaba.csp.sentinel.cluster.server.codec.netty.NettyRequestDecoder; import com.alibaba.csp.sentinel.cluster.server.codec.netty.NettyResponseEncoder; import com.alibaba.csp.sentinel.cluster.server.connection.Connection; import com.alibaba.csp.sentinel.cluster.server.connection.ConnectionPool; import com.alibaba.csp.sentinel.cluster.server.handler.TokenServerHandler; import com.alibaba.csp.sentinel.log.RecordLog; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.codec.LengthFieldPrepender; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import io.netty.util.concurrent.GenericFutureListener; import io.netty.util.internal.SystemPropertyUtil; import static com.alibaba.csp.sentinel.cluster.server.ServerConstants.*; /** * @author Eric Zhao * @since 1.4.0 */ public class NettyTransportServer implements ClusterTokenServer { private static final int DEFAULT_EVENT_LOOP_THREADS = Math.max(1, SystemPropertyUtil.getInt("io.netty.eventLoopThreads", Runtime.getRuntime().availableProcessors() * 2)); private static final int MAX_RETRY_TIMES = 3; private static final int RETRY_SLEEP_MS = 2000; private final int port; private NioEventLoopGroup bossGroup; private NioEventLoopGroup workerGroup; private final ConnectionPool connectionPool = new ConnectionPool(); private final AtomicInteger currentState = new AtomicInteger(SERVER_STATUS_OFF); private final AtomicInteger failedTimes = new AtomicInteger(0); public NettyTransportServer(int port) { this.port = port; } @Override public void start() { if (!currentState.compareAndSet(SERVER_STATUS_OFF, SERVER_STATUS_STARTING)) { return; } ServerBootstrap b = new ServerBootstrap(); this.bossGroup = new NioEventLoopGroup(1); this.workerGroup = new NioEventLoopGroup(DEFAULT_EVENT_LOOP_THREADS); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 128) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new LengthFieldBasedFrameDecoder(1024, 0, 2, 0, 2)); p.addLast(new NettyRequestDecoder()); p.addLast(new LengthFieldPrepender(2)); p.addLast(new NettyResponseEncoder()); p.addLast(new TokenServerHandler(connectionPool)); } }) .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .childOption(ChannelOption.SO_SNDBUF, 32 * 1024) .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) .childOption(ChannelOption.SO_TIMEOUT, 10) .childOption(ChannelOption.TCP_NODELAY, true) .childOption(ChannelOption.SO_RCVBUF, 32 * 1024); b.bind(port).addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(ChannelFuture future) { if (future.cause() != null) { RecordLog.info("[NettyTransportServer] Token server start failed (port=" + port + "), failedTimes: " + failedTimes.get(), future.cause()); currentState.compareAndSet(SERVER_STATUS_STARTING, SERVER_STATUS_OFF); int failCount = failedTimes.incrementAndGet(); if (failCount > MAX_RETRY_TIMES) { return; } try { Thread.sleep(failCount * RETRY_SLEEP_MS); start(); } catch (Throwable e) { RecordLog.info("[NettyTransportServer] Failed to start token server when retrying", e); } } else { RecordLog.info("[NettyTransportServer] Token server started success at port {}", port); currentState.compareAndSet(SERVER_STATUS_STARTING, SERVER_STATUS_STARTED); } } }); } @Override public void stop() { // If still initializing, wait for ready. while (currentState.get() == SERVER_STATUS_STARTING) { try { Thread.sleep(500); } catch (InterruptedException e) { // Ignore. } } if (currentState.compareAndSet(SERVER_STATUS_STARTED, SERVER_STATUS_OFF)) { try { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); connectionPool.shutdownAll(); failedTimes.set(0); RecordLog.info("[NettyTransportServer] Sentinel token server stopped"); } catch (Exception ex) { RecordLog.warn("[NettyTransportServer] Failed to stop token server (port=" + port + ")", ex); } } } public void refreshRunningServer() { connectionPool.refreshIdleTask(); } public void closeConnection(String clientIp, int clientPort) throws Exception { Connection connection = connectionPool.getConnection(clientIp, clientPort); connection.close(); } public void closeAll() throws Exception { List<Connection> connections = connectionPool.listAllConnection(); for (Connection connection : connections) { connection.close(); } } public List<String> listAllClient() { List<String> clients = new ArrayList<String>(); List<Connection> connections = connectionPool.listAllConnection(); for (Connection conn : connections) { clients.add(conn.getConnectionKey()); } return clients; } public int getCurrentState() { return currentState.get(); } public int clientCount() { return connectionPool.count(); } }
apache-2.0
whyka/netty-cookbook
chapter4/recipe2/src/main/java/chapter4/recipe2/StompWebSocketServer.java
2593
/* * Netty Cookbook */ package chapter4.recipe2; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.util.SelfSignedCertificate; /** * A HTTP server which serves Web Socket requests at: * * http://localhost:8080/websocket * * Open your browser at http://localhost:8080/, then the demo page will be loaded and a Web Socket connection will be * made automatically. * * This server illustrates support for the different web socket specification versions and will work with: * * <ul> * <li>Safari 5+ (draft-ietf-hybi-thewebsocketprotocol-00) * <li>Chrome 6-13 (draft-ietf-hybi-thewebsocketprotocol-00) * <li>Chrome 14+ (draft-ietf-hybi-thewebsocketprotocol-10) * <li>Chrome 16+ (RFC 6455 aka draft-ietf-hybi-thewebsocketprotocol-17) * <li>Firefox 7+ (draft-ietf-hybi-thewebsocketprotocol-10) * <li>Firefox 11+ (RFC 6455 aka draft-ietf-hybi-thewebsocketprotocol-17) * </ul> */ public final class StompWebSocketServer { static final boolean SSL = System.getProperty("ssl") != null; static final int PORT = Integer.parseInt(System.getProperty("port", SSL? "8443" : "8080")); public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); } else { sslCtx = null; } EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler()) .childHandler(new StompWebSocketServerInitializer(sslCtx)) ; Channel ch = b.bind(PORT).sync().channel(); System.out.println("Open your web browser and navigate to " + (SSL? "https" : "http") + "://127.0.0.1:" + PORT + '/'); ch.closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }
apache-2.0
abelCoronado93/one
src/oca/java/src/org/opennebula/client/OneSystem.java
5731
/******************************************************************************* * Copyright 2002-2017, OpenNebula Project, OpenNebula Systems * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package org.opennebula.client; import java.io.ByteArrayInputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; public class OneSystem { protected Client client; private static final String USER_QUOTA_INFO = "userquota.info"; private static final String USER_QUOTA_UPDATE = "userquota.update"; private static final String GROUP_QUOTA_INFO = "groupquota.info"; private static final String GROUP_QUOTA_UPDATE = "groupquota.update"; public static final String VERSION = "5.5.80"; public OneSystem(Client client) { this.client = client; } /** * Calls OpenNebula and retrieves the oned version * * @return The server's xml-rpc response encapsulated */ public OneResponse getOnedVersion() { return client.call("system.version"); } /** * Returns whether of not the oned version is the same as the OCA version * * @return true if oned is the same version */ public boolean compatibleVersion() { OneResponse r = getOnedVersion(); if (r.isError()) { return false; } String[] ocaVersion = VERSION.split("\\.", 3); String[] onedVersion = r.getMessage().split("\\.", 3); return ocaVersion.length == onedVersion.length && ocaVersion[0].equals(onedVersion[0]) && ocaVersion[1].equals(onedVersion[1]); } /** * Calls OpenNebula and retrieves oned configuration * * @return The server's xml-rpc response encapsulated */ public OneResponse getConfiguration() { return client.call("system.config"); } /** * Calls OpenNebula and retrieves oned configuration * * @return The xml root node in case of success, null otherwise */ public Node getConfigurationXML() { OneResponse r = getConfiguration(); Node xml = null; if (r.isError()) { return null; } try { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse( new ByteArrayInputStream(r.getMessage().getBytes())); xml = doc.getDocumentElement(); } catch (Exception e) {} return xml; } /** * Gets the default user quota limits * * @return the default user quota in case of success, Error otherwise */ public OneResponse getUserQuotas() { return client.call(USER_QUOTA_INFO); } /** * Gets the default user quota limits * * @return The xml root node in case of success, null otherwise */ public Node getUserQuotasXML() { OneResponse r = getUserQuotas(); Node xml = null; if (r.isError()) { return null; } try { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse( new ByteArrayInputStream(r.getMessage().getBytes())); xml = doc.getDocumentElement(); } catch (Exception e) {} return xml; } /** * Sets the default user quota limits * * @param quota a template (XML or txt) with the new quota limits * @return If an error occurs the error message contains the reason. */ public OneResponse setUserQuotas(String quota) { return client.call(USER_QUOTA_UPDATE, quota); } /** * Gets the default group quota limits * * @return the default group quota in case of success, Error otherwise */ public OneResponse getGroupQuotas() { return client.call(GROUP_QUOTA_INFO); } /** * Gets the default group quota limits * * @return The xml root node in case of success, null otherwise */ public Node getGroupQuotasXML() { OneResponse r = getGroupQuotas(); Node xml = null; if (r.isError()) { return null; } try { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse( new ByteArrayInputStream(r.getMessage().getBytes())); xml = doc.getDocumentElement(); } catch (Exception e) {} return xml; } /** * Sets the default group quota limits * * @param quota a template (XML or txt) with the new quota limits * @return If an error occurs the error message contains the reason. */ public OneResponse setGroupQuotas(String quota) { return client.call(GROUP_QUOTA_UPDATE, quota); } }
apache-2.0
ThoughtWorksStudios/mingle_hg_plugin
java_source_browser/test/com/thoughtworks/studios/mingle/hg/cmdline/LinePipeRunnableTest.java
730
//Copyright 2010 ThoughtWorks, Inc. Licensed under the Apache License, Version 2.0. package com.thoughtworks.studios.mingle.hg.cmdline; import org.junit.Test; import java.io.ByteArrayInputStream; import java.util.Arrays; public class LinePipeRunnableTest { @Test public void pipeWorks() throws Exception { String content = "expected\ntext\n"; ByteArrayInputStream in = new ByteArrayInputStream(content.getBytes()); TestLineHandler testLineHandler = new TestLineHandler(); PipeRunnable pipeRunnable = new LinePipeRunnable(in, testLineHandler); pipeRunnable.run(); String[] expectedLines = new String[]{"expected", "text"}; testLineHandler.assertLinesEqual(Arrays.asList(expectedLines)); } }
apache-2.0
googleads/google-ads-java
google-ads-stubs-v10/src/main/java/com/google/ads/googleads/v10/enums/AccountBudgetProposalStatusEnumOrBuilder.java
410
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v10/enums/account_budget_proposal_status.proto package com.google.ads.googleads.v10.enums; public interface AccountBudgetProposalStatusEnumOrBuilder extends // @@protoc_insertion_point(interface_extends:google.ads.googleads.v10.enums.AccountBudgetProposalStatusEnum) com.google.protobuf.MessageOrBuilder { }
apache-2.0
cucina/opencucina
search/src/test/java/org/cucina/search/query/criterion/InSearchCriterionTest.java
5756
package org.cucina.search.query.criterion; import org.cucina.core.marshal.JacksonMarshaller; import org.cucina.core.marshal.Marshaller; import org.cucina.core.utils.NameUtils; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; /** * JAVADOC for Class Level * * @author $Author: $ * @version $Revision: $ */ public class InSearchCriterionTest { private static final String MARSHALLED_PROJECTION = "{\"@class\":\"org.cucina.search.query.criterion.InSearchCriterion\",\"name\":\"name\",\"rootAlias\":\"root\",\"alias\":\"name\",\"booleanNot\":false,\"value\":[\"a\"]}"; private static final String MULTI_MARSHALLED_PROJECTION = "{\"@class\":\"org.cucina.search.query.criterion.InSearchCriterion\",\"name\":\"name\",\"rootAlias\":\"root\",\"alias\":\"name\",\"booleanNot\":false,\"value\":[\"a\",\"b\",\"c\"]}"; private static final String ROOT_ALIAS = "root"; private static final String PARENT_ALIAS = "parent"; private static final String PROPERTY = "name"; private InSearchCriterion criterion; private Marshaller marshaller; /** * Tests marshalls values correctly */ @Test public void marshalls() { assertEquals("Should have marshalled correctly", MARSHALLED_PROJECTION, marshaller.marshall(criterion)); assertEquals("Should have marshalled correctly", MULTI_MARSHALLED_PROJECTION, marshaller.marshall( new InSearchCriterion(PROPERTY, null, ROOT_ALIAS, Arrays.asList("a", "b", "c")))); } /** * Sets up test */ @Before public void setup() { criterion = new InSearchCriterion(PROPERTY, null, ROOT_ALIAS, Collections.singleton("a")); criterion.setParentAliases(Collections.singletonMap(ROOT_ALIAS, PARENT_ALIAS)); marshaller = new JacksonMarshaller(null, null); } /** * JAVADOC Method Level Comments */ @Test public void testMoreThanOne() { criterion = new InSearchCriterion(PROPERTY, null, ROOT_ALIAS, Arrays.asList("a", "b", "c")); criterion.setParentAliases(Collections.singletonMap(ROOT_ALIAS, PARENT_ALIAS)); assertEquals("Should return in with multiple values", PARENT_ALIAS + ".name in (?,?,?)", criterion.getRestriction()); } /** * alias is required */ @Test(expected = IllegalArgumentException.class) public void testNoAliasSupplied() { new InSearchCriterion(PROPERTY, null, null, Collections.singleton("a")); } /** * match is required */ @Test(expected = IllegalArgumentException.class) public void testNoMatchSupplied() { new InSearchCriterion(PROPERTY, null, ROOT_ALIAS, null); } /** * property is required */ @Test(expected = IllegalArgumentException.class) public void testNoPropertySupplied() { new InSearchCriterion(null, null, ROOT_ALIAS, Collections.singleton("a")); } /** * Tests restriction is correct */ @Test public void testRestriction() { assertEquals("Incorrect restriction", NameUtils.concat(PARENT_ALIAS, PROPERTY) + " = ?", criterion.getRestriction()); } /** * Tests property is nested two levels, should return final nested level as alias and * property */ @Test public void testSearchPropertyNameNestedTwoLevels() { InSearchCriterion localCriterion = new InSearchCriterion("grandParent.parent." + PROPERTY, null, ROOT_ALIAS, Collections.singleton("a")); localCriterion.setParentAliases(Collections.singletonMap("parent", PARENT_ALIAS)); assertEquals("Should return just root", NameUtils.concat("parent", PROPERTY) + " = ?", localCriterion.getRestriction()); } /** * Tests property is at root level */ @Test public void testSearchPropertyNameRootLevel() { InSearchCriterion localCriterion = new InSearchCriterion(PROPERTY, null, ROOT_ALIAS, Collections.singleton("a")); localCriterion.setParentAliases(Collections.singletonMap(ROOT_ALIAS, PARENT_ALIAS)); assertEquals("Should return just root", NameUtils.concat(PARENT_ALIAS, PROPERTY) + " = ?", localCriterion.getRestriction()); } /** * Tests property is nested one level, should return property provided */ @Test public void testSearchPropertyNestedOneLevels() { InSearchCriterion localCriterion = new InSearchCriterion("parent." + PROPERTY, null, ROOT_ALIAS, Collections.singleton("a")); localCriterion.setParentAliases(Collections.singletonMap("parent", PARENT_ALIAS)); assertEquals("Should return just root", NameUtils.concat("parent", PROPERTY) + " = ?", localCriterion.getRestriction()); } /** * Test values returned are as expected */ @Test public void testValues() { List<Object> values = criterion.getValues(); assertNotNull("values cannot be null", values); assertEquals("Incorrect number of values", 1, values.size()); } /** * unmarshalls values correctly */ @Test public void unmarshalls() { InSearchCriterion unmarshalledCrit = marshaller.unmarshall(MARSHALLED_PROJECTION, InSearchCriterion.class); assertNotNull("Should have returned projection", unmarshalledCrit); assertEquals("Should have set name", PROPERTY, unmarshalledCrit.getName()); assertTrue("Should have set foreign id", unmarshalledCrit.getValues().containsAll(Collections.singleton("a"))); assertEquals("Should have set rootAlias", ROOT_ALIAS, unmarshalledCrit.getRootAlias()); unmarshalledCrit = marshaller.unmarshall(MULTI_MARSHALLED_PROJECTION, InSearchCriterion.class); assertNotNull("Should have returned projection", unmarshalledCrit); assertEquals("Should have set name", PROPERTY, unmarshalledCrit.getName()); assertTrue("Should have set foreign id", unmarshalledCrit.getValues().containsAll(Arrays.asList("a", "b", "c"))); assertEquals("Should have set rootAlias", ROOT_ALIAS, unmarshalledCrit.getRootAlias()); } }
apache-2.0
trasa/aws-sdk-java
aws-java-sdk-iam/src/main/java/com/amazonaws/services/identitymanagement/model/User.java
25974
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.identitymanagement.model; import java.io.Serializable; /** * <p> * Contains information about an IAM user entity. * </p> * <p> * This data type is used as a response element in the following actions: * </p> * <ul> * <li> * <p> * <a>CreateUser</a> * </p> * </li> * <li> * <p> * <a>GetUser</a> * </p> * </li> * <li> * <p> * <a>ListUsers</a> * </p> * </li> * </ul> */ public class User implements Serializable, Cloneable { /** * <p> * The path to the user. For more information about paths, see <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >IAM Identifiers</a> in the <i>Using IAM</i> guide. * </p> */ private String path; /** * <p> * The friendly name identifying the user. * </p> */ private String userName; /** * <p> * The stable and unique string identifying the user. For more information * about IDs, see <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >IAM Identifiers</a> in the <i>Using IAM</i> guide. * </p> */ private String userId; /** * <p> * The Amazon Resource Name (ARN) that identifies the user. For more * information about ARNs and how to use ARNs in policies, see <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >IAM Identifiers</a> in the <i>Using IAM</i> guide. * </p> */ private String arn; /** * <p> * The date and time, in <a href="http://www.iso.org/iso/iso8601">ISO 8601 * date-time format</a>, when the user was created. * </p> */ private java.util.Date createDate; /** * <p> * The date and time, in <a href="http://www.iso.org/iso/iso8601">ISO 8601 * date-time format</a>, when the user's password was last used to sign in * to an AWS website. For a list of AWS websites that capture a user's last * sign-in time, see the <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/credential-reports.html" * >Credential Reports</a> topic in the <i>Using IAM</i> guide. If a * password is used more than once in a five-minute span, only the first use * is returned in this field. This field is null (not present) when: * </p> * <ul> * <li> * <p> * The user does not have a password * </p> * </li> * <li> * <p> * The password exists but has never been used (at least not since IAM * started tracking this information on October 20th, 2014 * </p> * </li> * <li> * <p> * there is no sign-in data associated with the user * </p> * </li> * </ul> * <p> * This value is returned only in the <a>GetUser</a> and <a>ListUsers</a> * actions. * </p> */ private java.util.Date passwordLastUsed; /** * Default constructor for User object. Callers should use the setter or * fluent setter (with...) methods to initialize the object after creating * it. */ public User() { } /** * Constructs a new User object. Callers should use the setter or fluent * setter (with...) methods to initialize any additional object members. * * @param path * The path to the user. For more information about paths, see <a * href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >IAM Identifiers</a> in the <i>Using IAM</i> guide. * @param userName * The friendly name identifying the user. * @param userId * The stable and unique string identifying the user. For more * information about IDs, see <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >IAM Identifiers</a> in the <i>Using IAM</i> guide. * @param arn * The Amazon Resource Name (ARN) that identifies the user. For more * information about ARNs and how to use ARNs in policies, see <a * href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >IAM Identifiers</a> in the <i>Using IAM</i> guide. * @param createDate * The date and time, in <a href="http://www.iso.org/iso/iso8601">ISO * 8601 date-time format</a>, when the user was created. */ public User(String path, String userName, String userId, String arn, java.util.Date createDate) { setPath(path); setUserName(userName); setUserId(userId); setArn(arn); setCreateDate(createDate); } /** * <p> * The path to the user. For more information about paths, see <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >IAM Identifiers</a> in the <i>Using IAM</i> guide. * </p> * * @param path * The path to the user. For more information about paths, see <a * href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >IAM Identifiers</a> in the <i>Using IAM</i> guide. */ public void setPath(String path) { this.path = path; } /** * <p> * The path to the user. For more information about paths, see <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >IAM Identifiers</a> in the <i>Using IAM</i> guide. * </p> * * @return The path to the user. For more information about paths, see <a * href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >IAM Identifiers</a> in the <i>Using IAM</i> guide. */ public String getPath() { return this.path; } /** * <p> * The path to the user. For more information about paths, see <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >IAM Identifiers</a> in the <i>Using IAM</i> guide. * </p> * * @param path * The path to the user. For more information about paths, see <a * href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >IAM Identifiers</a> in the <i>Using IAM</i> guide. * @return Returns a reference to this object so that method calls can be * chained together. */ public User withPath(String path) { setPath(path); return this; } /** * <p> * The friendly name identifying the user. * </p> * * @param userName * The friendly name identifying the user. */ public void setUserName(String userName) { this.userName = userName; } /** * <p> * The friendly name identifying the user. * </p> * * @return The friendly name identifying the user. */ public String getUserName() { return this.userName; } /** * <p> * The friendly name identifying the user. * </p> * * @param userName * The friendly name identifying the user. * @return Returns a reference to this object so that method calls can be * chained together. */ public User withUserName(String userName) { setUserName(userName); return this; } /** * <p> * The stable and unique string identifying the user. For more information * about IDs, see <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >IAM Identifiers</a> in the <i>Using IAM</i> guide. * </p> * * @param userId * The stable and unique string identifying the user. For more * information about IDs, see <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >IAM Identifiers</a> in the <i>Using IAM</i> guide. */ public void setUserId(String userId) { this.userId = userId; } /** * <p> * The stable and unique string identifying the user. For more information * about IDs, see <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >IAM Identifiers</a> in the <i>Using IAM</i> guide. * </p> * * @return The stable and unique string identifying the user. For more * information about IDs, see <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >IAM Identifiers</a> in the <i>Using IAM</i> guide. */ public String getUserId() { return this.userId; } /** * <p> * The stable and unique string identifying the user. For more information * about IDs, see <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >IAM Identifiers</a> in the <i>Using IAM</i> guide. * </p> * * @param userId * The stable and unique string identifying the user. For more * information about IDs, see <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >IAM Identifiers</a> in the <i>Using IAM</i> guide. * @return Returns a reference to this object so that method calls can be * chained together. */ public User withUserId(String userId) { setUserId(userId); return this; } /** * <p> * The Amazon Resource Name (ARN) that identifies the user. For more * information about ARNs and how to use ARNs in policies, see <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >IAM Identifiers</a> in the <i>Using IAM</i> guide. * </p> * * @param arn * The Amazon Resource Name (ARN) that identifies the user. For more * information about ARNs and how to use ARNs in policies, see <a * href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >IAM Identifiers</a> in the <i>Using IAM</i> guide. */ public void setArn(String arn) { this.arn = arn; } /** * <p> * The Amazon Resource Name (ARN) that identifies the user. For more * information about ARNs and how to use ARNs in policies, see <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >IAM Identifiers</a> in the <i>Using IAM</i> guide. * </p> * * @return The Amazon Resource Name (ARN) that identifies the user. For more * information about ARNs and how to use ARNs in policies, see <a * href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >IAM Identifiers</a> in the <i>Using IAM</i> guide. */ public String getArn() { return this.arn; } /** * <p> * The Amazon Resource Name (ARN) that identifies the user. For more * information about ARNs and how to use ARNs in policies, see <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >IAM Identifiers</a> in the <i>Using IAM</i> guide. * </p> * * @param arn * The Amazon Resource Name (ARN) that identifies the user. For more * information about ARNs and how to use ARNs in policies, see <a * href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >IAM Identifiers</a> in the <i>Using IAM</i> guide. * @return Returns a reference to this object so that method calls can be * chained together. */ public User withArn(String arn) { setArn(arn); return this; } /** * <p> * The date and time, in <a href="http://www.iso.org/iso/iso8601">ISO 8601 * date-time format</a>, when the user was created. * </p> * * @param createDate * The date and time, in <a href="http://www.iso.org/iso/iso8601">ISO * 8601 date-time format</a>, when the user was created. */ public void setCreateDate(java.util.Date createDate) { this.createDate = createDate; } /** * <p> * The date and time, in <a href="http://www.iso.org/iso/iso8601">ISO 8601 * date-time format</a>, when the user was created. * </p> * * @return The date and time, in <a * href="http://www.iso.org/iso/iso8601">ISO 8601 date-time * format</a>, when the user was created. */ public java.util.Date getCreateDate() { return this.createDate; } /** * <p> * The date and time, in <a href="http://www.iso.org/iso/iso8601">ISO 8601 * date-time format</a>, when the user was created. * </p> * * @param createDate * The date and time, in <a href="http://www.iso.org/iso/iso8601">ISO * 8601 date-time format</a>, when the user was created. * @return Returns a reference to this object so that method calls can be * chained together. */ public User withCreateDate(java.util.Date createDate) { setCreateDate(createDate); return this; } /** * <p> * The date and time, in <a href="http://www.iso.org/iso/iso8601">ISO 8601 * date-time format</a>, when the user's password was last used to sign in * to an AWS website. For a list of AWS websites that capture a user's last * sign-in time, see the <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/credential-reports.html" * >Credential Reports</a> topic in the <i>Using IAM</i> guide. If a * password is used more than once in a five-minute span, only the first use * is returned in this field. This field is null (not present) when: * </p> * <ul> * <li> * <p> * The user does not have a password * </p> * </li> * <li> * <p> * The password exists but has never been used (at least not since IAM * started tracking this information on October 20th, 2014 * </p> * </li> * <li> * <p> * there is no sign-in data associated with the user * </p> * </li> * </ul> * <p> * This value is returned only in the <a>GetUser</a> and <a>ListUsers</a> * actions. * </p> * * @param passwordLastUsed * The date and time, in <a href="http://www.iso.org/iso/iso8601">ISO * 8601 date-time format</a>, when the user's password was last used * to sign in to an AWS website. For a list of AWS websites that * capture a user's last sign-in time, see the <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/credential-reports.html" * >Credential Reports</a> topic in the <i>Using IAM</i> guide. If a * password is used more than once in a five-minute span, only the * first use is returned in this field. This field is null (not * present) when:</p> * <ul> * <li> * <p> * The user does not have a password * </p> * </li> * <li> * <p> * The password exists but has never been used (at least not since * IAM started tracking this information on October 20th, 2014 * </p> * </li> * <li> * <p> * there is no sign-in data associated with the user * </p> * </li> * </ul> * <p> * This value is returned only in the <a>GetUser</a> and * <a>ListUsers</a> actions. */ public void setPasswordLastUsed(java.util.Date passwordLastUsed) { this.passwordLastUsed = passwordLastUsed; } /** * <p> * The date and time, in <a href="http://www.iso.org/iso/iso8601">ISO 8601 * date-time format</a>, when the user's password was last used to sign in * to an AWS website. For a list of AWS websites that capture a user's last * sign-in time, see the <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/credential-reports.html" * >Credential Reports</a> topic in the <i>Using IAM</i> guide. If a * password is used more than once in a five-minute span, only the first use * is returned in this field. This field is null (not present) when: * </p> * <ul> * <li> * <p> * The user does not have a password * </p> * </li> * <li> * <p> * The password exists but has never been used (at least not since IAM * started tracking this information on October 20th, 2014 * </p> * </li> * <li> * <p> * there is no sign-in data associated with the user * </p> * </li> * </ul> * <p> * This value is returned only in the <a>GetUser</a> and <a>ListUsers</a> * actions. * </p> * * @return The date and time, in <a * href="http://www.iso.org/iso/iso8601">ISO 8601 date-time * format</a>, when the user's password was last used to sign in to * an AWS website. For a list of AWS websites that capture a user's * last sign-in time, see the <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/credential-reports.html" * >Credential Reports</a> topic in the <i>Using IAM</i> guide. If a * password is used more than once in a five-minute span, only the * first use is returned in this field. This field is null (not * present) when:</p> * <ul> * <li> * <p> * The user does not have a password * </p> * </li> * <li> * <p> * The password exists but has never been used (at least not since * IAM started tracking this information on October 20th, 2014 * </p> * </li> * <li> * <p> * there is no sign-in data associated with the user * </p> * </li> * </ul> * <p> * This value is returned only in the <a>GetUser</a> and * <a>ListUsers</a> actions. */ public java.util.Date getPasswordLastUsed() { return this.passwordLastUsed; } /** * <p> * The date and time, in <a href="http://www.iso.org/iso/iso8601">ISO 8601 * date-time format</a>, when the user's password was last used to sign in * to an AWS website. For a list of AWS websites that capture a user's last * sign-in time, see the <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/credential-reports.html" * >Credential Reports</a> topic in the <i>Using IAM</i> guide. If a * password is used more than once in a five-minute span, only the first use * is returned in this field. This field is null (not present) when: * </p> * <ul> * <li> * <p> * The user does not have a password * </p> * </li> * <li> * <p> * The password exists but has never been used (at least not since IAM * started tracking this information on October 20th, 2014 * </p> * </li> * <li> * <p> * there is no sign-in data associated with the user * </p> * </li> * </ul> * <p> * This value is returned only in the <a>GetUser</a> and <a>ListUsers</a> * actions. * </p> * * @param passwordLastUsed * The date and time, in <a href="http://www.iso.org/iso/iso8601">ISO * 8601 date-time format</a>, when the user's password was last used * to sign in to an AWS website. For a list of AWS websites that * capture a user's last sign-in time, see the <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/credential-reports.html" * >Credential Reports</a> topic in the <i>Using IAM</i> guide. If a * password is used more than once in a five-minute span, only the * first use is returned in this field. This field is null (not * present) when:</p> * <ul> * <li> * <p> * The user does not have a password * </p> * </li> * <li> * <p> * The password exists but has never been used (at least not since * IAM started tracking this information on October 20th, 2014 * </p> * </li> * <li> * <p> * there is no sign-in data associated with the user * </p> * </li> * </ul> * <p> * This value is returned only in the <a>GetUser</a> and * <a>ListUsers</a> actions. * @return Returns a reference to this object so that method calls can be * chained together. */ public User withPasswordLastUsed(java.util.Date passwordLastUsed) { setPasswordLastUsed(passwordLastUsed); return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getPath() != null) sb.append("Path: " + getPath() + ","); if (getUserName() != null) sb.append("UserName: " + getUserName() + ","); if (getUserId() != null) sb.append("UserId: " + getUserId() + ","); if (getArn() != null) sb.append("Arn: " + getArn() + ","); if (getCreateDate() != null) sb.append("CreateDate: " + getCreateDate() + ","); if (getPasswordLastUsed() != null) sb.append("PasswordLastUsed: " + getPasswordLastUsed()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof User == false) return false; User other = (User) obj; if (other.getPath() == null ^ this.getPath() == null) return false; if (other.getPath() != null && other.getPath().equals(this.getPath()) == false) return false; if (other.getUserName() == null ^ this.getUserName() == null) return false; if (other.getUserName() != null && other.getUserName().equals(this.getUserName()) == false) return false; if (other.getUserId() == null ^ this.getUserId() == null) return false; if (other.getUserId() != null && other.getUserId().equals(this.getUserId()) == false) return false; if (other.getArn() == null ^ this.getArn() == null) return false; if (other.getArn() != null && other.getArn().equals(this.getArn()) == false) return false; if (other.getCreateDate() == null ^ this.getCreateDate() == null) return false; if (other.getCreateDate() != null && other.getCreateDate().equals(this.getCreateDate()) == false) return false; if (other.getPasswordLastUsed() == null ^ this.getPasswordLastUsed() == null) return false; if (other.getPasswordLastUsed() != null && other.getPasswordLastUsed().equals( this.getPasswordLastUsed()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getPath() == null) ? 0 : getPath().hashCode()); hashCode = prime * hashCode + ((getUserName() == null) ? 0 : getUserName().hashCode()); hashCode = prime * hashCode + ((getUserId() == null) ? 0 : getUserId().hashCode()); hashCode = prime * hashCode + ((getArn() == null) ? 0 : getArn().hashCode()); hashCode = prime * hashCode + ((getCreateDate() == null) ? 0 : getCreateDate().hashCode()); hashCode = prime * hashCode + ((getPasswordLastUsed() == null) ? 0 : getPasswordLastUsed() .hashCode()); return hashCode; } @Override public User clone() { try { return (User) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException( "Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
apache-2.0
5agado/neural-networks
src/test/java/basic/TestPerceptron.java
2270
package basic; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import model.Perceptron; import model.PerceptronFunctions; import model.PerceptronFunctions.TrainingPair; import org.junit.Test; public class TestPerceptron { @Test public void testAND_OR() { double trueVal = 1.0; double falseVal = -1.0; //AND case List<Double> weights = Arrays.asList(0.5, 0.5); Perceptron p = new Perceptron(weights, -0.8, PerceptronFunctions.summation, PerceptronFunctions.activationThresholded); assertEquals(falseVal, p.getOutput(Arrays.asList(trueVal, falseVal)), 0); assertEquals(falseVal, p.getOutput(Arrays.asList(falseVal, falseVal)), 0); assertEquals(falseVal, p.getOutput(Arrays.asList(falseVal, trueVal)), 0); assertEquals(trueVal, p.getOutput(Arrays.asList(trueVal, trueVal)), 0); //OR case //TODO Why Mitchell says -0.3?? p.setBias(0.3); assertEquals(trueVal, p.getOutput(Arrays.asList(trueVal, falseVal)), 0); assertEquals(falseVal, p.getOutput(Arrays.asList(falseVal, falseVal)), 0); assertEquals(trueVal, p.getOutput(Arrays.asList(falseVal, trueVal)), 0); assertEquals(trueVal, p.getOutput(Arrays.asList(trueVal, trueVal)), 0); } @Test public void test() { Random rand = new Random(); double trueVal = 1.0; double falseVal = -1.0; List<TrainingPair<Double, Double>> trainingSet = new ArrayList<TrainingPair<Double, Double>>(); trainingSet.add(new TrainingPair<Double, Double>(Arrays.asList(trueVal, falseVal), falseVal)); trainingSet.add(new TrainingPair<Double, Double>(Arrays.asList(falseVal, falseVal), falseVal)); trainingSet.add(new TrainingPair<Double, Double>(Arrays.asList(falseVal, trueVal), falseVal)); trainingSet.add(new TrainingPair<Double, Double>(Arrays.asList(trueVal, trueVal), trueVal)); List<Double> weights = Arrays.asList(rand.nextDouble(), rand.nextDouble()); Perceptron p = new Perceptron(weights, rand.nextDouble(), PerceptronFunctions.summation, PerceptronFunctions.activationThresholded); PerceptronFunctions.perceptronRuleTraining.apply(trainingSet, p); System.out.println(p.getWeights().toString()); System.out.println(p.getBias()); } }
apache-2.0
kubernetes-client/java
kubernetes/src/main/java/io/kubernetes/client/openapi/models/V1FlexVolumeSource.java
6432
/* Copyright 2021 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package io.kubernetes.client.openapi.models; import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * FlexVolume represents a generic volume resource that is provisioned/attached using an exec based * plugin. */ @ApiModel( description = "FlexVolume represents a generic volume resource that is provisioned/attached using an exec based plugin.") @javax.annotation.Generated( value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2021-12-10T19:11:23.904Z[Etc/UTC]") public class V1FlexVolumeSource { public static final String SERIALIZED_NAME_DRIVER = "driver"; @SerializedName(SERIALIZED_NAME_DRIVER) private String driver; public static final String SERIALIZED_NAME_FS_TYPE = "fsType"; @SerializedName(SERIALIZED_NAME_FS_TYPE) private String fsType; public static final String SERIALIZED_NAME_OPTIONS = "options"; @SerializedName(SERIALIZED_NAME_OPTIONS) private Map<String, String> options = null; public static final String SERIALIZED_NAME_READ_ONLY = "readOnly"; @SerializedName(SERIALIZED_NAME_READ_ONLY) private Boolean readOnly; public static final String SERIALIZED_NAME_SECRET_REF = "secretRef"; @SerializedName(SERIALIZED_NAME_SECRET_REF) private V1LocalObjectReference secretRef; public V1FlexVolumeSource driver(String driver) { this.driver = driver; return this; } /** * Driver is the name of the driver to use for this volume. * * @return driver */ @ApiModelProperty( required = true, value = "Driver is the name of the driver to use for this volume.") public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public V1FlexVolumeSource fsType(String fsType) { this.fsType = fsType; return this; } /** * Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. * \&quot;ext4\&quot;, \&quot;xfs\&quot;, \&quot;ntfs\&quot;. The default filesystem depends on * FlexVolume script. * * @return fsType */ @javax.annotation.Nullable @ApiModelProperty( value = "Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". The default filesystem depends on FlexVolume script.") public String getFsType() { return fsType; } public void setFsType(String fsType) { this.fsType = fsType; } public V1FlexVolumeSource options(Map<String, String> options) { this.options = options; return this; } public V1FlexVolumeSource putOptionsItem(String key, String optionsItem) { if (this.options == null) { this.options = new HashMap<>(); } this.options.put(key, optionsItem); return this; } /** * Optional: Extra command options if any. * * @return options */ @javax.annotation.Nullable @ApiModelProperty(value = "Optional: Extra command options if any.") public Map<String, String> getOptions() { return options; } public void setOptions(Map<String, String> options) { this.options = options; } public V1FlexVolumeSource readOnly(Boolean readOnly) { this.readOnly = readOnly; return this; } /** * Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in * VolumeMounts. * * @return readOnly */ @javax.annotation.Nullable @ApiModelProperty( value = "Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.") public Boolean getReadOnly() { return readOnly; } public void setReadOnly(Boolean readOnly) { this.readOnly = readOnly; } public V1FlexVolumeSource secretRef(V1LocalObjectReference secretRef) { this.secretRef = secretRef; return this; } /** * Get secretRef * * @return secretRef */ @javax.annotation.Nullable @ApiModelProperty(value = "") public V1LocalObjectReference getSecretRef() { return secretRef; } public void setSecretRef(V1LocalObjectReference secretRef) { this.secretRef = secretRef; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } V1FlexVolumeSource v1FlexVolumeSource = (V1FlexVolumeSource) o; return Objects.equals(this.driver, v1FlexVolumeSource.driver) && Objects.equals(this.fsType, v1FlexVolumeSource.fsType) && Objects.equals(this.options, v1FlexVolumeSource.options) && Objects.equals(this.readOnly, v1FlexVolumeSource.readOnly) && Objects.equals(this.secretRef, v1FlexVolumeSource.secretRef); } @Override public int hashCode() { return Objects.hash(driver, fsType, options, readOnly, secretRef); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class V1FlexVolumeSource {\n"); sb.append(" driver: ").append(toIndentedString(driver)).append("\n"); sb.append(" fsType: ").append(toIndentedString(fsType)).append("\n"); sb.append(" options: ").append(toIndentedString(options)).append("\n"); sb.append(" readOnly: ").append(toIndentedString(readOnly)).append("\n"); sb.append(" secretRef: ").append(toIndentedString(secretRef)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
apache-2.0
dpmorocho/obd-api
src/test/java/com/github/dpmorocho/obd/comandos/ThrottleCommandTest.java
3853
package com.github.dpmorocho.obd.comandos; import static org.powermock.api.easymock.PowerMock.createMock; import static org.powermock.api.easymock.PowerMock.expectLastCall; import static org.powermock.api.easymock.PowerMock.replayAll; import static org.powermock.api.easymock.PowerMock.verifyAll; import static org.testng.Assert.assertEquals; import java.io.IOException; import java.io.InputStream; import org.powermock.core.classloader.annotations.PrepareForTest; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.github.dpmorocho.obd.comandos.motor.ThrottlePositionCommand; /** * Tests for ThrottlePositionCommand class. */ @PrepareForTest(InputStream.class) public class ThrottleCommandTest { private ThrottlePositionCommand command; private InputStream mockIn; /** * @throws Exception */ @BeforeMethod public void setUp() throws Exception { command = new ThrottlePositionCommand(); } /** * Test for valid InputStream read, maximum value of 100% * * @throws IOException */ @Test public void testMaxThrottlePositionValue() throws IOException { // mock InputStream read mockIn = createMock(InputStream.class); mockIn.read(); expectLastCall().andReturn((byte) '4'); expectLastCall().andReturn((byte) '1'); expectLastCall().andReturn((byte) ' '); expectLastCall().andReturn((byte) '1'); expectLastCall().andReturn((byte) '1'); expectLastCall().andReturn((byte) ' '); expectLastCall().andReturn((byte) 'F'); expectLastCall().andReturn((byte) 'F'); expectLastCall().andReturn((byte) '>'); replayAll(); // call the method to test command.readResult(mockIn); assertEquals(command.getPercentage(), 100f); verifyAll(); } /** * Test for valid InputStream read, 58.4% * * @throws IOException */ @Test public void testSomeThrottlePositionValue() throws IOException { // mock InputStream read mockIn = createMock(InputStream.class); mockIn.read(); expectLastCall().andReturn((byte) '4'); expectLastCall().andReturn((byte) '1'); expectLastCall().andReturn((byte) ' '); expectLastCall().andReturn((byte) '1'); expectLastCall().andReturn((byte) '1'); expectLastCall().andReturn((byte) ' '); expectLastCall().andReturn((byte) '9'); expectLastCall().andReturn((byte) '5'); expectLastCall().andReturn((byte) '>'); replayAll(); // call the method to test command.readResult(mockIn); assertEquals(command.getPercentage(), 58.431374f); verifyAll(); } /** * Test for valid InputStream read, minimum value 0% * * @throws IOException */ @Test public void testMinThrottlePositionValue() throws IOException { // mock InputStream read mockIn = createMock(InputStream.class); mockIn.read(); expectLastCall().andReturn((byte) '4'); expectLastCall().andReturn((byte) '1'); expectLastCall().andReturn((byte) ' '); expectLastCall().andReturn((byte) '1'); expectLastCall().andReturn((byte) '1'); expectLastCall().andReturn((byte) ' '); expectLastCall().andReturn((byte) '0'); expectLastCall().andReturn((byte) '0'); expectLastCall().andReturn((byte) '>'); replayAll(); // call the method to test command.readResult(mockIn); assertEquals(command.getPercentage(), 0f); verifyAll(); } /** * Clear resources. */ @AfterClass public void tearDown() { command = null; mockIn = null; } }
apache-2.0
bluefoot/scripts
gunnarr/gunnarr-core/src/main/java/info/bluefoot/gunnarr/filteroptions/FilterOptionsUtils.java
592
package info.bluefoot.gunnarr.filteroptions; import java.io.File; import java.util.Collection; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.IOFileFilter; import org.apache.commons.io.filefilter.WildcardFileFilter; public class FilterOptionsUtils { public static Collection<File> getFilesBasedOnFilterOptions(File baseDir, FilterOptions options) { WildcardFileFilter fileFilter = new WildcardFileFilter(options.getWildCard()); IOFileFilter dirFilter = null; return FileUtils.listFiles(baseDir, fileFilter, dirFilter); } }
apache-2.0
jonvestal/open-kilda
src-java/nbworker-topology/nbworker-storm-topology/src/test/java/org/openkilda/wfm/topology/nbworker/services/FlowOperationsServiceTest.java
27866
/* Copyright 2020 Telstra Open Source * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openkilda.wfm.topology.nbworker.services; import static com.google.common.collect.Lists.newArrayList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.openkilda.messaging.command.flow.FlowRequest; import org.openkilda.messaging.info.InfoData; import org.openkilda.messaging.model.FlowPatch; import org.openkilda.messaging.model.PatchEndpoint; import org.openkilda.model.Flow; import org.openkilda.model.FlowEncapsulationType; import org.openkilda.model.FlowPath; import org.openkilda.model.FlowPathDirection; import org.openkilda.model.FlowStatus; import org.openkilda.model.PathComputationStrategy; import org.openkilda.model.PathId; import org.openkilda.model.PathSegment; import org.openkilda.model.Switch; import org.openkilda.model.SwitchId; import org.openkilda.model.SwitchStatus; import org.openkilda.model.cookie.FlowSegmentCookie; import org.openkilda.persistence.inmemory.InMemoryGraphBasedTest; import org.openkilda.persistence.repositories.FlowPathRepository; import org.openkilda.persistence.repositories.FlowRepository; import org.openkilda.persistence.repositories.PathSegmentRepository; import org.openkilda.persistence.repositories.SwitchRepository; import org.openkilda.wfm.error.FlowNotFoundException; import org.openkilda.wfm.error.SwitchNotFoundException; import org.openkilda.wfm.share.flow.TestFlowBuilder; import org.openkilda.wfm.topology.nbworker.bolts.FlowOperationsCarrier; import org.openkilda.wfm.topology.nbworker.services.FlowOperationsService.UpdateFlowResult; import org.junit.BeforeClass; import org.junit.Test; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.stream.Collectors; public class FlowOperationsServiceTest extends InMemoryGraphBasedTest { public static final String FLOW_ID_1 = "flow_1"; public static final String FLOW_ID_2 = "flow_2"; public static final String FLOW_ID_3 = "flow_3"; public static final PathId FORWARD_PATH_1 = new PathId("forward_path_1"); public static final PathId FORWARD_PATH_2 = new PathId("forward_path_2"); public static final PathId FORWARD_PATH_3 = new PathId("forward_path_3"); public static final PathId REVERSE_PATH_1 = new PathId("reverse_path_1"); public static final PathId REVERSE_PATH_2 = new PathId("reverse_path_2"); public static final PathId REVERSE_PATH_3 = new PathId("reverse_path_3"); public static final long UNMASKED_COOKIE = 123; public static final SwitchId SWITCH_ID_1 = new SwitchId(1); public static final SwitchId SWITCH_ID_2 = new SwitchId(2); public static final SwitchId SWITCH_ID_3 = new SwitchId(3); public static final SwitchId SWITCH_ID_4 = new SwitchId(4); private static FlowOperationsService flowOperationsService; private static FlowRepository flowRepository; private static FlowPathRepository flowPathRepository; private static PathSegmentRepository pathSegmentRepository; private static SwitchRepository switchRepository; @BeforeClass public static void setUpOnce() { flowRepository = persistenceManager.getRepositoryFactory().createFlowRepository(); flowPathRepository = persistenceManager.getRepositoryFactory().createFlowPathRepository(); pathSegmentRepository = persistenceManager.getRepositoryFactory().createPathSegmentRepository(); switchRepository = persistenceManager.getRepositoryFactory().createSwitchRepository(); flowOperationsService = new FlowOperationsService(persistenceManager.getRepositoryFactory(), persistenceManager.getTransactionManager()); } @Test public void shouldUpdateMaxLatencyPriorityAndPinnedFlowFields() throws FlowNotFoundException { String testFlowId = "flow_id"; Long maxLatency = 555L; Integer priority = 777; PathComputationStrategy pathComputationStrategy = PathComputationStrategy.LATENCY; String description = "new_description"; Flow flow = new TestFlowBuilder() .flowId(testFlowId) .srcSwitch(createSwitch(SWITCH_ID_1)) .srcPort(1) .srcVlan(10) .destSwitch(createSwitch(SWITCH_ID_2)) .destPort(2) .destVlan(11) .encapsulationType(FlowEncapsulationType.TRANSIT_VLAN) .pathComputationStrategy(PathComputationStrategy.COST) .description("description") .status(FlowStatus.UP) .build(); flowRepository.add(flow); FlowPatch receivedFlow = FlowPatch.builder() .flowId(testFlowId) .maxLatency(maxLatency) .priority(priority) .pinned(true) .targetPathComputationStrategy(pathComputationStrategy) .description("new_description") .build(); Flow updatedFlow = flowOperationsService.updateFlow(new FlowCarrierImpl(), receivedFlow); assertEquals(maxLatency, updatedFlow.getMaxLatency()); assertEquals(priority, updatedFlow.getPriority()); assertEquals(pathComputationStrategy, updatedFlow.getTargetPathComputationStrategy()); assertEquals(description, updatedFlow.getDescription()); assertTrue(updatedFlow.isPinned()); receivedFlow = FlowPatch.builder() .flowId(testFlowId) .build(); updatedFlow = flowOperationsService.updateFlow(new FlowCarrierImpl(), receivedFlow); assertEquals(maxLatency, updatedFlow.getMaxLatency()); assertEquals(priority, updatedFlow.getPriority()); assertEquals(pathComputationStrategy, updatedFlow.getTargetPathComputationStrategy()); assertEquals(description, updatedFlow.getDescription()); assertTrue(updatedFlow.isPinned()); } @Test public void shouldPrepareFlowUpdateResultWithChangedStrategy() { // given: FlowPatch with COST strategy and Flow with MAX_LATENCY strategy String flowId = "test_flow_id"; FlowPatch flowDto = FlowPatch.builder() .flowId(flowId) .maxLatency(100L) .pathComputationStrategy(PathComputationStrategy.COST) .build(); Flow flow = Flow.builder() .flowId(flowId) .srcSwitch(Switch.builder().switchId(new SwitchId(1)).build()) .destSwitch(Switch.builder().switchId(new SwitchId(2)).build()) .pathComputationStrategy(PathComputationStrategy.MAX_LATENCY) .build(); // when: compare this flows UpdateFlowResult result = flowOperationsService.prepareFlowUpdateResult(flowDto, flow).build(); // then: needUpdateFlow flag set to true assertTrue(result.isNeedUpdateFlow()); } @Test public void shouldPrepareFlowUpdateResultWithChangedMaxLatencyFirstCase() { // given: FlowPatch with max latency and no strategy and Flow with MAX_LATENCY strategy and no max latency String flowId = "test_flow_id"; FlowPatch flowDto = FlowPatch.builder() .flowId(flowId) .maxLatency(100L) .build(); Flow flow = Flow.builder() .flowId(flowId) .srcSwitch(Switch.builder().switchId(new SwitchId(1)).build()) .destSwitch(Switch.builder().switchId(new SwitchId(2)).build()) .pathComputationStrategy(PathComputationStrategy.MAX_LATENCY) .build(); // when: compare this flows UpdateFlowResult result = flowOperationsService.prepareFlowUpdateResult(flowDto, flow).build(); // then: needRerouteFlow flag set to true assertTrue(result.isNeedUpdateFlow()); } @Test public void shouldPrepareFlowUpdateResultWithChangedMaxLatencySecondCase() { // given: FlowPatch with max latency and MAX_LATENCY strategy // and Flow with MAX_LATENCY strategy and no max latency String flowId = "test_flow_id"; FlowPatch flowDto = FlowPatch.builder() .flowId(flowId) .maxLatency(100L) .pathComputationStrategy(PathComputationStrategy.MAX_LATENCY) .build(); Flow flow = Flow.builder() .flowId(flowId) .srcSwitch(Switch.builder().switchId(new SwitchId(1)).build()) .destSwitch(Switch.builder().switchId(new SwitchId(2)).build()) .pathComputationStrategy(PathComputationStrategy.MAX_LATENCY) .build(); // when: compare this flows UpdateFlowResult result = flowOperationsService.prepareFlowUpdateResult(flowDto, flow).build(); // then: needRerouteFlow flag set to true assertTrue(result.isNeedUpdateFlow()); } @Test public void shouldPrepareFlowUpdateResultShouldNotUpdateFirstCase() { // given: FlowPatch with max latency and MAX_LATENCY strategy // and Flow with MAX_LATENCY strategy and same max latency String flowId = "test_flow_id"; FlowPatch flowDto = FlowPatch.builder() .flowId(flowId) .maxLatency(100L) .pathComputationStrategy(PathComputationStrategy.MAX_LATENCY) .build(); Flow flow = Flow.builder() .flowId(flowId) .srcSwitch(Switch.builder().switchId(new SwitchId(1)).build()) .destSwitch(Switch.builder().switchId(new SwitchId(2)).build()) .maxLatency(100L) .pathComputationStrategy(PathComputationStrategy.MAX_LATENCY) .build(); // when: compare this flows UpdateFlowResult result = flowOperationsService.prepareFlowUpdateResult(flowDto, flow).build(); // then: needRerouteFlow flag set to false assertFalse(result.isNeedUpdateFlow()); } @Test public void shouldPrepareFlowUpdateResultShouldNotUpdateSecondCase() { // given: FlowPatch with no max latency and no strategy // and Flow with MAX_LATENCY strategy and max latency String flowId = "test_flow_id"; FlowPatch flowDto = FlowPatch.builder() .flowId(flowId) .build(); Flow flow = Flow.builder() .flowId(flowId) .srcSwitch(Switch.builder().switchId(new SwitchId(1)).build()) .destSwitch(Switch.builder().switchId(new SwitchId(2)).build()) .maxLatency(100L) .pathComputationStrategy(PathComputationStrategy.MAX_LATENCY) .build(); UpdateFlowResult result = flowOperationsService.prepareFlowUpdateResult(flowDto, flow).build(); assertFalse(result.isNeedUpdateFlow()); } @Test public void shouldPrepareFlowUpdateResultWithNeedUpdateFlag() { String flowId = "test_flow_id"; Flow flow = Flow.builder() .flowId(flowId) .srcSwitch(Switch.builder().switchId(new SwitchId(1)).build()) .srcPort(2) .srcVlan(3) .destSwitch(Switch.builder().switchId(new SwitchId(2)).build()) .destPort(4) .destVlan(5) .bandwidth(1000) .allocateProtectedPath(true) .encapsulationType(FlowEncapsulationType.TRANSIT_VLAN) .pathComputationStrategy(PathComputationStrategy.COST) .build(); // new src switch FlowPatch flowPatch = FlowPatch.builder() .source(PatchEndpoint.builder().switchId(new SwitchId(3)).build()) .build(); UpdateFlowResult result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); //new src port flowPatch = FlowPatch.builder().source(PatchEndpoint.builder().portNumber(9).build()).build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); // new src vlan flowPatch = FlowPatch.builder().source(PatchEndpoint.builder().vlanId(9).build()).build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); // new src inner vlan flowPatch = FlowPatch.builder().source(PatchEndpoint.builder().innerVlanId(9).build()).build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); // new src LLDP flag flowPatch = FlowPatch.builder().source(PatchEndpoint.builder().trackLldpConnectedDevices(true).build()).build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); // new src ARP flag flowPatch = FlowPatch.builder().source(PatchEndpoint.builder().trackArpConnectedDevices(true).build()).build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); // new dst switch flowPatch = FlowPatch.builder().destination(PatchEndpoint.builder().switchId(new SwitchId(3)).build()).build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); //new dst port flowPatch = FlowPatch.builder().destination(PatchEndpoint.builder().portNumber(9).build()).build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); // new dst vlan flowPatch = FlowPatch.builder().destination(PatchEndpoint.builder().vlanId(9).build()).build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); // new dst inner vlan flowPatch = FlowPatch.builder().destination(PatchEndpoint.builder().innerVlanId(9).build()).build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); // new dst LLDP flag flowPatch = FlowPatch.builder() .destination(PatchEndpoint.builder().trackLldpConnectedDevices(true).build()) .build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); // new dst ARP flag flowPatch = FlowPatch.builder() .destination(PatchEndpoint.builder().trackArpConnectedDevices(true).build()) .build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); // new maximum bandwidth flowPatch = FlowPatch.builder().bandwidth(9000L).build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); // new flag allocate protected path flowPatch = FlowPatch.builder().allocateProtectedPath(false).build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); // add diverse flow id flowPatch = FlowPatch.builder().diverseFlowId("diverse_flow_id").build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); // new ignore bandwidth flag flowPatch = FlowPatch.builder().ignoreBandwidth(true).build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); // new encapsulation type flowPatch = FlowPatch.builder().encapsulationType(FlowEncapsulationType.VXLAN).build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); // new path computation strategy flowPatch = FlowPatch.builder().pathComputationStrategy(PathComputationStrategy.LATENCY).build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); } @Test public void getFlowsForEndpointNotReturnFlowsForOrphanedPaths() throws SwitchNotFoundException { Switch switchA = createSwitch(SWITCH_ID_1); Switch switchB = createSwitch(SWITCH_ID_2); Switch switchC = createSwitch(SWITCH_ID_3); Switch switchD = createSwitch(SWITCH_ID_4); Flow flow = createFlow(FLOW_ID_1, switchA, 1, switchC, 2, FORWARD_PATH_1, REVERSE_PATH_1, switchB); createOrphanFlowPaths(flow, switchA, 1, switchC, 2, FORWARD_PATH_3, REVERSE_PATH_3, switchD); assertEquals(0, flowOperationsService.getFlowsForEndpoint(switchD.getSwitchId(), null).size()); } @Test public void getFlowsForEndpointOneSwitchFlowNoPortTest() throws SwitchNotFoundException { Switch switchA = createSwitch(SWITCH_ID_1); createFlow(FLOW_ID_1, switchA, 1, switchA, 2, FORWARD_PATH_1, REVERSE_PATH_1, null); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_1, null), FLOW_ID_1); createFlow(FLOW_ID_2, switchA, 3, switchA, 4, FORWARD_PATH_2, REVERSE_PATH_2, null); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_1, null), FLOW_ID_1, FLOW_ID_2); } @Test public void getFlowsForEndpointMultiSwitchFlowNoPortTest() throws SwitchNotFoundException { Switch switchA = createSwitch(SWITCH_ID_1); Switch switchB = createSwitch(SWITCH_ID_2); createFlow(FLOW_ID_1, switchA, 1, switchB, 2, FORWARD_PATH_1, REVERSE_PATH_1, null); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_1, null), FLOW_ID_1); createFlow(FLOW_ID_2, switchB, 3, switchA, 4, FORWARD_PATH_2, REVERSE_PATH_2, null); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_1, null), FLOW_ID_1, FLOW_ID_2); } @Test public void getFlowsForEndpointTransitSwitchFlowNoPortTest() throws SwitchNotFoundException { Switch switchA = createSwitch(SWITCH_ID_1); Switch switchB = createSwitch(SWITCH_ID_2); Switch switchC = createSwitch(SWITCH_ID_3); createFlow(FLOW_ID_1, switchA, 1, switchC, 2, FORWARD_PATH_1, REVERSE_PATH_1, switchB); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_2, null), FLOW_ID_1); createFlow(FLOW_ID_2, switchC, 3, switchA, 4, FORWARD_PATH_2, REVERSE_PATH_2, switchB); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_2, null), FLOW_ID_1, FLOW_ID_2); } @Test public void getFlowsForEndpointSeveralFlowNoPortTest() throws SwitchNotFoundException { Switch switchA = createSwitch(SWITCH_ID_1); Switch switchB = createSwitch(SWITCH_ID_2); Switch switchC = createSwitch(SWITCH_ID_3); // one switch flow createFlow(FLOW_ID_1, switchB, 1, switchB, 2, FORWARD_PATH_1, REVERSE_PATH_1, null); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_2, null), FLOW_ID_1); // two switches flow createFlow(FLOW_ID_2, switchA, 3, switchB, 4, FORWARD_PATH_2, REVERSE_PATH_2, null); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_2, null), FLOW_ID_1, FLOW_ID_2); // three switches flow createFlow(FLOW_ID_3, switchA, 5, switchC, 6, FORWARD_PATH_3, REVERSE_PATH_3, switchB); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_2, null), FLOW_ID_1, FLOW_ID_2, FLOW_ID_3); } @Test public void getFlowsForEndpointOneSwitchFlowWithPortTest() throws SwitchNotFoundException { Switch switchA = createSwitch(SWITCH_ID_1); createFlow(FLOW_ID_1, switchA, 1, switchA, 2, FORWARD_PATH_1, REVERSE_PATH_1, null); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_1, 1), FLOW_ID_1); // flow on different port createFlow(FLOW_ID_2, switchA, 3, switchA, 4, FORWARD_PATH_2, REVERSE_PATH_2, null); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_1, 1), FLOW_ID_1); } @Test public void getFlowsForEndpointMultiSwitchFlowWithPortTest() throws SwitchNotFoundException { Switch switchA = createSwitch(SWITCH_ID_1); Switch switchB = createSwitch(SWITCH_ID_2); createFlow(FLOW_ID_1, switchA, 1, switchB, 2, FORWARD_PATH_1, REVERSE_PATH_1, null); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_1, 1), FLOW_ID_1); createFlow(FLOW_ID_2, switchB, 3, switchA, 1, FORWARD_PATH_2, REVERSE_PATH_2, null); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_1, 1), FLOW_ID_1, FLOW_ID_2); } @Test public void getFlowsForEndpointTransitSwitchFlowWithPortTest() throws SwitchNotFoundException { Switch switchA = createSwitch(SWITCH_ID_1); Switch switchB = createSwitch(SWITCH_ID_2); Switch switchC = createSwitch(SWITCH_ID_3); createFlow(FLOW_ID_1, switchA, 1, switchC, 2, FORWARD_PATH_1, REVERSE_PATH_1, switchB); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_2, 2), FLOW_ID_1); createFlow(FLOW_ID_2, switchC, 2, switchA, 4, FORWARD_PATH_2, REVERSE_PATH_2, switchB); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_2, 2), FLOW_ID_1, FLOW_ID_2); } private void assertFlows(Collection<Flow> actualFlows, String... expectedFlowIds) { assertEquals(expectedFlowIds.length, actualFlows.size()); assertEquals(new HashSet<>(Arrays.asList(expectedFlowIds)), actualFlows.stream().map(Flow::getFlowId).collect(Collectors.toSet())); } private Switch createSwitch(SwitchId switchId) { Switch sw = Switch.builder().switchId(switchId).status(SwitchStatus.ACTIVE).build(); switchRepository.add(sw); return sw; } private void createOrphanFlowPaths(Flow flow, Switch srcSwitch, int srcPort, Switch dstSwitch, int dstPort, PathId forwardPartId, PathId reversePathId, Switch transitSwitch) { FlowPath forwardPath = FlowPath.builder() .pathId(forwardPartId) .srcSwitch(srcSwitch) .destSwitch(dstSwitch) .cookie(new FlowSegmentCookie(FlowPathDirection.FORWARD, UNMASKED_COOKIE)) .build(); FlowPath reversePath = FlowPath.builder() .pathId(reversePathId) .srcSwitch(dstSwitch) .destSwitch(srcSwitch) .cookie(new FlowSegmentCookie(FlowPathDirection.REVERSE, UNMASKED_COOKIE)) .build(); if (!srcSwitch.getSwitchId().equals(dstSwitch.getSwitchId())) { if (transitSwitch == null) { // direct paths between src and dst switches forwardPath.setSegments(newArrayList(createPathSegment(srcSwitch, srcPort, dstSwitch, dstPort))); reversePath.setSegments(newArrayList(createPathSegment(dstSwitch, dstPort, srcSwitch, srcPort))); } else { // src switch ==> transit switch ==> dst switch forwardPath.setSegments(newArrayList( createPathSegment(srcSwitch, srcPort, transitSwitch, srcPort), createPathSegment(transitSwitch, dstPort, dstSwitch, dstPort))); reversePath.setSegments(newArrayList( createPathSegment(dstSwitch, dstPort, transitSwitch, dstPort), createPathSegment(transitSwitch, srcPort, srcSwitch, srcPort))); } } flowPathRepository.add(forwardPath); flowPathRepository.add(reversePath); flow.addPaths(forwardPath, reversePath); } private Flow createFlow(String flowId, Switch srcSwitch, int srcPort, Switch dstSwitch, int dstPort, PathId forwardPartId, PathId reversePathId, Switch transitSwitch) { Flow flow = Flow.builder() .flowId(flowId) .srcSwitch(srcSwitch) .srcPort(srcPort) .destSwitch(dstSwitch) .destPort(dstPort) .status(FlowStatus.UP) .build(); FlowPath forwardPath = FlowPath.builder() .pathId(forwardPartId) .srcSwitch(srcSwitch) .destSwitch(dstSwitch) .cookie(new FlowSegmentCookie(FlowPathDirection.FORWARD, UNMASKED_COOKIE)) .build(); FlowPath reversePath = FlowPath.builder() .pathId(reversePathId) .srcSwitch(dstSwitch) .destSwitch(srcSwitch) .cookie(new FlowSegmentCookie(FlowPathDirection.REVERSE, UNMASKED_COOKIE)) .build(); if (!srcSwitch.getSwitchId().equals(dstSwitch.getSwitchId())) { if (transitSwitch == null) { // direct paths between src and dst switches forwardPath.setSegments(newArrayList(createPathSegment(srcSwitch, srcPort, dstSwitch, dstPort))); reversePath.setSegments(newArrayList(createPathSegment(dstSwitch, dstPort, srcSwitch, srcPort))); } else { // src switch ==> transit switch ==> dst switch forwardPath.setSegments(newArrayList( createPathSegment(srcSwitch, srcPort, transitSwitch, srcPort), createPathSegment(transitSwitch, dstPort, dstSwitch, dstPort))); reversePath.setSegments(newArrayList( createPathSegment(dstSwitch, dstPort, transitSwitch, dstPort), createPathSegment(transitSwitch, srcPort, srcSwitch, srcPort))); } } flow.setForwardPath(forwardPath); flow.setReversePath(reversePath); flowRepository.add(flow); return flow; } private PathSegment createPathSegment(Switch srcSwitch, int srcPort, Switch dstSwitch, int dstPort) { PathSegment pathSegment = PathSegment.builder() .srcSwitch(srcSwitch) .srcPort(srcPort) .destSwitch(dstSwitch) .destPort(dstPort) .build(); pathSegmentRepository.add(pathSegment); return pathSegment; } private class FlowCarrierImpl implements FlowOperationsCarrier { @Override public void emitPeriodicPingUpdate(String flowId, boolean enabled) { } @Override public void sendUpdateRequest(FlowRequest request) { } @Override public void sendNorthboundResponse(InfoData data) { } } }
apache-2.0
metaborg/jsglr
org.spoofax.jsglr2.benchmark/src/main/java/org/spoofax/jsglr2/benchmark/jsglr2/JSGLR2Java8BenchmarkParsingAndImploding.java
412
package org.spoofax.jsglr2.benchmark.jsglr2; import org.spoofax.jsglr2.benchmark.BenchmarkTestSetWithParseTableReader; import org.spoofax.jsglr2.testset.TestSet; public class JSGLR2Java8BenchmarkParsingAndImploding extends JSGLR2BenchmarkParsingAndImploding { public JSGLR2Java8BenchmarkParsingAndImploding() { setTestSetReader(new BenchmarkTestSetWithParseTableReader<>(TestSet.java8)); } }
apache-2.0
Sogrey/CTK
gen/com/sogrey/ctk/R.java
29305
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.sogrey.ctk; public final class R { public static final class anim { public static final int progress_round=0x7f040000; public static final int reverse_anim=0x7f040001; public static final int rotating=0x7f040002; } public static final class attr { /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int tcvBackground=0x7f010000; /** <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int tcvBorder=0x7f010002; /** <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int tcvBorderItem=0x7f010004; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int tcvCanTagClick=0x7f01000c; /** <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int tcvEndText=0x7f01000a; /** <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int tcvItemBorderHorizontal=0x7f010006; /** <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int tcvItemBorderVertical=0x7f010005; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int tcvRightResId=0x7f01000b; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int tcvShowEndText=0x7f010008; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int tcvShowRightImg=0x7f010009; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int tcvSingleLine=0x7f010007; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int tcvTagResId=0x7f01000d; /** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int tcvTextColor=0x7f010001; /** <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int tcvTextSize=0x7f010003; } public static final class color { public static final int bg_gray=0x7f050011; public static final int black_20=0x7f050012; public static final int btn_blue_bg_sel_f=0x7f050010; public static final int clr_progress_dialog_bg=0x7f050013; public static final int s_black=0x7f050001; public static final int s_blue=0x7f050008; public static final int s_dark_gray=0x7f05000c; public static final int s_dark_gray2=0x7f05000d; public static final int s_dark_green=0x7f050007; public static final int s_dark_red=0x7f050004; public static final int s_drak_black=0x7f050002; public static final int s_gray=0x7f05000b; public static final int s_green=0x7f050005; public static final int s_light_blue=0x7f05000f; public static final int s_light_gray=0x7f05000a; public static final int s_red=0x7f050003; public static final int s_spuer_light_gray=0x7f050009; public static final int s_transparent=0x7f05000e; public static final int s_white=0x7f050000; public static final int s_yellow=0x7f050006; } public static final class dimen { /** Default screen margins, per the Android Design guidelines. Example customization of dimensions originally defined in res/values/dimens.xml (such as screen margins) for screens with more than 820dp of available width. This would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). */ public static final int activity_horizontal_margin=0x7f060000; public static final int activity_vertical_margin=0x7f060001; public static final int frontsize_large=0x7f060004; public static final int frontsize_normal=0x7f060006; public static final int frontsize_small=0x7f060007; public static final int frontsize_ssSmall=0x7f060009; public static final int frontsize_sssSmall=0x7f06000a; public static final int frontsize_ssslarge=0x7f060002; public static final int frontsize_superlarge=0x7f060003; public static final int frontsize_supersmall=0x7f060008; public static final int frontsize_tinylarge=0x7f060005; public static final int historyscore_tb=0x7f06000b; } public static final class drawable { public static final int arrow_right=0x7f020000; public static final int bg_white2gray_selector_norect=0x7f020001; public static final int button_back_24px=0x7f020002; public static final int dialog_bg=0x7f020003; public static final int dialog_btn_center=0x7f020004; public static final int dialog_btn_center_pressed=0x7f020005; public static final int dialog_btn_center_selector=0x7f020006; public static final int dialog_btn_left=0x7f020007; public static final int dialog_btn_left_pressed=0x7f020008; public static final int dialog_btn_left_selector=0x7f020009; public static final int dialog_btn_right=0x7f02000a; public static final int dialog_btn_right_pressed=0x7f02000b; public static final int dialog_btn_right_selector=0x7f02000c; public static final int ic_launcher=0x7f02000d; public static final int load_failed=0x7f02000e; public static final int load_succeed=0x7f02000f; public static final int loading=0x7f020010; public static final int pic_empty=0x7f020011; public static final int pic_err=0x7f020012; public static final int progress_01=0x7f020013; public static final int progress_02=0x7f020014; public static final int progress_03=0x7f020015; public static final int progress_04=0x7f020016; public static final int progress_05=0x7f020017; public static final int progress_06=0x7f020018; public static final int progress_07=0x7f020019; public static final int progress_08=0x7f02001a; public static final int progress_09=0x7f02001b; public static final int progress_10=0x7f02001c; public static final int progress_11=0x7f02001d; public static final int progress_12=0x7f02001e; public static final int pull_icon_big=0x7f02001f; public static final int pullup_icon_big=0x7f020020; public static final int refresh_failed=0x7f020021; public static final int refresh_succeed=0x7f020022; public static final int refreshing=0x7f020023; public static final int tag_background=0x7f020024; } public static final class id { public static final int btn_dialog_cancle=0x7f09000d; public static final int btn_dialog_ignore=0x7f09000f; public static final int btn_dialog_ok=0x7f090011; public static final int content_view=0x7f090006; public static final int head_view=0x7f09001f; public static final int id_tv_loadingmsg=0x7f090008; public static final int image=0x7f090002; public static final int img_imagepre_back=0x7f090001; public static final int indicator=0x7f090003; public static final int layout=0x7f090009; public static final int loading=0x7f090004; public static final int loadingImageView=0x7f090007; public static final int loading_icon=0x7f090015; public static final int loadmore_view=0x7f090013; public static final int loadstate_iv=0x7f090017; public static final int loadstate_tv=0x7f090016; public static final int lyt_dialog_content=0x7f09000c; public static final int lyt_dialog_title_line=0x7f09000b; public static final int lyt_lyt_pop_dialog_content=0x7f09001a; public static final int lyt_pop_dialog_root=0x7f090018; public static final int pager=0x7f090000; public static final int pull_icon=0x7f090020; public static final int pullup_icon=0x7f090014; public static final int refresh_view=0x7f090005; public static final int refreshing_icon=0x7f090021; public static final int state_iv=0x7f090023; public static final int state_tv=0x7f090022; public static final int tag=0x7f090012; public static final int txt_dialog_title=0x7f09000a; public static final int txt_lyt_pop_dialog_cancle=0x7f09001c; public static final int txt_lyt_pop_dialog_content=0x7f09001b; public static final int txt_lyt_pop_dialog_ok=0x7f09001e; public static final int txt_lyt_pop_dialog_title=0x7f090019; public static final int v_lyt_pop_dialog_cancle=0x7f09001d; public static final int view_dialog_cancle=0x7f09000e; public static final int view_dialog_ignore=0x7f090010; } public static final class layout { public static final int act_photoexpolor=0x7f030000; public static final int act_photoexpolor_pager_item=0x7f030001; public static final int activity_main=0x7f030002; public static final int common_pulltorefresh_listview=0x7f030003; public static final int customprogressdialog=0x7f030004; public static final int dialog_utils_lyt=0x7f030005; public static final int item_tag=0x7f030006; public static final int load_more=0x7f030007; public static final int lyt_pop_dialog=0x7f030008; public static final int refresh_head=0x7f030009; } public static final class string { public static final int action_settings=0x7f070002; public static final int app_name=0x7f070000; /** pullToRefresh */ public static final int head=0x7f070004; public static final int hello_world=0x7f070001; public static final int load_fail=0x7f07000e; public static final int load_succeed=0x7f07000d; public static final int loading=0x7f07000c; public static final int pull_to_refresh=0x7f070005; public static final int pullup_to_load=0x7f07000a; public static final int refresh_fail=0x7f070009; public static final int refresh_succeed=0x7f070008; public static final int refreshing=0x7f070007; public static final int release_to_load=0x7f07000b; public static final int release_to_refresh=0x7f070006; /** ImageView page */ public static final int viewpager_indicator=0x7f070003; } public static final class style { /** Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vXX/styles.xml on newer devices. Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. */ public static final int AppBaseTheme=0x7f080000; /** Application theme. */ public static final int AppTheme=0x7f080001; /** 圆角对话框 */ public static final int CircularDialog=0x7f080002; /** 等待对话框(全屏) */ public static final int CustomDialog=0x7f080003; public static final int CustomProgressDialog=0x7f080004; public static final int Transparent=0x7f080005; } public static final class styleable { /** Attributes that can be used with a TagCloudView. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #TagCloudView_tcvBackground com.sogrey.ctk:tcvBackground}</code></td><td></td></tr> <tr><td><code>{@link #TagCloudView_tcvBorder com.sogrey.ctk:tcvBorder}</code></td><td></td></tr> <tr><td><code>{@link #TagCloudView_tcvBorderItem com.sogrey.ctk:tcvBorderItem}</code></td><td></td></tr> <tr><td><code>{@link #TagCloudView_tcvCanTagClick com.sogrey.ctk:tcvCanTagClick}</code></td><td></td></tr> <tr><td><code>{@link #TagCloudView_tcvEndText com.sogrey.ctk:tcvEndText}</code></td><td></td></tr> <tr><td><code>{@link #TagCloudView_tcvItemBorderHorizontal com.sogrey.ctk:tcvItemBorderHorizontal}</code></td><td></td></tr> <tr><td><code>{@link #TagCloudView_tcvItemBorderVertical com.sogrey.ctk:tcvItemBorderVertical}</code></td><td></td></tr> <tr><td><code>{@link #TagCloudView_tcvRightResId com.sogrey.ctk:tcvRightResId}</code></td><td></td></tr> <tr><td><code>{@link #TagCloudView_tcvShowEndText com.sogrey.ctk:tcvShowEndText}</code></td><td></td></tr> <tr><td><code>{@link #TagCloudView_tcvShowRightImg com.sogrey.ctk:tcvShowRightImg}</code></td><td></td></tr> <tr><td><code>{@link #TagCloudView_tcvSingleLine com.sogrey.ctk:tcvSingleLine}</code></td><td></td></tr> <tr><td><code>{@link #TagCloudView_tcvTagResId com.sogrey.ctk:tcvTagResId}</code></td><td></td></tr> <tr><td><code>{@link #TagCloudView_tcvTextColor com.sogrey.ctk:tcvTextColor}</code></td><td></td></tr> <tr><td><code>{@link #TagCloudView_tcvTextSize com.sogrey.ctk:tcvTextSize}</code></td><td></td></tr> </table> @see #TagCloudView_tcvBackground @see #TagCloudView_tcvBorder @see #TagCloudView_tcvBorderItem @see #TagCloudView_tcvCanTagClick @see #TagCloudView_tcvEndText @see #TagCloudView_tcvItemBorderHorizontal @see #TagCloudView_tcvItemBorderVertical @see #TagCloudView_tcvRightResId @see #TagCloudView_tcvShowEndText @see #TagCloudView_tcvShowRightImg @see #TagCloudView_tcvSingleLine @see #TagCloudView_tcvTagResId @see #TagCloudView_tcvTextColor @see #TagCloudView_tcvTextSize */ public static final int[] TagCloudView = { 0x7f010000, 0x7f010001, 0x7f010002, 0x7f010003, 0x7f010004, 0x7f010005, 0x7f010006, 0x7f010007, 0x7f010008, 0x7f010009, 0x7f01000a, 0x7f01000b, 0x7f01000c, 0x7f01000d }; /** <p>This symbol is the offset where the {@link com.sogrey.ctk.R.attr#tcvBackground} attribute's value can be found in the {@link #TagCloudView} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.sogrey.ctk:tcvBackground */ public static final int TagCloudView_tcvBackground = 0; /** <p>This symbol is the offset where the {@link com.sogrey.ctk.R.attr#tcvBorder} attribute's value can be found in the {@link #TagCloudView} array. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.sogrey.ctk:tcvBorder */ public static final int TagCloudView_tcvBorder = 2; /** <p>This symbol is the offset where the {@link com.sogrey.ctk.R.attr#tcvBorderItem} attribute's value can be found in the {@link #TagCloudView} array. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.sogrey.ctk:tcvBorderItem */ public static final int TagCloudView_tcvBorderItem = 4; /** <p>This symbol is the offset where the {@link com.sogrey.ctk.R.attr#tcvCanTagClick} attribute's value can be found in the {@link #TagCloudView} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.sogrey.ctk:tcvCanTagClick */ public static final int TagCloudView_tcvCanTagClick = 12; /** <p>This symbol is the offset where the {@link com.sogrey.ctk.R.attr#tcvEndText} attribute's value can be found in the {@link #TagCloudView} array. <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.sogrey.ctk:tcvEndText */ public static final int TagCloudView_tcvEndText = 10; /** <p>This symbol is the offset where the {@link com.sogrey.ctk.R.attr#tcvItemBorderHorizontal} attribute's value can be found in the {@link #TagCloudView} array. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.sogrey.ctk:tcvItemBorderHorizontal */ public static final int TagCloudView_tcvItemBorderHorizontal = 6; /** <p>This symbol is the offset where the {@link com.sogrey.ctk.R.attr#tcvItemBorderVertical} attribute's value can be found in the {@link #TagCloudView} array. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.sogrey.ctk:tcvItemBorderVertical */ public static final int TagCloudView_tcvItemBorderVertical = 5; /** <p>This symbol is the offset where the {@link com.sogrey.ctk.R.attr#tcvRightResId} attribute's value can be found in the {@link #TagCloudView} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.sogrey.ctk:tcvRightResId */ public static final int TagCloudView_tcvRightResId = 11; /** <p>This symbol is the offset where the {@link com.sogrey.ctk.R.attr#tcvShowEndText} attribute's value can be found in the {@link #TagCloudView} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.sogrey.ctk:tcvShowEndText */ public static final int TagCloudView_tcvShowEndText = 8; /** <p>This symbol is the offset where the {@link com.sogrey.ctk.R.attr#tcvShowRightImg} attribute's value can be found in the {@link #TagCloudView} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.sogrey.ctk:tcvShowRightImg */ public static final int TagCloudView_tcvShowRightImg = 9; /** <p>This symbol is the offset where the {@link com.sogrey.ctk.R.attr#tcvSingleLine} attribute's value can be found in the {@link #TagCloudView} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.sogrey.ctk:tcvSingleLine */ public static final int TagCloudView_tcvSingleLine = 7; /** <p>This symbol is the offset where the {@link com.sogrey.ctk.R.attr#tcvTagResId} attribute's value can be found in the {@link #TagCloudView} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.sogrey.ctk:tcvTagResId */ public static final int TagCloudView_tcvTagResId = 13; /** <p>This symbol is the offset where the {@link com.sogrey.ctk.R.attr#tcvTextColor} attribute's value can be found in the {@link #TagCloudView} array. <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.sogrey.ctk:tcvTextColor */ public static final int TagCloudView_tcvTextColor = 1; /** <p>This symbol is the offset where the {@link com.sogrey.ctk.R.attr#tcvTextSize} attribute's value can be found in the {@link #TagCloudView} array. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.sogrey.ctk:tcvTextSize */ public static final int TagCloudView_tcvTextSize = 3; }; }
apache-2.0
alonerocky/PicasaPlus
app/src/main/java/com/google/api/client/util/ArrayMap.java
11840
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.util; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; /** * Memory-efficient map of keys to values with list-style random-access * semantics. * <p> * Conceptually, the keys and values are stored in a simpler array in order to * minimize memory use and provide for fast access to a key/value at a certain * index (for example {@link #getKey(int)}). However, traditional mapping * operations like {@link #get(Object)} and {@link #put(Object, Object)} are * slower because they need to look up all key/value pairs in the worst case. * * @since 2.2 * @author Yaniv Inbar */ public final class ArrayMap<K, V> extends AbstractMap<K, V> implements Cloneable { private int size; private Object[] data; private EntrySet entrySet; /** * Returns a new instance of an array map with initial capacity of zero. * Equivalent to calling the default constructor, except without the need to * specify the type parameters. For example: {@code ArrayMap<String, String> * map = ArrayMap.create();}. */ public static <K, V> ArrayMap<K, V> create() { return new ArrayMap<K, V>(); } /** * Returns a new instance of an array map of the given initial capacity. For * example: {@code ArrayMap<String, String> map = ArrayMap.create(8);}. */ public static <K, V> ArrayMap<K, V> create(int initialCapacity) { ArrayMap<K, V> result = create(); result.ensureCapacity(initialCapacity); return result; } /** * Returns a new instance of an array map of the given key value pairs in * alternating order. For example: {@code ArrayMap<String, String> map = * ArrayMap.of("key1", "value1", "key2", "value2", ...);}. * <p> * WARNING: there is no compile-time checking of the {@code keyValuePairs} * parameter to ensure that the keys or values have the correct type, so if * the wrong type is passed in, any problems will occur at runtime. Also, * there is no checking that the keys are unique, which the caller must ensure * is true. */ public static <K, V> ArrayMap<K, V> of(Object... keyValuePairs) { ArrayMap<K, V> result = create(1); int length = keyValuePairs.length; if (1 == (length % 2)) { throw new IllegalArgumentException("missing value for last key: " + keyValuePairs[length - 1]); } result.size = keyValuePairs.length / 2; Object[] data = result.data = new Object[length]; System.arraycopy(keyValuePairs, 0, data, 0, length); return result; } /** Returns the number of key-value pairs set. */ @Override public int size() { return this.size; } /** Returns the key at the given index or {@code null} if out of bounds. */ public K getKey(int index) { if (index < 0 || index >= this.size) { return null; } @SuppressWarnings("unchecked") K result = (K) this.data[index << 1]; return result; } /** Returns the value at the given index or {@code null} if out of bounds. */ public V getValue(int index) { if (index < 0 || index >= this.size) { return null; } return valueAtDataIndex(1 + (index << 1)); } /** * Sets the key/value mapping at the given index, overriding any existing * key/value mapping. * <p> * There is no checking done to ensure that the key does not already exist. * Therefore, this method is dangerous to call unless the caller can be * certain the key does not already exist in the map. * * @return previous value or {@code null} for none * @throws IndexOutOfBoundsException if index is negative */ public V set(int index, K key, V value) { if (index < 0) { throw new IndexOutOfBoundsException(); } int minSize = index + 1; ensureCapacity(minSize); int dataIndex = index << 1; V result = valueAtDataIndex(dataIndex + 1); setData(dataIndex, key, value); if (minSize > this.size) { this.size = minSize; } return result; } /** * Sets the value at the given index, overriding any existing value mapping. * * @return previous value or {@code null} for none * @throws IndexOutOfBoundsException if index is negative or {@code >=} size */ public V set(int index, V value) { int size = this.size; if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(); } int valueDataIndex = 1 + (index << 1); V result = valueAtDataIndex(valueDataIndex); this.data[valueDataIndex] = value; return result; } /** * Adds the key/value mapping at the end of the list. Behaves identically to * {@code set(size(), key, value)}. * * @throws IndexOutOfBoundsException if index is negative */ public void add(K key, V value) { set(this.size, key, value); } /** * Removes the key/value mapping at the given index, or ignored if the index * is out of bounds. * * @return previous value or {@code null} for none */ public V remove(int index) { return removeFromDataIndexOfKey(index << 1); } /** Returns whether there is a mapping for the given key. */ @Override public boolean containsKey(Object key) { return -2 != getDataIndexOfKey(key); } /** Returns the index of the given key or {@code -1} if there is no such key. */ public int getIndexOfKey(K key) { return getDataIndexOfKey(key) >> 1; } /** * Returns the value set for the given key or {@code null} if there is no such * mapping or if the mapping value is {@code null}. */ @Override public V get(Object key) { return valueAtDataIndex(getDataIndexOfKey(key) + 1); } /** * Sets the value for the given key, overriding any existing value. * * @return previous value or {@code null} for none */ @Override public V put(K key, V value) { int index = getIndexOfKey(key); if (index == -1) { index = this.size; } return set(index, key, value); } /** * Removes the key-value pair of the given key, or ignore if the key cannot be * found. * * @return previous value or {@code null} for none */ @Override public V remove(Object key) { return removeFromDataIndexOfKey(getDataIndexOfKey(key)); } /** Trims the internal array storage to minimize memory usage. */ public void trim() { setDataCapacity(this.size << 1); } /** * Ensures that the capacity of the internal arrays is at least a given * capacity. */ public void ensureCapacity(int minCapacity) { Object[] data = this.data; int minDataCapacity = minCapacity << 1; int oldDataCapacity = data == null ? 0 : data.length; if (minDataCapacity > oldDataCapacity) { int newDataCapacity = oldDataCapacity / 2 * 3 + 1; if (newDataCapacity % 2 == 1) { newDataCapacity++; } if (newDataCapacity < minDataCapacity) { newDataCapacity = minDataCapacity; } setDataCapacity(newDataCapacity); } } private void setDataCapacity(int newDataCapacity) { if (newDataCapacity == 0) { this.data = null; return; } int size = this.size; Object[] oldData = this.data; if (size == 0 || newDataCapacity != oldData.length) { Object[] newData = this.data = new Object[newDataCapacity]; if (size != 0) { System.arraycopy(oldData, 0, newData, 0, size << 1); } } } private void setData(int dataIndexOfKey, K key, V value) { Object[] data = this.data; data[dataIndexOfKey] = key; data[dataIndexOfKey + 1] = value; } private V valueAtDataIndex(int dataIndex) { if (dataIndex < 0) { return null; } @SuppressWarnings("unchecked") V result = (V) this.data[dataIndex]; return result; } /** * Returns the data index of the given key or {@code -2} if there is no such * key. */ private int getDataIndexOfKey(Object key) { int dataSize = this.size << 1; Object[] data = this.data; for (int i = 0; i < dataSize; i += 2) { Object k = data[i]; if (key == null ? k == null : key.equals(k)) { return i; } } return -2; } /** * Removes the key/value mapping at the given data index of key, or ignored if * the index is out of bounds. */ private V removeFromDataIndexOfKey(int dataIndexOfKey) { int dataSize = this.size << 1; if (dataIndexOfKey < 0 || dataIndexOfKey >= dataSize) { return null; } V result = valueAtDataIndex(dataIndexOfKey + 1); Object[] data = this.data; int moved = dataSize - dataIndexOfKey - 2; if (moved != 0) { System.arraycopy(data, dataIndexOfKey + 2, data, dataIndexOfKey, moved); } this.size--; setData(dataSize - 2, null, null); return result; } @Override public void clear() { this.size = 0; this.data = null; } @Override public boolean containsValue(Object value) { int dataSize = this.size << 1; Object[] data = this.data; for (int i = 1; i < dataSize; i += 2) { Object v = data[i]; if (value == null ? v == null : value.equals(v)) { return true; } } return false; } @Override public Set<Map.Entry<K, V>> entrySet() { EntrySet entrySet = this.entrySet; if (entrySet == null) { entrySet = this.entrySet = new EntrySet(); } return entrySet; } @Override public ArrayMap<K, V> clone() { try { @SuppressWarnings("unchecked") ArrayMap<K, V> result = (ArrayMap<K, V>) super.clone(); Object[] data = this.data; if (data != null) { int length = data.length; Object[] resultData = result.data = new Object[length]; System.arraycopy(data, 0, resultData, 0, length); } return result; } catch (CloneNotSupportedException e) { // won't happen return null; } } final class EntrySet extends AbstractSet<Map.Entry<K, V>> { @Override public Iterator<Map.Entry<K, V>> iterator() { return new EntryIterator(); } @Override public int size() { return ArrayMap.this.size; } } final class EntryIterator implements Iterator<Map.Entry<K, V>> { private boolean removed; private int nextIndex; public boolean hasNext() { return this.nextIndex < ArrayMap.this.size; } public Map.Entry<K, V> next() { int index = this.nextIndex; if (index == ArrayMap.this.size) { throw new NoSuchElementException(); } this.nextIndex++; return new Entry(index); } public void remove() { int index = this.nextIndex - 1; if (this.removed || index < 0) { throw new IllegalArgumentException(); } ArrayMap.this.remove(index); this.removed = true; } } final class Entry implements Map.Entry<K, V> { private int index; Entry(int index) { this.index = index; } public K getKey() { return ArrayMap.this.getKey(this.index); } public V getValue() { return ArrayMap.this.getValue(this.index); } public V setValue(V value) { return ArrayMap.this.set(this.index, value); } } }
apache-2.0
js0p/EthBadge
app/src/main/java/org/web3j/utils/Numeric.java
5168
package org.web3j.utils; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; /** * <p>Message codec functions.</p> * * <p>Implementation as per https://github.com/ethereum/wiki/wiki/JSON-RPC#hex-value-encoding</p> */ public final class Numeric { private static final String HEX_PREFIX = "0x"; private Numeric() { } public static String encodeQuantity(BigInteger value) { if (value.signum() != -1) { return HEX_PREFIX + value.toString(16); } else { //throw new MessageDecodingException("Negative values are not supported"); return null; } } public static BigInteger decodeQuantity(String value) { if (!isValidHexQuantity(value)) { //throw new MessageDecodingException("Value must be in format 0x[1-9]+[0-9]* or 0x0"); return null; } try { return new BigInteger(value.substring(2), 16); } catch (NumberFormatException e) { //throw new MessageDecodingException("Negative ", e); return null; } } private static boolean isValidHexQuantity(String value) { if (value == null) { return false; } if (value.length() < 3) { return false; } if (!value.startsWith(HEX_PREFIX)) { return false; } if (value.length() > 3 && value.charAt(2) == '0') { return false; } return true; } public static String cleanHexPrefix(String input) { if (containsHexPrefix(input)) { return input.substring(2); } else { return input; } } public static String prependHexPrefix(String input) { if (!containsHexPrefix(input)) { return HEX_PREFIX + input; } else { return input; } } public static boolean containsHexPrefix(String input) { return input.length() > 1 && input.charAt(0) == '0' && input.charAt(1) == 'x'; } public static BigInteger toBigInt(byte[] value, int offset, int length) { return toBigInt((Arrays.copyOfRange(value, offset, offset + length))); } public static BigInteger toBigInt(byte[] value) { return new BigInteger(1, value); } public static BigInteger toBigInt(String hexValue) { String cleanValue = cleanHexPrefix(hexValue); return new BigInteger(cleanValue, 16); } public static String toHexStringWithPrefix(BigInteger value) { return HEX_PREFIX + value.toString(16); } public static String toHexStringNoPrefix(BigInteger value) { return value.toString(16); } public static byte[] toBytesPadded(BigInteger value, int length) { byte[] result = new byte[length]; byte[] bytes = value.toByteArray(); int bytesLength; int srcOffset; if (bytes[0] == 0) { bytesLength = bytes.length - 1; srcOffset = 1; } else { bytesLength = bytes.length; srcOffset = 0; } if (bytesLength > length) { throw new RuntimeException("Input is too large to put in byte array of size " + length); } int destOffset = length - bytesLength; System.arraycopy(bytes, srcOffset, result, destOffset, bytesLength); return result; } public static byte[] hexStringToByteArray(String input) { String cleanInput = cleanHexPrefix(input); int len = cleanInput.length(); if (len == 0) { return new byte[] {}; } byte[] data; int startIdx; if (len % 2 != 0) { data = new byte[(len / 2) + 1]; data[0] = (byte) Character.digit(cleanInput.charAt(0), 16); startIdx = 1; } else { data = new byte[len / 2]; startIdx = 0; } for (int i = startIdx; i < len; i += 2) { data[(i + 1) / 2] = (byte) ((Character.digit(cleanInput.charAt(i), 16) << 4) + Character.digit(cleanInput.charAt(i+1), 16)); } return data; } public static String toHexString(byte[] input, int offset, int length, boolean withPrefix) { StringBuilder stringBuilder = new StringBuilder(); if (withPrefix) { stringBuilder.append("0x"); } for (int i = offset; i < offset + length; i++) { stringBuilder.append(String.format("%02x", input[i] & 0xFF)); } return stringBuilder.toString(); } public static String toHexStringNoPrefix(byte[] input) { return toHexString(input, 0, input.length, false); } public static String toHexString(byte[] input) { return toHexString(input, 0, input.length, true); } public static byte b(int m, int n) { return (byte) ( (m << 4) | n); } public static boolean isIntegerValue(BigDecimal value) { return value.signum() == 0 || value.scale() <= 0 || value.stripTrailingZeros().scale() <= 0; } }
apache-2.0
ITVlab/neodash
module-muzei/src/main/java/com/google/android/apps/muzei/settings/SettingsAdvancedFragment.java
8645
/* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.muzei.settings; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.SeekBar; import com.google.android.apps.muzei.NewWallpaperNotificationReceiver; import com.google.android.apps.muzei.render.MuzeiBlurRenderer; import net.nurik.roman.muzei.R; /** * Fragment for allowing the user to configure advanced settings. */ public class SettingsAdvancedFragment extends Fragment implements SettingsActivity.SettingsActivityMenuListener { private Handler mHandler = new Handler(); private SeekBar mBlurSeekBar; private SeekBar mDimSeekBar; private SeekBar mGreySeekBar; private View.OnFocusChangeListener mFocusChangeListener = new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { /*if (hasFocus) { v.setBackgroundColor(getResources().getColor(R.color.featuredart_color)); } else { v.setBackgroundColor(getResources().getColor(android.R.color.white)); }*/ } }; public SettingsAdvancedFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.settings_advanced_fragment, container, false); mBlurSeekBar = (SeekBar) rootView.findViewById(R.id.blur_amount); mBlurSeekBar.setProgress(Prefs.getSharedPreferences(getContext()) .getInt(Prefs.PREF_BLUR_AMOUNT, MuzeiBlurRenderer.DEFAULT_BLUR)); mBlurSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int value, boolean fromUser) { if (fromUser) { mHandler.removeCallbacks(mUpdateBlurRunnable); mHandler.postDelayed(mUpdateBlurRunnable, 750); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); mBlurSeekBar.setOnFocusChangeListener(mFocusChangeListener); mDimSeekBar = (SeekBar) rootView.findViewById(R.id.dim_amount); mDimSeekBar.setProgress(Prefs.getSharedPreferences(getContext()) .getInt(Prefs.PREF_DIM_AMOUNT, MuzeiBlurRenderer.DEFAULT_MAX_DIM)); mDimSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int value, boolean fromUser) { if (fromUser) { mHandler.removeCallbacks(mUpdateDimRunnable); mHandler.postDelayed(mUpdateDimRunnable, 750); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); mDimSeekBar.setOnFocusChangeListener(mFocusChangeListener); mGreySeekBar = (SeekBar) rootView.findViewById(R.id.grey_amount); mGreySeekBar.setProgress(Prefs.getSharedPreferences(getContext()) .getInt(Prefs.PREF_GREY_AMOUNT, MuzeiBlurRenderer.DEFAULT_GREY)); mGreySeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int value, boolean fromUser) { if (fromUser) { mHandler.removeCallbacks(mUpdateGreyRunnable); mHandler.postDelayed(mUpdateGreyRunnable, 750); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); mGreySeekBar.setOnFocusChangeListener(mFocusChangeListener); CheckBox mNotifyNewWallpaperCheckBox = (CheckBox) rootView.findViewById( R.id.notify_new_wallpaper_checkbox); mNotifyNewWallpaperCheckBox.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton button, boolean checked) { PreferenceManager.getDefaultSharedPreferences(getContext()).edit() .putBoolean(NewWallpaperNotificationReceiver.PREF_ENABLED, checked) .apply(); } }); mNotifyNewWallpaperCheckBox.setChecked(PreferenceManager.getDefaultSharedPreferences(getContext()) .getBoolean(NewWallpaperNotificationReceiver.PREF_ENABLED, true)); CheckBox mBlurOnLockScreenCheckBox = (CheckBox) rootView.findViewById( R.id.blur_on_lockscreen_checkbox); mBlurOnLockScreenCheckBox.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton button, boolean checked) { Prefs.getSharedPreferences(getContext()).edit() .putBoolean(Prefs.PREF_DISABLE_BLUR_WHEN_LOCKED, !checked) .apply(); } } ); mBlurOnLockScreenCheckBox.setChecked(!Prefs.getSharedPreferences(getContext()) .getBoolean(Prefs.PREF_DISABLE_BLUR_WHEN_LOCKED, false)); return rootView; } @Override public void onAttach(Activity activity) { if (activity instanceof SettingsActivity) { ((SettingsActivity) activity).inflateMenuFromFragment(R.menu.settings_advanced); } super.onAttach(activity); } @Override public void onDestroy() { super.onDestroy(); mHandler.removeCallbacksAndMessages(null); } private Runnable mUpdateBlurRunnable = new Runnable() { @Override public void run() { Prefs.getSharedPreferences(getContext()).edit() .putInt(Prefs.PREF_BLUR_AMOUNT, mBlurSeekBar.getProgress()) .apply(); } }; private Runnable mUpdateDimRunnable = new Runnable() { @Override public void run() { Prefs.getSharedPreferences(getContext()).edit() .putInt(Prefs.PREF_DIM_AMOUNT, mDimSeekBar.getProgress()) .apply(); } }; private Runnable mUpdateGreyRunnable = new Runnable() { @Override public void run() { Prefs.getSharedPreferences(getContext()).edit() .putInt(Prefs.PREF_GREY_AMOUNT, mGreySeekBar.getProgress()) .apply(); } }; @Override public void onSettingsActivityMenuItemClick(MenuItem item) { if (item.getItemId() == R.id.action_reset_defaults) { Prefs.getSharedPreferences(getContext()).edit() .putInt(Prefs.PREF_BLUR_AMOUNT, MuzeiBlurRenderer.DEFAULT_BLUR) .putInt(Prefs.PREF_DIM_AMOUNT, MuzeiBlurRenderer.DEFAULT_MAX_DIM) .putInt(Prefs.PREF_GREY_AMOUNT, MuzeiBlurRenderer.DEFAULT_GREY) .apply(); mBlurSeekBar.setProgress(MuzeiBlurRenderer.DEFAULT_BLUR); mDimSeekBar.setProgress(MuzeiBlurRenderer.DEFAULT_MAX_DIM); mGreySeekBar.setProgress(MuzeiBlurRenderer.DEFAULT_GREY); } } }
apache-2.0
minibhati93/android-sqlite-implementation
src/com/example/lessons/DeviceList.java
11157
package com.example.lessons; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Iterator; import java.util.Set; import android.annotation.SuppressLint; import android.app.ActionBar; import android.app.AlertDialog; import android.app.ProgressDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.os.ParcelUuid; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; @SuppressLint("NewApi") public class DeviceList extends ActionBarActivity{ private ProgressDialog mProgressDlg; private ArrayList<BluetoothDevice> mDeviceList = new ArrayList<BluetoothDevice>(); private ArrayList<BluetoothDevice> mpairedList = new ArrayList<BluetoothDevice>(); private BluetoothAdapter mBluetoothAdapter; private ListView lv; private ArrayAdapter<String> mArrayAdapter ; private OutputStream outputStream; private InputStream inStream; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActionBar bar = getActionBar(); bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#33cc5c"))); setContentView(R.layout.list_devices); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); mProgressDlg = new ProgressDialog(this); mProgressDlg.setMessage("Scanning..."); mProgressDlg.setCancelable(false); mProgressDlg.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); mBluetoothAdapter.cancelDiscovery(); } }); Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); ArrayList<String> list1 = new ArrayList<String>(); // If there are paired devices if (pairedDevices.size() > 0) { // Loop through paired devices for (BluetoothDevice device : pairedDevices) { // Add the name and address to an array adapter to show in a ListView Log.d("Main", "paired device: "+device.getName()); list1.add(device.getName()); if(!mpairedList.contains(device)){ mpairedList.add(device); } } lv =(ListView)findViewById(R.id.devices); mArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list1); lv.setAdapter(mArrayAdapter); lv.setOnItemLongClickListener(new OnItemLongClickListener(){ @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { final BluetoothDevice device = mpairedList.get(position); ListView t1=showAlert(); t1.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub unpairDevice(device); } }); return false; } }); lv.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub BluetoothDevice device = mpairedList.get(position); ParcelUuid[] uuids = device.getUuids(); try { BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid()); socket.connect(); outputStream = socket.getOutputStream(); inStream = socket.getInputStream(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } } public void write(String s) throws IOException { outputStream.write(s.getBytes()); } public void run() { final int BUFFER_SIZE = 1024; byte[] buffer = new byte[BUFFER_SIZE]; int bytes = 0; while (true) { try { bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes); } catch (IOException e) { e.printStackTrace(); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.list_devices, menu); //return true; return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.scan_device) { mProgressDlg.show(); getAvailableDevices(); } return super.onOptionsItemSelected(item); } @Override public void onPause() { if (mBluetoothAdapter != null) { if (mBluetoothAdapter.isDiscovering()) { mBluetoothAdapter.cancelDiscovery(); } } super.onPause(); } @Override public void onDestroy() { unregisterReceiver(mReceiver); super.onDestroy(); } protected void onStop() { super.onStop(); // Always call the superclass method first // Save the note's current draft, because the activity is stopping // and we want to be sure the current note progress isn't lost. } private void getAvailableDevices() { if (mBluetoothAdapter.isDiscovering()){ mBluetoothAdapter.cancelDiscovery(); } mBluetoothAdapter.startDiscovery(); IntentFilter filter = new IntentFilter(); filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); filter.addAction(BluetoothDevice.ACTION_FOUND); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); registerReceiver(mReceiver, filter); } private final BroadcastReceiver mReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) { final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); if (state == BluetoothAdapter.STATE_ON) { } } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) { mDeviceList = new ArrayList<BluetoothDevice>(); } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { mProgressDlg.dismiss(); final ArrayList<String> list = new ArrayList<String>(); Iterator<BluetoothDevice> itr = mDeviceList.iterator(); while (itr.hasNext()) { // Get Services for paired devices BluetoothDevice device = itr.next(); Log.d("Main", "devices found: "+device.getName()); list.add(device.getName()); } mArrayAdapter = new ArrayAdapter<String>(context,android.R.layout.simple_list_item_1,list); lv.setAdapter(mArrayAdapter); lv.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //Log.d("Main", "devices found: "+deviceList.get(position)); showToast("Pairing device "+list.get(position)+"..."); BluetoothDevice device = mDeviceList.get(position); pairDevice(device); } }); } else if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if(!mDeviceList.contains(device)){ mDeviceList.add(device); } } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) { final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR); final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR); if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) { showToast("Paired"); } else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){ showToast("Unpaired"); } mArrayAdapter.notifyDataSetChanged(); } } }; public void showToast(String msg){ Toast.makeText(getApplicationContext(),msg ,Toast.LENGTH_LONG).show(); } private void pairDevice(BluetoothDevice device) { try { Method method = device.getClass().getMethod("createBond", (Class[]) null); method.invoke(device, (Object[]) null); } catch (Exception e) { e.printStackTrace(); } } private ListView showAlert() { String names[]={"Unpair"}; AlertDialog.Builder alertDialog = new AlertDialog.Builder(DeviceList.this); LayoutInflater inflater = getLayoutInflater(); View convertView = (View) inflater.inflate(R.layout.list_devices, null); alertDialog.setView(convertView); ListView lv1 = (ListView) convertView.findViewById(R.id.devices1); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,names); lv1.setAdapter(adapter); alertDialog.show(); return lv1; } private void unpairDevice(BluetoothDevice device) { try { Method method = device.getClass().getMethod("removeBond", (Class[]) null); method.invoke(device, (Object[]) null); showToast("Unpaired"); mArrayAdapter.notifyDataSetChanged(); return; } catch (Exception e) { e.printStackTrace(); } } }
apache-2.0
aparnachaudhary/javaee-service-registry
javaee-service-registry/src/main/java/io/github/aparnachaudhary/javaee/service/registry/event/EndpointAdded.java
533
package io.github.aparnachaudhary.javaee.service.registry.event; import io.github.aparnachaudhary.javaee.service.registry.EndpointId; /** * @author Aparna Chaudhary */ public class EndpointAdded implements EndpointEvent { private EndpointId endpointId; public EndpointAdded(EndpointId endpointId) { this.endpointId = endpointId; } public EndpointId getEndpointId() { return endpointId; } public void setEndpointId(EndpointId endpointId) { this.endpointId = endpointId; } }
apache-2.0
tdiesler/gravia
itests/common/src/main/java/org/jboss/test/gravia/itests/sub/d/ServiceD.java
2642
/* * #%L * Gravia :: Integration Tests :: Common * %% * Copyright (C) 2010 - 2014 JBoss by Red Hat * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package org.jboss.test.gravia.itests.sub.d; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import org.jboss.test.gravia.itests.sub.d1.ServiceD1; import org.osgi.service.component.ComponentContext; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; @Component(service = { ServiceD.class }, immediate = true) public class ServiceD { static AtomicInteger INSTANCE_COUNT = new AtomicInteger(); final String name = getClass().getSimpleName() + "#" + INSTANCE_COUNT.incrementAndGet(); final AtomicReference<ServiceD1> ref = new AtomicReference<ServiceD1>(); final CountDownLatch activateLatch = new CountDownLatch(1); final CountDownLatch deactivateLatch = new CountDownLatch(1); @Activate void activate(ComponentContext context) { activateLatch.countDown(); } @Deactivate void deactivate() { deactivateLatch.countDown(); } public boolean awaitActivate(long timeout, TimeUnit unit) throws InterruptedException { return activateLatch.await(timeout, unit); } public boolean awaitDeactivate(long timeout, TimeUnit unit) throws InterruptedException { return deactivateLatch.await(timeout, unit); } @Reference void bindServiceD1(ServiceD1 service) { ref.set(service); } void unbindServiceD1(ServiceD1 service) { ref.compareAndSet(service, null); } public ServiceD1 getServiceD1() { return ref.get(); } public String doStuff(String msg) { ServiceD1 srv = ref.get(); return name + ":" + srv.doStuff(msg); } @Override public String toString() { return name; } }
apache-2.0
oanc/org.anc.lapps.oauth
org.anc.lapps.oauth.database/src/main/java/org/anc/lapps/oauth/database/SequenceDatabase.java
415
package org.anc.lapps.oauth.database; import org.springframework.data.repository.Repository; import java.util.List; /** * @author Keith Suderman */ public interface SequenceDatabase extends Repository<Sequence,Long> { List<Sequence> findAll(); Sequence findById(Long id); Sequence findByName(String name); void delete(Sequence sequence); void save(Sequence sequence); // void update(Sequence sequence); }
apache-2.0
googleapis/google-api-java-client-services
clients/google-api-services-cloudbuild/v1/1.31.0/com/google/api/services/cloudbuild/v1/model/StorageSourceManifest.java
4256
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.cloudbuild.v1.model; /** * Location of the source manifest in Google Cloud Storage. This feature is in Preview; see * description [here](https://github.com/GoogleCloudPlatform/cloud-builders/tree/master/gcs- * fetcher). * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Cloud Build API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class StorageSourceManifest extends com.google.api.client.json.GenericJson { /** * Google Cloud Storage bucket containing the source manifest (see [Bucket Name * Requirements](https://cloud.google.com/storage/docs/bucket-naming#requirements)). * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String bucket; /** * Google Cloud Storage generation for the object. If the generation is omitted, the latest * generation will be used. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.lang.Long generation; /** * Google Cloud Storage object containing the source manifest. This object must be a JSON file. * The value may be {@code null}. */ @com.google.api.client.util.Key("object") private java.lang.String object__; /** * Google Cloud Storage bucket containing the source manifest (see [Bucket Name * Requirements](https://cloud.google.com/storage/docs/bucket-naming#requirements)). * @return value or {@code null} for none */ public java.lang.String getBucket() { return bucket; } /** * Google Cloud Storage bucket containing the source manifest (see [Bucket Name * Requirements](https://cloud.google.com/storage/docs/bucket-naming#requirements)). * @param bucket bucket or {@code null} for none */ public StorageSourceManifest setBucket(java.lang.String bucket) { this.bucket = bucket; return this; } /** * Google Cloud Storage generation for the object. If the generation is omitted, the latest * generation will be used. * @return value or {@code null} for none */ public java.lang.Long getGeneration() { return generation; } /** * Google Cloud Storage generation for the object. If the generation is omitted, the latest * generation will be used. * @param generation generation or {@code null} for none */ public StorageSourceManifest setGeneration(java.lang.Long generation) { this.generation = generation; return this; } /** * Google Cloud Storage object containing the source manifest. This object must be a JSON file. * @return value or {@code null} for none */ public java.lang.String getObject() { return object__; } /** * Google Cloud Storage object containing the source manifest. This object must be a JSON file. * @param object__ object__ or {@code null} for none */ public StorageSourceManifest setObject(java.lang.String object__) { this.object__ = object__; return this; } @Override public StorageSourceManifest set(String fieldName, Object value) { return (StorageSourceManifest) super.set(fieldName, value); } @Override public StorageSourceManifest clone() { return (StorageSourceManifest) super.clone(); } }
apache-2.0
equella/Equella
Source/Plugins/Applet/com.tle.common.applet/src/com/tle/common/applet/KeepAliveTask.java
2314
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * The Apereo Foundation licenses this file to you under the Apache License, * Version 2.0, (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tle.common.applet; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class KeepAliveTask { private static final Log LOGGER = LogFactory.getLog(KeepAliveTask.class); public static final long KEEP_ALIVE_DELAY = TimeUnit.SECONDS.toMillis(10); public static final long KEEP_ALIVE_RATE = TimeUnit.MINUTES.toMillis(2); private TimerTask task; private final SessionHolder holder; public KeepAliveTask(SessionHolder holder) { this.holder = holder; } public void keepAlive() { LOGGER.trace("Invoking keep alive"); holder.getLoginService().keepAlive(); } public void onSchedule() { LOGGER.info("Scheduling keep alive task"); // Create a new task and start it. Timer daemon = new Timer(true); task = new TimerTask() { @Override public void run() { KeepAliveTask.this.run(); } }; daemon.scheduleAtFixedRate(task, KEEP_ALIVE_DELAY, KEEP_ALIVE_RATE); } public boolean isScheduled() { return task != null; } /* * (non-Javadoc) * @see java.lang.Runnable#run() */ public void run() { try { keepAlive(); } catch (Exception ex) { LOGGER.warn("Keep-alive message has failed", ex); } } public void cancel() { if (task != null) { LOGGER.info("Cancelling keep alive task"); task.cancel(); } } }
apache-2.0
krasa/DevSupportApp
src/main/java/krasa/overnight/OvernightResultsPage.java
9347
package krasa.overnight; import java.util.*; import krasa.core.frontend.commons.*; import krasa.core.frontend.commons.table.*; import krasa.core.frontend.pages.BasePage; import krasa.overnight.domain.Result; import org.apache.commons.lang3.time.DateUtils; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.OnChangeAjaxBehavior; import org.apache.wicket.extensions.ajax.markup.html.repeater.data.table.AjaxFallbackDefaultDataTable; import org.apache.wicket.extensions.markup.html.form.DateTextField; import org.apache.wicket.extensions.markup.html.repeater.data.table.*; import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider; import org.apache.wicket.extensions.yui.calendar.DatePicker; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.link.*; import org.apache.wicket.markup.html.panel.*; import org.apache.wicket.model.*; import org.apache.wicket.spring.injection.annot.SpringBean; public class OvernightResultsPage extends BasePage { private final IModel<List<Result>> model; private final AjaxFallbackDefaultDataTable<Result, String> table; private final AjaxFallbackDefaultDataTable<Result, String> differenceFromTable; private final IModel<List<Result>> fromModel; @SpringBean OvernightFacade overnightFacade; private Date date = new Date(); private Date differenceFromDate = DateUtils.addDays(new Date(), -1); public OvernightResultsPage() { Form form = new Form("form"); queue(form); DateTextField df = new DateTextField("date", new PropertyModel<Date>(this, "date"), "dd.MM.yyyy"); df.add(new DatePicker()); df.add(new OnChangeAjaxBehavior() { @Override protected void onUpdate(AjaxRequestTarget target) { target.add(table); target.add(differenceFromTable); } }); DateTextField differenceFromDateField = new DateTextField("differenceFromDate", new PropertyModel<Date>(this, "differenceFromDate"), "dd.MM.yyyy"); differenceFromDateField.add(new DatePicker()); differenceFromDateField.add(new OnChangeAjaxBehavior() { @Override protected void onUpdate(AjaxRequestTarget target) { target.add(differenceFromTable); } }); form.add(df); form.add(differenceFromDateField); model = getModel(); fromModel = getFromModel(); ArrayList<IColumn<Result, String>> iColumns = getiColumns(); table = new AjaxFallbackDefaultDataTable<>("table", iColumns, getSortableDataProvider(), Integer.MAX_VALUE); queue(table); differenceFromTable = new AjaxFallbackDefaultDataTable<>("differenceFromTable", iColumns, getDifferenceSortableDataProvider(), 100); form.add(differenceFromTable); } private ISortableDataProvider<Result, String> getDifferenceSortableDataProvider() { return new SortableDataProvider<Result, String>() { @Override public Iterator<Result> iterator(long first, long count) { ListIterator<Result> listIterator = fromModel.getObject().listIterator((int) first); return listIterator; } @Override public long size() { List<Result> object = fromModel.getObject(); return object.size(); } @Override public IModel<Result> model(Result object) { return new OvernightDbModel(object); } @Override public void detach() { super.detach(); fromModel.detach(); } }; } protected SortableDataProvider<Result, String> getSortableDataProvider() { return new SortableDataProvider<Result, String>() { @Override public Iterator<Result> iterator(long first, long count) { List<Result> object = model.getObject(); ListIterator<Result> listIterator = object.listIterator((int) first); return listIterator; } @Override public long size() { List<Result> object = model.getObject(); return object.size(); } @Override public IModel<Result> model(Result object) { return new OvernightDbModel(object); } @Override public void detach() { super.detach(); model.detach(); } }; } protected ArrayList<IColumn<Result, String>> getiColumns() { ArrayList<IColumn<Result, String>> iColumns = new ArrayList<>(); iColumns.add(new PanelColumn<Result>(new Model<>("result"), "result") { @Override protected Panel getPanel(String componentId, IModel<Result> rowModel) { return new LabelPanel(componentId, new PropertyModel<>(rowModel, "result.value")) { @Override protected Component getComponent(String id, IModel labelModel) { return new StyledLabel(id, labelModel); } }; } }); iColumns.add(new PropertyColumn<Result, String>(new Model<String>("component"), "testName.component.name")); iColumns.add(new PropertyColumn<Result, String>(new Model<String>("country"), "country.code")); iColumns.add(new LinkColumn<Result, String>(new Model<String>("name"), "name") { @Override protected AbstractLink getLinkComponent(String id, IModel<String> labelModel, IModel<Result> rowModel) { Result result = rowModel.getObject(); String date = org.apache.commons.lang3.time.FastDateFormat.getInstance("yyyy-MM-dd").format( DateUtils.addHours(result.getTimeStamp(), -OvernightDao.OFFSET)); String environment = result.getTargetEnvironment().getName(); String testNameName = result.getTestName().getName(); String component = result.getTestName().getComponent().getName(); String name = result.getName(); String href; if (result.getTestingTool().getName().equals("soapui")) { switch (component) { case "dcb": { component = "DCB3_TEST_"; } } component = component + result.getCountry().getCode().toUpperCase(); href = getSoapUiUrl(result, date, environment, component, name); } else { href = getAutotestUrl(result, date, environment, component, name); } return new ExternalLink(id, href, testNameName); } }); iColumns.add(new PropertyColumn<Result, String>(new Model<String>("target"), "targetEnvironment.name")); iColumns.add(new PropertyColumn<Result, String>(new Model<String>("injector"), "injectorEnvironment.name")); iColumns.add(new DateColumn<Result>(new Model<String>("time"), "timeStamp")); ; ; return iColumns; } private String getAutotestUrl(Result result, String date, String environment, String component, String name) { String packageName; packageName = "overnight_" + component + "_all-" + result.getTargetEnvironment().getName() + "-stub-" + result.getCountry().getCode() + "-all"; String href = getRoot(result) + date + "/" + environment + "/" + packageName; return href; } private String getSoapUiUrl(Result result, String date, String environment, String component, String name) { String href; String packageName = ""; String postfix; if (result.getTestName().getComponent().getName().equals("ssa")) { postfix = ""; } else if (result.getTestName().getName().contains("Subscription")) { postfix = ""; } else { if (name.startsWith("GET_out")) { packageName = "GUT_OUT"; } else if (name.startsWith("R10_Echo")) { packageName = "echo"; } else if (name.startsWith("R10_GetProvisioning")) { packageName = "getProvisioning"; } else if (name.startsWith("R10_Auth")) { packageName = "auth"; } else if (name.contains("CancelNo")) { packageName = "cancelNotification"; } else if (name.startsWith("TestCase")) { packageName = "invalid_calls"; } else if (name.startsWith("run_DCB_processor")) { packageName = "Run_DCB_processor"; } else if (name.startsWith("run_DCB_processor")) { packageName = "Run_DCB_processor"; } if (packageName.length() > 0) { packageName = packageName + "/"; } postfix = "/" + component + "/" + packageName + name + "/"; } href = getRoot(result) + date + "/" + environment + postfix; return href; } private String getRoot(Result result) { String name = result.getInjectorEnvironment().getName(); if (name.equals("autotest")) { name = ""; } else { name = name + "."; } return "http://autotest." + name + "tmdev/::OVERNIGHTS::/"; } protected LoadableDetachableModel<List<Result>> getModel() { return new LoadableDetachableModel<List<Result>>() { @Override protected List<Result> load() { return overnightFacade.getResults(DateUtils.truncate(date, Calendar.DAY_OF_MONTH), 1000); } }; } protected IModel<List<Result>> getFromModel() { return new LoadableDetachableModel<List<Result>>() { @Override protected List<Result> load() { List<Result> from = overnightFacade.getResults( DateUtils.truncate(differenceFromDate, Calendar.DAY_OF_MONTH), 1000); Set<String> keys = new HashSet<>(); for (Result result : from) { keys.add(getKey(result)); } List<Result> results = new ArrayList<>(); for (Result result : model.getObject()) { if (!keys.contains(getKey(result))) { results.add(result); } } return results; } }; } protected String getKey(Result result) { return result.getTestName().getComponent().getName() + result.getTargetEnvironment().getName() + result.getCountry().getCode() + result.getName(); } @Override protected Component newLeftColumnPanel(String id) { EmptyPanel components = new EmptyPanel(id); components.setVisible(false); return components; } }
apache-2.0
b2ihealthcare/snow-owl
fhir/com.b2international.snowowl.fhir.core/src/com/b2international/snowowl/fhir/core/request/codesystem/FhirCodeSystemResourceConverter.java
3453
/* * Copyright 2021 B2i Healthcare Pte Ltd, http://b2i.sg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.b2international.snowowl.fhir.core.request.codesystem; import java.util.List; import javax.annotation.OverridingMethodsMustInvokeSuper; import com.b2international.commons.http.ExtendedLocale; import com.b2international.snowowl.core.ResourceURI; import com.b2international.snowowl.core.ServiceProvider; import com.b2international.snowowl.core.codesystem.CodeSystemRequests; import com.b2international.snowowl.fhir.core.model.codesystem.Concept; import com.b2international.snowowl.fhir.core.model.codesystem.Filter; import com.b2international.snowowl.fhir.core.model.codesystem.IConceptProperty; import com.b2international.snowowl.fhir.core.model.codesystem.SupportedCodeSystemRequestProperties; /** * @since 8.0 */ public interface FhirCodeSystemResourceConverter { FhirCodeSystemResourceConverter DEFAULT = new FhirCodeSystemResourceConverter() { }; /** * Implementers may count the number of concepts in the given resource. This method by default uses the generic concept search API to provide the count value. * * @param resourceUri * @return */ default int count(ServiceProvider context, ResourceURI resourceUri) { return CodeSystemRequests.prepareSearchConcepts() .setLimit(0) .filterByCodeSystemUri(resourceUri) .buildAsync() .execute(context) .getTotal(); } /** * Implementers may expand a FHIR CodeSystem with its concepts if they wish to include them. This method by default does nothing. * * @param context - the context to use when expanding additional information * @param resourceURI * @param locales */ default List<Concept> expandConcepts(ServiceProvider context, ResourceURI resourceURI, List<ExtendedLocale> locales) { return List.of(); } /** * Implementers may expand a FHIR CodeSystem with its available filters if they wish to include them. This method by default does nothing. * * @param context - the context to use when expanding additional information * @param resourceURI * @param locales */ default List<Filter> expandFilters(ServiceProvider context, ResourceURI resourceURI, List<ExtendedLocale> locales) { return List.of(); } /** * Implementers may expand the FHIR CodeSystem with its available concept properties if they wish to include them. This method returns the common * code system request properties by default. Overriding methods must ensure they return these as well when customizing the return value. * * @param context * - the context to use when expanding additional information * @param resourceURI * @param locales */ @OverridingMethodsMustInvokeSuper default List<IConceptProperty> expandProperties(ServiceProvider context, ResourceURI resourceURI, List<ExtendedLocale> locales) { return List.of(SupportedCodeSystemRequestProperties.values()); } }
apache-2.0
cgs1999/mybams
src/core/com/pinhuba/core/daoimpl/OaWarehouseDaoImpl.java
380
package com.pinhuba.core.daoimpl; import org.springframework.stereotype.Repository; import com.pinhuba.core.pojo.*; import com.pinhuba.core.dao.*; /** * 表:OA_WAREHOUSE 对应daoImpl */ @Repository public class OaWarehouseDaoImpl extends BaseHapiDaoimpl<OaWarehouse, Long> implements IOaWarehouseDao { public OaWarehouseDaoImpl(){ super(OaWarehouse.class); } }
apache-2.0
yulianzhilan/BLOG
blog/src/main/java/dto/article/ArticleSummaryDTO.java
2078
package dto.article; import java.util.Date; /** * 此类用于展示文章 * Created by scott on 2017/4/24. */ public class ArticleSummaryDTO { /** * PK */ private int id; /** * 文章名称 */ private String name; /** * 概括 */ private String description; /** * 作者id */ private int userId; /** * 最后更新时间 */ private Date modify; /** * 作者昵称 */ private String nickName; private String title; /** * 评论数 */ private int comments; private int photoId; private String photoUrl; 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 getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public Date getModify() { return modify; } public void setModify(Date modify) { this.modify = modify; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public int getComments() { return comments; } public void setComments(int comments) { this.comments = comments; } public int getPhotoId() { return photoId; } public void setPhotoId(int photoId) { this.photoId = photoId; } public String getPhotoUrl() { return photoUrl; } public void setPhotoUrl(String photoUrl) { this.photoUrl = photoUrl; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
apache-2.0
AndruByrne/something_wicked_this_way_came
app/src/main/java/com/anthropicandroid/sfcrimedata/module/DataStoreModule.java
633
package com.anthropicandroid.sfcrimedata.module; import android.content.Context; import com.anthropicandroid.sfcrimedata.services.DataStore; import com.google.maps.android.geojson.GeoJsonLayer; import java.util.ArrayList; import java.util.List; import dagger.Module; import dagger.Provides; /* * Created by Andrew Brin on 7/10/2016. */ @Module public class DataStoreModule { @Provides @NaviActivityScope DataStore getDataStore(Context context){ return new DataStore(context); } @Provides @NaviActivityScope List<GeoJsonLayer> getLayerRegister(){ return new ArrayList<>(); } }
apache-2.0
adamrduffy/trinidad-1.0.x
trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/uinode/UIXComponentUINode.java
12075
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.myfaces.trinidadinternal.uinode; import java.io.IOException; import java.util.Iterator; import javax.faces.component.UIComponent; import java.lang.reflect.UndeclaredThrowableException; import org.apache.myfaces.trinidad.logging.TrinidadLogger; import org.apache.myfaces.trinidadinternal.ui.AttributeKey; import org.apache.myfaces.trinidadinternal.ui.NodeRole; import org.apache.myfaces.trinidadinternal.ui.Renderer; import org.apache.myfaces.trinidadinternal.ui.RendererFactory; import org.apache.myfaces.trinidadinternal.ui.RendererManager; import org.apache.myfaces.trinidadinternal.ui.UIXRenderingContext; import org.apache.myfaces.trinidadinternal.ui.RoledRenderer; import org.apache.myfaces.trinidadinternal.ui.UIConstants; import org.apache.myfaces.trinidadinternal.ui.UINode; import org.apache.myfaces.trinidadinternal.ui.collection.AttributeMap; import org.apache.myfaces.trinidadinternal.ui.data.BoundValue; import org.apache.myfaces.trinidadinternal.ui.laf.base.PreAndPostRenderer; import org.apache.myfaces.trinidad.component.UIXComponent; /** * Subclass for UIX components. * <p> * @version $Name: $ ($Revision: adfrt/faces/adf-faces-impl/src/main/java/oracle/adfinternal/view/faces/uinode/UIXComponentUINode.java#0 $) $Date: 10-nov-2005.18:49:20 $ * @deprecated This class comes from the old Java 1.2 UIX codebase and should not be used anymore. */ @Deprecated public class UIXComponentUINode extends UIComponentUINode { public UIXComponentUINode( UIXComponent component, String namespace, AttributeMap attributes) { super(component, namespace); _attributes = attributes; } /** * Returns the role that this node occupies. */ @Override public NodeRole getNodeRole(UIXRenderingContext context) { if (context != null) { Renderer renderer = getRenderer(context, this); if (renderer instanceof RoledRenderer) { return ((RoledRenderer) renderer).getNodeRole(context, this); } // Null Renderer - for our components - means components // like switcher. else if (renderer == null) { return UIConstants.STATE_ROLE; } } return UIConstants.UNKNOWN_ROLE; } @Override public Iterator<AttributeKey> getAttributeNames(UIXRenderingContext context) { AttributeMap attributes = getAttributeMap(false); if (attributes != null) { return attributes.attributeKeys(context); } else { return null; } } @Override public void setAttributeValue( AttributeKey attrKey, Object value ) { AttributeMap attrDict = getAttributeMap((value != null)); if (attrDict != null) { attrDict.setAttribute(attrKey, value); } } /** * Returns the value of the attribute with the specified name in the * RenderingContext. If no attribute with the specified name exists * in this UINode, or a checked Exception occurs in retrieving the value of * the attribute, <CODE>null</CODE> will be returned. * <p> * Note that as with indexed children and named children, the presence of * of an attribute is no guarantee that the Renderer used to render this * UINode will actually use the attribute. The presence of attributes * should only be considered as hints to the Renderer. * <p> * <STRONG>If the UINode is mutable and may be modified and read in different * threads, it is the programmer's responsibility to ensure proper * synchronization. * </STRONG> * <p> * @see #getAttributeNames */ @Override public Object getAttributeValue(UIXRenderingContext context, AttributeKey attrKey) { return getAttributeValueImpl(context, attrKey, true); } /** * Returns the value of the attribute with a specified name, without * attempting to further resolve that value - as if , for instance, * it might be a BoundValue. * <p> * @see org.apache.myfaces.trinidadinternal.ui.data.BoundValue */ @Override public Object getRawAttributeValue(UIXRenderingContext context, AttributeKey attrKey) { return getAttributeValueImpl(context, attrKey, false); } public void renderInternal(UIXRenderingContext context, UINode dataNode) throws IOException { Renderer renderer = null; try { renderer = getRenderer(context, dataNode); } catch( UndeclaredThrowableException e ) { if (_LOG.isWarning()) _LOG.warning(e.getMessage()); return; } if (renderer != null) { // See if we need to push/pop ourselves. This should only // happen in two cases: // - We're the root of the tree. // - We're a private bean, and a Renderer called render() directly // instead of using composite widgets. boolean pushAndPop = (context.getRenderedAncestorNode(0) != dataNode); if (pushAndPop) { context.pushChild(dataNode, null, -1); context.pushRenderedChild(context, dataNode); } try { renderer.render(context, dataNode); } // Annotate all exceptions thrown by UIX to indicate // which component is the guilty one catch (RuntimeException re) { _handleRenderException(re); } finally { if (pushAndPop) { context.popRenderedChild(context); context.popChild(); } } } else { _logNoRenderer(context); } } public void prerenderInternal(UIXRenderingContext context, UINode dataNode) throws IOException { Renderer renderer = null; try { renderer = getRenderer(context, dataNode); } catch( UndeclaredThrowableException e ) { if (_LOG.isWarning()) _LOG.warning(e.getMessage()); return; } assert(renderer instanceof PreAndPostRenderer); // =-=AEW PUSH-POP-CATCH??? if (renderer != null) { // See if we need to push/pop ourselves. This should only // happen in two cases: // - We're the root of the tree. // - We're a private bean, and a Renderer called render() directly // instead of using composite widgets. boolean pushAndPop = (context.getRenderedAncestorNode(0) != dataNode); if (pushAndPop) { context.pushChild(dataNode, null, -1); context.pushRenderedChild(context, dataNode); } try { ((PreAndPostRenderer) renderer).prerender(context, dataNode); } // Annotate all exceptions thrown by UIX to indicate // which component is the guilty one catch (RuntimeException re) { _handleRenderException(re); } finally { if (pushAndPop) { context.popRenderedChild(context); context.popChild(); } } } else { _logNoRenderer(context); } } public void postrenderInternal(UIXRenderingContext context, UINode dataNode) throws IOException { Renderer renderer = null; try { renderer = getRenderer(context, dataNode); } catch( UndeclaredThrowableException e ) { if (_LOG.isWarning()) _LOG.warning(e.getMessage()); return; } assert(renderer instanceof PreAndPostRenderer); // =-=AEW PUSH-POP-CATCH??? if (renderer != null) { // See if we need to push/pop ourselves. This should only // happen in two cases: // - We're the root of the tree. // - We're a private bean, and a Renderer called render() directly // instead of using composite widgets. boolean pushAndPop = (context.getRenderedAncestorNode(0) != dataNode); if (pushAndPop) { context.pushChild(dataNode, null, -1); context.pushRenderedChild(context, dataNode); } try { ((PreAndPostRenderer) renderer).postrender(context, dataNode); } // Annotate all exceptions thrown by UIX to indicate // which component is the guilty one catch (RuntimeException re) { _handleRenderException(re); } finally { if (pushAndPop) { context.popRenderedChild(context); context.popChild(); } } } else { _logNoRenderer(context); } } private void _handleRenderException( RuntimeException re) throws IOException { if (re instanceof UndeclaredThrowableException) { // Our UnsynchronizedPrintWriter catches IOExceptions and // rethrows these wrapped in UndeclaredThrowableExceptions. If we // catch any UndeclaredThrowableExceptions which have an IOExceptions // as the root cause, let's just rethrow the original // IOException so that the original stack trace will be // preserved. Throwable rootCause = ((UndeclaredThrowableException)re).getCause(); if (rootCause instanceof IOException) throw ((IOException)rootCause); } throw re; } private void _logNoRenderer(UIXRenderingContext context) { if (_LOG.isWarning()) { RendererManager manager = context.getRendererManager(); RendererFactory factory = manager.getFactory(getNamespaceURI()); if (factory == null) { _LOG.warning("NO_RENDERERFACTORY_REGISTERED_COMPONENT", getNamespaceURI()); } else { _LOG.warning("NO_RENDERER_REGISTERED", this); } } } protected Renderer getRenderer( UIXRenderingContext context, UINode dataNode ) { // get the renderer for ourselves RendererManager manager = context.getRendererManager(); String localName = getLocalName(); if (localName == null) return null; return manager.getRenderer(getNamespaceURI(), localName); } /** * Bottleneck method for all attribute getting. */ protected Object getAttributeValueImpl( UIXRenderingContext context, AttributeKey attrKey, boolean returnBoundValue ) { AttributeMap attributes = getAttributeMap(false); if (attributes != null) { Object value = attributes.getAttribute(context, attrKey); if (returnBoundValue && (value instanceof BoundValue)) { value = ((BoundValue)value).getValue(context); } return value; } else { return null; } } /** * Returns the AttributeMap used to store attributes. * <p> * @param createIfNull if true, creates * an AttributeMap object if one has not yet been created. */ protected final AttributeMap getAttributeMap( boolean createIfNull ) { if (createIfNull && (_attributes == null)) { // This should not happen; we set the attributes in the // construtor throw new IllegalStateException(); } return _attributes; } static UIXComponentUINode __getAdapter(UIComponent component) { // =-=AEW How to assert this is only called when allowable? return (UIXComponentUINode) __getUINode(component); } private AttributeMap _attributes; private static final TrinidadLogger _LOG = TrinidadLogger.createTrinidadLogger(UIXComponentUINode.class); }
apache-2.0
soundTricker/gas-library-box-server
src/main/java/com/appspot/soundtricker/gaslibrarybox/controller/backend/task/DeleteFromFusionTableController.java
887
package com.appspot.soundtricker.gaslibrarybox.controller.backend.task; import java.util.logging.Logger; import org.slim3.controller.Controller; import org.slim3.controller.Navigation; import com.appspot.soundtricker.gaslibrarybox.service.FusionService; import com.google.common.base.Strings; public class DeleteFromFusionTableController extends Controller { private static final Logger logger = Logger .getLogger(DeleteFromFusionTableController.class.getName()); @Override public Navigation run() throws Exception { String key = asString("key"); if (Strings.isNullOrEmpty(key)) { logger.severe("key parameter is empty."); return null; } String rowID = FusionService.getRowID(key); if (rowID == null) { logger.warning("Not found library:" + key); return null; } FusionService.delete(rowID); logger.fine("Delete " + key); return null; } }
apache-2.0
jishenghua/JSH_ERP
jshERP-boot/src/main/java/com/jsh/erp/datasource/mappers/AccountItemMapperEx.java
1519
package com.jsh.erp.datasource.mappers; import com.jsh.erp.datasource.entities.AccountItem; import com.jsh.erp.datasource.entities.AccountItemExample; import com.jsh.erp.datasource.vo.AccountItemVo4List; import org.apache.ibatis.annotations.Param; import java.math.BigDecimal; import java.util.Date; import java.util.List; public interface AccountItemMapperEx { List<AccountItem> selectByConditionAccountItem( @Param("name") String name, @Param("type") Integer type, @Param("remark") String remark, @Param("offset") Integer offset, @Param("rows") Integer rows); Long countsByAccountItem( @Param("name") String name, @Param("type") Integer type, @Param("remark") String remark); List<AccountItemVo4List> getDetailList( @Param("headerId") Long headerId); int batchDeleteAccountItemByIds(@Param("updateTime") Date updateTime, @Param("updater") Long updater, @Param("ids") String[] ids); List<AccountItem> getAccountItemListByAccountIds(@Param("accountIds") String[] accountIds); List<AccountItem> getAccountItemListByHeaderIds(@Param("headerIds") String[] headerIds); List<AccountItem> getAccountItemListByInOutItemIds(@Param("inOutItemIds") String[] inOutItemIds); int batchDeleteAccountItemByHeadIds(@Param("updateTime") Date updateTime, @Param("updater") Long updater, @Param("ids") String[] ids); BigDecimal getEachAmountByBillId(@Param("billId") Long billId); }
apache-2.0