signature:
public class GridFactoryImpl { /** * Sets the column converters .
 * @ param collectionPropertyConverter
 * the collection property converter
 * @ param grid
 * the grid */
private static void setColumnConverters ( final ListPropertyConverter [ ] collectionPropertyConverter , final Grid grid ) { } }

implementation: if ( collectionPropertyConverter != null ) { for ( final ListPropertyConverter converter : collectionPropertyConverter ) { grid . removeColumn ( converter . getColumn ( ) ) ; final Column column = grid . addColumn ( converter ) ; column . setCaption ( WordUtils . capitalize ( converter . getColumn ( ) ) ) ; column . setId ( converter . getColumn ( ) ) ; } }


signature:
public class ObjectFactory { /** * Creates a new Object object .
 * @ param value the value
 * @ return the JAXB element < person container element > */
@ XmlElementDecl ( namespace = "http://personlista.riksdagen.external.model.cia.hack23.com/impl" , name = "personlista" ) public JAXBElement < PersonContainerElement > createPersonlista ( final PersonContainerElement value ) { } }

implementation: return new JAXBElement < > ( _Personlista_QNAME , PersonContainerElement . class , null , value ) ;


signature:
public class ObjectFactory { /** * Creates a new Object object .
 * @ param value the value
 * @ return the JAXB element < sweden county data container > */
@ XmlElementDecl ( namespace = "http://kommunvalkrets.val.external.model.cia.hack23.com/impl" , name = "root" ) public JAXBElement < SwedenCountyDataContainer > createRoot ( final SwedenCountyDataContainer value ) { } }

implementation: return new JAXBElement < > ( _Root_QNAME , SwedenCountyDataContainer . class , null , value ) ;


signature:
public class ObjectFactory { /** * Creates a new Object object .
 * @ param value the value
 * @ return the JAXB element < sweden election type container element > */
@ XmlElementDecl ( namespace = "http://partier.val.external.model.cia.hack23.com/impl" , name = "root" ) public JAXBElement < SwedenElectionTypeContainerElement > createRoot ( final SwedenElectionTypeContainerElement value ) { } }

implementation: return new JAXBElement < > ( _Root_QNAME , SwedenElectionTypeContainerElement . class , null , value ) ;


signature:
public class DocumentChartDataManagerImpl { /** * Gets the document type map .
 * @ return the document type map */
private Map < String , List < ViewRiksdagenDocumentTypeDailySummary > > getDocumentTypeMap ( ) { } }

implementation: final DataContainer < ViewRiksdagenDocumentTypeDailySummary , RiksdagenDocumentTypeSummaryEmbeddedId > documentTypeSummaryDailyDataContainer = getApplicationManager ( ) . getDataContainer ( ViewRiksdagenDocumentTypeDailySummary . class ) ; return documentTypeSummaryDailyDataContainer . getAll ( ) . parallelStream ( ) . filter ( t -> t != null && ! t . getEmbeddedId ( ) . getPublicDate ( ) . startsWith ( YEAR_PREFIX ) && StringUtils . containsIgnoreCase ( MOT_PROP_BET , t . getEmbeddedId ( ) . getDocumentType ( ) ) ) . collect ( Collectors . groupingBy ( t -> t . getEmbeddedId ( ) . getDocumentType ( ) ) ) ;


signature:
public class DocumentChartDataManagerImpl { /** * Adds the data series .
 * @ param simpleDateFormat the simple date format
 * @ param parseInputDateFormat the parse input date format
 * @ param dataSeries the data series
 * @ param series the series
 * @ param entry the entry */
private static void addDataSeries ( final SimpleDateFormat simpleDateFormat , final SimpleDateFormat parseInputDateFormat , final DataSeries dataSeries , final Series series , final Entry < String , List < ViewRiksdagenDocumentTypeDailySummary > > entry ) { } }

implementation: series . addSeries ( new XYseries ( ) . setLabel ( entry . getKey ( ) ) ) ; dataSeries . newSeries ( ) ; for ( final ViewRiksdagenDocumentTypeDailySummary item : entry . getValue ( ) ) { if ( item != null && item . getEmbeddedId ( ) . getPublicDate ( ) . length ( ) > 0 ) { try { dataSeries . add ( simpleDateFormat . format ( parseInputDateFormat . parse ( item . getEmbeddedId ( ) . getPublicDate ( ) ) ) , item . getTotal ( ) ) ; } catch ( final ParseException e ) { LOGGER . warn ( "Problem parsing date:{}" , item . getEmbeddedId ( ) . getPublicDate ( ) ) ; } } }


signature:
public class SwedenElectionTypeContainerElement { /** * Gets the election types .
 * @ return the election types */
@ OneToMany ( targetEntity = SwedenElectionType . class , cascade = { } }

implementation: CascadeType . ALL } ) @ JoinColumn ( name = "ELECTION_TYPES_SWEDEN_ELECTI_0" ) public List < SwedenElectionType > getElectionTypes ( ) { return this . electionTypes ;


signature:
public class SankeyChartState { /** * Adds the data row .
 * @ param from the from
 * @ param to the to
 * @ param weight the weight */
public void addDataRow ( final String from , final String to , int weight ) { } }

implementation: final ArrayList < Object > valueData = new ArrayList < > ( ) ; valueData . add ( from ) ; valueData . add ( to ) ; valueData . add ( weight ) ; values . add ( valueData ) ;


signature:
public class CommitteeProposalData { /** * Gets the ballot summary item .
 * @ return the ballot summary item */
@ Basic @ Column ( name = "BALLOT_SUMMARY_ITEM" ) @ Lob public String getBallotSummaryItem ( ) { } }

implementation: return XmlAdapterUtils . unmarshall ( ElementAsString . class , this . getBallotSummary ( ) ) ;


signature:
public class CountryElement { /** * Gets the region .
 * @ return the region */
@ Embedded @ AttributeOverrides ( { } }

implementation: @ AttributeOverride ( name = "value" , column = @ Column ( name = "REGION_VALUE" ) ) , @ AttributeOverride ( name = "id" , column = @ Column ( name = "REGION_ID" ) ) } ) public Region getRegion ( ) { return region ;


signature:
public class CountryElement { /** * Gets the adminregion .
 * @ return the adminregion */
@ Embedded @ AttributeOverrides ( { } }

implementation: @ AttributeOverride ( name = "value" , column = @ Column ( name = "ADMINREGION_VALUE" ) ) , @ AttributeOverride ( name = "id" , column = @ Column ( name = "ADMINREGION_ID" ) ) } ) public Adminregion getAdminregion ( ) { return adminregion ;


signature:
public class CountryElement { /** * Gets the income level .
 * @ return the income level */
@ Embedded @ AttributeOverrides ( { } }

implementation: @ AttributeOverride ( name = "value" , column = @ Column ( name = "INCOME_LEVEL_VALUE" ) ) , @ AttributeOverride ( name = "id" , column = @ Column ( name = "INCOME_LEVEL_ID" ) ) } ) public IncomeLevel getIncomeLevel ( ) { return incomeLevel ;


signature:
public class CountryElement { /** * Gets the lending type .
 * @ return the lending type */
@ Embedded @ AttributeOverrides ( { } }

implementation: @ AttributeOverride ( name = "value" , column = @ Column ( name = "LENDING_TYPE_VALUE" ) ) , @ AttributeOverride ( name = "id" , column = @ Column ( name = "LENDING_TYPE_ID" ) ) } ) public LendingType getLendingType ( ) { return lendingType ;


signature:
public class BallotContainer { /** * Gets the ballot document data .
 * @ return the ballot document data */
@ ManyToOne ( targetEntity = BallotDocumentData . class , cascade = { } }

implementation: CascadeType . ALL } ) @ JoinColumn ( name = "BALLOT_DOCUMENT_DATA_BALLOT__0" ) public BallotDocumentData getBallotDocumentData ( ) { return ballotDocumentData ;


signature:
public class BallotContainer { /** * Gets the ballot document element .
 * @ return the ballot document element */
@ ManyToOne ( targetEntity = BallotDocumentElement . class , cascade = { } }

implementation: CascadeType . ALL } ) @ JoinColumn ( name = "BALLOT_DOCUMENT_ELEMENT_BALL_0" ) public BallotDocumentElement getBallotDocumentElement ( ) { return ballotDocumentElement ;


signature:
public class EncryptProperty { /** * The main method .
 * @ param args the arguments */
public static void main ( String [ ] args ) { } }

implementation: if ( args . length == EXPECTED_NUMBER_ARGS ) { final String encryptValue = new EncryptProperty ( ) . encryptValue ( args [ 0 ] , args [ 1 ] ) ; System . out . println ( ENCRYPTED_VALUE + encryptValue ) ; System . out . println ( ENCRYPTED_PROPERTY_VALUE + ENC_CONTENT_PREFIX + encryptValue + ENC_CONTENT_SUFFIX ) ; } else { System . out . println ( HELP_MESSAGE ) ; }


signature:
public class EncryptProperty { /** * Encrypt value .
 * @ param symmetricKey
 * the symmetric key
 * @ param value
 * the value
 * @ return the string */
public String encryptValue ( final String symmetricKey , final String value ) { } }

implementation: return getEncryptor ( symmetricKey ) . encrypt ( value ) ;


signature:
public class EncryptProperty { /** * Gets the encryptor .
 * @ param symmetricKey
 * the symmetric key
 * @ return the encryptor */
private static StandardPBEStringEncryptor getEncryptor ( final String symmetricKey ) { } }

implementation: Security . addProvider ( new BouncyCastleProvider ( ) ) ; final StandardPBEStringEncryptor mySecondEncryptor = new StandardPBEStringEncryptor ( ) ; mySecondEncryptor . setProviderName ( BC_PROVIDER_NAME ) ; mySecondEncryptor . setAlgorithm ( PBEWITHSHA256AND128BITAES_CBC_BC ) ; mySecondEncryptor . setPassword ( symmetricKey ) ; return mySecondEncryptor ;


signature:
public class EncryptProperty { /** * Decrypt value .
 * @ param symmetricKey
 * the symmetric key
 * @ param value
 * the value
 * @ return the string */
public String decryptValue ( final String symmetricKey , final String value ) { } }

implementation: return getEncryptor ( symmetricKey ) . decrypt ( value ) ;


signature:
public class RiksdagenPersonApiImpl { /** * / * ( non - Javadoc )
 * @ see com . hack23 . cia . service . external . riksdagen . api . RiksdagenPersonApi # getPerson ( java . lang . String ) */
@ Override public PersonData getPerson ( final String id ) throws DataFailureException { } }

implementation: try { final String url = PERSON . replace ( ID_KEY , id ) ; return ( ( JAXBElement < com . hack23 . cia . model . external . riksdagen . person . impl . PersonContainerData > ) xmlAgent . unmarshallXml ( personUnmarshaller , url , HTTP_PERSON_RIKSDAGEN_EXTERNAL_MODEL_CIA_HACK23_COM_IMPL , null , null ) ) . getValue ( ) . getPerson ( ) ; } catch ( final XmlAgentException e ) { LOGGER . warn ( PROBLEM_GETTING_PERSON_DATA_ID_S_FROM_DATA_RIKSDAGEN_SE , id ) ; throw new DataFailureException ( e ) ; }


signature:
public class RiksdagenPersonApiImpl { /** * / * ( non - Javadoc )
 * @ see com . hack23 . cia . service . external . riksdagen . api . RiksdagenPersonApi # getPersonList ( ) */
@ Override public PersonContainerElement getPersonList ( ) throws DataFailureException { } }

implementation: try { return ( ( JAXBElement < PersonContainerElement > ) xmlAgent . unmarshallXml ( personListUnmarshaller , PERSON_LIST , HTTP_PERSONLISTA_RIKSDAGEN_EXTERNAL_MODEL_CIA_HACK23_COM_IMPL , null , null ) ) . getValue ( ) ; } catch ( final XmlAgentException e ) { LOGGER . warn ( PROBLEM_GETTING_PERSON_LIST_FROM_DATA_RIKSDAGEN_SE ) ; throw new DataFailureException ( e ) ; }


signature:
public class SwedenCountyElectoralRegionContainer { /** * Gets the county electoral regions .
 * @ return the county electoral regions */
@ OneToMany ( targetEntity = SwedenCountyElectoralRegion . class , cascade = { } }

implementation: CascadeType . ALL } ) @ JoinColumn ( name = "COUNTY_ELECTORAL_REGIONS_SWE_0" ) public List < SwedenCountyElectoralRegion > getCountyElectoralRegions ( ) { return this . countyElectoralRegions ;


signature:
public class AbstractJob { /** * Gets the job context holder .
 * @ param jobContext
 * the job context
 * @ return the job context holder */
protected final JobContextHolder getJobContextHolder ( final JobExecutionContext jobContext ) { } }

implementation: final Scheduler scheduler = jobContext . getScheduler ( ) ; JobContextHolder bean = null ; try { final SchedulerContext schedulerContext = scheduler . getContext ( ) ; final ApplicationContext appContext = ( ApplicationContext ) schedulerContext . get ( APPLICATION_CONTEXT ) ; bean = appContext . getBean ( JobContextHolder . class ) ; } catch ( final SchedulerException e ) { LOGGER . error ( "Failed to get JobContextHolder" , e ) ; } return bean ;


signature:
public class Agency { /** * Gets the value of the portals property .
 * This accessor method returns a reference to the live list ,
 * not a snapshot . Therefore any modification you make to the
 * returned list will be present inside the JAXB object .
 * This is why there is not a < CODE > set < / CODE > method for the portals property .
 * For example , to add a new item , do as follows :
 * < pre >
 * getPortals ( ) . add ( newItem ) ;
 * < / pre >
 * Objects of the following type ( s ) are allowed in the list
 * { @ link Portal } */
@ OneToMany ( targetEntity = Portal . class , cascade = { } }

implementation: CascadeType . ALL } ) @ JoinColumn ( name = "PORTALS_AGENCY_HJID" ) public List < Portal > getPortals ( ) { if ( portals == null ) { portals = new ArrayList < > ( ) ; } return this . portals ;


signature:
public class AbstractUserHomePageModContentFactoryImpl { /** * Gets the active user account .
 * @ return the active user account */
protected final Optional < UserAccount > getActiveUserAccount ( ) { } }

implementation: final DataContainer < UserAccount , Long > dataContainer = getApplicationManager ( ) . getDataContainer ( UserAccount . class ) ; return dataContainer . getAllBy ( UserAccount_ . userId , UserContextUtil . getUserIdFromSecurityContext ( ) ) . stream ( ) . findFirst ( ) ;


signature:
public class DocumentContainerElement { /** * Gets the dokument .
 * @ return the dokument */
@ OneToMany ( targetEntity = DocumentElement . class , cascade = { } }

implementation: CascadeType . ALL } ) @ JoinColumn ( name = "DOKUMENT_DOCUMENT_CONTAINER__0" ) public List < DocumentElement > getDokument ( ) { return this . dokument ;


signature:
public class AbstractView { /** * Creates the basic layout with panel and footer .
 * @ param panelName
 * the panel name */
protected final void createBasicLayoutWithPanelAndFooter ( final String panelName ) { } }

implementation: final VerticalLayout layout = createFullSizeVerticalLayout ( ) ; final VerticalLayout pageModeContent = createFullSizeVerticalLayout ( false , false ) ; layout . addComponent ( pageModeContent ) ; final HorizontalLayout topHeader = new HorizontalLayout ( ) ; addLogoToHeader ( topHeader ) ; createTopTitleHeader ( topHeader ) ; topHeaderRightPanel . removeAllComponents ( ) ; topHeader . addComponent ( topHeaderRightPanel ) ; topHeader . setComponentAlignment ( topHeaderRightPanel , Alignment . MIDDLE_RIGHT ) ; topHeader . setExpandRatio ( topHeaderRightPanel , ContentRatio . LARGE ) ; createTopHeaderActionsForUserContext ( ) ; topHeaderRightPanel . setWidth ( "100%" ) ; topHeaderRightPanel . setHeight ( "50px" ) ; topHeader . setWidth ( "100%" ) ; topHeader . setHeight ( "50px" ) ; pageModeContent . addComponent ( topHeader ) ; pageModeContent . setComponentAlignment ( topHeader , Alignment . TOP_CENTER ) ; pageModeContent . addComponent ( getBarmenu ( ) ) ; pageModeContent . setComponentAlignment ( getBarmenu ( ) , Alignment . TOP_CENTER ) ; panel = new Panel ( panelName ) ; panel . addStyleName ( "v-panel-page-panel" ) ; panel . setSizeFull ( ) ; pageModeContent . addComponent ( panel ) ; pageModeContent . setExpandRatio ( panel , ContentRatio . FULL_SIZE ) ; pageModeContent . addComponent ( pageLinkFactory . createMainViewPageLink ( ) ) ; setContent ( layout ) ; setWidth ( 100 , Unit . PERCENTAGE ) ; setHeight ( 100 , Unit . PERCENTAGE ) ; setSizeFull ( ) ;


signature:
public class AbstractView { /** * Creates the top header actions for user context . */
private void createTopHeaderActionsForUserContext ( ) { } }

implementation: if ( UserContextUtil . allowRoleInSecurityContext ( ROLE_ADMIN ) || UserContextUtil . allowRoleInSecurityContext ( ROLE_USER ) ) { final Link userHomePageLink = pageLinkFactory . createUserHomeViewPageLink ( ) ; topHeaderRightPanel . addComponent ( userHomePageLink ) ; topHeaderRightPanel . setComponentAlignment ( userHomePageLink , Alignment . MIDDLE_RIGHT ) ; final Button logoutButton = new Button ( LOGOUT , VaadinIcons . SIGN_OUT ) ; final LogoutRequest logoutRequest = new LogoutRequest ( ) ; logoutRequest . setSessionId ( RequestContextHolder . currentRequestAttributes ( ) . getSessionId ( ) ) ; logoutButton . addClickListener ( new LogoutClickListener ( logoutRequest ) ) ; topHeaderRightPanel . addComponent ( logoutButton ) ; topHeaderRightPanel . setComponentAlignment ( logoutButton , Alignment . MIDDLE_RIGHT ) ; } else { final Link createRegisterPageLink = pageLinkFactory . createRegisterPageLink ( ) ; topHeaderRightPanel . addComponent ( createRegisterPageLink ) ; topHeaderRightPanel . setComponentAlignment ( createRegisterPageLink , Alignment . MIDDLE_RIGHT ) ; final Link createLoginPageLink = pageLinkFactory . createLoginPageLink ( ) ; topHeaderRightPanel . addComponent ( createLoginPageLink ) ; topHeaderRightPanel . setComponentAlignment ( createLoginPageLink , Alignment . MIDDLE_RIGHT ) ; }


signature:
public class AbstractView { /** * Creates the full size vertical layout .
 * @ param margin
 * the margin
 * @ param spacing
 * the spacing
 * @ return the vertical layout */
private static VerticalLayout createFullSizeVerticalLayout ( final boolean margin , final boolean spacing ) { } }

implementation: final VerticalLayout layout = new VerticalLayout ( ) ; layout . setMargin ( margin ) ; layout . setSpacing ( spacing ) ; layout . setWidth ( 100 , Unit . PERCENTAGE ) ; layout . setHeight ( 100 , Unit . PERCENTAGE ) ; return layout ;


signature:
public class AbstractView { /** * Adds the logo to header .
 * @ param topHeader
 * the top header */
private static void addLogoToHeader ( final HorizontalLayout topHeader ) { } }

implementation: final ThemeResource ciaLogoResource = new ThemeResource ( "cia-logo.png" ) ; final Image ciaLogoImage = new Image ( null , ciaLogoResource ) ; topHeader . addComponent ( ciaLogoImage ) ; ciaLogoImage . setWidth ( "60px" ) ; ciaLogoImage . setHeight ( "60px" ) ; topHeader . setComponentAlignment ( ciaLogoImage , Alignment . MIDDLE_LEFT ) ; topHeader . setExpandRatio ( ciaLogoImage , ContentRatio . SMALL ) ;


signature:
public class AbstractView { /** * Creates the top title header .
 * @ param topHeader
 * the top header */
private static void createTopTitleHeader ( final HorizontalLayout topHeader ) { } }

implementation: final HorizontalLayout topTitleHeadertPanel = new HorizontalLayout ( ) ; final Label titleLabel = new Label ( "Citizen Intelligence Agency" ) ; titleLabel . setStyleName ( "Header" ) ; topTitleHeadertPanel . addComponent ( titleLabel ) ; topTitleHeadertPanel . setComponentAlignment ( titleLabel , Alignment . MIDDLE_LEFT ) ; final Label sloganLabel = new Label ( "// Tracking politicians like bugs!" ) ; sloganLabel . setStyleName ( "HeaderSlogan" ) ; topTitleHeadertPanel . addComponent ( sloganLabel ) ; topTitleHeadertPanel . setComponentAlignment ( sloganLabel , Alignment . MIDDLE_RIGHT ) ; topHeader . addComponent ( topTitleHeadertPanel ) ; topHeader . setComponentAlignment ( topTitleHeadertPanel , Alignment . MIDDLE_LEFT ) ; topHeader . setExpandRatio ( topTitleHeadertPanel , ContentRatio . GRID ) ;


signature:
public class ObjectFactory { /** * Creates a new Object object .
 * @ param value the value
 * @ return the JAXB element < sweden county electoral region container > */
@ XmlElementDecl ( namespace = "http://landstingvalkrets.val.external.model.cia.hack23.com/impl" , name = "root" ) public JAXBElement < SwedenCountyElectoralRegionContainer > createRoot ( final SwedenCountyElectoralRegionContainer value ) { } }

implementation: return new JAXBElement < > ( _Root_QNAME , SwedenCountyElectoralRegionContainer . class , null , value ) ;


signature:
public class EmailServiceImpl { /** * Inits the settings . */
@ PostConstruct public void initSettings ( ) { } }

implementation: final Collection < GrantedAuthority > authorities = AuthorityUtils . createAuthorityList ( "ROLE_ADMIN" ) ; final Authentication authentication = new UsernamePasswordAuthenticationToken ( "system.init" , "n/a" , authorities ) ; SecurityContextHolder . getContext ( ) . setAuthentication ( authentication ) ; LOGGER . info ( EMAIL_SETTINGS , applicationConfigurationService . checkValueOrLoadDefault ( EMAIL_CONFIGURATION_SEND_EMAILS , SEND_EMAIL , ConfigurationGroup . EXTERNAL_SERVICES , EmailServiceImpl . class . getSimpleName ( ) , SEND_EMAIL , RESPONSIBLE_FOR_SENDING_EMAIL , APPLICATION_EMAIL_SEND_EMAIL , "false" ) ) ; LOGGER . info ( EMAIL_SETTINGS , applicationConfigurationService . checkValueOrLoadDefault ( EMAIL_CONFIGURATION_FROM_EMAIL , FROM_EMAIL , ConfigurationGroup . EXTERNAL_SERVICES , EmailServiceImpl . class . getSimpleName ( ) , SEND_EMAIL , RESPONSIBLE_FOR_SENDING_EMAIL , APPLICATION_EMAIL_FROM_EMAIL , "admin@hack23.com" ) ) ; LOGGER . info ( EMAIL_SETTINGS , applicationConfigurationService . checkValueOrLoadDefault ( EMAIL_CONFIGURATION_SMTP_HOST , SMTP_HOST , ConfigurationGroup . EXTERNAL_SERVICES , EmailServiceImpl . class . getSimpleName ( ) , SMTP_HOST , RESPONSIBLE_FOR_SENDING_EMAIL , APPLICATION_EMAIL_SMTP_HOST , "localhost" ) ) ; LOGGER . info ( EMAIL_SETTINGS , applicationConfigurationService . checkValueOrLoadDefault ( EMAIL_CONFIGURATION_SMTP_PORT , SMTP_PORT , ConfigurationGroup . EXTERNAL_SERVICES , EmailServiceImpl . class . getSimpleName ( ) , SMTP_PORT , RESPONSIBLE_FOR_SENDING_EMAIL , APPLICATION_EMAIL_SMTP_PORT , DEFAULT_SMTP_PORT ) ) ; LOGGER . info ( EMAIL_SETTINGS , applicationConfigurationService . checkValueOrLoadDefault ( EMAIL_CONFIGURATION_SMTP_USERNAME , SMTP_USERNAME , ConfigurationGroup . EXTERNAL_SERVICES , EmailServiceImpl . class . getSimpleName ( ) , SMTP_USERNAME , RESPONSIBLE_FOR_SENDING_EMAIL , APPLICATION_EMAIL_SMTP_USERNAME , "username" ) ) ; LOGGER . info ( EMAIL_SETTINGS , applicationConfigurationService . checkValueOrLoadDefault ( EMAIL_CONFIGURATION_SMTP_SECRET , SMTP_SECRET , ConfigurationGroup . EXTERNAL_SERVICES , EmailServiceImpl . class . getSimpleName ( ) , SMTP_SECRET , RESPONSIBLE_FOR_SENDING_EMAIL , APPLICATION_EMAIL_SMTP_SECRET , "password" ) ) ; LOGGER . info ( EMAIL_SETTINGS , applicationConfigurationService . checkValueOrLoadDefault ( EMAIL_CONFIGURATION_SMTP_AUTH , SMTP_AUTH , ConfigurationGroup . EXTERNAL_SERVICES , EmailServiceImpl . class . getSimpleName ( ) , SMTP_AUTH , RESPONSIBLE_FOR_SENDING_EMAIL , APPLICATION_EMAIL_SMTP_AUTH , "true" ) ) ; LOGGER . info ( EMAIL_SETTINGS , applicationConfigurationService . checkValueOrLoadDefault ( EMAIL_CONFIGURATION_SMTP_STARTTLS_ENABLE , SMTP_STARTTLS_ENABLE , ConfigurationGroup . EXTERNAL_SERVICES , EmailServiceImpl . class . getSimpleName ( ) , SMTP_STARTTLS_ENABLE , RESPONSIBLE_FOR_SENDING_EMAIL , APPLICATION_EMAIL_SMTP_STARTTLS_ENABLE , "true" ) ) ; SecurityContextHolder . getContext ( ) . setAuthentication ( null ) ;


signature:
public class EmailServiceImpl { /** * Gets the mail sender .
 * @ return the mail sender */
private JavaMailSender getMailSender ( ) { } }

implementation: final JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl ( ) ; final ApplicationConfiguration smtpHostConfig = applicationConfigurationService . checkValueOrLoadDefault ( EMAIL_CONFIGURATION_SMTP_HOST , SMTP_HOST , ConfigurationGroup . EXTERNAL_SERVICES , EmailServiceImpl . class . getSimpleName ( ) , SMTP_HOST , RESPONSIBLE_FOR_SENDING_EMAIL , APPLICATION_EMAIL_SMTP_HOST , "localhost" ) ; final ApplicationConfiguration smtpPort = applicationConfigurationService . checkValueOrLoadDefault ( EMAIL_CONFIGURATION_SMTP_PORT , SMTP_PORT , ConfigurationGroup . EXTERNAL_SERVICES , EmailServiceImpl . class . getSimpleName ( ) , SMTP_PORT , RESPONSIBLE_FOR_SENDING_EMAIL , APPLICATION_EMAIL_SMTP_PORT , DEFAULT_SMTP_PORT ) ; final ApplicationConfiguration smtpUsername = applicationConfigurationService . checkValueOrLoadDefault ( EMAIL_CONFIGURATION_SMTP_USERNAME , SMTP_USERNAME , ConfigurationGroup . EXTERNAL_SERVICES , EmailServiceImpl . class . getSimpleName ( ) , SMTP_USERNAME , RESPONSIBLE_FOR_SENDING_EMAIL , APPLICATION_EMAIL_SMTP_USERNAME , "username" ) ; final ApplicationConfiguration smtpPassword = applicationConfigurationService . checkValueOrLoadDefault ( EMAIL_CONFIGURATION_SMTP_SECRET , SMTP_SECRET , ConfigurationGroup . EXTERNAL_SERVICES , EmailServiceImpl . class . getSimpleName ( ) , SMTP_SECRET , RESPONSIBLE_FOR_SENDING_EMAIL , APPLICATION_EMAIL_SMTP_SECRET , "password" ) ; final ApplicationConfiguration smtpAuth = applicationConfigurationService . checkValueOrLoadDefault ( EMAIL_CONFIGURATION_SMTP_AUTH , SMTP_AUTH , ConfigurationGroup . EXTERNAL_SERVICES , EmailServiceImpl . class . getSimpleName ( ) , SMTP_AUTH , RESPONSIBLE_FOR_SENDING_EMAIL , APPLICATION_EMAIL_SMTP_AUTH , "true" ) ; final ApplicationConfiguration smtpStartTlsEnable = applicationConfigurationService . checkValueOrLoadDefault ( EMAIL_CONFIGURATION_SMTP_STARTTLS_ENABLE , SMTP_STARTTLS_ENABLE , ConfigurationGroup . EXTERNAL_SERVICES , EmailServiceImpl . class . getSimpleName ( ) , SMTP_STARTTLS_ENABLE , RESPONSIBLE_FOR_SENDING_EMAIL , APPLICATION_EMAIL_SMTP_STARTTLS_ENABLE , "true" ) ; javaMailSender . setHost ( smtpHostConfig . getPropertyValue ( ) ) ; javaMailSender . setPort ( getSmtpPort ( smtpPort ) ) ; javaMailSender . setUsername ( smtpUsername . getPropertyValue ( ) ) ; javaMailSender . setPassword ( smtpPassword . getPropertyValue ( ) ) ; final Properties javaMailProperties = new Properties ( ) ; javaMailProperties . setProperty ( MAIL_SMTP_AUTH , smtpAuth . getPropertyValue ( ) ) ; javaMailProperties . setProperty ( MAIL_SMTP_STARTTLS_ENABLE , smtpStartTlsEnable . getPropertyValue ( ) ) ; javaMailSender . setJavaMailProperties ( javaMailProperties ) ; return javaMailSender ;


signature:
public class EmailServiceImpl { /** * Gets the smtp port .
 * @ param smtpPort the smtp port
 * @ return the smtp port */
private static int getSmtpPort ( final ApplicationConfiguration smtpPort ) { } }

implementation: if ( StringUtils . isNumeric ( smtpPort . getPropertyValue ( ) ) ) { return Integer . parseInt ( smtpPort . getPropertyValue ( ) ) ; } else { return Integer . parseInt ( DEFAULT_SMTP_PORT ) ; }


signature:
public class ConfigurationManagerImpl { /** * Find language .
 * @ param locale
 * the locale
 * @ return the language data */
private LanguageData findLanguage ( final String locale ) { } }

implementation: for ( final LanguageData languageData : languageDataDAO . getAll ( ) ) { if ( languageData . getLanguageCode ( ) . equalsIgnoreCase ( locale ) ) { return languageData ; } } return null ;


signature:
public class ConfigurationManagerImpl { /** * Gets the supported locales language data .
 * @ return the supported locales language data */
private static List < LanguageData > getSupportedLocalesLanguageData ( ) { } }

implementation: final List < LanguageData > languages = new ArrayList < > ( ) ; for ( final Locale locale : DateFormat . getAvailableLocales ( ) ) { final String localeString = locale . toString ( ) . trim ( ) ; if ( locale . getDisplayCountry ( Locale . ENGLISH ) . length ( ) == 0 && ! StringUtils . isEmpty ( localeString ) && localeString . length ( ) == EXPECTED_LOCALE_LENGTH ) { languages . add ( new LanguageData ( ) . withCreatedDate ( new Date ( ) ) . withLanguageCode ( localeString ) . withLanguageName ( locale . getDisplayName ( Locale . ENGLISH ) ) . withLanguageEnabled ( Boolean . FALSE ) ) ; } } return languages ;


signature:
public class BallotChartsPageModContentFactoryImpl { /** * Creates the issue concern map .
 * @ param partyBallotList
 * the party ballot list
 * @ return the map */
private static Map < String , List < ViewRiksdagenVoteDataBallotPartySummary > > createIssueConcernMap ( final List < ViewRiksdagenVoteDataBallotPartySummary > partyBallotList ) { } }

implementation: final Map < String , List < ViewRiksdagenVoteDataBallotPartySummary > > concernIssuePartyBallotSummaryMap = new HashMap < > ( ) ; for ( final ViewRiksdagenVoteDataBallotPartySummary partySummary : partyBallotList ) { if ( partySummary . getEmbeddedId ( ) . getIssue ( ) != null || partySummary . getEmbeddedId ( ) . getConcern ( ) != null ) { final String key = partySummary . getEmbeddedId ( ) . getIssue ( ) + partySummary . getEmbeddedId ( ) . getConcern ( ) ; final List < ViewRiksdagenVoteDataBallotPartySummary > partySummarList = concernIssuePartyBallotSummaryMap . computeIfAbsent ( key , k -> new ArrayList < > ( ) ) ; partySummarList . add ( partySummary ) ; } } return concernIssuePartyBallotSummaryMap ;


signature:
public class NameSpaceUtil { /** * Sets the name space on xml stream .
 * @ param in the in
 * @ param nameSpace the name space
 * @ return the source
 * @ throws JDOMException the JDOM exception
 * @ throws IOException Signals that an I / O exception has occurred . */
public static Source setNameSpaceOnXmlStream ( final InputStream in , final String nameSpace ) throws JDOMException , IOException { } }

implementation: final SAXBuilder sb = new SAXBuilder ( new XMLReaderSAX2Factory ( false ) ) ; final Document doc = sb . build ( in ) ; doc . getRootElement ( ) . setNamespace ( Namespace . getNamespace ( nameSpace ) ) ; return new JDOMSource ( doc ) ;


signature:
public class AbstractChartDataManagerImpl { /** * Adds the chart .
 * @ param content
 * the content
 * @ param caption
 * the caption
 * @ param chart
 * the chart
 * @ param fullPage
 * the full page */
protected final void addChart ( final AbstractOrderedLayout content , final String caption , final DCharts chart , final boolean fullPage ) { } }

implementation: final HorizontalLayout horizontalLayout = new HorizontalLayout ( ) ; final int browserWindowWidth = getChartWindowWidth ( ) ; final int browserWindowHeight = getChartWindowHeight ( fullPage ) ; horizontalLayout . setWidth ( browserWindowWidth , Unit . PIXELS ) ; horizontalLayout . setHeight ( browserWindowHeight , Unit . PIXELS ) ; horizontalLayout . setMargin ( true ) ; horizontalLayout . setSpacing ( false ) ; horizontalLayout . addStyleName ( "v-layout-content-overview-panel-level1" ) ; final Panel formPanel = new Panel ( ) ; formPanel . setSizeFull ( ) ; formPanel . setContent ( horizontalLayout ) ; formPanel . setCaption ( caption ) ; content . addComponent ( formPanel ) ; content . setExpandRatio ( formPanel , ContentRatio . LARGE ) ; chart . setWidth ( 100 , Unit . PERCENTAGE ) ; chart . setHeight ( 100 , Unit . PERCENTAGE ) ; chart . setMarginRight ( CHART_RIGHT_MARGIN ) ; chart . setMarginLeft ( CHART_LEFT_MARGIN ) ; chart . setMarginBottom ( CHART_BOTTOM_MARGIN_SIZE ) ; chart . setMarginTop ( CHART_TOP_MARGIN_SIZE ) ; horizontalLayout . addComponent ( chart ) ; chart . setCaption ( caption ) ;


signature:
public class AbstractChartDataManagerImpl { /** * Gets the chart window height .
 * @ param fullPage the full page
 * @ return the chart window height */
private static int getChartWindowHeight ( final boolean fullPage ) { } }

implementation: if ( fullPage ) { return Math . max ( ( int ) ( Page . getCurrent ( ) . getBrowserWindowHeight ( ) * HEIGHT_PERCENTAGE_FULL_PAGE ) , MINIMUM_CHART_HEIGHT_FULL_PAGE ) ; } else { return Math . max ( ( int ) ( Page . getCurrent ( ) . getBrowserWindowHeight ( ) * HEIGHT_PERCETAGE_HALF_PAGE ) , NINIMUM_CHART_HEIGHT_HALF_PAGE ) ; }


signature:
public class AbstractChartDataManagerImpl { /** * Gets the party name .
 * @ param party
 * the party
 * @ return the party name */
protected final String getPartyName ( final String party ) { } }

implementation: final DataContainer < ViewRiksdagenParty , String > dataContainer = applicationManager . getDataContainer ( ViewRiksdagenParty . class ) ; final Optional < ViewRiksdagenParty > matchingObjects = dataContainer . getAll ( ) . stream ( ) . filter ( ( final ViewRiksdagenParty p ) -> p . getPartyId ( ) . equalsIgnoreCase ( party ) ) . findFirst ( ) ; if ( matchingObjects . isPresent ( ) ) { return matchingObjects . get ( ) . getPartyName ( ) ; } else { return party ; }


signature:
public class PersonDocumentChartDataManagerImpl { /** * Gets the view riksdagen politician document daily summary map .
 * @ return the view riksdagen politician document daily summary map */
private Map < String , List < ViewRiksdagenPoliticianDocumentDailySummary > > getViewRiksdagenPoliticianDocumentDailySummaryMap ( ) { } }

implementation: final DataContainer < ViewRiksdagenPoliticianDocumentDailySummary , RiksdagenDocumentPersonSummaryEmbeddedId > politicianBallotSummaryDailyDataContainer = getApplicationManager ( ) . getDataContainer ( ViewRiksdagenPoliticianDocumentDailySummary . class ) ; return politicianBallotSummaryDailyDataContainer . getAll ( ) . parallelStream ( ) . filter ( Objects :: nonNull ) . collect ( Collectors . groupingBy ( t -> t . getEmbeddedId ( ) . getPersonId ( ) ) ) ;


signature:
public class SSODigestAuthenticator { /** * " login " is copied without changes from FormAuthenticator */
@ Override public UserIdentity login ( String username , Object password , ServletRequest request ) { } }

implementation: UserIdentity user = super . login ( username , password , request ) ; if ( user != null ) { HttpSession session = ( ( HttpServletRequest ) request ) . getSession ( true ) ; Authentication cached = new SessionAuthentication ( getAuthMethod ( ) , user , password ) ; session . setAttribute ( SessionAuthentication . __J_AUTHENTICATED , cached ) ; } return user ;


signature:
public class JarScannerEx { /** * Scan the provided ServletContext and classloader for JAR files . Each JAR
 * file found will be passed to the callback handler to be processed .
 * @ param context The ServletContext - used to locate and access WEB - INF / lib
 * @ param classloader The classloader - used to access JARs not in WEB - INF / lib
 * @ param callback The handler to process any JARs found
 * @ param jarsToSkip List of JARs to ignore . If this list is null , a default
 * list will be read from the system property defined by
 * { @ link Constants # SKIP _ JARS _ PROPERTY } */
@ Override public void scan ( ServletContext context , ClassLoader classloader , JarScannerCallback callback , Set < String > jarsToSkip ) { } }

implementation:
if ( log . isTraceEnabled ( ) ) { log . trace ( sm . getString ( "jarScan.webinflibStart" ) ) ; } jarsToSkip = jarsToSkip == null ? new HashSet ( ) : new HashSet ( jarsToSkip ) ; jarsToSkip . addAll ( skipPatterns . asSet ( ) ) ; jarsToSkip = Collections . unmodifiableSet ( jarsToSkip ) ; final Set < String > ignoredJars ; if ( jarsToSkip == null ) { ignoredJars = defaultJarsToSkip ; } else { ignoredJars = jarsToSkip ; } // Scan WEB - INF / lib
Set < String > dirList = context . getResourcePaths ( Constants . WEB_INF_LIB ) ; if ( dirList != null ) { Iterator < String > it = dirList . iterator ( ) ; while ( it . hasNext ( ) ) { String path = it . next ( ) ; if ( path . endsWith ( Constants . JAR_EXT ) && ! Matcher . matchName ( ignoredJars , path . substring ( path . lastIndexOf ( "/" ) + 1 ) ) ) { // Need to scan this JAR
if ( log . isDebugEnabled ( ) ) { log . debug ( sm . getString ( "jarScan.webinflibJarScan" , path ) ) ; } URL url = null ; try { // File URLs are always faster to work with so use them
// if available .
String realPath = context . getRealPath ( path ) ; if ( realPath == null ) { url = context . getResource ( path ) ; } else { url = ( new File ( realPath ) ) . toURI ( ) . toURL ( ) ; } process ( callback , url ) ; } catch ( IOException e ) { log . warn ( sm . getString ( "jarScan.webinflibFail" , url ) , e ) ; } } else { if ( log . isTraceEnabled ( ) ) { log . trace ( sm . getString ( "jarScan.webinflibJarNoScan" , path ) ) ; } } } } // Scan the classpath
if ( scanClassPath && classloader != null ) { if ( log . isTraceEnabled ( ) ) { log . trace ( sm . getString ( "jarScan.classloaderStart" ) ) ; } ClassLoader loader = classloader ; ClassLoader stopLoader = null ; if ( ! scanBootstrapClassPath ) { // Stop when we reach the bootstrap class loader
stopLoader = ClassLoader . getSystemClassLoader ( ) . getParent ( ) ; } Set < URL > processedUrls = new HashSet < URL > ( ) ; while ( loader != null && loader != stopLoader ) { if ( loader instanceof URLClassLoader ) { URL [ ] urls = ( ( URLClassLoader ) loader ) . getURLs ( ) ; for ( int i = 0 ; i < urls . length ; i ++ ) { URL url = urls [ i ] ; if ( processedUrls . contains ( url ) ) { continue ; } processedUrls . add ( url ) ; // Extract the jarName if there is one to be found
String jarName = getJarName ( url ) ; // Skip JARs known not to be interesting and JARs
// in WEB - INF / lib we have already scanned
if ( jarName != null && ! ( Matcher . matchName ( ignoredJars , jarName ) || url . toString ( ) . contains ( Constants . WEB_INF_LIB + jarName ) ) ) { if ( log . isDebugEnabled ( ) ) { log . debug ( sm . getString ( "jarScan.classloaderJarScan" , url ) ) ; } try { process ( callback , url ) ; } catch ( IOException ioe ) { log . warn ( sm . getString ( "jarScan.classloaderFail" , url ) , ioe ) ; } } else { if ( log . isTraceEnabled ( ) ) { log . trace ( sm . getString ( "jarScan.classloaderJarNoScan" , url ) ) ; } } } } loader = loader . getParent ( ) ; } }


signature:
public class JarScannerEx { /** * Scan a URL for JARs with the optional extensions to look at all files
 * and all directories . */
private void process ( JarScannerCallback callback , URL url ) throws IOException { } }

implementation:
if ( log . isTraceEnabled ( ) ) { log . trace ( sm . getString ( "jarScan.jarUrlStart" , url ) ) ; } URLConnection conn = url . openConnection ( ) ; if ( conn instanceof JarURLConnection ) { callback . scan ( ( JarURLConnection ) conn ) ; } else { String urlStr = url . toString ( ) ; if ( urlStr . startsWith ( "file:" ) || urlStr . startsWith ( "jndi:" ) || urlStr . startsWith ( "http:" ) || urlStr . startsWith ( "https:" ) ) { if ( urlStr . endsWith ( Constants . JAR_EXT ) ) { URL jarURL = new URL ( "jar:" + urlStr + "!/" ) ; callback . scan ( ( JarURLConnection ) jarURL . openConnection ( ) ) ; } else { File f ; try { f = new File ( url . toURI ( ) ) ; if ( f . isFile ( ) && scanAllFiles ) { // Treat this file as a JAR
URL jarURL = new URL ( "jar:" + urlStr + "!/" ) ; callback . scan ( ( JarURLConnection ) jarURL . openConnection ( ) ) ; } else if ( f . isDirectory ( ) && scanAllDirectories ) { File metainf = new File ( f , "META-INF" ) ; if ( metainf . isDirectory ( ) ) { callback . scan ( f ) ; } } } catch ( URISyntaxException e ) { // Wrap the exception and re - throw
IOException ioe = new IOException ( ) ; ioe . initCause ( e ) ; throw ioe ; } } } }


signature:
public class JarScannerEx { /** * Extract the JAR name , if present , from a URL */
private String getJarName ( URL url ) { } }

implementation: String name = null ; String path = url . getPath ( ) ; int end = path . indexOf ( Constants . JAR_EXT ) ; if ( end != - 1 ) { int start = path . lastIndexOf ( "/" , end ) ; name = path . substring ( start + 1 , end + 4 ) ; } else if ( isScanAllDirectories ( ) ) { int start = path . lastIndexOf ( "/" ) ; name = path . substring ( start + 1 ) ; } return name ;


signature:
public class EagleBeanFactoryPostProcessor { /** * 注入Registry
 * @ param beanFactory bean工厂
 * @ throws Exception */
private void registerRegistry ( DefaultListableBeanFactory beanFactory ) throws Exception { } }

implementation: if ( CollectionUtil . isEmpty ( eagleConfig . getRegistry ( ) ) ) { throw new EagleFrameException ( "eagle.registry not config" ) ; } for ( RegistryConfig config : eagleConfig . getRegistry ( ) ) { String id = config . getId ( ) ; id = Strings . isNullOrEmpty ( id ) ? config . getName ( ) : config . getId ( ) ; BeanDefinitionBuilder beanBuilder = generateBuilder ( config , RegistryBean . class ) ; beanFactory . registerBeanDefinition ( generateId ( id , beanBuilder , beanFactory ) , beanBuilder . getBeanDefinition ( ) ) ; }


signature:
public class EagleBeanFactoryPostProcessor { /** * 注入Protocol
 * @ param beanFactory bean工厂
 * @ throws Exception */
private void registryProtocol ( DefaultListableBeanFactory beanFactory ) throws Exception { } }

implementation: if ( CollectionUtil . isEmpty ( eagleConfig . getProtocol ( ) ) ) { throw new EagleFrameException ( "eagle.protocol not config" ) ; } for ( ProtocolConfig config : eagleConfig . getProtocol ( ) ) { String id = config . getId ( ) ; id = Strings . isNullOrEmpty ( id ) ? config . getName ( ) : config . getId ( ) ; BeanDefinitionBuilder beanBuilder = generateBuilder ( config , ProtocolBean . class ) ; beanFactory . registerBeanDefinition ( generateId ( id , beanBuilder , beanFactory ) , beanBuilder . getBeanDefinition ( ) ) ; }


signature:
public class EagleBeanFactoryPostProcessor { /** * 注入BaseService
 * @ param beanFactory bean工厂
 * @ throws Exception */
private void registryBaseService ( DefaultListableBeanFactory beanFactory ) throws Exception { } }

implementation: if ( CollectionUtil . isEmpty ( eagleConfig . getBaseService ( ) ) ) { return ; } for ( BootBaseServiceConfig config : eagleConfig . getBaseService ( ) ) { String id = config . getId ( ) ; BeanDefinitionBuilder beanBuilder = generateBuilder ( config , BaseServiceBean . class ) ; multiRef ( "registries" , config . getRegistry ( ) , beanBuilder ) ; beanFactory . registerBeanDefinition ( generateId ( id , beanBuilder , beanFactory ) , beanBuilder . getBeanDefinition ( ) ) ; }


signature:
public class EagleBeanFactoryPostProcessor { /** * 注入BaseRefer
 * @ param beanFactory bean工厂
 * @ throws Exception */
private void registryBaseRefer ( DefaultListableBeanFactory beanFactory ) throws Exception { } }

implementation: if ( CollectionUtil . isEmpty ( eagleConfig . getBaseRefer ( ) ) ) { return ; } for ( BootBaseReferConfig config : eagleConfig . getBaseRefer ( ) ) { String id = config . getId ( ) ; BeanDefinitionBuilder beanBuilder = generateBuilder ( config , BaseReferBean . class ) ; multiRef ( "registries" , config . getRegistry ( ) , beanBuilder ) ; multiRef ( "protocols" , config . getProtocol ( ) , beanBuilder ) ; beanFactory . registerBeanDefinition ( generateId ( id , beanBuilder , beanFactory ) , beanBuilder . getBeanDefinition ( ) ) ; }


signature:
public class ExecutorQueue { /** * 注 : tomcat的代码进行一些小变更 */
public boolean offer ( Runnable o ) { } }

implementation:
int poolSize = threadPoolExecutor . getPoolSize ( ) ; // we are maxed out on threads , simply queue the object
if ( poolSize == threadPoolExecutor . getMaximumPoolSize ( ) ) { return super . offer ( o ) ; } // we have idle threads , just add it to the queue
// note that we don ' t use getActiveCount ( ) , see BZ 49730
if ( threadPoolExecutor . getSubmittedTasksCount ( ) <= poolSize ) { return super . offer ( o ) ; } // if we have less threads than maximum force creation of a new
// thread
if ( poolSize < threadPoolExecutor . getMaximumPoolSize ( ) ) { return false ; } // if we reached here , we need to add it to the queue
return super . offer ( o ) ;


signature:
public class StringUtil { /** * Splits the specified { @ link String } with the specified delimiter . This operation is a simplified and optimized
 * version of { @ link String # split ( String ) } . */
public static String [ ] split ( String value , char delim ) { } }

implementation:
final int end = value . length ( ) ; final List < String > res = new ArrayList < String > ( ) ; int start = 0 ; for ( int i = 0 ; i < end ; i ++ ) { if ( value . charAt ( i ) == delim ) { if ( start == i ) { res . add ( EMPTY_STRING ) ; } else { res . add ( value . substring ( start , i ) ) ; } start = i + 1 ; } } if ( start == 0 ) { // If no delimiter was found in the value
res . add ( value ) ; } else { if ( start != end ) { // Add the last element if it ' s not empty .
res . add ( value . substring ( start , end ) ) ; } else { // Truncate trailing empty elements .
for ( int i = res . size ( ) - 1 ; i >= 0 ; i -- ) { if ( res . get ( i ) . isEmpty ( ) ) { res . remove ( i ) ; } else { break ; } } } } return res . toArray ( new String [ res . size ( ) ] ) ;


signature:
public class StringUtil { /** * Generates a simplified name from a { @ link Class } . Similar to { @ link Class # getSimpleName ( ) } , but it works fine
 * with anonymous classes . */
public static String simpleClassName ( Class < ? > clazz ) { } }

implementation: Package pkg = clazz . getPackage ( ) ; if ( pkg != null ) { return clazz . getName ( ) . substring ( pkg . getName ( ) . length ( ) + 1 ) ; } else { return clazz . getName ( ) ; }


signature:
public class DistributeIdGenerator { /** * 获得下一个ID ( 该方法是线程安全的 )
 * @ return SnowflakeId */
public synchronized long nextId ( ) { } }

implementation:
long timestamp = timeGen ( ) ; // 如果当前时间小于上一次ID生成的时间戳 , 说明系统时钟回退过这个时候应当抛出异常
if ( timestamp < lastTimestamp ) { throw new RuntimeException ( String . format ( "Clock moved backwards.  Refusing to generate id for %d milliseconds" , lastTimestamp - timestamp ) ) ; } // 如果是同一时间生成的 , 则进行毫秒内序列
if ( lastTimestamp == timestamp ) { sequence = ( sequence + 1 ) & sequenceMask ; // 毫秒内序列溢出
if ( sequence == 0 ) { // 阻塞到下一个毫秒 , 获得新的时间戳
timestamp = tilNextMillis ( lastTimestamp ) ; } } // 时间戳改变 , 毫秒内序列重置
else { sequence = 0L ; } // 上次生成ID的时间截
lastTimestamp = timestamp ; // 移位并通过或运算拼到一起组成64位的ID
return ( ( timestamp - twepoch ) << timestampLeftShift ) | sequence ;


signature:
public class AopTargetUtil { /** * 获取目标对象class .
 * @ param proxy 代理对象
 * @ return 目标对象class */
public static Class < ? > getTargetClass ( Object proxy ) throws Exception { } }

implementation:
if ( ! AopUtils . isAopProxy ( proxy ) ) { return proxy . getClass ( ) ; // 不是代理对象
} return AopUtils . getTargetClass ( proxy ) ;


signature:
public class AopTargetUtil { /** * 获取目标对象 .
 * @ param proxy 代理对象
 * @ return 目标对象 */
public static Object getTarget ( final Object proxy ) { } }

implementation: if ( ! AopUtils . isAopProxy ( proxy ) ) { return proxy ; } if ( AopUtils . isJdkDynamicProxy ( proxy ) ) { return getProxyTargetObject ( proxy , "h" ) ; } else { return getProxyTargetObject ( proxy , "CGLIB$CALLBACK_0" ) ; }


signature:
public class ExceptionUtil { /** * 将Throwable异常转换为字符串 .
 * @ param cause 需要转换的异常
 * @ return 转换后的异常字符串 */
public static String transform ( final Throwable cause ) { } }

implementation: if ( null == cause ) { return "" ; } StringWriter result = new StringWriter ( ) ; try ( PrintWriter writer = new PrintWriter ( result ) ) { cause . printStackTrace ( writer ) ; } return result . toString ( ) ;


signature:
public class ReflectUtil { /** * 获取method方式的接口参数 , 以逗号分割 , 拼接clz列表 。 如果没有参数 , 那么void表示
 * @ param method
 * @ return */
public static String getMethodParamDesc ( Method method ) { } }

implementation: if ( method . getParameterTypes ( ) == null || method . getParameterTypes ( ) . length == 0 ) { return null ; } StringBuilder builder = new StringBuilder ( ) ; Class < ? > [ ] clzs = method . getParameterTypes ( ) ; for ( Class < ? > clz : clzs ) { String className = getName ( clz ) ; builder . append ( className ) . append ( PARAM_CLASS_SPLIT ) ; } return builder . substring ( 0 , builder . length ( ) - 1 ) ;


signature:
public class ReflectUtil { /** * 获取方法的标示 : method _ name + " ( " + paramDesc + " ) "
 * @ param method
 * @ return */
public static String getMethodDesc ( Method method ) { } }

implementation: String methodParamDesc = getMethodParamDesc ( method ) ; return getMethodDesc ( method . getName ( ) , methodParamDesc ) ;


signature:
public class ReflectUtil { /** * 获取方法的标示 : method _ name + " ( " + paramDesc + " ) "
 * @ param
 * @ return */
public static String getMethodDesc ( String methodName , String paramDesc ) { } }

implementation: if ( paramDesc == null ) { return String . format ( METHOD_DESC_VOID , methodName ) ; } else { return String . format ( METHOD_DESC_PARAM , methodName , paramDesc ) ; }


signature:
public class ReflectUtil { /** * 需要支持一维数组 、 二维数组等
 * @ param
 * @ return */
public static String getName ( Class < ? > clz ) { } }

implementation:
if ( clz == null ) { return null ; } String className = class2NameCache . get ( clz ) ; if ( className != null ) { return className ; } className = getNameWithoutCache ( clz ) ; // 与name2ClassCache同样道理 , 如果没有恶心的代码 , 这块内存大小应该可控
class2NameCache . putIfAbsent ( clz , className ) ; return className ;


signature:
public class ReflectUtil { /** * 获取clz public method
 * < pre >
 * 1 ) 不包含构造函数
 * 2 ) 不包含Object . class
 * 3 ) 包含该clz的父类的所有public方法
 * < / pre >
 * @ param clz
 * @ return */
public static List < Method > getPublicMethod ( Class < ? > clz ) { } }

implementation: Method [ ] methods = clz . getMethods ( ) ; List < Method > ret = new ArrayList < Method > ( ) ; for ( Method method : methods ) { boolean isPublic = Modifier . isPublic ( method . getModifiers ( ) ) ; boolean isNotObjectClass = method . getDeclaringClass ( ) != Object . class ; if ( isPublic && isNotObjectClass ) { ret . add ( method ) ; } } return ret ;


signature:
public class IpUtil { /** * 获取本机IP地址 .
 * 有限获取外网IP地址 .
 * 也有可能是链接着路由器的最终IP地址 .
 * @ return 本机IP地址 */
public static String getIp ( ) { } }

implementation: if ( null != cachedIpAddress ) { return cachedIpAddress ; } Enumeration < NetworkInterface > netInterfaces ; try { netInterfaces = NetworkInterface . getNetworkInterfaces ( ) ; } catch ( final SocketException ex ) { throw new EagleFrameException ( ex ) ; } String localIpAddress = null ; while ( netInterfaces . hasMoreElements ( ) ) { NetworkInterface netInterface = netInterfaces . nextElement ( ) ; Enumeration < InetAddress > ipAddresses = netInterface . getInetAddresses ( ) ; while ( ipAddresses . hasMoreElements ( ) ) { InetAddress ipAddress = ipAddresses . nextElement ( ) ; if ( isPublicIpAddress ( ipAddress ) ) { String publicIpAddress = ipAddress . getHostAddress ( ) ; cachedIpAddress = publicIpAddress ; return publicIpAddress ; } if ( isLocalIpAddress ( ipAddress ) ) { localIpAddress = ipAddress . getHostAddress ( ) ; } } } cachedIpAddress = localIpAddress ; return localIpAddress ;


signature:
public class RegistryCenterRestfulApi { /** * 判断是否存在已连接的注册中心配置 .
 * @ param request HTTP请求
 * @ return 是否存在已连接的注册中心配置 */
@ RequestMapping ( value = "/activated" , method = RequestMethod . GET ) public boolean activated ( final HttpServletRequest request ) { } }

implementation: return regCenterService . loadActivated ( ) . isPresent ( ) ;


signature:
public class RegistryCenterRestfulApi { /** * 读取注册中心配置集合 .
 * @ param request HTTP请求
 * @ return 注册中心配置集合 */
@ RequestMapping ( value = "/load" , method = RequestMethod . GET ) public Collection < RegistryCenterConfiguration > load ( final HttpServletRequest request ) { } }

implementation: Optional < RegistryCenterConfiguration > regCenterConfig = regCenterService . loadActivated ( ) ; if ( regCenterConfig . isPresent ( ) ) { setRegistryCenterNameToSession ( regCenterConfig . get ( ) , request . getSession ( ) ) ; } return regCenterService . loadAll ( ) . getRegistryCenterConfiguration ( ) ;


signature:
public class RegistryCenterRestfulApi { /** * 添加注册中心 .
 * @ param config 注册中心配置
 * @ return 是否添加成功 */
@ RequestMapping ( value = "/add" , method = RequestMethod . POST ) public boolean add ( final @ RequestBody RegistryCenterConfiguration config ) { } }

implementation: return regCenterService . add ( config ) ;


signature:
public class RegistryCenterRestfulApi { /** * 删除注册中心 .
 * @ param config 注册中心配置 */
@ RequestMapping ( value = "/delete" , method = RequestMethod . DELETE ) public boolean delete ( final @ RequestBody RegistryCenterConfiguration config ) { } }

implementation: regCenterService . delete ( config . getName ( ) ) ; return true ;


signature:
public class EmbedZookeeperServer { /** * 内存版的内嵌Zookeeper .
 * @ param port Zookeeper的通信端口号 */
public static void start ( final int port ) { } }

implementation: try { testingServer = new TestingServer ( port , new File ( String . format ( "target/test_zk_data/%s/" , System . nanoTime ( ) ) ) ) ; } catch ( final Exception ex ) { ex . printStackTrace ( ) ; } finally { Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( ) { @ Override public void run ( ) { try { Thread . sleep ( 1000L ) ; testingServer . close ( ) ; } catch ( final InterruptedException | IOException ex ) { } } } ) ; }


signature:
public class EagleTraceCglibProxy { /** * Process a return value . Wraps a return of { @ code this } if necessary to be the
 * { @ code proxy } and also verifies that { @ code null } is not returned as a primitive . */
private static Object processReturnType ( Object proxy , Object target , Method method , Object retVal ) { } }

implementation:
// Massage return value if necessary
if ( retVal != null && retVal == target && ! RawTargetAccess . class . isAssignableFrom ( method . getDeclaringClass ( ) ) ) { // Special case : it returned " this " . Note that we can ' t help
// if the target sets a reference to itself in another returned object .
retVal = proxy ; } Class < ? > returnType = method . getReturnType ( ) ; if ( retVal == null && returnType != Void . TYPE && returnType . isPrimitive ( ) ) { throw new AopInvocationException ( "Null return value from advice does not match primitive return type for: " + method ) ; } return retVal ;


signature:
public class NettyClient { /** * 只有单线程执行该方法 , 不用加同步 */
public AbstractNettyChannel newChannel ( ) throws InterruptedException { } }

implementation: ChannelFuture channelFuture = bootstrap . connect ( remoteAddress ) . sync ( ) ; Channel channel = channelFuture . channel ( ) ; return this . callBack == null ? new SyncNettyChannel ( this , channel ) : new AsyncNettyChannel ( this , channel ) ;


signature:
public class NettyClient { /** * 联系调用失败超过配置的次数 , 将该client设置为无效 */
public void incrErrorCount ( ) { } }

implementation:
long count = errorCount . incrementAndGet ( ) ; // 如果节点是可用状态 , 同时当前连续失败的次数超过限制maxClientConnection次 , 那么把该节点标示为不可用
if ( count >= maxInvokeError && stat . get ( ) ) { if ( stat . compareAndSet ( true , false ) ) { logger . error ( "NettyClient unavailable Error: config='" + config . getInterfaceName ( ) + "' '" + config . identity ( ) + "'" ) ; } }


signature:
public class NettyClient { /** * 通过心跳机制检测如果client恢复 , 则重新启用client */
public void resetErrorCount ( ) { } }

implementation: errorCount . set ( 0 ) ; if ( ! stat . get ( ) && init . get ( ) && errorCount . intValue ( ) < maxInvokeError && stat . compareAndSet ( false , true ) ) { logger . info ( "NettyClient recover available: interfaceName='" + config . getInterfaceName ( ) + "' '" + config . identity ( ) + "'" ) ; }


signature:
public class RegistryCenterFactory { /** * 创建注册中心 .
 * @ param connectString 注册中心连接字符串
 * @ param namespace 注册中心命名空间
 * @ param digest 注册中心凭证
 * @ return 注册中心对象 */
public static CoordinatorRegistryCenter createCoordinatorRegistryCenter ( final String connectString , final String namespace , final Optional < String > digest ) { } }

implementation: Hasher hasher = Hashing . md5 ( ) . newHasher ( ) . putString ( connectString , Charsets . UTF_8 ) . putString ( namespace , Charsets . UTF_8 ) ; if ( digest . isPresent ( ) ) { hasher . putString ( digest . get ( ) , Charsets . UTF_8 ) ; } HashCode hashCode = hasher . hash ( ) ; CoordinatorRegistryCenter result = REG_CENTER_REGISTRY . get ( hashCode ) ; if ( null != result ) { return result ; } MergeConfig zkConfig = new MergeConfig ( ) ; zkConfig . addExt ( ConfigEnum . address . getName ( ) , connectString ) ; zkConfig . addExt ( ConfigEnum . namespace . getName ( ) , namespace ) ; if ( digest . isPresent ( ) ) { zkConfig . addExt ( ConfigEnum . digest . getName ( ) , digest . get ( ) ) ; } result = new ZookeeperRegistryCenter ( zkConfig ) ; result . init ( ) ; REG_CENTER_REGISTRY . put ( hashCode , result ) ; return result ;


signature:
public class ServiceApiFactory { /** * 创建服务管理API对象 .
 * @ param connectString 注册中心连接字符串
 * @ param namespace 注册中心命名空间
 * @ param digest 注册中心凭证
 * @ return 服务管理API对象 */
public static InterfaceApiService createServiceAPI ( final String connectString , final String namespace , final Optional < String > digest ) { } }

implementation: return new InterfaceApiServiceImpl ( RegistryCenterFactory . createCoordinatorRegistryCenter ( connectString , namespace , digest ) ) ;


signature:
public class MonkeyRunnerMojo { /** * Actually plays tests .
 * @ param device
 * the device on which tests are going to be executed .
 * @ param iTestRunListeners
 * test run listeners .
 * @ throws MojoExecutionException
 * if exercising app threw an exception and isIgnoreTestFailures is false . .
 * @ throws MojoFailureException
 * if exercising app failed and isIgnoreTestFailures is false . */
protected void run ( IDevice device , ITestRunListener ... iTestRunListeners ) throws MojoExecutionException , MojoFailureException { } }

implementation: this . mTestListeners = iTestRunListeners ; getLog ( ) . debug ( "Parsed values for Android Monkey Runner invocation: " ) ; CommandExecutor executor = CommandExecutor . Factory . createDefaultCommmandExecutor ( ) ; if ( ! Os . isFamily ( Os . FAMILY_WINDOWS ) ) { executor . setCustomShell ( new CustomBourneShell ( ) ) ; } executor . setLogger ( this . getLog ( ) ) ; String command = getAndroidSdk ( ) . getMonkeyRunnerPath ( ) ; List < String > pluginParameters = new ArrayList < String > ( ) ; if ( parsedPlugins != null && parsedPlugins . length != 0 ) { for ( String plugin : parsedPlugins ) { String pluginFilePath = new File ( project . getBasedir ( ) , plugin ) . getAbsolutePath ( ) ; pluginParameters . add ( "-plugin " + pluginFilePath ) ; } } if ( parsedPrograms != null && ! parsedPrograms . isEmpty ( ) ) { handleTestRunStarted ( ) ; errorListener = new MonkeyRunnerErrorListener ( ) ; executor . setErrorListener ( errorListener ) ; for ( Program program : parsedPrograms ) { List < String > parameters = new ArrayList < String > ( pluginParameters ) ; String programFileName = new File ( project . getBasedir ( ) , program . getFilename ( ) ) . getAbsolutePath ( ) ; parameters . add ( programFileName ) ; String testName = programFileName ; if ( testName . contains ( "/" ) ) { testName . substring ( testName . indexOf ( '/' ) + 1 ) ; } mCurrentTestIndentifier = new TestIdentifier ( "MonkeyTest " , testName ) ; String programOptions = program . getOptions ( ) ; if ( parsedInjectDeviceSerialNumberIntoScript != null && parsedInjectDeviceSerialNumberIntoScript ) { parameters . add ( device . getSerialNumber ( ) ) ; } if ( programOptions != null && ! StringUtils . isEmpty ( programOptions ) ) { parameters . add ( programOptions ) ; } try { getLog ( ) . info ( "Running command: " + command ) ; getLog ( ) . info ( "with parameters: " + parameters ) ; handleTestStarted ( ) ; executor . setCaptureStdOut ( true ) ; executor . executeCommand ( command , parameters , true ) ; handleTestEnded ( ) ; } catch ( ExecutionException e ) { getLog ( ) . info ( "Monkey runner produced errors" ) ; handleTestRunFailed ( e . getMessage ( ) ) ; if ( ! isIgnoreTestFailures ( ) ) { getLog ( ) . info ( "Project is configured to fail on error." ) ; getLog ( ) . info ( "Inspect monkey runner reports or re-run with -X to see monkey runner errors in log" ) ; getLog ( ) . info ( "Failing build as configured. Ignore following error message." ) ; if ( errorListener . hasError ) { getLog ( ) . info ( "Stack trace is:" ) ; getLog ( ) . info ( errorListener . getStackTrace ( ) ) ; } throw new MojoExecutionException ( "" , e ) ; } } if ( errorListener . hasError ( ) ) { handleCrash ( ) ; } } handleTestRunEnded ( ) ; } getLog ( ) . info ( "Monkey runner test runs completed successfully." ) ;


signature:
public class AbstractEmulatorMojo { /** * Are we running on a flavour of Windows .
 * @ return */
private boolean isWindows ( ) { } }

implementation: boolean result ; if ( OS_NAME . toLowerCase ( ) . contains ( "windows" ) ) { result = true ; } else { result = false ; } getLog ( ) . debug ( "isWindows: " + result ) ; return result ;


signature:
public class AbstractEmulatorMojo { /** * Start the Android Emulator with the specified options .
 * @ throws org . apache . maven . plugin . MojoExecutionException
 * @ see # emulatorAvd
 * @ see # emulatorWait
 * @ see # emulatorOptions */
protected void startAndroidEmulator ( ) throws MojoExecutionException { } }

implementation:
parseParameters ( ) ; CommandExecutor executor = CommandExecutor . Factory . createDefaultCommmandExecutor ( ) ; executor . setLogger ( this . getLog ( ) ) ; try { String filename ; if ( isWindows ( ) ) { filename = writeEmulatorStartScriptWindows ( ) ; } else { filename = writeEmulatorStartScriptUnix ( ) ; } final AndroidDebugBridge androidDebugBridge = initAndroidDebugBridge ( ) ; if ( androidDebugBridge . isConnected ( ) ) { waitForInitialDeviceList ( androidDebugBridge ) ; List < IDevice > devices = Arrays . asList ( androidDebugBridge . getDevices ( ) ) ; int numberOfDevices = devices . size ( ) ; getLog ( ) . info ( "Found " + numberOfDevices + " devices connected with the Android Debug Bridge" ) ; IDevice existingEmulator = findExistingEmulator ( devices ) ; if ( existingEmulator == null ) { getLog ( ) . info ( START_EMULATOR_MSG + filename ) ; executor . executeCommand ( filename , null ) ; getLog ( ) . info ( START_EMULATOR_WAIT_MSG + parsedWait ) ; // wait for the emulator to start up
boolean booted = waitUntilDeviceIsBootedOrTimeout ( androidDebugBridge ) ; if ( booted ) { getLog ( ) . info ( "Emulator is up and running." ) ; unlockEmulator ( androidDebugBridge ) ; } else { throw new MojoExecutionException ( "Timeout while waiting for emulator to startup." ) ; } } else { getLog ( ) . info ( String . format ( "Emulator already running [Serial No: '%s', AVD Name '%s']. " + "Skipping start and wait." , existingEmulator . getSerialNumber ( ) , existingEmulator . getAvdName ( ) ) ) ; } } } catch ( Exception e ) { throw new MojoExecutionException ( "" , e ) ; }


signature:
public class AbstractEmulatorMojo { /** * Unlocks the emulator .
 * @ param androidDebugBridge */
void unlockEmulator ( AndroidDebugBridge androidDebugBridge ) { } }

implementation: if ( emulatorUnlock ) { IDevice myEmulator = findExistingEmulator ( Arrays . asList ( androidDebugBridge . getDevices ( ) ) ) ; int devicePort = extractPortFromDevice ( myEmulator ) ; if ( devicePort == - 1 ) { getLog ( ) . info ( "Unable to retrieve port to unlock emulator " + DeviceHelper . getDescriptiveName ( myEmulator ) ) ; } else { getLog ( ) . info ( "Unlocking emulator " + DeviceHelper . getDescriptiveName ( myEmulator ) ) ; sendEmulatorCommand ( devicePort , "event send EV_KEY:KEY_SOFT1:1" ) ; sendEmulatorCommand ( devicePort , "event send EV_KEY:KEY_SOFT1:0" ) ; sendEmulatorCommand ( devicePort , "event send EV_KEY:KEY_SOFT1:1" ) ; sendEmulatorCommand ( devicePort , "event send EV_KEY:KEY_SOFT1:0" ) ; } }


signature:
public class AbstractEmulatorMojo { /** * TODO Higher default timeout ( s ) ? : Perhaps at least for emulators , since they are probably booted or even created on demand */
boolean waitUntilDeviceIsBootedOrTimeout ( AndroidDebugBridge androidDebugBridge ) throws MojoExecutionException { } }

implementation:
final long timeout = System . currentTimeMillis ( ) + Long . parseLong ( parsedWait ) ; IDevice myEmulator ; boolean devOnline ; boolean sysBootCompleted = false ; long remainingTime = 0 ; // If necessary , wait until the device is online or the specified timeout is reached
boolean waitingForConnection = false ; do { myEmulator = findExistingEmulator ( Arrays . asList ( androidDebugBridge . getDevices ( ) ) ) ; devOnline = ( myEmulator != null ) && ( myEmulator . isOnline ( ) ) ; if ( devOnline ) { break ; } else { myEmulator = null ; } if ( ! waitingForConnection ) { waitingForConnection = true ; getLog ( ) . info ( "Waiting for the device to go online..." ) ; } try { Thread . sleep ( MILLIS_TO_SLEEP_BETWEEN_DEVICE_ONLINE_CHECKS ) ; } catch ( InterruptedException e ) { throw new MojoExecutionException ( "Interrupted waiting for device to become ready" ) ; } remainingTime = timeout - System . currentTimeMillis ( ) ; } while ( remainingTime > 0 ) ; if ( devOnline ) { boolean waitingForBootCompleted = false ; final String [ ] bootIndicatorPropValues = new String [ BOOT_INDICATOR_PROP_NAMES . length ] ; boolean anyTargetStateReached = false ; boolean requiredTargetStatesReached = false ; // If necessary , wait until the device ' s system is booted or the specified timeout is reached
do { try { // update state flags . . .
anyTargetStateReached = false ; requiredTargetStatesReached = true ; for ( int indicatorProp = 0 ; indicatorProp < BOOT_INDICATOR_PROP_NAMES . length ; ++ indicatorProp ) { // issue an un - cached property request
boolean targetStateReached = ( bootIndicatorPropValues [ indicatorProp ] != null && bootIndicatorPropValues [ indicatorProp ] . equals ( BOOT_INDICATOR_PROP_TARGET_VALUES [ indicatorProp ] ) ) ; if ( ! targetStateReached ) { // ( re ) query
bootIndicatorPropValues [ indicatorProp ] = myEmulator . getPropertySync ( BOOT_INDICATOR_PROP_NAMES [ indicatorProp ] ) ; targetStateReached = ( bootIndicatorPropValues [ indicatorProp ] != null && bootIndicatorPropValues [ indicatorProp ] . equals ( BOOT_INDICATOR_PROP_TARGET_VALUES [ indicatorProp ] ) ) ; } anyTargetStateReached |= targetStateReached ; requiredTargetStatesReached &= BOOT_INDICATOR_PROP_WAIT_FOR [ indicatorProp ] ? targetStateReached : true ; getLog ( ) . debug ( BOOT_INDICATOR_PROP_NAMES [ indicatorProp ] + " : " + bootIndicatorPropValues [ indicatorProp ] + ( targetStateReached ? " == " : " != " ) + BOOT_INDICATOR_PROP_TARGET_VALUES [ indicatorProp ] + " [" + ( targetStateReached ? "OK" : "PENDING" ) + ']' ) ; } } catch ( TimeoutException e ) { // TODO Abort here ? Not too problematic since timeouts are used
// optimistically ignore this exception and continue . . .
} catch ( AdbCommandRejectedException e ) { // TODO Abort here ? Not too problematic since timeouts are used
// optimistically ignore this exception and continue . . .
} catch ( ShellCommandUnresponsiveException e ) { // TODO Abort here ? Not too problematic since timeouts are used
// optimistically ignore this exception and continue . . .
} catch ( IOException e ) { throw new MojoExecutionException ( "IO error during status request" , e ) ; } remainingTime = timeout - System . currentTimeMillis ( ) ; if ( remainingTime > 0 ) { // consider the boot process to be finished , if all required states have been reached
sysBootCompleted = requiredTargetStatesReached ; } else { // on timeout , use any indicator
sysBootCompleted = anyTargetStateReached ; } if ( remainingTime > 0 && ! sysBootCompleted ) { if ( ! waitingForBootCompleted ) { waitingForBootCompleted = true ; getLog ( ) . info ( "Waiting for the device to finish booting..." ) ; } try { Thread . sleep ( MILLIS_TO_SLEEP_BETWEEN_SYS_BOOTED_CHECKS ) ; } catch ( InterruptedException e ) { throw new MojoExecutionException ( "Interrupted while waiting for the device to finish booting" ) ; } } } while ( ! sysBootCompleted && remainingTime > 0 ) ; if ( sysBootCompleted && remainingTime < START_TIMEOUT_REMAINING_TIME_WARNING_THRESHOLD ) { getLog ( ) . warn ( "Boot indicators have been signalled, but remaining time was " + remainingTime + " ms" ) ; } } return sysBootCompleted ;


signature:
public class AbstractEmulatorMojo { /** * Checks whether the given device has the same AVD name as the device which the current command
 * is related to . < code > true < / code > returned if the device AVD names are identical ( independent of case )
 * and < code > false < / code > if the device AVD names are different .
 * @ param device The device to check
 * @ return Boolean results of the check */
private boolean isExistingEmulator ( IDevice device ) { } }

implementation: return ( ( device . getAvdName ( ) != null ) && ( device . getAvdName ( ) . equalsIgnoreCase ( parsedAvd ) ) ) ;


signature:
public class AbstractEmulatorMojo { /** * Writes the script to start the emulator in the background for windows based environments .
 * @ return absolute path name of start script
 * @ throws IOException
 * @ throws MojoExecutionException */
private String writeEmulatorStartScriptWindows ( ) throws MojoExecutionException { } }

implementation:
String filename = SCRIPT_FOLDER + "\\android-maven-plugin-emulator-start.vbs" ; File file = new File ( filename ) ; PrintWriter writer = null ; try { writer = new PrintWriter ( new FileWriter ( file ) ) ; // command needs to be assembled before unique window title since it parses settings and sets up parsedAvd
// and others .
String command = assembleStartCommandLine ( ) ; String uniqueWindowTitle = "AndroidMavenPlugin-AVD" + parsedAvd ; writer . println ( "Dim oShell" ) ; writer . println ( "Set oShell = WScript.CreateObject(\"WScript.shell\")" ) ; String cmdPath = System . getenv ( "COMSPEC" ) ; if ( cmdPath == null ) { cmdPath = "cmd.exe" ; } String cmd = cmdPath + " /X /C START /SEPARATE \"\"" + uniqueWindowTitle + "\"\"  " + command . trim ( ) ; writer . println ( "oShell.run \"" + cmd + "\"" ) ; } catch ( IOException e ) { getLog ( ) . error ( "Failure writing file " + filename ) ; } finally { if ( writer != null ) { writer . flush ( ) ; writer . close ( ) ; } } file . setExecutable ( true ) ; return filename ;


signature:
public class AbstractEmulatorMojo { /** * Writes the script to start the emulator in the background for unix based environments .
 * @ return absolute path name of start script
 * @ throws IOException
 * @ throws MojoExecutionException */
private String writeEmulatorStartScriptUnix ( ) throws MojoExecutionException { } }

implementation:
String filename = SCRIPT_FOLDER + "/android-maven-plugin-emulator-start.sh" ; File sh ; sh = new File ( "/bin/bash" ) ; if ( ! sh . exists ( ) ) { sh = new File ( "/usr/bin/bash" ) ; } if ( ! sh . exists ( ) ) { sh = new File ( "/bin/sh" ) ; } File file = new File ( filename ) ; PrintWriter writer = null ; try { writer = new PrintWriter ( new FileWriter ( file ) ) ; writer . println ( "#!" + sh . getAbsolutePath ( ) ) ; writer . print ( assembleStartCommandLine ( ) ) ; writer . print ( " 1>/dev/null 2>&1 &" ) ; // redirect outputs and run as background task
} catch ( IOException e ) { getLog ( ) . error ( "Failure writing file " + filename ) ; } finally { if ( writer != null ) { writer . flush ( ) ; writer . close ( ) ; } } file . setExecutable ( true ) ; return filename ;


signature:
public class AbstractEmulatorMojo { /** * Stop the running Android Emulator .
 * @ throws org . apache . maven . plugin . MojoExecutionException */
protected void stopAndroidEmulator ( ) throws MojoExecutionException { } }

implementation: parseParameters ( ) ; final AndroidDebugBridge androidDebugBridge = initAndroidDebugBridge ( ) ; if ( androidDebugBridge . isConnected ( ) ) { List < IDevice > devices = Arrays . asList ( androidDebugBridge . getDevices ( ) ) ; int numberOfDevices = devices . size ( ) ; getLog ( ) . info ( "Found " + numberOfDevices + " devices connected with the Android Debug Bridge" ) ; for ( IDevice device : devices ) { if ( device . isEmulator ( ) ) { if ( isExistingEmulator ( device ) ) { stopEmulator ( device ) ; } } else { getLog ( ) . info ( "Skipping stop. Not an emulator. " + DeviceHelper . getDescriptiveName ( device ) ) ; } } }


signature:
public class AbstractEmulatorMojo { /** * This method contains the code required to stop an emulator
 * @ param device The device to stop */
private void stopEmulator ( IDevice device ) { } }

implementation: int devicePort = extractPortFromDevice ( device ) ; if ( devicePort == - 1 ) { getLog ( ) . info ( "Unable to retrieve port to stop emulator " + DeviceHelper . getDescriptiveName ( device ) ) ; } else { getLog ( ) . info ( "Stopping emulator " + DeviceHelper . getDescriptiveName ( device ) ) ; sendEmulatorCommand ( devicePort , "avd stop" ) ; boolean killed = sendEmulatorCommand ( devicePort , "kill" ) ; if ( ! killed ) { getLog ( ) . info ( "Emulator failed to stop " + DeviceHelper . getDescriptiveName ( device ) ) ; } else { getLog ( ) . info ( "Emulator stopped successfully " + DeviceHelper . getDescriptiveName ( device ) ) ; } }


signature:
public class AbstractEmulatorMojo { /** * This method extracts a port number from the serial number of a device .
 * It assumes that the device name is of format [ xxxx - nnnn ] where nnnn is the
 * port number .
 * @ param device The device to extract the port number from .
 * @ return Returns the port number of the device */
private int extractPortFromDevice ( IDevice device ) { } }

implementation:
String portStr = StringUtils . substringAfterLast ( device . getSerialNumber ( ) , "-" ) ; if ( StringUtils . isNotBlank ( portStr ) && StringUtils . isNumeric ( portStr ) ) { return Integer . parseInt ( portStr ) ; } // If the port is not available then return - 1
return - 1 ;


signature:
public class AbstractEmulatorMojo { /** * Sends a user command to the running emulator via its telnet interface .
 * @ param port The emulator ' s telnet port .
 * @ param command The command to execute on the emulator ' s telnet interface .
 * @ return Whether sending the command succeeded . */
private boolean sendEmulatorCommand ( // final Launcher launcher ,
// final PrintStream logger ,
final int port , final String command ) { } }

implementation:
Callable < Boolean > task = new Callable < Boolean > ( ) { public Boolean call ( ) throws IOException { Socket socket = null ; BufferedReader in = null ; PrintWriter out = null ; try { socket = new Socket ( "127.0.0.1" , port ) ; out = new PrintWriter ( socket . getOutputStream ( ) , true ) ; in = new BufferedReader ( new InputStreamReader ( socket . getInputStream ( ) ) ) ; if ( in . readLine ( ) == null ) { return false ; } out . write ( command ) ; out . write ( "\r\n" ) ; } finally { try { out . close ( ) ; in . close ( ) ; socket . close ( ) ; } catch ( Exception e ) { // Do nothing
} } return true ; } private static final long serialVersionUID = 1L ; } ; boolean result = false ; try { ExecutorService executor = Executors . newSingleThreadExecutor ( ) ; Future < Boolean > future = executor . submit ( task ) ; result = future . get ( ) ; } catch ( Exception e ) { getLog ( ) . error ( String . format ( "Failed to execute emulator command '%s': %s" , command , e ) ) ; } return result ;


signature:
public class AbstractEmulatorMojo { /** * Assemble the command line for starting the emulator based on the parameters supplied in the pom file and on the
 * command line . It should not be that painful to do work with command line and pom supplied values but evidently
 * it is .
 * @ return
 * @ throws MojoExecutionException
 * @ see com . simpligility . maven . plugins . android . configuration . Emulator */
private String assembleStartCommandLine ( ) throws MojoExecutionException { } }

implementation: String emulatorPath ; if ( ! "SdkTools" . equals ( parsedEmulatorLocation ) ) { emulatorPath = new File ( parsedEmulatorLocation , parsedExecutable ) . getAbsolutePath ( ) ; } else { emulatorPath = new File ( getAndroidSdk ( ) . getToolsPath ( ) , parsedExecutable ) . getAbsolutePath ( ) ; } StringBuilder startCommandline = new StringBuilder ( "\"\"" ) . append ( emulatorPath ) . append ( "\"\"" ) . append ( " -avd " ) . append ( parsedAvd ) . append ( " " ) ; if ( ! StringUtils . isEmpty ( parsedOptions ) ) { startCommandline . append ( parsedOptions ) ; } getLog ( ) . info ( "Android emulator command: " + startCommandline ) ; return startCommandline . toString ( ) ;


signature:
public class AbstractEmulatorMojo { /** * Get executable value for emulator from command line options or default to " emulator " .
 * @ return */
private String determineExecutable ( ) { } }

implementation: String emulator ; if ( emulatorExecutable != null ) { emulator = emulatorExecutable ; } else { emulator = "emulator" ; } return emulator ;


signature:
public class AbstractEmulatorMojo { /** * Get wait value for emulator from command line option .
 * @ return if available return command line value otherwise return default value ( 5000 ) . */
String determineWait ( ) { } }

implementation: String wait ; if ( emulatorWait != null ) { wait = emulatorWait ; } else { wait = "5000" ; } return wait ;


signature:
public class AbstractEmulatorMojo { /** * Get options value for emulator from command line option .
 * @ return if available return command line value otherwise return default value ( " " ) . */
private String determineOptions ( ) { } }

implementation: String options ; if ( emulatorOptions != null ) { options = emulatorOptions ; } else { options = "" ; } return options ;


signature:
public class AbstractEmulatorMojo { /** * Get avd value for emulator from command line option .
 * @ return if available return command line value otherwise return default value ( " Default " ) . */
String determineAvd ( ) { } }

implementation: String avd ; if ( emulatorAvd != null ) { avd = emulatorAvd ; } else { avd = "Default" ; } return avd ;


signature:
public class AbstractEmulatorMojo { /** * Get location value for emulator from command line option .
 * @ return if available return command line value otherwise return default value ( " SdkTools " ) . */
String determineEmulatorLocation ( ) { } }

implementation: String location ; if ( emulatorLocation != null ) { location = emulatorLocation ; } else { location = "SdkTools" ; } return location ;


signature:
public class JarHelper { /** * Unjars the specified jar file into the the specified directory
 * @ param jarFile
 * @ param outputDirectory
 * @ param unjarListener
 * @ throws IOException */
public static void unjar ( JarFile jarFile , File outputDirectory , UnjarListener unjarListener ) throws IOException { } }

implementation:
for ( Enumeration en = jarFile . entries ( ) ; en . hasMoreElements ( ) ; ) { JarEntry entry = ( JarEntry ) en . nextElement ( ) ; File entryFile = new File ( outputDirectory , entry . getName ( ) ) ; if ( unjarListener . include ( entry ) ) { // Create the output directory if need be
if ( ! entryFile . getParentFile ( ) . exists ( ) ) { if ( ! entryFile . getParentFile ( ) . mkdirs ( ) ) { throw new IOException ( "Error creating output directory: " + entryFile . getParentFile ( ) ) ; } } // If the entry is an actual file , unzip that too
if ( ! entry . isDirectory ( ) ) { final InputStream in = jarFile . getInputStream ( entry ) ; try { final OutputStream out = new FileOutputStream ( entryFile ) ; try { IOUtil . copy ( in , out ) ; } finally { IOUtils . closeQuietly ( out ) ; } } finally { IOUtils . closeQuietly ( in ) ; } } } }


signature:
public class PushMojo { /** * Calculates a map which contains all files to be pushed to the device or
 * emulator . The source filename works as the key while the value is the
 * destination .
 * @ return a map with file source - > destination pairs
 * @ throws MojoExecutionException */
private Map < String , String > calculateSourceDestinationMapping ( ) throws MojoExecutionException { } }

implementation:
Map < String , String > result = new HashMap < String , String > ( ) ; File sourceFile = new File ( parsedSource ) ; final String destinationPath ; if ( parsedDestination . endsWith ( "/" ) ) { destinationPath = parsedDestination + sourceFile . getName ( ) ; } else { destinationPath = parsedDestination ; } if ( sourceFile . isFile ( ) ) { // only put the source in
final String sourcePath = sourceFile . getAbsolutePath ( ) ; result . put ( sourcePath , destinationPath ) ; } else { if ( sourceFile . isDirectory ( ) ) { // find recursively all files to be pushed
@ SuppressWarnings ( "unchecked" ) Collection < File > filesList = FileUtils . listFiles ( sourceFile , null , true ) ; for ( File file : filesList ) { // make the file ' s path relative - this is kind of a hack but it
// works just fine in this controlled environment
String filePath = file . getAbsolutePath ( ) . substring ( sourceFile . getAbsolutePath ( ) . length ( ) ) ; filePath = filePath . replace ( System . getProperty ( "file.separator" ) , "/" ) ; result . put ( file . getAbsolutePath ( ) , destinationPath + filePath ) ; } } else { throw new MojoExecutionException ( "Cannot execute push goal: File or directory " + sourceFile . getAbsolutePath ( ) + " does not exist." ) ; } } return result ;


signature:
public class DependencyCollector { /** * Visits all nodes from the given node and collects dependencies .
 * @ param node DependencyNode from which to search .
 * @ param collecting Whether we are currently collecting artifacts . */
public void visit ( DependencyNode node , boolean collecting ) { } }

implementation: if ( collecting ) { dependencies . add ( node . getArtifact ( ) ) ; } if ( matchesTarget ( node . getArtifact ( ) ) ) { collecting = true ; log . debug ( "Found target. Collecting dependencies after " + node . getArtifact ( ) ) ; } for ( final DependencyNode child : node . getChildren ( ) ) { visit ( child , collecting ) ; }


signature:
public class ArtifactResolverHelper { /** * Filters provided artifacts and selects only defined types based on { @ code types } argument
 * or all types if { @ code types } argument is empty .
 * @ param allArtifacts artifacts to be filtered
 * @ param types artifact types to be selected
 * @ return a { @ code List } of all project dependencies . Never { @ code null } .
 * This excludes artifacts of the { @ code EXCLUDED _ DEPENDENCY _ SCOPES } scopes .
 * And this should maintain dependency order to comply with library project resource precedence . */
public Set < Artifact > getFilteredArtifacts ( Iterable < Artifact > allArtifacts , String ... types ) { } }

implementation: return getFilteredArtifacts ( EXCLUDE_NON_PACKAGED_SCOPES , allArtifacts , types ) ;


signature:
public class ArtifactResolverHelper { /** * Filters provided artifacts and selects only defined types based on { @ code types } argument
 * or all types if { @ code types } argument is empty .
 * @ param filteredScopes scopes to be filtered
 * @ param allArtifacts artifacts to be filtered
 * @ param types artifact types to be selected
 * @ return a { @ code List } of all project dependencies . Never { @ code null } .
 * This should maintain dependency order to comply with library project resource precedence . */
public Set < Artifact > getFilteredArtifacts ( List < String > filteredScopes , Iterable < Artifact > allArtifacts , String ... types ) { } }

implementation: final List < String > acceptTypeList = Arrays . asList ( types ) ; boolean acceptAllArtifacts = acceptTypeList . isEmpty ( ) ; final Set < Artifact > results = new LinkedHashSet < Artifact > ( ) ; for ( Artifact artifact : allArtifacts ) { if ( artifact == null ) { continue ; } if ( filteredScopes . contains ( artifact . getScope ( ) ) ) { continue ; } if ( acceptAllArtifacts || acceptTypeList . contains ( artifact . getType ( ) ) ) { results . add ( artifact ) ; } } return results ;


signature:
public class ArtifactResolverHelper { /** * Attempts to resolve an { @ link org . apache . maven . artifact . Artifact } to a { @ link java . io . File } .
 * @ param artifact to resolve
 * @ return a { @ link java . io . File } to the resolved artifact , never < code > null < / code > .
 * @ throws org . apache . maven . plugin . MojoExecutionException if the artifact could not be resolved . */
public File resolveArtifactToFile ( Artifact artifact ) throws MojoExecutionException { } }

implementation: final Artifact resolvedArtifact = resolveArtifact ( artifact ) ; final File jar = resolvedArtifact . getFile ( ) ; if ( jar == null ) { throw new MojoExecutionException ( "Could not resolve artifact " + artifact . getId ( ) + ". Please install it with \"mvn install:install-file ...\" or deploy it to a repository " + "with \"mvn deploy:deploy-file ...\"" ) ; } return jar ;


signature:
public class ArtifactResolverHelper { /** * Resolves an artifact to a particular repository .
 * @ param artifact Artifact to resolve
 * @ return fully resolved artifact . */
private Artifact resolveArtifact ( Artifact artifact ) throws MojoExecutionException { } }

implementation: final ArtifactResolutionRequest artifactResolutionRequest = new ArtifactResolutionRequest ( ) ; artifactResolutionRequest . setArtifact ( artifact ) ; if ( remoteArtifactRepositories != null && ! remoteArtifactRepositories . isEmpty ( ) ) { artifactResolutionRequest . setRemoteRepositories ( remoteArtifactRepositories ) ; } final ArtifactResolutionResult resolutionResult = this . artifactResolver . resolve ( artifactResolutionRequest ) ; log . debug ( "Resolving : " + artifact ) ; if ( resolutionResult . getArtifacts ( ) . size ( ) == 0 ) { throw new MojoExecutionException ( "Could not resolve artifact " + artifact + ". Please install it with \"mvn install:install-file ...\" or deploy it to a repository " + "with \"mvn deploy:deploy-file ...\"" ) ; } if ( resolutionResult . getArtifacts ( ) . size ( ) > 1 ) { log . debug ( "Resolved artifacts : " + resolutionResult . getArtifacts ( ) ) ; throw new MojoExecutionException ( "Could not resolve artifact " + artifact + " to single target. Found the following possible options : " + resolutionResult . getArtifacts ( ) ) ; } final Artifact resolvedArtifact = resolutionResult . getArtifacts ( ) . iterator ( ) . next ( ) ; log . debug ( "Resolved : " + resolvedArtifact ) ; return resolvedArtifact ;


signature:
public class InstrumentationArgumentParser { /** * Parses the given { @ code flatArgs } into a map of key / value pairs .
 * @ param flatArgs the flat representation of arguments , might be null
 * @ return a map representation of the given key / value pair list , might be empty
 * @ throws IllegalArgumentException when the given list contains unparseable entries */
public static Map < String , String > parse ( final List < String > flatArgs ) { } }

implementation: if ( flatArgs == null ) { return Collections . EMPTY_MAP ; } final Map < String , String > mappedArgs = new HashMap < String , String > ( ) ; for ( final String flatArg : flatArgs ) { final AbstractMap . SimpleEntry < String , String > keyValuePair = parseKeyValuePair ( flatArg ) ; mappedArgs . put ( keyValuePair . getKey ( ) , keyValuePair . getValue ( ) ) ; } return mappedArgs ;


signature:
public class AbstractAndroidMojo { /** * Provides transitive dependency artifacts having types defined by { @ code types } argument
 * or all types if { @ code types } argument is empty
 * @ param types artifact types to be selected
 * @ return a { @ code List } of all project dependencies . Never { @ code null } .
 * This excludes artifacts of the { @ link ArtifactResolverHelper . EXCLUDE _ NON _ PACKAGED _ SCOPES } scopes .
 * This should maintain dependency order to comply with library project resource precedence . */
protected Set < Artifact > getTransitiveDependencyArtifacts ( String ... types ) { } }

implementation: return getArtifactResolverHelper ( ) . getFilteredArtifacts ( project . getArtifacts ( ) , types ) ;


signature:
public class AbstractAndroidMojo { /** * Initialize the Android Debug Bridge and wait for it to start . Does not reinitialize it if it has
 * already been initialized ( that would through and IllegalStateException . . . ) . Synchronized sine
 * the init call in the library is also synchronized . . just in case . */
protected AndroidDebugBridge initAndroidDebugBridge ( ) throws MojoExecutionException { } }

implementation: synchronized ( ADB_LOCK ) { if ( ! adbInitialized ) { DdmPreferences . setTimeOut ( adbConnectionTimeout ) ; AndroidDebugBridge . init ( false ) ; adbInitialized = true ; } AndroidDebugBridge androidDebugBridge = AndroidDebugBridge . createBridge ( getAndroidSdk ( ) . getAdbPath ( ) , false ) ; waitUntilConnected ( androidDebugBridge ) ; return androidDebugBridge ; }


signature:
public class AbstractAndroidMojo { /** * Run a wait loop until adb is connected or trials run out . This method seems to work more reliably then using a
 * listener . */
private void waitUntilConnected ( AndroidDebugBridge adb ) { } }

implementation: int trials = 10 ; final int connectionWaitTime = 50 ; while ( trials > 0 ) { try { Thread . sleep ( connectionWaitTime ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } if ( adb . isConnected ( ) ) { break ; } trials -- ; }


signature:
public class AbstractAndroidMojo { /** * Wait for the Android Debug Bridge to return an initial device list . */
protected void waitForInitialDeviceList ( final AndroidDebugBridge androidDebugBridge ) throws MojoExecutionException { } }

implementation: if ( ! androidDebugBridge . hasInitialDeviceList ( ) ) { getLog ( ) . info ( "Waiting for initial device list from the Android Debug Bridge" ) ; long limitTime = System . currentTimeMillis ( ) + ADB_TIMEOUT_MS ; while ( ! androidDebugBridge . hasInitialDeviceList ( ) && ( System . currentTimeMillis ( ) < limitTime ) ) { try { Thread . sleep ( 1000 ) ; } catch ( InterruptedException e ) { throw new MojoExecutionException ( "Interrupted waiting for initial device list from Android Debug Bridge" ) ; } } if ( ! androidDebugBridge . hasInitialDeviceList ( ) ) { getLog ( ) . error ( "Did not receive initial device list from the Android Debug Bridge." ) ; } }


signature:
public class AbstractAndroidMojo { /** * Deploys an apk file to a connected emulator or usb device .
 * @ param apkFile the file to deploy
 * @ throws MojoExecutionException If there is a problem deploying the apk file . */
protected void deployApk ( final File apkFile ) throws MojoExecutionException , MojoFailureException { } }

implementation: if ( undeployBeforeDeploy ) { undeployApk ( apkFile ) ; } doWithDevices ( new DeviceCallback ( ) { public void doWithDevice ( final IDevice device ) throws MojoExecutionException { String deviceLogLinePrefix = DeviceHelper . getDeviceLogLinePrefix ( device ) ; try { device . installPackage ( apkFile . getAbsolutePath ( ) , true ) ; getLog ( ) . info ( deviceLogLinePrefix + "Successfully installed " + apkFile . getAbsolutePath ( ) ) ; getLog ( ) . debug ( " to " + DeviceHelper . getDescriptiveName ( device ) ) ; } catch ( InstallException e ) { throw new MojoExecutionException ( deviceLogLinePrefix + "Install of " + apkFile . getAbsolutePath ( ) + " failed." , e ) ; } } } ) ;


signature:
public class AbstractAndroidMojo { /** * Deploy the apk built with the current projects to all attached devices and emulators .
 * Skips other projects in a multi - module build without terminating .
 * @ throws MojoExecutionException
 * @ throws MojoFailureException */
protected void deployBuiltApk ( ) throws MojoExecutionException , MojoFailureException { } }

implementation: if ( project . getPackaging ( ) . equals ( APK ) ) { File apkFile = new File ( targetDirectory , finalName + "." + APK ) ; deployApk ( apkFile ) ; } else { getLog ( ) . info ( "Project packaging is not apk, skipping deployment." ) ; }


signature:
public class AbstractAndroidMojo { /** * Performs the callback action on the devices determined by
 * { @ link # shouldDoWithThisDevice ( com . android . ddmlib . IDevice ) }
 * @ param deviceCallback the action to perform on each device
 * @ throws org . apache . maven . plugin . MojoExecutionException
 * in case there is a problem
 * @ throws org . apache . maven . plugin . MojoFailureException
 * in case there is a problem */
protected void doWithDevices ( final DeviceCallback deviceCallback ) throws MojoExecutionException , MojoFailureException { } }

implementation:
final AndroidDebugBridge androidDebugBridge = initAndroidDebugBridge ( ) ; if ( ! androidDebugBridge . isConnected ( ) ) { throw new MojoExecutionException ( "Android Debug Bridge is not connected." ) ; } waitForInitialDeviceList ( androidDebugBridge ) ; List < IDevice > devices = Arrays . asList ( androidDebugBridge . getDevices ( ) ) ; int numberOfDevices = devices . size ( ) ; getLog ( ) . debug ( "Found " + numberOfDevices + " devices connected with the Android Debug Bridge" ) ; if ( devices . size ( ) == 0 ) { throw new MojoExecutionException ( "No online devices attached." ) ; } int threadCount = getDeviceThreads ( ) ; if ( getDeviceThreads ( ) == 0 ) { getLog ( ) . info ( "android.devicesThreads parameter not set, using a thread for each attached device" ) ; threadCount = numberOfDevices ; } else { getLog ( ) . info ( "android.devicesThreads parameter set to " + getDeviceThreads ( ) ) ; } boolean shouldRunOnAllDevices = getDevices ( ) . size ( ) == 0 ; if ( shouldRunOnAllDevices ) { getLog ( ) . info ( "android.devices parameter not set, using all attached devices" ) ; } else { getLog ( ) . info ( "android.devices parameter set to " + getDevices ( ) . toString ( ) ) ; } ArrayList < DoThread > doThreads = new ArrayList < DoThread > ( ) ; ExecutorService executor = Executors . newFixedThreadPool ( threadCount ) ; for ( final IDevice idevice : devices ) { if ( shouldRunOnAllDevices ) { String deviceType = idevice . isEmulator ( ) ? "Emulator " : "Device " ; getLog ( ) . info ( deviceType + DeviceHelper . getDescriptiveName ( idevice ) + " found." ) ; } if ( shouldRunOnAllDevices || shouldDoWithThisDevice ( idevice ) ) { DoThread deviceDoThread = new DoThread ( ) { public void runDo ( ) throws MojoFailureException , MojoExecutionException { deviceCallback . doWithDevice ( idevice ) ; } } ; doThreads . add ( deviceDoThread ) ; executor . execute ( deviceDoThread ) ; } } executor . shutdown ( ) ; while ( ! executor . isTerminated ( ) ) { // waiting for threads finish
} throwAnyDoThreadErrors ( doThreads ) ; if ( ! shouldRunOnAllDevices && doThreads . isEmpty ( ) ) { throw new MojoExecutionException ( "No device found for android.device=" + getDevices ( ) . toString ( ) ) ; }


signature:
public class AbstractAndroidMojo { /** * Determines if this { @ link IDevice } ( s ) should be used
 * @ param idevice the device to check
 * @ return if the device should be used
 * @ throws org . apache . maven . plugin . MojoExecutionException
 * in case there is a problem
 * @ throws org . apache . maven . plugin . MojoFailureException
 * in case there is a problem */
private boolean shouldDoWithThisDevice ( IDevice idevice ) throws MojoExecutionException , MojoFailureException { } }

implementation:
for ( String device : getDevices ( ) ) { // use specified device or all emulators or all devices
if ( "emulator" . equals ( device ) && idevice . isEmulator ( ) ) { return true ; } if ( "usb" . equals ( device ) && ! idevice . isEmulator ( ) ) { return true ; } if ( idevice . isEmulator ( ) && ( device . equalsIgnoreCase ( idevice . getAvdName ( ) ) || device . equalsIgnoreCase ( idevice . getSerialNumber ( ) ) ) ) { return true ; } if ( ! idevice . isEmulator ( ) && device . equals ( idevice . getSerialNumber ( ) ) ) { return true ; } } return false ;


signature:
public class AbstractAndroidMojo { /** * Undeploys an apk from a connected emulator or usb device . Also deletes the application ' s data and cache
 * directories on the device .
 * @ param apkFile the file to undeploy
 * @ return < code > true < / code > if successfully undeployed , < code > false < / code > otherwise . */
protected boolean undeployApk ( File apkFile ) throws MojoExecutionException , MojoFailureException { } }

implementation: final String packageName ; packageName = extractPackageNameFromApk ( apkFile ) ; return undeployApk ( packageName ) ;


signature:
public class AbstractAndroidMojo { /** * Undeploys an apk , specified by package name , from a connected emulator
 * or usb device . Also deletes the application ' s data and cache
 * directories on the device .
 * @ param packageName the package name to undeploy .
 * @ return < code > true < / code > if successfully undeployed , < code > false < / code > otherwise . */
protected boolean undeployApk ( final String packageName ) throws MojoExecutionException , MojoFailureException { } }

implementation:
final AtomicBoolean result = new AtomicBoolean ( true ) ; // if no devices are present , it counts as successful
doWithDevices ( new DeviceCallback ( ) { public void doWithDevice ( final IDevice device ) throws MojoExecutionException { String deviceLogLinePrefix = DeviceHelper . getDeviceLogLinePrefix ( device ) ; try { device . uninstallPackage ( packageName ) ; getLog ( ) . info ( deviceLogLinePrefix + "Successfully uninstalled " + packageName ) ; getLog ( ) . debug ( " from " + DeviceHelper . getDescriptiveName ( device ) ) ; result . set ( true ) ; } catch ( InstallException e ) { result . set ( false ) ; throw new MojoExecutionException ( deviceLogLinePrefix + "Uninstall of " + packageName + " failed." , e ) ; } } } ) ; return result . get ( ) ;


signature:
public class AbstractAndroidMojo { /** * Extracts the package name from an apk file .
 * @ param apkFile apk file to extract package name from .
 * @ return the package name from inside the apk file . */
protected String extractPackageNameFromApk ( File apkFile ) throws MojoExecutionException { } }

implementation: CommandExecutor executor = CommandExecutor . Factory . createDefaultCommmandExecutor ( ) ; executor . setLogger ( this . getLog ( ) ) ; executor . setCaptureStdOut ( true ) ; executor . setCaptureStdErr ( true ) ; AaptCommandBuilder commandBuilder = AaptCommandBuilder . dump ( getLog ( ) ) . xmlTree ( ) . setPathToApk ( apkFile . getAbsolutePath ( ) ) . addAssetFile ( "AndroidManifest.xml" ) ; getLog ( ) . info ( getAndroidSdk ( ) . getAaptPath ( ) + " " + commandBuilder . toString ( ) ) ; try { executor . executeCommand ( getAndroidSdk ( ) . getAaptPath ( ) , commandBuilder . build ( ) , false ) ; final String xmlTree = executor . getStandardOut ( ) ; return extractPackageNameFromAndroidManifestXmlTree ( xmlTree ) ; } catch ( ExecutionException e ) { throw new MojoExecutionException ( "Error while trying to figure out package name from inside apk file " + apkFile ) ; } finally { String errout = executor . getStandardError ( ) ; if ( ( errout != null ) && ( errout . trim ( ) . length ( ) > 0 ) ) { getLog ( ) . error ( errout ) ; } }


signature:
public class AbstractAndroidMojo { /** * Extracts the package name from an XmlTree dump of AndroidManifest . xml by the < code > aapt < / code > tool .
 * @ param aaptDumpXmlTree output from < code > aapt dump xmltree & lt ; apkFile & gt ; AndroidManifest . xml
 * @ return the package name from inside the apkFile . */
protected String extractPackageNameFromAndroidManifestXmlTree ( String aaptDumpXmlTree ) { } }

implementation:
final Scanner scanner = new Scanner ( aaptDumpXmlTree ) ; // Finds the root element named " manifest " .
scanner . findWithinHorizon ( "^E: manifest" , 0 ) ; // Finds the manifest element ' s attribute named " package " .
scanner . findWithinHorizon ( "  A: package=\"" , 0 ) ; // Extracts the package value including the trailing double quote .
String packageName = scanner . next ( ".*?\"" ) ; // Removes the double quote .
packageName = packageName . substring ( 0 , packageName . length ( ) - 1 ) ; return packageName ;