idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
5,800
public Response createSystemProperty ( SystemProperty property ) { return restClient . post ( "system/properties" , property , new HashMap < String , String > ( ) ) ; }
Creates the system property .
5,801
public Response updateSystemProperty ( SystemProperty property ) { return restClient . put ( "system/properties/" + property . getKey ( ) , property , new HashMap < String , String > ( ) ) ; }
Update system property .
5,802
public Response deleteSystemProperty ( String propertyName ) { return restClient . delete ( "system/properties/" + propertyName , new HashMap < String , String > ( ) ) ; }
Delete system property .
5,803
public GroupEntity getGroup ( String groupName ) { return restClient . get ( "groups/" + groupName , GroupEntity . class , new HashMap < String , String > ( ) ) ; }
Gets the group .
5,804
public Response updateGroup ( GroupEntity group ) { return restClient . put ( "groups/" + group . getName ( ) , group , new HashMap < String , String > ( ) ) ; }
Update group .
5,805
public Response deleteGroup ( String groupName ) { return restClient . delete ( "groups/" + groupName , new HashMap < String , String > ( ) ) ; }
Delete group .
5,806
public RosterEntities getRoster ( String username ) { return restClient . get ( "users/" + username + "/roster" , RosterEntities . class , new HashMap < String , String > ( ) ) ; }
Gets the roster .
5,807
public Response addRosterEntry ( String username , RosterItemEntity rosterItemEntity ) { return restClient . post ( "users/" + username + "/roster" , rosterItemEntity , new HashMap < String , String > ( ) ) ; }
Adds the roster entry .
5,808
public Response updateRosterEntry ( String username , RosterItemEntity rosterItemEntity ) { return restClient . put ( "users/" + username + "/roster/" + rosterItemEntity . getJid ( ) , rosterItemEntity , new HashMap < String , String > ( ) ) ; }
Update roster entry .
5,809
public Response deleteRosterEntry ( String username , String jid ) { return restClient . delete ( "users/" + username + "/roster/" + jid , new HashMap < String , String > ( ) ) ; }
Delete roster entry .
5,810
public String getMessage ( Context context ) { if ( customMessage != null ) { return customMessage ; } return context . getResources ( ) . getString ( message ) ; }
Getter for the error message .
5,811
@ SuppressWarnings ( "ConstantConditions" ) private void showResult ( String message ) { Snackbar . make ( rootLayout , message , Snackbar . LENGTH_LONG ) . show ( ) ; }
Shows a Snackbar on the bottom of the layout
5,812
static float dipToPixels ( Resources resources , int dip ) { return TypedValue . applyDimension ( TypedValue . COMPLEX_UNIT_DIP , dip , resources . getDisplayMetrics ( ) ) ; }
Converts dp into px .
5,813
private void parseAuthentication ( Intent data ) { String idToken = data . getStringExtra ( Constants . ID_TOKEN_EXTRA ) ; String accessToken = data . getStringExtra ( Constants . ACCESS_TOKEN_EXTRA ) ; String tokenType = data . getStringExtra ( Constants . TOKEN_TYPE_EXTRA ) ; String refreshToken = data . getStringExtra ( Constants . REFRESH_TOKEN_EXTRA ) ; long expiresIn = data . getLongExtra ( Constants . EXPIRES_IN_EXTRA , 0 ) ; Credentials credentials = new Credentials ( idToken , accessToken , tokenType , refreshToken , expiresIn ) ; Log . d ( TAG , "User authenticated!" ) ; onAuthentication ( credentials ) ; }
Extracts the Authentication data from the intent data .
5,814
public ParameterizableRequest < Void , AuthenticationException > getCodeRequest ( AuthenticationAPIClient apiClient , String connectionName ) { Log . d ( TAG , String . format ( "Generating Passwordless Code/Link request for connection %s" , connectionName ) ) ; ParameterizableRequest < Void , AuthenticationException > request ; if ( getMode ( ) == PasswordlessMode . EMAIL_CODE ) { request = apiClient . passwordlessWithEmail ( getEmailOrNumber ( ) , PasswordlessType . CODE ) ; } else if ( getMode ( ) == PasswordlessMode . EMAIL_LINK ) { request = apiClient . passwordlessWithEmail ( getEmailOrNumber ( ) , PasswordlessType . ANDROID_LINK ) ; } else if ( getMode ( ) == PasswordlessMode . SMS_CODE ) { request = apiClient . passwordlessWithSMS ( getEmailOrNumber ( ) , PasswordlessType . CODE ) ; } else { request = apiClient . passwordlessWithSMS ( getEmailOrNumber ( ) , PasswordlessType . ANDROID_LINK ) ; } return request . addParameter ( KEY_CONNECTION , connectionName ) ; }
Creates the ParameterizableRequest that will initiate the Passwordless Authentication flow .
5,815
public AuthenticationRequest getLoginRequest ( AuthenticationAPIClient apiClient , String emailOrNumber ) { Log . d ( TAG , String . format ( "Generating Passwordless Login request for identity %s" , emailOrNumber ) ) ; if ( getMode ( ) == PasswordlessMode . EMAIL_CODE || getMode ( ) == PasswordlessMode . EMAIL_LINK ) { return apiClient . loginWithEmail ( emailOrNumber , getCode ( ) ) ; } else { return apiClient . loginWithPhoneNumber ( emailOrNumber , getCode ( ) ) ; } }
Creates the AuthenticationRequest that will finish the Passwordless Authentication flow .
5,816
public boolean isValid ( String password ) { if ( password == null ) { return false ; } boolean length = hasMinimumLength ( password , getMinimumLength ( ) ) ; boolean other = true ; switch ( complexity . getPasswordPolicy ( ) ) { case PasswordStrength . EXCELLENT : boolean atLeast = atLeastThree ( hasLowercaseCharacters ( password ) , hasUppercaseCharacters ( password ) , hasNumericCharacters ( password ) , hasSpecialCharacters ( password ) ) ; other = hasIdenticalCharacters ( password ) && atLeast ; break ; case PasswordStrength . GOOD : other = atLeastThree ( hasLowercaseCharacters ( password ) , hasUppercaseCharacters ( password ) , hasNumericCharacters ( password ) , hasSpecialCharacters ( password ) ) ; break ; case PasswordStrength . FAIR : other = allThree ( hasLowercaseCharacters ( password ) , hasUppercaseCharacters ( password ) , hasNumericCharacters ( password ) ) ; break ; case PasswordStrength . LOW : case PasswordStrength . NONE : } return length && other ; }
Checks that all the requirements are meet .
5,817
public void showProgress ( boolean show ) { if ( actionButton != null ) { actionButton . showProgress ( show ) ; } if ( formLayout != null ) { formLayout . setEnabled ( ! show ) ; } }
Displays a progress bar on top of the action button . This will also enable or disable the action button .
5,818
public void showProgress ( boolean show ) { Log . v ( TAG , show ? "Disabling the button while showing progress" : "Enabling the button and hiding progress" ) ; setEnabled ( ! show ) ; progress . setVisibility ( show ? VISIBLE : GONE ) ; if ( show ) { icon . setVisibility ( INVISIBLE ) ; labeledLayout . setVisibility ( INVISIBLE ) ; return ; } icon . setVisibility ( shouldShowLabel ? GONE : VISIBLE ) ; labeledLayout . setVisibility ( ! shouldShowLabel ? GONE : VISIBLE ) ; }
Used to display a progress bar and disable the button .
5,819
public void showLabel ( boolean showLabel ) { shouldShowLabel = showLabel ; labeledLayout . setVisibility ( showLabel ? VISIBLE : GONE ) ; icon . setVisibility ( ! showLabel ? VISIBLE : GONE ) ; }
Whether to show an icon or a label with the current selected mode . By default it will show the icon .
5,820
public void codeSent ( String emailOrNumber ) { Log . d ( TAG , "Now showing the Code Input Form" ) ; if ( passwordlessRequestCodeLayout != null ) { removeView ( passwordlessRequestCodeLayout ) ; if ( socialLayout != null ) { socialLayout . setVisibility ( GONE ) ; } if ( orSeparatorMessage != null ) { orSeparatorMessage . setVisibility ( GONE ) ; } } addPasswordlessInputCodeLayout ( emailOrNumber ) ; lockWidget . updateHeaderTitle ( R . string . com_auth0_lock_title_passwordless ) ; }
Notifies the form that the code was correctly sent and it should now wait for the user to input the valid code .
5,821
public boolean resume ( int requestCode , int resultCode , Intent intent ) { return WebAuthProvider . resume ( requestCode , resultCode , intent ) ; }
Finishes the authentication flow in the WebAuthProvider
5,822
protected void updateBorder ( ) { boolean isFocused = input . hasFocus ( ) && ! input . isInTouchMode ( ) ; ViewUtils . setBackground ( outline , hasValidInput ? ( isFocused ? focusedOutlineBackground : normalOutlineBackground ) : errorOutlineBackground ) ; errorDescription . setVisibility ( hasValidInput ? GONE : VISIBLE ) ; requestLayout ( ) ; }
Updates the view knowing if the input is valid or not .
5,823
protected boolean validate ( boolean validateEmptyFields ) { boolean isValid = false ; String value = dataType == PASSWORD ? getText ( ) : getText ( ) . trim ( ) ; if ( ! validateEmptyFields && value . isEmpty ( ) ) { return true ; } switch ( dataType ) { case TEXT_NAME : case NUMBER : case PASSWORD : case NON_EMPTY_USERNAME : isValid = ! value . isEmpty ( ) ; break ; case EMAIL : isValid = value . matches ( EMAIL_REGEX ) ; break ; case USERNAME : isValid = value . matches ( USERNAME_REGEX ) && value . length ( ) >= 1 && value . length ( ) <= 15 ; break ; case USERNAME_OR_EMAIL : final boolean validEmail = value . matches ( EMAIL_REGEX ) ; final boolean validUsername = value . matches ( USERNAME_REGEX ) && value . length ( ) >= 1 && value . length ( ) <= 15 ; isValid = validEmail || validUsername ; break ; case MOBILE_PHONE : case PHONE_NUMBER : isValid = value . matches ( PHONE_NUMBER_REGEX ) ; break ; case MFA_CODE : isValid = value . matches ( CODE_REGEX ) ; break ; } Log . v ( TAG , "Field validation results: Is valid? " + isValid ) ; return isValid ; }
Validates the input data and updates the icon . DataType must be set .
5,824
public void setText ( String text ) { input . setText ( "" ) ; if ( text != null ) { input . append ( text ) ; } }
Updates the input field text .
5,825
public void clearInput ( ) { Log . v ( TAG , "Input cleared and validation errors removed" ) ; input . setText ( "" ) ; hasValidInput = true ; updateBorder ( ) ; showPasswordToggle . setChecked ( false ) ; }
Removes any text present on the input field and clears any validation error if present .
5,826
public static int styleForStrategy ( String strategyName ) { int style = R . style . Lock_Theme_AuthStyle ; switch ( strategyName ) { case "amazon" : style = R . style . Lock_Theme_AuthStyle_Amazon ; break ; case "aol" : style = R . style . Lock_Theme_AuthStyle_AOL ; break ; case "bitbucket" : style = R . style . Lock_Theme_AuthStyle_BitBucket ; break ; case "dropbox" : style = R . style . Lock_Theme_AuthStyle_Dropbox ; break ; case "yahoo" : style = R . style . Lock_Theme_AuthStyle_Yahoo ; break ; case "linkedin" : style = R . style . Lock_Theme_AuthStyle_LinkedIn ; break ; case "google-oauth2" : style = R . style . Lock_Theme_AuthStyle_GoogleOAuth2 ; break ; case "twitter" : style = R . style . Lock_Theme_AuthStyle_Twitter ; break ; case "facebook" : style = R . style . Lock_Theme_AuthStyle_Facebook ; break ; case "box" : style = R . style . Lock_Theme_AuthStyle_Box ; break ; case "evernote" : style = R . style . Lock_Theme_AuthStyle_Evernote ; break ; case "evernote-sandbox" : style = R . style . Lock_Theme_AuthStyle_EvernoteSandbox ; break ; case "exact" : style = R . style . Lock_Theme_AuthStyle_Exact ; break ; case "github" : style = R . style . Lock_Theme_AuthStyle_GitHub ; break ; case "instagram" : style = R . style . Lock_Theme_AuthStyle_Instagram ; break ; case "miicard" : style = R . style . Lock_Theme_AuthStyle_MiiCard ; break ; case "paypal" : style = R . style . Lock_Theme_AuthStyle_Paypal ; break ; case "paypal-sandbox" : style = R . style . Lock_Theme_AuthStyle_PaypalSandbox ; break ; case "salesforce" : style = R . style . Lock_Theme_AuthStyle_Salesforce ; break ; case "salesforce-community" : style = R . style . Lock_Theme_AuthStyle_SalesforceCommunity ; break ; case "salesforce-sandbox" : style = R . style . Lock_Theme_AuthStyle_SalesforceSandbox ; break ; case "soundcloud" : style = R . style . Lock_Theme_AuthStyle_SoundCloud ; break ; case "windowslive" : style = R . style . Lock_Theme_AuthStyle_WindowsLive ; break ; case "yammer" : style = R . style . Lock_Theme_AuthStyle_Yammer ; break ; case "baidu" : style = R . style . Lock_Theme_AuthStyle_Baidu ; break ; case "fitbit" : style = R . style . Lock_Theme_AuthStyle_Fitbit ; break ; case "planningcenter" : style = R . style . Lock_Theme_AuthStyle_PlanningCenter ; break ; case "renren" : style = R . style . Lock_Theme_AuthStyle_RenRen ; break ; case "thecity" : style = R . style . Lock_Theme_AuthStyle_TheCity ; break ; case "thecity-sandbox" : style = R . style . Lock_Theme_AuthStyle_TheCitySandbox ; break ; case "thirtysevensignals" : style = R . style . Lock_Theme_AuthStyle_ThirtySevenSignals ; break ; case "vkontakte" : style = R . style . Lock_Theme_AuthStyle_Vkontakte ; break ; case "weibo" : style = R . style . Lock_Theme_AuthStyle_Weibo ; break ; case "wordpress" : style = R . style . Lock_Theme_AuthStyle_Wordpress ; break ; case "yandex" : style = R . style . Lock_Theme_AuthStyle_Yandex ; break ; case "shopify" : style = R . style . Lock_Theme_AuthStyle_Shopify ; break ; case "dwolla" : style = R . style . Lock_Theme_AuthStyle_Dwolla ; break ; } return style ; }
It will resolve the given Strategy Name to a valid Style .
5,827
@ SuppressWarnings ( "unused" ) public Intent newIntent ( Context context ) { Intent lockIntent = new Intent ( context , PasswordlessLockActivity . class ) ; lockIntent . putExtra ( Constants . OPTIONS_EXTRA , options ) ; lockIntent . addFlags ( Intent . FLAG_ACTIVITY_NEW_TASK ) ; return lockIntent ; }
Builds a new intent to launch LockActivity with the previously configured options
5,828
public OAuthConnection parse ( String email ) { String domain = extractDomain ( email ) ; if ( domain == null ) { return null ; } domain = domain . toLowerCase ( ) ; for ( OAuthConnection c : connections ) { String mainDomain = domainForConnection ( c ) ; if ( domain . equalsIgnoreCase ( mainDomain ) ) { return c ; } List < String > aliases = c . valueForKey ( DOMAIN_ALIASES_KEY , List . class ) ; if ( aliases != null ) { for ( String d : aliases ) { if ( d . equalsIgnoreCase ( domain ) ) { return c ; } } } } return null ; }
Tries to find a valid domain with the given input .
5,829
public String extractUsername ( String email ) { int indexAt = email . indexOf ( AT_SYMBOL ) ; if ( indexAt == - 1 ) { return null ; } return email . substring ( 0 , indexAt ) ; }
Extracts the username part from the email
5,830
private String extractDomain ( String email ) { int indexAt = email . indexOf ( AT_SYMBOL ) + 1 ; if ( indexAt == 0 ) { return null ; } String domain = email . substring ( indexAt ) ; if ( domain . isEmpty ( ) ) { return null ; } return domain ; }
Extracts the domain part from the email
5,831
private String extractStringValue ( XMLObject xmlo ) { if ( xmlo instanceof XSString ) { return ( ( XSString ) xmlo ) . getValue ( ) ; } else if ( xmlo instanceof XSAnyImpl ) { return ( ( XSAnyImpl ) xmlo ) . getTextContent ( ) ; } logger . warn ( "Unable to map attribute class {} to String. Unknown type. Enable TRACE logging to see attribute name" , xmlo . getClass ( ) ) ; return null ; }
Extracts the string value of the XMLObject depending upon its type .
5,832
public static Map < String , Set < String > > parseAttributeToAttributeMapping ( final Map < String , ? extends Object > mapping ) { if ( mapping == null ) { return new HashMap < > ( ) ; } final Map < String , Set < String > > mappedAttributesBuilder = new LinkedHashMap < > ( ) ; for ( final Map . Entry < String , ? extends Object > mappingEntry : mapping . entrySet ( ) ) { final String sourceAttrName = mappingEntry . getKey ( ) ; Validate . notNull ( sourceAttrName , "attribute name can not be null in Map" ) ; final Object mappedAttribute = mappingEntry . getValue ( ) ; if ( mappedAttribute == null ) { mappedAttributesBuilder . put ( sourceAttrName , null ) ; } else if ( mappedAttribute instanceof String ) { final Set < String > mappedSet = new HashSet < > ( ) ; mappedSet . add ( mappedAttribute . toString ( ) ) ; mappedAttributesBuilder . put ( sourceAttrName , mappedSet ) ; } else if ( mappedAttribute instanceof Collection ) { final Collection < ? > sourceSet = ( Collection < ? > ) mappedAttribute ; final Set < String > mappedSet = new LinkedHashSet < > ( ) ; for ( final Object sourceObj : sourceSet ) { if ( sourceObj != null ) { mappedSet . add ( sourceObj . toString ( ) ) ; } else { mappedSet . add ( null ) ; } } mappedAttributesBuilder . put ( sourceAttrName , mappedSet ) ; } else { throw new IllegalArgumentException ( "Invalid mapped type. key='" + sourceAttrName + "', value type='" + mappedAttribute . getClass ( ) . getName ( ) + "'" ) ; } } return new HashMap < > ( mappedAttributesBuilder ) ; }
Translate from a more flexible Attribute to Attribute mapping format to a Map from String to Set of Strings .
5,833
public void initialize ( ) { for ( final SearchScope scope : SearchScope . values ( ) ) { if ( scope . ordinal ( ) == this . searchControls . getSearchScope ( ) ) { this . searchScope = scope ; } } }
Initializes the object after properties are set .
5,834
private SearchRequest createRequest ( final SearchFilter filter ) { final SearchRequest request = new SearchRequest ( ) ; request . setBaseDn ( this . baseDN ) ; request . setSearchFilter ( filter ) ; if ( getResultAttributeMapping ( ) != null && ! getResultAttributeMapping ( ) . isEmpty ( ) ) { final String [ ] attributes = getResultAttributeMapping ( ) . keySet ( ) . toArray ( new String [ getResultAttributeMapping ( ) . size ( ) ] ) ; request . setReturnAttributes ( attributes ) ; } else if ( searchControls . getReturningAttributes ( ) != null && searchControls . getReturningAttributes ( ) . length > 0 ) { request . setReturnAttributes ( searchControls . getReturningAttributes ( ) ) ; } else { request . setReturnAttributes ( ReturnAttributes . ALL_USER . value ( ) ) ; } request . setSearchScope ( this . searchScope ) ; request . setSizeLimit ( this . searchControls . getCountLimit ( ) ) ; request . setTimeLimit ( Duration . ofSeconds ( searchControls . getTimeLimit ( ) ) ) ; return request ; }
Creates a search request from a search filter .
5,835
protected Map < String , List < Object > > buildMutableAttributeMap ( final Map < String , List < Object > > attributes ) { final Map < String , List < Object > > mutableValuesBuilder = this . createMutableAttributeMap ( attributes . size ( ) ) ; for ( final Map . Entry < String , List < Object > > attrEntry : attributes . entrySet ( ) ) { final String key = attrEntry . getKey ( ) ; List < Object > value = attrEntry . getValue ( ) ; if ( value != null ) { value = new ArrayList < > ( value ) ; } mutableValuesBuilder . put ( key , value ) ; } return mutableValuesBuilder ; }
Do a deep clone of an attribute Map to ensure it is completley mutable .
5,836
public void setScriptFile ( final String scriptFile ) { this . scriptFile = scriptFile ; this . scriptType = determineScriptType ( scriptFile ) ; if ( scriptType != SCRIPT_TYPE . CONTENTS ) { this . engineName = getScriptEngineName ( scriptFile ) ; } }
this object would be better if engineName and scriptFile couldn t change
5,837
public static String getScriptEngineName ( String filename ) { String extension = FilenameUtils . getExtension ( filename ) ; if ( StringUtils . isBlank ( extension ) ) { logger . warn ( "Can't determine engine name based on filename without extension {}" , filename ) ; return null ; } ScriptEngineManager manager = new ScriptEngineManager ( ) ; List < ScriptEngineFactory > engines = manager . getEngineFactories ( ) ; for ( ScriptEngineFactory engineFactory : engines ) { List < String > extensions = engineFactory . getExtensions ( ) ; for ( String supportedExt : extensions ) { if ( extension . equals ( supportedExt ) ) { return engineFactory . getNames ( ) . get ( 0 ) ; } } } logger . warn ( "Can't determine engine name based on filename and available script engines {}" , filename ) ; return null ; }
This method is static is available as utility for users that are passing the contents of a script and want to set the engineName property based on a filename .
5,838
public void setUserInfoCache ( final Map < Serializable , Set < IPersonAttributes > > userInfoCache ) { if ( userInfoCache == null ) { throw new IllegalArgumentException ( "userInfoCache may not be null" ) ; } this . userInfoCache = userInfoCache ; }
The Map to use for caching results . Only get put and remove are used so the Map may be backed by a real caching implementation .
5,839
public void setNullResultsObject ( final Set < IPersonAttributes > nullResultsObject ) { if ( nullResultsObject == null ) { throw new IllegalArgumentException ( "nullResultsObject may not be null" ) ; } this . nullResultsObject = nullResultsObject ; }
Used to specify the placeholder object to put in the cache for null results . Defaults to a minimal Set . Most installations will not need to set this .
5,840
public void setBackingMap ( final Map < String , Map < String , List < Object > > > backingMap ) { if ( backingMap == null ) { this . backingMap = new HashMap < > ( ) ; this . possibleUserAttributeNames = new HashSet < > ( ) ; } else { this . backingMap = new LinkedHashMap < > ( backingMap ) ; this . initializePossibleAttributeNames ( ) ; } }
The backing Map to use for queries the outer map is keyed on the query attribute . The inner Map is the set of user attributes to be returned for the query attribute .
5,841
private void initializePossibleAttributeNames ( ) { final Set < String > possibleAttribNames = new LinkedHashSet < > ( ) ; for ( final Map < String , List < Object > > attributeMapForSomeUser : this . backingMap . values ( ) ) { final Set < String > keySet = attributeMapForSomeUser . keySet ( ) ; possibleAttribNames . addAll ( keySet ) ; } this . possibleUserAttributeNames = Collections . unmodifiableSet ( possibleAttribNames ) ; }
Compute the set of attribute names that map to a value for at least one user in our backing map and store it as the instance variable possibleUserAttributeNames .
5,842
public Set < IPersonAttributes > getPeopleWithMultivaluedAttributes ( final Map < String , List < Object > > query , final IPersonAttributeDaoFilter filter ) { if ( query == null ) { throw new IllegalArgumentException ( "seed may not be null" ) ; } return Collections . singleton ( ( IPersonAttributes ) new AttributeNamedPersonImpl ( getUsernameAttributeProvider ( ) . getUsernameAttribute ( ) , query ) ) ; }
Returns a duplicate of the seed it is passed .
5,843
protected String canonicalizeDataAttributeForSql ( final String dataAttribute ) { if ( this . caseInsensitiveDataAttributes == null || this . caseInsensitiveDataAttributes . isEmpty ( ) || ! ( this . caseInsensitiveDataAttributes . containsKey ( dataAttribute ) ) ) { return dataAttribute ; } if ( this . dataAttributeCaseCanonicalizationFunctions == null || this . dataAttributeCaseCanonicalizationFunctions . isEmpty ( ) ) { return dataAttribute ; } CaseCanonicalizationMode canonicalizationMode = this . caseInsensitiveDataAttributes . get ( dataAttribute ) ; if ( canonicalizationMode == null ) { canonicalizationMode = getDefaultCaseCanonicalizationMode ( ) ; } final MessageFormat mf = this . dataAttributeCaseCanonicalizationFunctions . get ( canonicalizationMode ) ; if ( mf == null ) { return dataAttribute ; } return mf . format ( new String [ ] { dataAttribute } ) ; }
Canonicalize the data - layer attribute column with the given name via SQL function . This is as opposed to canonicalizing query attributes or application attributes passed into or mapped out of the data layer . Canonicalization of a data - layer column should only be necessary if the data layer if you require case - insensitive searching on a mixed - case column in a case - sensitive data layer . Careful though as this can result in table scanning if the data layer does not support function - based indices .
5,844
protected Map < String , List < Object > > buildImmutableAttributeMap ( final Map < String , List < Object > > attributes ) { final Map < String , List < Object > > immutableValuesBuilder = this . createImmutableAttributeMap ( attributes . size ( ) ) ; final Pattern arrayPattern = Pattern . compile ( "\\{(.*)\\}" ) ; for ( final Map . Entry < String , List < Object > > attrEntry : attributes . entrySet ( ) ) { final String key = attrEntry . getKey ( ) ; List < Object > value = attrEntry . getValue ( ) ; if ( value != null ) { if ( ! value . isEmpty ( ) ) { final Object result = value . get ( 0 ) ; if ( Array . class . isInstance ( result ) ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Column {} is classified as a SQL array" , key ) ; } final String values = result . toString ( ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Converting SQL array values {} using pattern {}" , values , arrayPattern . pattern ( ) ) ; } final Matcher matcher = arrayPattern . matcher ( values ) ; if ( matcher . matches ( ) ) { final String [ ] groups = matcher . group ( 1 ) . split ( "," ) ; value = Arrays . asList ( groups ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Converted SQL array values {}" , values ) ; } } } } value = Collections . unmodifiableList ( value ) ; } if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Collecting attribute {} with value(s) {}" , key , value ) ; } immutableValuesBuilder . put ( key , value ) ; } return immutableValuesBuilder ; }
Take the constructor argument and convert the Map and List values into read - only form .
5,845
protected final IPersonAttributes mapPersonAttributes ( final IPersonAttributes person ) { final Map < String , List < Object > > personAttributes = person . getAttributes ( ) ; final Map < String , List < Object > > mappedAttributes ; if ( this . resultAttributeMapping == null ) { if ( caseInsensitiveResultAttributes != null && ! ( caseInsensitiveResultAttributes . isEmpty ( ) ) ) { mappedAttributes = new LinkedHashMap < > ( ) ; for ( final Map . Entry < String , List < Object > > attribute : personAttributes . entrySet ( ) ) { final String attributeName = attribute . getKey ( ) ; mappedAttributes . put ( attributeName , canonicalizeAttribute ( attributeName , attribute . getValue ( ) , caseInsensitiveResultAttributes ) ) ; } } else { mappedAttributes = personAttributes ; } } else { mappedAttributes = new LinkedHashMap < > ( ) ; for ( final Map . Entry < String , Set < String > > resultAttrEntry : this . resultAttributeMapping . entrySet ( ) ) { final String dataKey = resultAttrEntry . getKey ( ) ; if ( personAttributes . containsKey ( dataKey ) ) { Set < String > resultKeys = resultAttrEntry . getValue ( ) ; if ( resultKeys == null ) { resultKeys = ImmutableSet . of ( dataKey ) ; } List < Object > value = personAttributes . get ( dataKey ) ; for ( final String resultKey : resultKeys ) { value = canonicalizeAttribute ( resultKey , value , caseInsensitiveResultAttributes ) ; if ( resultKey == null ) { mappedAttributes . put ( dataKey , value ) ; } else { mappedAttributes . put ( resultKey , value ) ; } } } } } final IPersonAttributes newPerson ; final String name = person . getName ( ) ; if ( name != null ) { newPerson = new NamedPersonImpl ( usernameCaseCanonicalizationMode . canonicalize ( name ) , mappedAttributes ) ; } else { final String userNameAttribute = this . getConfiguredUserNameAttribute ( ) ; final IPersonAttributes tmpNewPerson = new AttributeNamedPersonImpl ( userNameAttribute , mappedAttributes ) ; newPerson = new NamedPersonImpl ( usernameCaseCanonicalizationMode . canonicalize ( tmpNewPerson . getName ( ) ) , mappedAttributes ) ; } return newPerson ; }
Uses resultAttributeMapping to return a copy of the IPersonAttributes with only the attributes specified in resultAttributeMapping mapped to their result attribute names .
5,846
protected List < Object > canonicalizeAttribute ( final String key , final List < Object > value , final Map < String , CaseCanonicalizationMode > config ) { if ( value == null || value . isEmpty ( ) || config == null || ! ( config . containsKey ( key ) ) ) { return value ; } CaseCanonicalizationMode canonicalizationMode = config . get ( key ) ; if ( canonicalizationMode == null ) { canonicalizationMode = defaultCaseCanonicalizationMode ; } final List < Object > canonicalizedValues = new ArrayList < > ( value . size ( ) ) ; for ( final Object origValue : value ) { if ( origValue instanceof String ) { canonicalizedValues . add ( canonicalizationMode . canonicalize ( ( String ) origValue , caseCanonicalizationLocale ) ) ; } else { canonicalizedValues . add ( origValue ) ; } } return canonicalizedValues ; }
Canonicalize the attribute values if they are present in the config map .
5,847
protected Set < IPersonAttributes > getAttributesFromDao ( final Map < String , List < Object > > seed , final boolean isFirstQuery , final IPersonAttributeDao currentlyConsidering , final Set < IPersonAttributes > resultPeople , final IPersonAttributeDaoFilter filter ) { if ( isFirstQuery || ( ! stopIfFirstDaoReturnsNull && ( resultPeople == null || resultPeople . size ( ) == 0 ) ) ) { return currentlyConsidering . getPeopleWithMultivaluedAttributes ( seed , filter ) ; } else if ( stopIfFirstDaoReturnsNull && ! isFirstQuery && ( resultPeople == null || resultPeople . size ( ) == 0 ) ) { return null ; } Set < IPersonAttributes > mergedPeopleResults = null ; for ( final IPersonAttributes person : resultPeople ) { final Map < String , List < Object > > queryAttributes = new LinkedHashMap < > ( ) ; final String userName = person . getName ( ) ; if ( userName != null ) { final Map < String , List < Object > > userNameMap = this . toSeedMap ( userName ) ; queryAttributes . putAll ( userNameMap ) ; } final Map < String , List < Object > > personAttributes = person . getAttributes ( ) ; queryAttributes . putAll ( personAttributes ) ; final Set < IPersonAttributes > newResults = currentlyConsidering . getPeopleWithMultivaluedAttributes ( queryAttributes , filter ) ; if ( newResults != null ) { if ( mergedPeopleResults == null ) { mergedPeopleResults = new LinkedHashSet < > ( newResults ) ; } else { mergedPeopleResults = this . attrMerger . mergeResults ( mergedPeopleResults , newResults ) ; } } } return mergedPeopleResults ; }
If this is the first call or there are no results in the resultPeople Set and stopIfFirstDaoReturnsNull = false the seed map is used . If not the attributes of the first user in the resultPeople Set are used for each child dao . If stopIfFirstDaoReturnsNull = true and the first query returned no results in the resultPeopleSet return null .
5,848
protected Set < IPersonAttributes > getAttributesFromDao ( final Map < String , List < Object > > seed , final boolean isFirstQuery , final IPersonAttributeDao currentlyConsidering , final Set < IPersonAttributes > resultPeople , final IPersonAttributeDaoFilter filter ) { return currentlyConsidering . getPeopleWithMultivaluedAttributes ( seed , filter ) ; }
Calls the current IPersonAttributeDao from using the seed .
5,849
public List < Object > removeAttribute ( final String name ) { List < Object > removedValues = null ; for ( final IAdditionalDescriptors additionalDescriptors : this . delegateDescriptors ) { final List < Object > values = additionalDescriptors . removeAttribute ( name ) ; if ( values != null ) { if ( removedValues == null ) { removedValues = new ArrayList < > ( values ) ; } else { removedValues . addAll ( values ) ; } } } return removedValues ; }
Returns list of all removed values
5,850
public List < Object > setAttributeValues ( final String name , final List < Object > values ) { List < Object > replacedValues = null ; for ( final IAdditionalDescriptors additionalDescriptors : delegateDescriptors ) { final List < Object > oldValues = additionalDescriptors . setAttributeValues ( name , values ) ; if ( oldValues != null ) { if ( replacedValues == null ) { replacedValues = new ArrayList < > ( oldValues ) ; } else { replacedValues . addAll ( oldValues ) ; } } } return replacedValues ; }
Returns list of all replaced values
5,851
protected void addRequestProperties ( final HttpServletRequest httpServletRequest , final Map < String , List < Object > > attributes ) { if ( this . remoteUserAttribute != null ) { final String remoteUser = httpServletRequest . getRemoteUser ( ) ; attributes . put ( this . remoteUserAttribute , list ( remoteUser ) ) ; } if ( this . remoteAddrAttribute != null ) { final String remoteAddr = httpServletRequest . getRemoteAddr ( ) ; attributes . put ( this . remoteAddrAttribute , list ( remoteAddr ) ) ; } if ( this . remoteHostAttribute != null ) { final String remoteHost = httpServletRequest . getRemoteHost ( ) ; attributes . put ( this . remoteHostAttribute , list ( remoteHost ) ) ; } if ( this . serverNameAttribute != null ) { final String serverName = httpServletRequest . getServerName ( ) ; attributes . put ( this . serverNameAttribute , list ( serverName ) ) ; } if ( this . serverPortAttribute != null ) { final int serverPort = httpServletRequest . getServerPort ( ) ; attributes . put ( this . serverPortAttribute , list ( serverPort ) ) ; } }
Add other properties from the request to the attributes map .
5,852
protected void addRequestCookies ( final HttpServletRequest httpServletRequest , final Map < String , List < Object > > attributes ) { final Cookie [ ] cookies = httpServletRequest . getCookies ( ) ; if ( cookies == null ) { return ; } for ( final Cookie cookie : cookies ) { final String cookieName = cookie . getName ( ) ; if ( this . cookieAttributeMapping . containsKey ( cookieName ) ) { for ( final String attributeName : this . cookieAttributeMapping . get ( cookieName ) ) { attributes . put ( attributeName , list ( cookie . getValue ( ) ) ) ; } } } }
Add request cookies to the attributes map
5,853
protected void addRequestHeaders ( final HttpServletRequest httpServletRequest , final Map < String , List < Object > > attributes ) { for ( final Map . Entry < String , Set < String > > headerAttributeEntry : this . headerAttributeMapping . entrySet ( ) ) { final String headerName = headerAttributeEntry . getKey ( ) ; final String value = httpServletRequest . getHeader ( headerName ) ; if ( value != null ) { for ( final String attributeName : headerAttributeEntry . getValue ( ) ) { attributes . put ( attributeName , headersToIgnoreSemicolons . contains ( headerName ) ? list ( value ) : splitOnSemiColonHandlingBackslashEscaping ( value ) ) ; } } } }
Add request headers to the attributes map
5,854
public void append ( final Filter query ) { switch ( this . queryType ) { case OR : { this . orFilter . or ( query ) ; } break ; default : case AND : { this . andFilter . and ( query ) ; } break ; } }
Append the query Filter to the underlying logical Filter
5,855
protected boolean isCacheValid ( final Long lastModified ) { return ( lastModified != null && lastModified <= this . lastModifiedTime ) || ( lastModified == null && ( this . lastModifiedTime + this . noLastModifiedReloadPeriod ) <= System . currentTimeMillis ( ) ) ; }
Determines if the cached unmarshalled object is still valid
5,856
protected Map < String , Object > flattenResults ( final Map < String , List < Object > > multivaluedUserAttributes ) { if ( ! this . enabled ) { return null ; } if ( multivaluedUserAttributes == null ) { return null ; } final Map < String , Object > userAttributes = new LinkedHashMap < > ( multivaluedUserAttributes . size ( ) ) ; for ( final Map . Entry < String , List < Object > > attrEntry : multivaluedUserAttributes . entrySet ( ) ) { final String attrName = attrEntry . getKey ( ) ; final List < Object > attrValues = attrEntry . getValue ( ) ; final Object value ; if ( attrValues == null || attrValues . size ( ) == 0 ) { value = null ; } else { value = attrValues . get ( 0 ) ; } userAttributes . put ( attrName , value ) ; } logger . debug ( "Flattened Map='{}' into Map='{}'" , multivaluedUserAttributes , userAttributes ) ; return userAttributes ; }
Takes a &lt ; String List&lt ; Object&gt ; &gt ; Map and coverts it to a &lt ; String Object&gt ; Map . This implementation takes the first value of each List to use as the value for the new Map .
5,857
public void execute ( ) { if ( "pom" . equals ( project . getPackaging ( ) ) ) { getLog ( ) . info ( "Skipping SCoverage execution for project with packaging type 'pom'" ) ; return ; } if ( skip ) { getLog ( ) . info ( "Skipping Scoverage execution" ) ; return ; } long ts = System . currentTimeMillis ( ) ; SCoverageForkedLifecycleConfigurator . afterForkedLifecycleExit ( project , reactorProjects ) ; long te = System . currentTimeMillis ( ) ; getLog ( ) . debug ( String . format ( "Mojo execution time: %d ms" , te - ts ) ) ; }
Creates artifact file containing instrumented classes .
5,858
public void execute ( ) { if ( "pom" . equals ( project . getPackaging ( ) ) ) { return ; } if ( skip ) { return ; } long ts = System . currentTimeMillis ( ) ; Properties projectProperties = project . getProperties ( ) ; restoreProperty ( projectProperties , "sbt._scalacOptions" ) ; restoreProperty ( projectProperties , "sbt._scalacPlugins" ) ; restoreProperty ( projectProperties , "addScalacArgs" ) ; restoreProperty ( projectProperties , "analysisCacheFile" ) ; restoreProperty ( projectProperties , "maven.test.failure.ignore" ) ; long te = System . currentTimeMillis ( ) ; getLog ( ) . debug ( String . format ( "Mojo execution time: %d ms" , te - ts ) ) ; }
Restores project original configuration after compilation with SCoverage instrumentation .
5,859
private void addScoverageDependenciesToClasspath ( Artifact scalaScoveragePluginArtifact ) throws MojoExecutionException { @ SuppressWarnings ( "unchecked" ) Set < Artifact > set = new LinkedHashSet < Artifact > ( project . getDependencyArtifacts ( ) ) ; set . add ( scalaScoveragePluginArtifact ) ; project . setDependencyArtifacts ( set ) ; }
We need to tweak our test classpath for Scoverage .
5,860
public void execute ( ) throws MojoExecutionException { if ( ! canGenerateReport ( ) ) { getLog ( ) . info ( "Skipping SCoverage report generation" ) ; return ; } try { RenderingContext context = new RenderingContext ( outputDirectory , getOutputName ( ) + ".html" ) ; SiteRendererSink sink = new SiteRendererSink ( context ) ; Locale locale = Locale . getDefault ( ) ; generate ( sink , locale ) ; } catch ( MavenReportException e ) { String prefix = "An error has occurred in " + getName ( Locale . ENGLISH ) + " report generation" ; throw new MojoExecutionException ( prefix + ": " + e . getMessage ( ) , e ) ; } }
Generates SCoverage report .
5,861
protected String getRecommendedVersionRecursive ( Project project , ModuleVersionSelector mvSelector ) { String version = project . getExtensions ( ) . getByType ( RecommendationProviderContainer . class ) . getRecommendedVersion ( mvSelector . getGroup ( ) , mvSelector . getName ( ) ) ; if ( version != null ) return version ; if ( project . getParent ( ) != null ) return getRecommendedVersionRecursive ( project . getParent ( ) , mvSelector ) ; return null ; }
Look for recommended versions in a project and each of its ancestors in order until one is found or the root is reached
5,862
public Integer getAccountsCount ( final QueryParams params ) { FluentCaseInsensitiveStringsMap map = doHEAD ( Accounts . ACCOUNTS_RESOURCE , params ) ; return Integer . parseInt ( map . getFirstValue ( X_RECORDS_HEADER_NAME ) ) ; }
Get number of Accounts matching the query params
5,863
public Integer getCouponsCount ( final QueryParams params ) { FluentCaseInsensitiveStringsMap map = doHEAD ( Coupons . COUPONS_RESOURCE , params ) ; return Integer . parseInt ( map . getFirstValue ( X_RECORDS_HEADER_NAME ) ) ; }
Get number of Coupons matching the query params
5,864
public Integer getSubscriptionsCount ( final QueryParams params ) { FluentCaseInsensitiveStringsMap map = doHEAD ( Subscription . SUBSCRIPTION_RESOURCE , params ) ; return Integer . parseInt ( map . getFirstValue ( X_RECORDS_HEADER_NAME ) ) ; }
Get number of Subscriptions matching the query params
5,865
public Integer getTransactionsCount ( final QueryParams params ) { FluentCaseInsensitiveStringsMap map = doHEAD ( Transactions . TRANSACTIONS_RESOURCE , params ) ; return Integer . parseInt ( map . getFirstValue ( X_RECORDS_HEADER_NAME ) ) ; }
Get number of Transactions matching the query params
5,866
public Transaction getTransaction ( final String transactionId ) { if ( transactionId == null || transactionId . isEmpty ( ) ) throw new RuntimeException ( "transactionId cannot be empty!" ) ; return doGET ( Transactions . TRANSACTIONS_RESOURCE + "/" + transactionId , Transaction . class ) ; }
Lookup a transaction
5,867
public void refundTransaction ( final String transactionId , final BigDecimal amount ) { String url = Transactions . TRANSACTIONS_RESOURCE + "/" + transactionId ; if ( amount != null ) { url = url + "?amount_in_cents=" + ( amount . intValue ( ) * 100 ) ; } doDELETE ( url ) ; }
Refund a transaction
5,868
public Invoice getInvoice ( final String invoiceId ) { if ( invoiceId == null || invoiceId . isEmpty ( ) ) throw new RuntimeException ( "invoiceId cannot be empty!" ) ; return doGET ( Invoices . INVOICES_RESOURCE + "/" + invoiceId , Invoice . class ) ; }
Lookup an invoice given an invoice id
5,869
public Invoice markInvoiceSuccessful ( final String invoiceId ) { return doPUT ( Invoices . INVOICES_RESOURCE + "/" + invoiceId + "/mark_successful" , null , Invoice . class ) ; }
Mark an invoice as paid successfully - Recurly Enterprise Feature
5,870
public InvoiceCollection markInvoiceFailed ( final String invoiceId ) { return doPUT ( Invoices . INVOICES_RESOURCE + "/" + invoiceId + "/mark_failed" , null , InvoiceCollection . class ) ; }
Mark an invoice as failed collection
5,871
public Invoice forceCollectInvoice ( final String invoiceId ) { return doPUT ( Invoices . INVOICES_RESOURCE + "/" + invoiceId + "/collect" , null , Invoice . class ) ; }
Force collect an invoice
5,872
public Integer getPlansCount ( final QueryParams params ) { FluentCaseInsensitiveStringsMap map = doHEAD ( Plans . PLANS_RESOURCE , params ) ; return Integer . parseInt ( map . getFirstValue ( X_RECORDS_HEADER_NAME ) ) ; }
Get number of Plans matching the query params
5,873
public Redemption getCouponRedemptionByAccount ( final String accountCode ) { return doGET ( Accounts . ACCOUNTS_RESOURCE + "/" + accountCode + Redemption . REDEMPTION_RESOURCE , Redemption . class ) ; }
Lookup the first coupon redemption on an account .
5,874
public Redemptions getCouponRedemptionsByAccount ( final String accountCode ) { return doGET ( Accounts . ACCOUNTS_RESOURCE + "/" + accountCode + Redemption . REDEMPTIONS_RESOURCE , Redemptions . class , new QueryParams ( ) ) ; }
Lookup all coupon redemptions on an account .
5,875
public Redemption getCouponRedemptionByInvoice ( final String invoiceId ) { return doGET ( Invoices . INVOICES_RESOURCE + "/" + invoiceId + Redemption . REDEMPTION_RESOURCE , Redemption . class ) ; }
Lookup the first coupon redemption on an invoice .
5,876
public Redemptions getCouponRedemptionsBySubscription ( final String subscriptionUuid , final QueryParams params ) { return doGET ( Subscription . SUBSCRIPTION_RESOURCE + "/" + subscriptionUuid + Redemptions . REDEMPTIONS_RESOURCE , Redemptions . class , params ) ; }
Lookup all coupon redemptions on a subscription given query params .
5,877
public void deleteCouponRedemption ( final String accountCode , final String redemptionUuid ) { doDELETE ( Accounts . ACCOUNTS_RESOURCE + "/" + accountCode + Redemption . REDEMPTIONS_RESOURCE + "/" + redemptionUuid ) ; }
Deletes a specific redemption .
5,878
public void generateUniqueCodes ( final String couponCode , final Coupon coupon ) { doPOST ( Coupon . COUPON_RESOURCE + "/" + couponCode + Coupon . GENERATE_RESOURCE , coupon , null ) ; }
Generates unique codes for a bulk coupon .
5,879
public Coupons getUniqueCouponCodes ( final String couponCode , final QueryParams params ) { return doGET ( Coupon . COUPON_RESOURCE + "/" + couponCode + Coupon . UNIQUE_CODES_RESOURCE , Coupons . class , params ) ; }
Lookup all unique codes for a bulk coupon given query params .
5,880
public Integer getGiftCardsCount ( final QueryParams params ) { FluentCaseInsensitiveStringsMap map = doHEAD ( GiftCards . GIFT_CARDS_RESOURCE , params ) ; return Integer . parseInt ( map . getFirstValue ( X_RECORDS_HEADER_NAME ) ) ; }
Get number of GiftCards matching the query params
5,881
public static Type detect ( final String payload ) { final Matcher m = ROOT_NAME . matcher ( payload ) ; if ( m . find ( ) && m . groupCount ( ) >= 1 ) { final String root = m . group ( 1 ) ; try { return Type . valueOf ( CaseFormat . LOWER_UNDERSCORE . to ( CaseFormat . UPPER_CAMEL , root ) ) ; } catch ( IllegalArgumentException e ) { log . warn ( "Enable to detect notification type, no type for {}" , root ) ; return null ; } } log . warn ( "Enable to detect notification type" ) ; return null ; }
Detect notification type based on the xml root name .
5,882
public static GiftCard . Redemption createRedemption ( String accountCode ) { Redemption redemption = new Redemption ( ) ; redemption . setAccountCode ( accountCode ) ; return redemption ; }
Builds a redemption request
5,883
public Invoice getOriginalInvoice ( ) { if ( originalInvoice != null && originalInvoice . getHref ( ) != null && ! originalInvoice . getHref ( ) . isEmpty ( ) ) { originalInvoice = fetch ( originalInvoice , Invoice . class ) ; } return originalInvoice ; }
Fetches the original invoice if the href is populated otherwise return the current original invoice .
5,884
public static String asWKT ( Geometry geometry ) { if ( geometry == null ) { return null ; } WKTWriter wktWriter = new WKTWriter ( ) ; return wktWriter . write ( geometry ) ; }
Convert a Geometry value into a Well Known Text value .
5,885
public static Geometry multiplyZ ( Geometry geometry , double z ) throws SQLException { if ( geometry == null ) { return null ; } geometry . apply ( new MultiplyZCoordinateSequenceFilter ( z ) ) ; return geometry ; }
Multiply the z values of the geometry by another double value . NaN values are not updated .
5,886
public void insertRow ( Object [ ] values ) throws IOException { if ( ! ( values [ geometryFieldIndex ] instanceof Geometry ) ) { if ( values [ geometryFieldIndex ] == null ) { throw new IOException ( "Shape files do not support NULL Geometry values." ) ; } else { throw new IllegalArgumentException ( "Field at " + geometryFieldIndex + " should be an instance of Geometry," + " found " + values [ geometryFieldIndex ] . getClass ( ) + " instead." ) ; } } shapefileWriter . writeGeometry ( ( Geometry ) values [ geometryFieldIndex ] ) ; Object [ ] dbfValues = new Object [ values . length - 1 ] ; if ( geometryFieldIndex > 0 ) { System . arraycopy ( values , 0 , dbfValues , 0 , geometryFieldIndex ) ; } if ( geometryFieldIndex + 1 < values . length ) { System . arraycopy ( values , geometryFieldIndex + 1 , dbfValues , geometryFieldIndex , dbfValues . length - geometryFieldIndex ) ; } dbfDriver . insertRow ( dbfValues ) ; }
Insert values in the row
5,887
public void initDriver ( File shpFile , ShapeType shapeType , DbaseFileHeader dbaseHeader ) throws IOException { String path = shpFile . getAbsolutePath ( ) ; String nameWithoutExt = path . substring ( 0 , path . lastIndexOf ( '.' ) ) ; this . shpFile = new File ( nameWithoutExt + ".shp" ) ; this . shxFile = new File ( nameWithoutExt + ".shx" ) ; this . dbfFile = new File ( nameWithoutExt + ".dbf" ) ; FileOutputStream shpFos = new FileOutputStream ( shpFile ) ; FileOutputStream shxFos = new FileOutputStream ( shxFile ) ; shapefileWriter = new ShapefileWriter ( shpFos . getChannel ( ) , shxFos . getChannel ( ) ) ; this . shapeType = shapeType ; shapefileWriter . writeHeaders ( shapeType ) ; dbfDriver . initDriver ( dbfFile , dbaseHeader ) ; }
Init Driver for Write mode
5,888
private static void getPunctualGeometry ( ArrayList < Point > points , Geometry geometry ) { for ( int i = 0 ; i < geometry . getNumGeometries ( ) ; i ++ ) { Geometry subGeom = geometry . getGeometryN ( i ) ; if ( subGeom instanceof Point ) { points . add ( ( Point ) subGeom ) ; } else if ( subGeom instanceof GeometryCollection ) { getPunctualGeometry ( points , subGeom ) ; } } }
Filter point from a geometry
5,889
private static void getLinealGeometry ( ArrayList < LineString > lines , Geometry geometry ) { for ( int i = 0 ; i < geometry . getNumGeometries ( ) ; i ++ ) { Geometry subGeom = geometry . getGeometryN ( i ) ; if ( subGeom instanceof LineString ) { lines . add ( ( LineString ) subGeom ) ; } else if ( subGeom instanceof GeometryCollection ) { getLinealGeometry ( lines , subGeom ) ; } } }
Filter line from a geometry
5,890
private static void getArealGeometry ( ArrayList < Polygon > polygones , Geometry geometry ) { for ( int i = 0 ; i < geometry . getNumGeometries ( ) ; i ++ ) { Geometry subGeom = geometry . getGeometryN ( i ) ; if ( subGeom instanceof Polygon ) { polygones . add ( ( Polygon ) subGeom ) ; } else if ( subGeom instanceof GeometryCollection ) { getArealGeometry ( polygones , subGeom ) ; } } }
Filter polygon from a geometry
5,891
public static String toGML ( Geometry geom ) { if ( geom == null ) { return null ; } int srid = geom . getSRID ( ) ; GMLWriter gmlw = new GMLWriter ( ) ; if ( srid != - 1 || srid != 0 ) { gmlw . setSrsName ( "EPSG:" + geom . getSRID ( ) ) ; } return gmlw . write ( geom ) ; }
Write the GML
5,892
public static Point projectPoint ( Geometry point , Geometry geometry ) { if ( point == null || geometry == null ) { return null ; } if ( point . getDimension ( ) == 0 && geometry . getDimension ( ) == 1 ) { LengthIndexedLine ll = new LengthIndexedLine ( geometry ) ; double index = ll . project ( point . getCoordinate ( ) ) ; return geometry . getFactory ( ) . createPoint ( ll . extractPoint ( index ) ) ; } else { return null ; } }
Project a point on a linestring or multilinestring
5,893
public static ResultSet triangleContouring ( Connection connection , String tableName , Value ... varArgs ) throws SQLException { if ( connection . getMetaData ( ) . getURL ( ) . equals ( HACK_URL ) ) { return new ExplodeResultSet ( connection , tableName , Collections . singletonList ( 0.0 ) ) . getResultSet ( ) ; } ExplodeResultSet rowSource = null ; if ( varArgs . length > 3 ) { if ( varArgs [ 0 ] instanceof ValueString && varArgs [ 1 ] instanceof ValueString && varArgs [ 2 ] instanceof ValueString ) { List < Double > isoLvls = new ArrayList < Double > ( varArgs . length - 3 ) ; for ( int idArg = 3 ; idArg < varArgs . length ; idArg ++ ) { isoLvls . add ( varArgs [ idArg ] . getDouble ( ) ) ; } rowSource = new ExplodeResultSet ( connection , tableName , varArgs [ 0 ] . getString ( ) , varArgs [ 1 ] . getString ( ) , varArgs [ 2 ] . getString ( ) , isoLvls ) ; } } if ( rowSource == null ) { List < Double > isoLvls = new ArrayList < Double > ( varArgs . length ) ; for ( Value value : varArgs ) { if ( value instanceof ValueArray ) { for ( Value arrVal : ( ( ValueArray ) value ) . getList ( ) ) { isoLvls . add ( arrVal . getDouble ( ) ) ; } } else { isoLvls . add ( value . getDouble ( ) ) ; } } rowSource = new ExplodeResultSet ( connection , tableName , isoLvls ) ; } return rowSource . getResultSet ( ) ; }
Iso contouring using Z M attributes of geometries
5,894
public static boolean getConnectedComponents ( Connection connection , String inputTable , String orientation ) throws SQLException { KeyedGraph graph = prepareGraph ( connection , inputTable , orientation , null , VUCent . class , Edge . class ) ; if ( graph == null ) { return false ; } final List < Set < VUCent > > componentsList = getConnectedComponents ( graph , orientation ) ; final TableLocation tableName = TableUtilities . parseInputTable ( connection , inputTable ) ; final TableLocation nodesName = TableUtilities . suffixTableLocation ( tableName , NODE_COMP_SUFFIX ) ; final TableLocation edgesName = TableUtilities . suffixTableLocation ( tableName , EDGE_COMP_SUFFIX ) ; if ( storeNodeConnectedComponents ( connection , nodesName , edgesName , componentsList ) ) { if ( storeEdgeConnectedComponents ( connection , tableName , nodesName , edgesName ) ) { return true ; } } return false ; }
Calculate the node and edge connected component tables .
5,895
public static LineString createLine ( Geometry pointA , Geometry ... optionalPoints ) throws SQLException { if ( pointA == null || optionalPoints . length > 0 && optionalPoints [ 0 ] == null ) { return null ; } if ( pointA . getNumGeometries ( ) == 1 && ! atLeastTwoPoints ( optionalPoints , countPoints ( pointA ) ) ) { throw new SQLException ( "At least two points are required to make a line." ) ; } List < Coordinate > coordinateList = new LinkedList < Coordinate > ( ) ; addCoordinatesToList ( pointA , coordinateList ) ; for ( Geometry optionalPoint : optionalPoints ) { addCoordinatesToList ( optionalPoint , coordinateList ) ; } return ( ( Geometry ) pointA ) . getFactory ( ) . createLineString ( coordinateList . toArray ( new Coordinate [ optionalPoints . length ] ) ) ; }
Constructs a LINESTRING from the given POINTs or MULTIPOINTs
5,896
public void initialise ( XMLReader reader , AbstractGpxParserDefault parent ) { setReader ( reader ) ; setParent ( parent ) ; setContentBuffer ( parent . getContentBuffer ( ) ) ; setRtePreparedStmt ( parent . getRtePreparedStmt ( ) ) ; setRteptPreparedStmt ( parent . getRteptPreparedStmt ( ) ) ; setElementNames ( parent . getElementNames ( ) ) ; setCurrentLine ( parent . getCurrentLine ( ) ) ; setRteList ( new ArrayList < Coordinate > ( ) ) ; }
Create a new specific parser . It has in memory the default parser the contentBuffer the elementNames the currentLine and the rteID .
5,897
public static Coordinate createCoordinate ( Attributes attributes ) throws NumberFormatException { double lat ; double lon ; try { lat = Double . parseDouble ( attributes . getValue ( GPXTags . LAT ) ) ; } catch ( NumberFormatException e ) { throw new NumberFormatException ( "Cannot parse the latitude value" ) ; } try { lon = Double . parseDouble ( attributes . getValue ( GPXTags . LON ) ) ; } catch ( NumberFormatException e ) { throw new NumberFormatException ( "Cannot parse the longitude value" ) ; } String eleValue = attributes . getValue ( GPXTags . ELE ) ; double ele = Double . NaN ; if ( eleValue != null ) { try { ele = Double . parseDouble ( eleValue ) ; } catch ( NumberFormatException e ) { throw new NumberFormatException ( "Cannot parse the elevation value" ) ; } } return new Coordinate ( lon , lat , ele ) ; }
General method to create a coordinate from a gpx point .
5,898
public static Double getMinX ( Geometry geom ) { if ( geom != null ) { return geom . getEnvelopeInternal ( ) . getMinX ( ) ; } else { return null ; } }
Returns the minimal x - value of the given geometry .
5,899
public static Point createPoint ( double x , double y ) throws SQLException { return createPoint ( x , y , Coordinate . NULL_ORDINATE ) ; }
Constructs POINT from two doubles .