idx
int64 0
41.2k
| question
stringlengths 83
4.15k
| target
stringlengths 5
715
|
|---|---|---|
3,600
|
private void setLoggingLevel ( DesiredCapabilities caps ) { final LoggingPreferences logPrefs = new LoggingPreferences ( ) ; logPrefs . enable ( LogType . BROWSER , Level . ALL ) ; logPrefs . enable ( LogType . CLIENT , Level . OFF ) ; logPrefs . enable ( LogType . DRIVER , Level . OFF ) ; logPrefs . enable ( LogType . PERFORMANCE , Level . OFF ) ; logPrefs . enable ( LogType . PROFILER , Level . OFF ) ; logPrefs . enable ( LogType . SERVER , Level . OFF ) ; caps . setCapability ( CapabilityType . LOGGING_PREFS , logPrefs ) ; }
|
Sets the logging level of the generated web driver .
|
3,601
|
public static String getPath ( Driver currentDriver ) { final OperatingSystem currentOperatingSystem = OperatingSystem . getCurrentOperatingSystem ( ) ; String format = "" ; if ( "webdriver.ie.driver" . equals ( currentDriver . driverName ) ) { format = Utilities . setProperty ( Context . getWebdriversProperties ( currentDriver . driverName ) , "src/test/resources/drivers/%s/internetexplorer/%s/IEDriverServer%s" ) ; } else if ( "webdriver.chrome.driver" . equals ( currentDriver . driverName ) ) { format = Utilities . setProperty ( Context . getWebdriversProperties ( currentDriver . driverName ) , "src/test/resources/drivers/%s/googlechrome/%s/chromedriver%s" ) ; } else if ( "webdriver.gecko.driver" . equals ( currentDriver . driverName ) ) { format = Utilities . setProperty ( Context . getWebdriversProperties ( currentDriver . driverName ) , "src/test/resources/drivers/%s/firefox/%s/geckodriver%s" ) ; } return String . format ( format , currentOperatingSystem . getOperatingSystemDir ( ) , SystemArchitecture . getCurrentSystemArchitecture ( ) . getSystemArchitectureName ( ) , currentOperatingSystem . getSuffixBinary ( ) ) ; }
|
Get the path of the driver given in parameters .
|
3,602
|
public static String getUrlByPagekey ( String pageKey ) { if ( pageKey != null ) { for ( final Map . Entry < String , Application > application : getInstance ( ) . applications . entrySet ( ) ) { for ( final Map . Entry < String , String > urlPage : application . getValue ( ) . getUrlPages ( ) . entrySet ( ) ) { if ( pageKey . equals ( urlPage . getKey ( ) ) ) { return Auth . usingAuthentication ( urlPage . getValue ( ) ) ; } } } } else { return null ; } return null ; }
|
Get url name in a string by page key .
|
3,603
|
public static String getApplicationByPagekey ( String pageKey ) { if ( pageKey != null ) { for ( final Map . Entry < String , Application > application : getInstance ( ) . applications . entrySet ( ) ) { for ( final Map . Entry < String , String > urlPage : application . getValue ( ) . getUrlPages ( ) . entrySet ( ) ) { if ( pageKey . equals ( urlPage . getKey ( ) ) ) { return application . getKey ( ) ; } } } } else { return null ; } return null ; }
|
Get application name in a string by page key .
|
3,604
|
private boolean isApplicationFound ( String applicationName ) { boolean applicationFinded = false ; List < String > appList = application . get ( ) ; if ( ! appList . isEmpty ( ) ) { if ( appList . contains ( applicationName ) ) { applicationFinded = true ; } else { logger . info ( "Application [{}] do not exist. You must create an application named [{}] first." , applicationName , applicationName ) ; } } else { logger . info ( CLI_YOU_MUST_CREATE_AN_APPLICATION_FIRST ) ; } return applicationFinded ; }
|
Is application found looking for if applicationName match with an existing application .
|
3,605
|
public void remove ( String applicationName , Class < ? > robotContext , boolean verbose ) { logger . info ( "Remove application named [{}]." , applicationName ) ; removeApplicationPages ( applicationName , robotContext , verbose ) ; removeApplicationSteps ( applicationName , robotContext , verbose ) ; removeApplicationModel ( applicationName , robotContext , verbose ) ; removeApplicationContext ( robotContext , applicationName , verbose ) ; removeApplicationSelector ( applicationName , verbose ) ; removeApplicationInPropertiesFile ( applicationName , robotContext . getSimpleName ( ) . replaceAll ( "Context" , "" ) , verbose ) ; removeApplicationInEnvPropertiesFile ( applicationName , "ci" , verbose ) ; removeApplicationInEnvPropertiesFile ( applicationName , "dev" , verbose ) ; removeApplicationInEnvPropertiesFile ( applicationName , "prod" , verbose ) ; }
|
Remove target application to your robot .
|
3,606
|
private boolean applyChange ( boolean isChangeAvailable , Supplier < C > changeToApply ) { if ( isChangeAvailable ) { canMerge = false ; C change = changeToApply . get ( ) ; this . expectedChange = change ; performingAction . suspendWhile ( ( ) -> apply . accept ( change ) ) ; if ( this . expectedChange != null ) { throw new IllegalStateException ( "Expected change not received:\n" + this . expectedChange ) ; } invalidateProperties ( ) ; return true ; } else { return false ; } }
|
Helper method for reducing code duplication
|
3,607
|
public List < Message > pollQueue ( ) { boolean success = false ; ProgressStatus pollQueueStatus = new ProgressStatus ( ProgressState . pollQueue , new BasicPollQueueInfo ( 0 , success ) ) ; final Object reportObject = progressReporter . reportStart ( pollQueueStatus ) ; ReceiveMessageRequest request = new ReceiveMessageRequest ( ) . withAttributeNames ( ALL_ATTRIBUTES ) ; request . setQueueUrl ( config . getSqsUrl ( ) ) ; request . setVisibilityTimeout ( config . getVisibilityTimeout ( ) ) ; request . setMaxNumberOfMessages ( DEFAULT_SQS_MESSAGE_SIZE_LIMIT ) ; request . setWaitTimeSeconds ( DEFAULT_WAIT_TIME_SECONDS ) ; List < Message > sqsMessages = new ArrayList < Message > ( ) ; try { ReceiveMessageResult result = sqsClient . receiveMessage ( request ) ; sqsMessages = result . getMessages ( ) ; logger . info ( "Polled " + sqsMessages . size ( ) + " sqs messages from " + config . getSqsUrl ( ) ) ; success = true ; } catch ( AmazonServiceException e ) { LibraryUtils . handleException ( exceptionHandler , pollQueueStatus , e , "Failed to poll sqs message." ) ; } finally { LibraryUtils . endToProcess ( progressReporter , success , pollQueueStatus , reportObject ) ; } return sqsMessages ; }
|
Poll SQS queue for incoming messages filter them and return a list of SQS Messages .
|
3,608
|
public List < CloudTrailSource > parseMessage ( List < Message > sqsMessages ) { List < CloudTrailSource > sources = new ArrayList < > ( ) ; for ( Message sqsMessage : sqsMessages ) { boolean parseMessageSuccess = false ; ProgressStatus parseMessageStatus = new ProgressStatus ( ProgressState . parseMessage , new BasicParseMessageInfo ( sqsMessage , parseMessageSuccess ) ) ; final Object reportObject = progressReporter . reportStart ( parseMessageStatus ) ; CloudTrailSource ctSource = null ; try { ctSource = sourceSerializer . getSource ( sqsMessage ) ; if ( containsCloudTrailLogs ( ctSource ) ) { sources . add ( ctSource ) ; parseMessageSuccess = true ; } } catch ( Exception e ) { LibraryUtils . handleException ( exceptionHandler , parseMessageStatus , e , "Failed to parse sqs message." ) ; } finally { if ( containsCloudTrailValidationMessage ( ctSource ) || shouldDeleteMessageUponFailure ( parseMessageSuccess ) ) { deleteMessageFromQueue ( sqsMessage , new ProgressStatus ( ProgressState . deleteMessage , new BasicParseMessageInfo ( sqsMessage , false ) ) ) ; } LibraryUtils . endToProcess ( progressReporter , parseMessageSuccess , parseMessageStatus , reportObject ) ; } } return sources ; }
|
Given a list of raw SQS message parse each of them and return a list of CloudTrailSource .
|
3,609
|
public void deleteMessageFromQueue ( Message sqsMessage , ProgressStatus progressStatus ) { final Object reportObject = progressReporter . reportStart ( progressStatus ) ; boolean deleteMessageSuccess = false ; try { sqsClient . deleteMessage ( new DeleteMessageRequest ( config . getSqsUrl ( ) , sqsMessage . getReceiptHandle ( ) ) ) ; deleteMessageSuccess = true ; } catch ( AmazonServiceException e ) { LibraryUtils . handleException ( exceptionHandler , progressStatus , e , "Failed to delete sqs message." ) ; } LibraryUtils . endToProcess ( progressReporter , deleteMessageSuccess , progressStatus , reportObject ) ; }
|
Delete a message from the SQS queue that you specified in the configuration file .
|
3,610
|
private void validate ( ) { LibraryUtils . checkArgumentNotNull ( config , "configuration is null" ) ; LibraryUtils . checkArgumentNotNull ( exceptionHandler , "exceptionHandler is null" ) ; LibraryUtils . checkArgumentNotNull ( progressReporter , "progressReporter is null" ) ; LibraryUtils . checkArgumentNotNull ( sqsClient , "sqsClient is null" ) ; LibraryUtils . checkArgumentNotNull ( sourceSerializer , "sourceSerializer is null" ) ; }
|
Convenient function to validate input .
|
3,611
|
private Properties loadProperty ( String propertiesFile ) { Properties prop = new Properties ( ) ; try { InputStream in = getClass ( ) . getResourceAsStream ( propertiesFile ) ; prop . load ( in ) ; in . close ( ) ; } catch ( IOException e ) { throw new IllegalStateException ( "Cannot load property file at " + propertiesFile , e ) ; } return prop ; }
|
Load properties from a classpath property file .
|
3,612
|
private int getIntProperty ( Properties prop , String name ) { String propertyValue = prop . getProperty ( name ) ; return Integer . parseInt ( propertyValue ) ; }
|
Convert a string representation of a property to an integer type .
|
3,613
|
private Boolean getBooleanProperty ( Properties prop , String name ) { String propertyValue = prop . getProperty ( name ) ; return Boolean . parseBoolean ( propertyValue ) ; }
|
Convert a string representation of a property to a boolean type .
|
3,614
|
private void validateEvent ( CloudTrailEvent event ) { if ( event . getEventData ( ) . getAccountId ( ) == null ) { logger . error ( String . format ( "Event %s doesn't have account ID." , event . getEventData ( ) ) ) ; } }
|
Do simple validation before processing .
|
3,615
|
public List < CloudTrailSource > getSources ( ) { List < Message > sqsMessages = sqsManager . pollQueue ( ) ; return sqsManager . parseMessage ( sqsMessages ) ; }
|
Poll messages from SQS queue and convert messages to CloudTrailSource .
|
3,616
|
public void processSource ( CloudTrailSource source ) { boolean filterSourceOut = false ; boolean downloadLogSuccess = true ; boolean processSourceSuccess = false ; ProgressStatus processSourceStatus = new ProgressStatus ( ProgressState . processSource , new BasicProcessSourceInfo ( source , processSourceSuccess ) ) ; final Object processSourceReportObject = progressReporter . reportStart ( processSourceStatus ) ; try { if ( ! sourceFilter . filterSource ( source ) ) { logger . debug ( "AWSCloudTrailSource " + source + " has been filtered out." ) ; processSourceSuccess = true ; filterSourceOut = true ; } else { int nLogFilesToProcess = ( ( SQSBasedSource ) source ) . getLogs ( ) . size ( ) ; for ( CloudTrailLog ctLog : ( ( SQSBasedSource ) source ) . getLogs ( ) ) { boolean processLogSuccess = false ; ProgressStatus processLogStatus = new ProgressStatus ( ProgressState . processLog , new BasicProcessLogInfo ( source , ctLog , processLogSuccess ) ) ; final Object processLogReportObject = progressReporter . reportStart ( processLogStatus ) ; try { byte [ ] s3ObjectBytes = s3Manager . downloadLog ( ctLog , source ) ; if ( s3ObjectBytes == null ) { downloadLogSuccess = false ; continue ; } try ( GZIPInputStream gzippedInputStream = new GZIPInputStream ( new ByteArrayInputStream ( s3ObjectBytes ) ) ; EventSerializer serializer = getEventSerializer ( gzippedInputStream , ctLog ) ) { emitEvents ( serializer ) ; nLogFilesToProcess -- ; processLogSuccess = true ; } catch ( IllegalArgumentException | IOException e ) { LibraryUtils . handleException ( exceptionHandler , processLogStatus , e , "Failed to parse log file." ) ; } } finally { LibraryUtils . endToProcess ( progressReporter , processLogSuccess , processLogStatus , processLogReportObject ) ; } } if ( nLogFilesToProcess == 0 ) { processSourceSuccess = true ; } } } catch ( CallbackException ex ) { exceptionHandler . handleException ( ex ) ; } finally { cleanupMessage ( filterSourceOut , downloadLogSuccess , processSourceSuccess , source ) ; LibraryUtils . endToProcess ( progressReporter , processSourceSuccess , processSourceStatus , processSourceReportObject ) ; } }
|
Retrieve S3 object URL from source then downloads the object processes each event through call back functions .
|
3,617
|
private void deleteMessageAfterProcessSource ( ProgressState progressState , CloudTrailSource source ) { ProgressStatus deleteMessageStatus = new ProgressStatus ( progressState , new BasicProcessSourceInfo ( source , false ) ) ; sqsManager . deleteMessageFromQueue ( ( ( SQSBasedSource ) source ) . getSqsMessage ( ) , deleteMessageStatus ) ; }
|
Delete SQS message after processing source .
|
3,618
|
public void start ( ) { logger . info ( "Started AWSCloudTrailProcessingLibrary." ) ; validateBeforeStart ( ) ; scheduledThreadPool . scheduleAtFixedRate ( new ScheduledJob ( readerFactory ) , 0L , EXECUTION_DELAY , TimeUnit . MICROSECONDS ) ; }
|
Start processing AWS CloudTrail logs .
|
3,619
|
private void validateBeforeStart ( ) { LibraryUtils . checkArgumentNotNull ( config , "Configuration is null." ) ; config . validate ( ) ; LibraryUtils . checkArgumentNotNull ( sourceFilter , "sourceFilter is null." ) ; LibraryUtils . checkArgumentNotNull ( eventFilter , "eventFilter is null." ) ; LibraryUtils . checkArgumentNotNull ( eventsProcessor , "eventsProcessor is null." ) ; LibraryUtils . checkArgumentNotNull ( progressReporter , "progressReporter is null." ) ; LibraryUtils . checkArgumentNotNull ( exceptionHandler , "exceptionHandler is null." ) ; LibraryUtils . checkArgumentNotNull ( scheduledThreadPool , "scheduledThreadPool is null." ) ; LibraryUtils . checkArgumentNotNull ( mainThreadPool , "mainThreadPool is null." ) ; LibraryUtils . checkArgumentNotNull ( readerFactory , "readerFactory is null." ) ; }
|
Validate the user s input before processing logs .
|
3,620
|
public CloudTrailEventMetadata getMetadata ( int charStart , int charEnd ) { String rawEvent = logFile . substring ( charStart , charEnd + 1 ) ; int offset = rawEvent . indexOf ( "{" ) ; rawEvent = rawEvent . substring ( offset ) ; CloudTrailEventMetadata metadata = new LogDeliveryInfo ( ctLog , charStart + offset , charEnd , rawEvent ) ; return metadata ; }
|
Find the raw event in string format from logFileContent based on character start index and end index .
|
3,621
|
protected void readArrayHeader ( ) throws IOException { if ( jsonParser . nextToken ( ) != JsonToken . START_OBJECT ) { throw new JsonParseException ( "Not a Json object" , jsonParser . getCurrentLocation ( ) ) ; } jsonParser . nextToken ( ) ; if ( ! jsonParser . getText ( ) . equals ( RECORDS ) ) { throw new JsonParseException ( "Not a CloudTrail log" , jsonParser . getCurrentLocation ( ) ) ; } if ( jsonParser . nextToken ( ) != JsonToken . START_ARRAY ) { throw new JsonParseException ( "Not a CloudTrail log" , jsonParser . getCurrentLocation ( ) ) ; } }
|
Read the header of an AWS CloudTrail log .
|
3,622
|
public boolean hasNextEvent ( ) throws IOException { JsonToken nextToken = jsonParser . nextToken ( ) ; return nextToken == JsonToken . START_OBJECT || nextToken == JsonToken . START_ARRAY ; }
|
Indicates whether the CloudTrail log has more events to read .
|
3,623
|
public CloudTrailEvent getNextEvent ( ) throws IOException { CloudTrailEventData eventData = new CloudTrailEventData ( ) ; String key ; int charStart = ( int ) jsonParser . getTokenLocation ( ) . getCharOffset ( ) ; while ( jsonParser . nextToken ( ) != JsonToken . END_OBJECT ) { key = jsonParser . getCurrentName ( ) ; switch ( key ) { case "eventVersion" : String eventVersion = jsonParser . nextTextValue ( ) ; if ( Double . parseDouble ( eventVersion ) > SUPPORTED_EVENT_VERSION ) { logger . debug ( String . format ( "EventVersion %s is not supported by CloudTrail." , eventVersion ) ) ; } eventData . add ( key , eventVersion ) ; break ; case "userIdentity" : this . parseUserIdentity ( eventData ) ; break ; case "eventTime" : eventData . add ( CloudTrailEventField . eventTime . name ( ) , convertToDate ( jsonParser . nextTextValue ( ) ) ) ; break ; case "eventID" : eventData . add ( key , convertToUUID ( jsonParser . nextTextValue ( ) ) ) ; break ; case "readOnly" : this . parseReadOnly ( eventData ) ; break ; case "resources" : this . parseResources ( eventData ) ; break ; case "managementEvent" : this . parseManagementEvent ( eventData ) ; break ; default : eventData . add ( key , parseDefaultValue ( key ) ) ; break ; } } this . setAccountId ( eventData ) ; int charEnd = ( int ) jsonParser . getTokenLocation ( ) . getCharOffset ( ) ; CloudTrailEventMetadata metaData = getMetadata ( charStart , charEnd ) ; return new CloudTrailEvent ( eventData , metaData ) ; }
|
Get the next event from the CloudTrail log and parse it .
|
3,624
|
private void setAccountId ( CloudTrailEventData eventData ) { if ( eventData . getRecipientAccountId ( ) != null ) { eventData . add ( "accountId" , eventData . getRecipientAccountId ( ) ) ; return ; } if ( eventData . getUserIdentity ( ) != null && eventData . getUserIdentity ( ) . getAccountId ( ) != null ) { eventData . add ( "accountId" , eventData . getUserIdentity ( ) . getAccountId ( ) ) ; return ; } if ( eventData . getUserIdentity ( ) != null && eventData . getUserIdentity ( ) . getAccountId ( ) == null && eventData . getUserIdentity ( ) . getSessionContext ( ) != null && eventData . getUserIdentity ( ) . getSessionContext ( ) . getSessionIssuer ( ) != null && eventData . getUserIdentity ( ) . getSessionContext ( ) . getSessionIssuer ( ) . getAccountId ( ) != null ) { eventData . add ( "accountId" , eventData . getUserIdentity ( ) . getSessionContext ( ) . getSessionIssuer ( ) . getAccountId ( ) ) ; } }
|
Set AccountId in CloudTrailEventData top level from either recipientAccountID or from UserIdentity . If recipientAccountID exists then recipientAccountID is set to accountID ; otherwise accountID is retrieved from UserIdentity .
|
3,625
|
private void parseReadOnly ( CloudTrailEventData eventData ) throws IOException { jsonParser . nextToken ( ) ; Boolean readOnly = null ; if ( jsonParser . getCurrentToken ( ) != JsonToken . VALUE_NULL ) { readOnly = jsonParser . getBooleanValue ( ) ; } eventData . add ( CloudTrailEventField . readOnly . name ( ) , readOnly ) ; }
|
Parses the event readOnly attribute .
|
3,626
|
private void parseManagementEvent ( CloudTrailEventData eventData ) throws IOException { jsonParser . nextToken ( ) ; Boolean managementEvent = null ; if ( jsonParser . getCurrentToken ( ) != JsonToken . VALUE_NULL ) { managementEvent = jsonParser . getBooleanValue ( ) ; } eventData . add ( CloudTrailEventField . managementEvent . name ( ) , managementEvent ) ; }
|
Parses the event managementEvent attribute .
|
3,627
|
private void parseResources ( CloudTrailEventData eventData ) throws IOException { JsonToken nextToken = jsonParser . nextToken ( ) ; if ( nextToken == JsonToken . VALUE_NULL ) { eventData . add ( CloudTrailEventField . resources . name ( ) , null ) ; return ; } if ( nextToken != JsonToken . START_ARRAY ) { throw new JsonParseException ( "Not a list of resources object" , jsonParser . getCurrentLocation ( ) ) ; } List < Resource > resources = new ArrayList < Resource > ( ) ; while ( jsonParser . nextToken ( ) != JsonToken . END_ARRAY ) { resources . add ( parseResource ( ) ) ; } eventData . add ( CloudTrailEventField . resources . name ( ) , resources ) ; }
|
Parses a list of Resource .
|
3,628
|
private Resource parseResource ( ) throws IOException { if ( jsonParser . getCurrentToken ( ) != JsonToken . START_OBJECT ) { throw new JsonParseException ( "Not a Resource object" , jsonParser . getCurrentLocation ( ) ) ; } Resource resource = new Resource ( ) ; while ( jsonParser . nextToken ( ) != JsonToken . END_OBJECT ) { String key = jsonParser . getCurrentName ( ) ; switch ( key ) { default : resource . add ( key , parseDefaultValue ( key ) ) ; break ; } } return resource ; }
|
Parses a single Resource .
|
3,629
|
private String parseDefaultValue ( String key ) throws IOException { jsonParser . nextToken ( ) ; String value = null ; JsonToken currentToken = jsonParser . getCurrentToken ( ) ; if ( currentToken != JsonToken . VALUE_NULL ) { if ( currentToken == JsonToken . START_ARRAY || currentToken == JsonToken . START_OBJECT ) { JsonNode node = jsonParser . readValueAsTree ( ) ; value = node . toString ( ) ; } else { value = jsonParser . getValueAsString ( ) ; } } return value ; }
|
Parses the event with key as default value .
|
3,630
|
private Map < String , String > parseAttributes ( ) throws IOException { if ( jsonParser . nextToken ( ) != JsonToken . START_OBJECT ) { throw new JsonParseException ( "Not a Attributes object" , jsonParser . getCurrentLocation ( ) ) ; } Map < String , String > attributes = new HashMap < > ( ) ; while ( jsonParser . nextToken ( ) != JsonToken . END_OBJECT ) { String key = jsonParser . getCurrentName ( ) ; String value = jsonParser . nextTextValue ( ) ; attributes . put ( key , value ) ; } return attributes ; }
|
Parses attributes as a Map used in both parseWebIdentitySessionContext and parseSessionContext
|
3,631
|
private Date convertToDate ( String dateInString ) throws IOException { Date date = null ; if ( dateInString != null ) { try { date = LibraryUtils . getUtcSdf ( ) . parse ( dateInString ) ; } catch ( ParseException e ) { throw new IOException ( "Cannot parse " + dateInString + " as Date" , e ) ; } } return date ; }
|
This method convert a String to Date type . When parse error happened return current date .
|
3,632
|
public static void endToProcess ( ProgressReporter progressReporter , boolean processSuccess , ProgressStatus progressStatus , Object reportObject ) { progressStatus . getProgressInfo ( ) . setIsSuccess ( processSuccess ) ; progressReporter . reportEnd ( progressStatus , reportObject ) ; }
|
A wrapper function of reporting the result of the processing .
|
3,633
|
private void validate ( ) { LibraryUtils . checkArgumentNotNull ( config , "Configuration is null." ) ; LibraryUtils . checkArgumentNotNull ( eventsProcessor , "Events Processor is null." ) ; LibraryUtils . checkArgumentNotNull ( sourceFilter , "Source Filter is null." ) ; LibraryUtils . checkArgumentNotNull ( eventFilter , "Event Filter is null." ) ; LibraryUtils . checkArgumentNotNull ( progressReporter , "Progress Reporter is null." ) ; LibraryUtils . checkArgumentNotNull ( exceptionHandler , "Exception Handler is null." ) ; LibraryUtils . checkArgumentNotNull ( s3Manager , "S3 Manager is null." ) ; LibraryUtils . checkArgumentNotNull ( sqsManager , "SQS Manager is null." ) ; }
|
Validate input parameters .
|
3,634
|
public void handleException ( ProcessingLibraryException exception ) { ProgressStatus status = exception . getStatus ( ) ; ProgressState state = status . getProgressState ( ) ; ProgressInfo info = status . getProgressInfo ( ) ; logger . error ( String . format ( "Exception. Progress State: %s. Progress Information: %s." , state , info ) ) ; }
|
Exception handler that simply log progress state and progress information .
|
3,635
|
public boolean filterEvent ( CloudTrailEvent event ) throws CallbackException { CloudTrailEventData eventData = event . getEventData ( ) ; String eventSource = eventData . getEventSource ( ) ; String eventName = eventData . getEventName ( ) ; return eventSource . equals ( EC2_EVENTS ) && eventName . startsWith ( "Delete" ) ; }
|
Event filter that only keep EC2 deletion API calls .
|
3,636
|
@ SuppressWarnings ( "unchecked" ) public List < Resource > getResources ( ) { return ( List < Resource > ) get ( CloudTrailEventField . resources . name ( ) ) ; }
|
Get the resources used in the operation .
|
3,637
|
public boolean filterSource ( CloudTrailSource source ) throws CallbackException { source = ( SQSBasedSource ) source ; Map < String , String > sourceAttributes = source . getSourceAttributes ( ) ; String accountId = sourceAttributes . get ( SourceAttributeKeys . ACCOUNT_ID . getAttributeKey ( ) ) ; String receivedCount = sourceAttributes . get ( SourceAttributeKeys . APPROXIMATE_RECEIVE_COUNT . getAttributeKey ( ) ) ; int approximateReceivedCount = Integer . parseInt ( receivedCount ) ; return approximateReceivedCount <= MAX_RECEIVED_COUNT && accountIDs . contains ( accountId ) ; }
|
This Sample Source Filter filter out messages that have been received more than 3 times and accountIDs in a certain range .
|
3,638
|
@ SuppressWarnings ( { "unchecked" , "rawtypes" } ) public Map < String , String > getAttributes ( ) { return ( Map ) this . get ( CloudTrailEventField . attributes . name ( ) ) ; }
|
Get attributes .
|
3,639
|
public byte [ ] downloadLog ( CloudTrailLog ctLog , CloudTrailSource source ) { boolean success = false ; ProgressStatus downloadLogStatus = new ProgressStatus ( ProgressState . downloadLog , new BasicProcessLogInfo ( source , ctLog , success ) ) ; final Object downloadSourceReportObject = progressReporter . reportStart ( downloadLogStatus ) ; byte [ ] s3ObjectBytes = null ; try { S3Object s3Object = this . getObject ( ctLog . getS3Bucket ( ) , ctLog . getS3ObjectKey ( ) ) ; try ( S3ObjectInputStream s3InputStream = s3Object . getObjectContent ( ) ) { s3ObjectBytes = LibraryUtils . toByteArray ( s3InputStream ) ; } ctLog . setLogFileSize ( s3Object . getObjectMetadata ( ) . getContentLength ( ) ) ; success = true ; logger . info ( "Downloaded log file " + ctLog . getS3ObjectKey ( ) + " from " + ctLog . getS3Bucket ( ) ) ; } catch ( AmazonServiceException | IOException e ) { String exceptionMessage = String . format ( "Fail to download log file %s/%s." , ctLog . getS3Bucket ( ) , ctLog . getS3ObjectKey ( ) ) ; LibraryUtils . handleException ( exceptionHandler , downloadLogStatus , e , exceptionMessage ) ; } finally { LibraryUtils . endToProcess ( progressReporter , success , downloadLogStatus , downloadSourceReportObject ) ; } return s3ObjectBytes ; }
|
Downloads an AWS CloudTrail log from the specified source .
|
3,640
|
public S3Object getObject ( String bucketName , String objectKey ) { try { return s3Client . getObject ( bucketName , objectKey ) ; } catch ( AmazonServiceException e ) { logger . error ( "Failed to get object " + objectKey + " from s3 bucket " + bucketName ) ; throw e ; } }
|
Download an S3 object .
|
3,641
|
private void validate ( ) { LibraryUtils . checkArgumentNotNull ( config , "configuration is null" ) ; LibraryUtils . checkArgumentNotNull ( exceptionHandler , "exceptionHandler is null" ) ; LibraryUtils . checkArgumentNotNull ( progressReporter , "progressReporter is null" ) ; LibraryUtils . checkArgumentNotNull ( s3Client , "s3Client is null" ) ; }
|
Validates input parameters .
|
3,642
|
public SourceType identifyWithEventName ( String source , String eventName ) { if ( eventName . startsWith ( CREATE_EVENT_PREFIX ) ) { return getCloudTrailSourceType ( source ) ; } return SourceType . Other ; }
|
Identify the source type with event action .
|
3,643
|
public static int resultSetTypeToSqlLite ( int columnType ) { int type ; switch ( columnType ) { case Types . INTEGER : case Types . BIGINT : case Types . SMALLINT : case Types . TINYINT : case Types . BOOLEAN : type = ResultUtils . FIELD_TYPE_INTEGER ; break ; case Types . VARCHAR : case Types . DATE : type = ResultUtils . FIELD_TYPE_STRING ; break ; case Types . REAL : case Types . FLOAT : case Types . DOUBLE : type = ResultUtils . FIELD_TYPE_FLOAT ; break ; case Types . BLOB : type = ResultUtils . FIELD_TYPE_BLOB ; break ; case Types . NULL : type = ResultUtils . FIELD_TYPE_NULL ; break ; default : throw new GeoPackageException ( "Unsupported ResultSet Metadata Column Type: " + columnType ) ; } return type ; }
|
Get the SQLite type from the ResultSetMetaData column type
|
3,644
|
public static boolean create ( File file ) { boolean created = false ; if ( GeoPackageIOUtils . hasFileExtension ( file ) ) { GeoPackageValidate . validateGeoPackageExtension ( file ) ; } else { file = GeoPackageIOUtils . addFileExtension ( file , GeoPackageConstants . GEOPACKAGE_EXTENSION ) ; } if ( file . exists ( ) ) { throw new GeoPackageException ( "GeoPackage already exists: " + file . getAbsolutePath ( ) ) ; } else { GeoPackageConnection connection = connect ( file ) ; connection . setApplicationId ( ) ; connection . setUserVersion ( ) ; GeoPackageTableCreator tableCreator = new GeoPackageTableCreator ( connection ) ; tableCreator . createRequired ( ) ; connection . close ( ) ; created = true ; } return created ; }
|
Create a GeoPackage
|
3,645
|
public static GeoPackage open ( String name , File file ) { if ( GeoPackageIOUtils . hasFileExtension ( file ) ) { GeoPackageValidate . validateGeoPackageExtension ( file ) ; } else { file = GeoPackageIOUtils . addFileExtension ( file , GeoPackageConstants . GEOPACKAGE_EXTENSION ) ; } GeoPackageConnection connection = connect ( file ) ; GeoPackageTableCreator tableCreator = new GeoPackageTableCreator ( connection ) ; GeoPackage geoPackage = new GeoPackageImpl ( name , file , connection , tableCreator ) ; try { GeoPackageValidate . validateMinimumTables ( geoPackage ) ; } catch ( RuntimeException e ) { geoPackage . close ( ) ; throw e ; } return geoPackage ; }
|
Open a GeoPackage
|
3,646
|
private static GeoPackageConnection connect ( File file ) { String databaseUrl = "jdbc:sqlite:" + file . getPath ( ) ; try { Class . forName ( "org.sqlite.JDBC" ) ; } catch ( ClassNotFoundException e ) { throw new GeoPackageException ( "Failed to load the SQLite JDBC driver" , e ) ; } Connection databaseConnection ; try { databaseConnection = DriverManager . getConnection ( databaseUrl ) ; } catch ( SQLException e ) { throw new GeoPackageException ( "Failed to get connection to the SQLite file: " + file . getAbsolutePath ( ) , e ) ; } ConnectionSource connectionSource ; try { connectionSource = new JdbcConnectionSource ( databaseUrl ) ; } catch ( SQLException e ) { throw new GeoPackageException ( "Failed to get connection source to the SQLite file: " + file . getAbsolutePath ( ) , e ) ; } GeoPackageConnection connection = new GeoPackageConnection ( file , databaseConnection , connectionSource ) ; return connection ; }
|
Connect to a GeoPackage file
|
3,647
|
public void setTileData ( BufferedImage image , String imageFormat ) throws IOException { byte [ ] bytes = ImageUtils . writeImageToBytes ( image , imageFormat ) ; setTileData ( bytes ) ; }
|
Set the tile data from an image
|
3,648
|
public ResultSet query ( String sql , String [ ] args ) { return SQLUtils . query ( connection , sql , args ) ; }
|
Perform a database query
|
3,649
|
public boolean hasTile ( BoundingBox requestBoundingBox ) { boolean hasTile = false ; ProjectionTransform transformRequestToTiles = requestProjection . getTransformation ( tilesProjection ) ; BoundingBox tilesBoundingBox = requestBoundingBox . transform ( transformRequestToTiles ) ; List < TileMatrix > tileMatrices = getTileMatrices ( tilesBoundingBox ) ; for ( int i = 0 ; ! hasTile && i < tileMatrices . size ( ) ; i ++ ) { TileMatrix tileMatrix = tileMatrices . get ( i ) ; TileResultSet tileResults = retrieveTileResults ( tilesBoundingBox , tileMatrix ) ; if ( tileResults != null ) { try { hasTile = tileResults . getCount ( ) > 0 ; } finally { tileResults . close ( ) ; } } } return hasTile ; }
|
Check if the tile table contains a tile for the request bounding box
|
3,650
|
public GeoPackageTile getTile ( BoundingBox requestBoundingBox ) { GeoPackageTile tile = null ; ProjectionTransform transformRequestToTiles = requestProjection . getTransformation ( tilesProjection ) ; BoundingBox tilesBoundingBox = requestBoundingBox . transform ( transformRequestToTiles ) ; List < TileMatrix > tileMatrices = getTileMatrices ( tilesBoundingBox ) ; for ( int i = 0 ; tile == null && i < tileMatrices . size ( ) ; i ++ ) { TileMatrix tileMatrix = tileMatrices . get ( i ) ; TileResultSet tileResults = retrieveTileResults ( tilesBoundingBox , tileMatrix ) ; if ( tileResults != null ) { try { if ( tileResults . getCount ( ) > 0 ) { BoundingBox requestProjectedBoundingBox = requestBoundingBox . transform ( transformRequestToTiles ) ; int requestedTileWidth = width != null ? width : ( int ) tileMatrix . getTileWidth ( ) ; int requestedTileHeight = height != null ? height : ( int ) tileMatrix . getTileHeight ( ) ; int tileWidth = requestedTileWidth ; int tileHeight = requestedTileHeight ; if ( ! sameProjection ) { tileWidth = ( int ) Math . round ( ( requestProjectedBoundingBox . getMaxLongitude ( ) - requestProjectedBoundingBox . getMinLongitude ( ) ) / tileMatrix . getPixelXSize ( ) ) ; tileHeight = ( int ) Math . round ( ( requestProjectedBoundingBox . getMaxLatitude ( ) - requestProjectedBoundingBox . getMinLatitude ( ) ) / tileMatrix . getPixelYSize ( ) ) ; } GeoPackageTile geoPackageTile = drawTile ( tileMatrix , tileResults , requestProjectedBoundingBox , tileWidth , tileHeight ) ; if ( geoPackageTile != null ) { if ( ! sameProjection && geoPackageTile . getImage ( ) != null ) { BufferedImage reprojectTile = reprojectTile ( geoPackageTile . getImage ( ) , requestedTileWidth , requestedTileHeight , requestBoundingBox , transformRequestToTiles , tilesBoundingBox ) ; geoPackageTile = new GeoPackageTile ( requestedTileWidth , requestedTileHeight , reprojectTile ) ; } tile = geoPackageTile ; } } } finally { tileResults . close ( ) ; } } } return tile ; }
|
Get the tile from the request bounding box in the request projection
|
3,651
|
private GeoPackageTile drawTile ( TileMatrix tileMatrix , TileResultSet tileResults , BoundingBox requestProjectedBoundingBox , int tileWidth , int tileHeight ) { GeoPackageTile geoPackageTile = null ; Graphics graphics = null ; while ( tileResults . moveToNext ( ) ) { TileRow tileRow = tileResults . getRow ( ) ; BufferedImage tileDataImage ; try { tileDataImage = tileRow . getTileDataImage ( ) ; } catch ( IOException e ) { throw new GeoPackageException ( "Failed to read the tile row image data" , e ) ; } BoundingBox tileBoundingBox = TileBoundingBoxUtils . getBoundingBox ( tileSetBoundingBox , tileMatrix , tileRow . getTileColumn ( ) , tileRow . getTileRow ( ) ) ; BoundingBox overlap = requestProjectedBoundingBox . overlap ( tileBoundingBox ) ; if ( overlap != null ) { ImageRectangle src = TileBoundingBoxJavaUtils . getRectangle ( tileMatrix . getTileWidth ( ) , tileMatrix . getTileHeight ( ) , tileBoundingBox , overlap ) ; ImageRectangle dest = TileBoundingBoxJavaUtils . getRectangle ( tileWidth , tileHeight , requestProjectedBoundingBox , overlap ) ; if ( src . isValid ( ) && dest . isValid ( ) ) { if ( imageFormat != null ) { if ( geoPackageTile == null ) { BufferedImage bufferedImage = ImageUtils . createBufferedImage ( tileWidth , tileHeight , imageFormat ) ; graphics = bufferedImage . getGraphics ( ) ; geoPackageTile = new GeoPackageTile ( tileWidth , tileHeight , bufferedImage ) ; } graphics . drawImage ( tileDataImage , dest . getLeft ( ) , dest . getTop ( ) , dest . getRight ( ) , dest . getBottom ( ) , src . getLeft ( ) , src . getTop ( ) , src . getRight ( ) , src . getBottom ( ) , null ) ; } else { if ( geoPackageTile != null || ! src . equals ( dest ) ) { throw new GeoPackageException ( "Raw image only supported when the images are aligned with the tile format requiring no combining and cropping" ) ; } geoPackageTile = new GeoPackageTile ( tileWidth , tileHeight , tileRow . getTileData ( ) ) ; } } } } if ( geoPackageTile != null && geoPackageTile . getImage ( ) != null && ImageUtils . isFullyTransparent ( geoPackageTile . getImage ( ) ) ) { geoPackageTile = null ; } return geoPackageTile ; }
|
Draw the tile from the tile results
|
3,652
|
private BufferedImage reprojectTile ( BufferedImage tile , int requestedTileWidth , int requestedTileHeight , BoundingBox requestBoundingBox , ProjectionTransform transformRequestToTiles , BoundingBox tilesBoundingBox ) { final double requestedWidthUnitsPerPixel = ( requestBoundingBox . getMaxLongitude ( ) - requestBoundingBox . getMinLongitude ( ) ) / requestedTileWidth ; final double requestedHeightUnitsPerPixel = ( requestBoundingBox . getMaxLatitude ( ) - requestBoundingBox . getMinLatitude ( ) ) / requestedTileHeight ; final double tilesDistanceWidth = tilesBoundingBox . getMaxLongitude ( ) - tilesBoundingBox . getMinLongitude ( ) ; final double tilesDistanceHeight = tilesBoundingBox . getMaxLatitude ( ) - tilesBoundingBox . getMinLatitude ( ) ; final int width = tile . getWidth ( ) ; final int height = tile . getHeight ( ) ; int [ ] pixels = new int [ width * height ] ; tile . getRGB ( 0 , 0 , width , height , pixels , 0 , width ) ; int [ ] projectedPixels = new int [ requestedTileWidth * requestedTileHeight ] ; for ( int y = 0 ; y < requestedTileHeight ; y ++ ) { for ( int x = 0 ; x < requestedTileWidth ; x ++ ) { double longitude = requestBoundingBox . getMinLongitude ( ) + ( x * requestedWidthUnitsPerPixel ) ; double latitude = requestBoundingBox . getMaxLatitude ( ) - ( y * requestedHeightUnitsPerPixel ) ; ProjCoordinate fromCoord = new ProjCoordinate ( longitude , latitude ) ; ProjCoordinate toCoord = transformRequestToTiles . transform ( fromCoord ) ; double projectedLongitude = toCoord . x ; double projectedLatitude = toCoord . y ; int xPixel = ( int ) Math . round ( ( ( projectedLongitude - tilesBoundingBox . getMinLongitude ( ) ) / tilesDistanceWidth ) * width ) ; int yPixel = ( int ) Math . round ( ( ( tilesBoundingBox . getMaxLatitude ( ) - projectedLatitude ) / tilesDistanceHeight ) * height ) ; xPixel = Math . max ( 0 , xPixel ) ; xPixel = Math . min ( width - 1 , xPixel ) ; yPixel = Math . max ( 0 , yPixel ) ; yPixel = Math . min ( height - 1 , yPixel ) ; int color = pixels [ ( yPixel * width ) + xPixel ] ; projectedPixels [ ( y * requestedTileWidth ) + x ] = color ; } } BufferedImage projectedTileImage = new BufferedImage ( requestedTileWidth , requestedTileHeight , tile . getType ( ) ) ; projectedTileImage . setRGB ( 0 , 0 , requestedTileWidth , requestedTileHeight , projectedPixels , 0 , requestedTileWidth ) ; return projectedTileImage ; }
|
Reproject the tile to the requested projection
|
3,653
|
public BoundingBox getBoundingBox ( ) { GeometryEnvelope envelope = null ; long offset = 0 ; boolean hasResults = true ; while ( hasResults ) { hasResults = false ; FeatureResultSet resultSet = featureDao . queryForChunk ( chunkLimit , offset ) ; try { while ( resultSet . moveToNext ( ) ) { hasResults = true ; FeatureRow featureRow = resultSet . getRow ( ) ; GeometryEnvelope featureEnvelope = featureRow . getGeometryEnvelope ( ) ; if ( featureEnvelope != null ) { if ( envelope == null ) { envelope = featureEnvelope ; } else { envelope = envelope . union ( featureEnvelope ) ; } } } } finally { resultSet . close ( ) ; } offset += chunkLimit ; } BoundingBox boundingBox = null ; if ( envelope != null ) { boundingBox = new BoundingBox ( envelope ) ; } return boundingBox ; }
|
Manually build the bounds of the feature table
|
3,654
|
private void createFunction ( String name , GeometryFunction function ) { try { Function . create ( getGeoPackage ( ) . getConnection ( ) . getConnection ( ) , name , function ) ; } catch ( SQLException e ) { log . log ( Level . SEVERE , "Failed to create function: " + name , e ) ; } }
|
Create the function for the connection
|
3,655
|
private BufferedImage drawTile ( int tileWidth , int tileHeight , String text ) { BufferedImage image = new BufferedImage ( tileWidth , tileHeight , BufferedImage . TYPE_INT_ARGB ) ; Graphics2D graphics = image . createGraphics ( ) ; graphics . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_ON ) ; if ( tileFillColor != null ) { graphics . setColor ( tileFillColor ) ; graphics . fillRect ( 0 , 0 , tileWidth , tileHeight ) ; } if ( tileBorderColor != null ) { graphics . setColor ( tileBorderColor ) ; graphics . setStroke ( new BasicStroke ( tileBorderStrokeWidth ) ) ; graphics . drawRect ( 0 , 0 , tileWidth , tileHeight ) ; } graphics . setFont ( new Font ( textFont , Font . PLAIN , textSize ) ) ; FontMetrics fontMetrics = graphics . getFontMetrics ( ) ; int textWidth = fontMetrics . stringWidth ( text ) ; int textHeight = fontMetrics . getAscent ( ) ; int centerX = ( int ) ( image . getWidth ( ) / 2.0f ) ; int centerY = ( int ) ( image . getHeight ( ) / 2.0f ) ; if ( circleColor != null || circleFillColor != null ) { int diameter = Math . max ( textWidth , textHeight ) ; float radius = diameter / 2.0f ; radius = radius + ( diameter * circlePaddingPercentage ) ; int paddedDiameter = Math . round ( radius * 2 ) ; int circleX = Math . round ( centerX - radius ) ; int circleY = Math . round ( centerY - radius ) ; if ( circleFillColor != null ) { graphics . setColor ( circleFillColor ) ; graphics . setStroke ( new BasicStroke ( circleStrokeWidth ) ) ; graphics . fillOval ( circleX , circleY , paddedDiameter , paddedDiameter ) ; } if ( circleColor != null ) { graphics . setColor ( circleColor ) ; graphics . setStroke ( new BasicStroke ( circleStrokeWidth ) ) ; graphics . drawOval ( circleX , circleY , paddedDiameter , paddedDiameter ) ; } } float textX = centerX - ( textWidth / 2.0f ) ; float textY = centerY + ( textHeight / 2.0f ) ; graphics . setColor ( textColor ) ; graphics . drawString ( text , textX , textY ) ; return image ; }
|
Draw a tile with the provided text label in the middle
|
3,656
|
public static BufferedImage createBufferedImage ( int width , int height , String imageFormat ) { int imageType ; switch ( imageFormat . toLowerCase ( ) ) { case IMAGE_FORMAT_JPG : case IMAGE_FORMAT_JPEG : imageType = BufferedImage . TYPE_INT_RGB ; break ; default : imageType = BufferedImage . TYPE_INT_ARGB ; } BufferedImage image = new BufferedImage ( width , height , imageType ) ; return image ; }
|
Create a buffered image for the dimensions and image format
|
3,657
|
public static boolean isFullyTransparent ( BufferedImage image ) { boolean transparent = true ; for ( int x = 0 ; x < image . getWidth ( ) ; x ++ ) { for ( int y = 0 ; y < image . getHeight ( ) ; y ++ ) { transparent = isTransparent ( image , x , y ) ; if ( ! transparent ) { break ; } } if ( ! transparent ) { break ; } } return transparent ; }
|
Check if the image is fully transparent meaning it contains only transparent pixels as an empty image
|
3,658
|
public static boolean isTransparent ( BufferedImage image , int x , int y ) { int pixel = image . getRGB ( x , y ) ; boolean transparent = ( pixel >> 24 ) == 0x00 ; return transparent ; }
|
Check if the pixel in the image at the x and y is transparent
|
3,659
|
public static BufferedImage getImage ( byte [ ] imageBytes ) throws IOException { BufferedImage image = null ; if ( imageBytes != null ) { ByteArrayInputStream stream = new ByteArrayInputStream ( imageBytes ) ; image = ImageIO . read ( stream ) ; stream . close ( ) ; } return image ; }
|
Get a buffered image of the image bytes
|
3,660
|
public static byte [ ] writeImageToBytes ( BufferedImage image , String formatName , Float quality ) throws IOException { byte [ ] bytes = null ; if ( quality != null ) { bytes = compressAndWriteImageToBytes ( image , formatName , quality ) ; } else { bytes = writeImageToBytes ( image , formatName ) ; } return bytes ; }
|
Write the image to bytes in the provided format and optional quality
|
3,661
|
public static byte [ ] writeImageToBytes ( BufferedImage image , String formatName ) throws IOException { ByteArrayOutputStream stream = new ByteArrayOutputStream ( ) ; ImageIO . write ( image , formatName , stream ) ; stream . flush ( ) ; byte [ ] bytes = stream . toByteArray ( ) ; stream . close ( ) ; return bytes ; }
|
Write the image to bytes in the provided format
|
3,662
|
public static byte [ ] compressAndWriteImageToBytes ( BufferedImage image , String formatName , float quality ) { byte [ ] bytes = null ; Iterator < ImageWriter > writers = ImageIO . getImageWritersByFormatName ( formatName ) ; if ( writers == null || ! writers . hasNext ( ) ) { throw new GeoPackageException ( "No Image Writer to compress format: " + formatName ) ; } ImageWriter writer = writers . next ( ) ; ImageWriteParam writeParam = writer . getDefaultWriteParam ( ) ; writeParam . setCompressionMode ( ImageWriteParam . MODE_EXPLICIT ) ; writeParam . setCompressionQuality ( quality ) ; ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; ImageOutputStream ios = null ; try { ios = ImageIO . createImageOutputStream ( baos ) ; writer . setOutput ( ios ) ; writer . write ( null , new IIOImage ( image , null , null ) , writeParam ) ; writer . dispose ( ) ; bytes = baos . toByteArray ( ) ; } catch ( IOException e ) { throw new GeoPackageException ( "Failed to compress image to format: " + formatName + ", with quality: " + quality , e ) ; } finally { closeQuietly ( ios ) ; closeQuietly ( baos ) ; } return bytes ; }
|
Compress and write the image to bytes in the provided format and quality
|
3,663
|
public IconRow queryForRow ( StyleMappingRow styleMappingRow ) { IconRow iconRow = null ; UserCustomRow userCustomRow = queryForIdRow ( styleMappingRow . getRelatedId ( ) ) ; if ( userCustomRow != null ) { iconRow = getRow ( userCustomRow ) ; } return iconRow ; }
|
Query for the icon row from a style mapping row
|
3,664
|
public void setScale ( float scale ) { this . scale = scale ; linePaint . setStrokeWidth ( scale * lineStrokeWidth ) ; polygonPaint . setStrokeWidth ( scale * polygonStrokeWidth ) ; featurePaintCache . clear ( ) ; }
|
Set the scale
|
3,665
|
public byte [ ] drawTileBytes ( int x , int y , int zoom ) { BufferedImage image = drawTile ( x , y , zoom ) ; byte [ ] tileData = null ; if ( image != null ) { try { tileData = ImageUtils . writeImageToBytes ( image , compressFormat ) ; } catch ( IOException e ) { LOGGER . log ( Level . SEVERE , "Failed to create tile. x: " + x + ", y: " + y + ", zoom: " + zoom , e ) ; } } return tileData ; }
|
Draw the tile and get the bytes from the x y and zoom level
|
3,666
|
public BufferedImage drawTile ( int x , int y , int zoom ) { BufferedImage image ; if ( isIndexQuery ( ) ) { image = drawTileQueryIndex ( x , y , zoom ) ; } else { image = drawTileQueryAll ( x , y , zoom ) ; } return image ; }
|
Draw a tile image from the x y and zoom level
|
3,667
|
public BufferedImage drawTileQueryIndex ( int x , int y , int zoom ) { BoundingBox webMercatorBoundingBox = TileBoundingBoxUtils . getWebMercatorBoundingBox ( x , y , zoom ) ; BufferedImage image = null ; long tileCount = queryIndexedFeaturesCount ( webMercatorBoundingBox ) ; if ( tileCount > 0 ) { CloseableIterator < GeometryIndex > results = queryIndexedFeatures ( webMercatorBoundingBox ) ; try { if ( maxFeaturesPerTile == null || tileCount <= maxFeaturesPerTile . longValue ( ) ) { image = drawTile ( zoom , webMercatorBoundingBox , results ) ; } else if ( maxFeaturesTileDraw != null ) { image = maxFeaturesTileDraw . drawTile ( tileWidth , tileHeight , tileCount , results ) ; } } finally { try { results . close ( ) ; } catch ( IOException e ) { LOGGER . log ( Level . WARNING , "Failed to close result set for query on x: " + x + ", y: " + y + ", zoom: " + zoom , e ) ; } } } return image ; }
|
Draw a tile image from the x y and zoom level by querying features in the tile location
|
3,668
|
public long queryIndexedFeaturesCount ( BoundingBox webMercatorBoundingBox ) { BoundingBox expandedQueryBoundingBox = expandBoundingBox ( webMercatorBoundingBox ) ; long count = featureIndex . count ( expandedQueryBoundingBox , WEB_MERCATOR_PROJECTION ) ; return count ; }
|
Query for feature result count in the bounding box
|
3,669
|
public CloseableIterator < GeometryIndex > queryIndexedFeatures ( int x , int y , int zoom ) { BoundingBox webMercatorBoundingBox = TileBoundingBoxUtils . getWebMercatorBoundingBox ( x , y , zoom ) ; return queryIndexedFeatures ( webMercatorBoundingBox ) ; }
|
Query for feature results in the x y and zoom
|
3,670
|
public CloseableIterator < GeometryIndex > queryIndexedFeatures ( BoundingBox webMercatorBoundingBox ) { BoundingBox expandedQueryBoundingBox = expandBoundingBox ( webMercatorBoundingBox ) ; CloseableIterator < GeometryIndex > results = featureIndex . query ( expandedQueryBoundingBox , WEB_MERCATOR_PROJECTION ) ; return results ; }
|
Query for feature results in the bounding box
|
3,671
|
public BufferedImage drawTileQueryAll ( int x , int y , int zoom ) { BoundingBox boundingBox = TileBoundingBoxUtils . getWebMercatorBoundingBox ( x , y , zoom ) ; BufferedImage image = null ; FeatureResultSet resultSet = featureDao . queryForAll ( ) ; try { int totalCount = resultSet . getCount ( ) ; if ( totalCount > 0 ) { if ( maxFeaturesPerTile == null || totalCount <= maxFeaturesPerTile ) { image = drawTile ( zoom , boundingBox , resultSet ) ; } else if ( maxFeaturesTileDraw != null ) { image = maxFeaturesTileDraw . drawUnindexedTile ( tileWidth , tileHeight , totalCount , resultSet ) ; } } } finally { resultSet . close ( ) ; } return image ; }
|
Draw a tile image from the x y and zoom level by querying all features . This could be very slow if there are a lot of features
|
3,672
|
protected Graphics2D getGraphics ( BufferedImage image ) { Graphics2D graphics = image . createGraphics ( ) ; graphics . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_ON ) ; return graphics ; }
|
Get a graphics for the image
|
3,673
|
private Paint getStylePaint ( StyleRow style , FeatureDrawType drawType ) { Paint paint = featurePaintCache . getPaint ( style , drawType ) ; if ( paint == null ) { mil . nga . geopackage . style . Color color = null ; Float strokeWidth = null ; switch ( drawType ) { case CIRCLE : color = style . getColorOrDefault ( ) ; break ; case STROKE : color = style . getColorOrDefault ( ) ; strokeWidth = this . scale * ( float ) style . getWidthOrDefault ( ) ; break ; case FILL : color = style . getFillColor ( ) ; strokeWidth = this . scale * ( float ) style . getWidthOrDefault ( ) ; break ; default : throw new GeoPackageException ( "Unsupported Draw Type: " + drawType ) ; } Paint stylePaint = new Paint ( ) ; stylePaint . setColor ( new Color ( color . getColorWithAlpha ( ) , true ) ) ; if ( strokeWidth != null ) { stylePaint . setStrokeWidth ( strokeWidth ) ; } synchronized ( featurePaintCache ) { paint = featurePaintCache . getPaint ( style , drawType ) ; if ( paint == null ) { featurePaintCache . setPaint ( style , drawType , stylePaint ) ; paint = stylePaint ; } } } return paint ; }
|
Get the style paint from cache or create and cache it
|
3,674
|
protected boolean isTransparent ( BufferedImage image ) { boolean transparent = false ; if ( image != null ) { WritableRaster raster = image . getAlphaRaster ( ) ; if ( raster != null ) { transparent = true ; done : for ( int x = 0 ; x < image . getWidth ( ) ; x ++ ) { for ( int y = 0 ; y < image . getHeight ( ) ; y ++ ) { if ( raster . getSample ( x , y , 0 ) > 0 ) { transparent = false ; break done ; } } } } } return transparent ; }
|
Determine if the image is transparent
|
3,675
|
public ContentValues toContentValues ( ) { ContentValues contentValues = new ContentValues ( ) ; for ( TColumn column : table . getColumns ( ) ) { if ( ! column . isPrimaryKey ( ) ) { Object value = values [ column . getIndex ( ) ] ; String columnName = column . getName ( ) ; if ( value == null ) { contentValues . putNull ( columnName ) ; } else { columnToContentValue ( contentValues , column , value ) ; } } } return contentValues ; }
|
Convert the row to content values
|
3,676
|
protected void columnToContentValue ( ContentValues contentValues , TColumn column , Object value ) { String columnName = column . getName ( ) ; if ( value instanceof Number ) { if ( value instanceof Byte ) { validateValue ( column , value , Byte . class , Short . class , Integer . class , Long . class ) ; contentValues . put ( columnName , ( Byte ) value ) ; } else if ( value instanceof Short ) { validateValue ( column , value , Short . class , Integer . class , Long . class ) ; contentValues . put ( columnName , ( Short ) value ) ; } else if ( value instanceof Integer ) { validateValue ( column , value , Integer . class , Long . class ) ; contentValues . put ( columnName , ( Integer ) value ) ; } else if ( value instanceof Long ) { validateValue ( column , value , Long . class , Double . class ) ; contentValues . put ( columnName , ( Long ) value ) ; } else if ( value instanceof Float ) { validateValue ( column , value , Float . class ) ; contentValues . put ( columnName , ( Float ) value ) ; } else if ( value instanceof Double ) { validateValue ( column , value , Double . class ) ; contentValues . put ( columnName , ( Double ) value ) ; } else { throw new GeoPackageException ( "Unsupported Number type: " + value . getClass ( ) . getSimpleName ( ) ) ; } } else if ( value instanceof String ) { validateValue ( column , value , String . class ) ; String stringValue = ( String ) value ; if ( column . getMax ( ) != null && stringValue . length ( ) > column . getMax ( ) ) { throw new GeoPackageException ( "String is larger than the column max. Size: " + stringValue . length ( ) + ", Max: " + column . getMax ( ) + ", Column: " + columnName ) ; } contentValues . put ( columnName , stringValue ) ; } else if ( value instanceof byte [ ] ) { validateValue ( column , value , byte [ ] . class ) ; byte [ ] byteValue = ( byte [ ] ) value ; if ( column . getMax ( ) != null && byteValue . length > column . getMax ( ) ) { throw new GeoPackageException ( "Byte array is larger than the column max. Size: " + byteValue . length + ", Max: " + column . getMax ( ) + ", Column: " + columnName ) ; } contentValues . put ( columnName , byteValue ) ; } }
|
Map the column to the content values
|
3,677
|
public UserCustomResultSet queryByIds ( long baseId , long relatedId ) { return query ( buildWhereIds ( baseId , relatedId ) , buildWhereIdsArgs ( baseId , relatedId ) ) ; }
|
Query by both base id and related id
|
3,678
|
public boolean isIndexed ( FeatureIndexType type ) { boolean indexed = false ; if ( type == null ) { indexed = isIndexed ( ) ; } else { switch ( type ) { case GEOPACKAGE : indexed = featureTableIndex . isIndexed ( ) ; break ; case RTREE : indexed = rTreeIndexTableDao . has ( ) ; break ; default : throw new GeoPackageException ( "Unsupported FeatureIndexType: " + type ) ; } } return indexed ; }
|
Is the feature table indexed in the provided type location
|
3,679
|
public FeatureIndexResults query ( ) { FeatureIndexResults results = null ; switch ( getIndexedType ( ) ) { case GEOPACKAGE : long count = featureTableIndex . count ( ) ; CloseableIterator < GeometryIndex > geometryIndices = featureTableIndex . query ( ) ; results = new FeatureIndexGeoPackageResults ( featureTableIndex , count , geometryIndices ) ; break ; case RTREE : UserCustomResultSet resultSet = rTreeIndexTableDao . queryForAll ( ) ; results = new FeatureIndexRTreeResults ( rTreeIndexTableDao , resultSet ) ; break ; default : FeatureResultSet featureResultSet = featureDao . queryForAll ( ) ; results = new FeatureIndexFeatureResults ( featureResultSet ) ; } return results ; }
|
Query for all feature index results
|
3,680
|
public long count ( BoundingBox boundingBox ) { long count = 0 ; switch ( getIndexedType ( ) ) { case GEOPACKAGE : count = featureTableIndex . count ( boundingBox ) ; break ; case RTREE : count = rTreeIndexTableDao . count ( boundingBox ) ; break ; default : count = manualFeatureQuery . count ( boundingBox ) ; } return count ; }
|
Query for feature index count within the bounding box projected correctly
|
3,681
|
public FeatureIndexResults query ( GeometryEnvelope envelope ) { FeatureIndexResults results = null ; switch ( getIndexedType ( ) ) { case GEOPACKAGE : long count = featureTableIndex . count ( envelope ) ; CloseableIterator < GeometryIndex > geometryIndices = featureTableIndex . query ( envelope ) ; results = new FeatureIndexGeoPackageResults ( featureTableIndex , count , geometryIndices ) ; break ; case RTREE : UserCustomResultSet resultSet = rTreeIndexTableDao . query ( envelope ) ; results = new FeatureIndexRTreeResults ( rTreeIndexTableDao , resultSet ) ; break ; default : results = manualFeatureQuery . query ( envelope ) ; } return results ; }
|
Query for feature index results within the Geometry Envelope
|
3,682
|
public long count ( GeometryEnvelope envelope ) { long count = 0 ; switch ( getIndexedType ( ) ) { case GEOPACKAGE : count = featureTableIndex . count ( envelope ) ; break ; case RTREE : count = rTreeIndexTableDao . count ( envelope ) ; break ; default : count = manualFeatureQuery . count ( envelope ) ; } return count ; }
|
Query for feature index count within the Geometry Envelope
|
3,683
|
public Integer getZoomLevelMax ( int zoomLevel ) { Integer zoomMax = zoomLevelMax . get ( zoomLevel ) ; if ( zoomMax == null ) { zoomMax = 0 ; } return zoomMax ; }
|
Get the max at the zoom level
|
3,684
|
public int getZoomLevelProgress ( int zoomLevel ) { Integer zoomProgress = zoomLevelProgress . get ( zoomLevel ) ; if ( zoomProgress == null ) { zoomProgress = 0 ; } return zoomProgress ; }
|
Get the total progress at the zoom level
|
3,685
|
public BufferedImage createImage ( ) { BufferedImage image = null ; Graphics2D graphics = null ; for ( int layer = 0 ; layer < 4 ; layer ++ ) { BufferedImage layerImage = layeredImage [ layer ] ; if ( layerImage != null ) { if ( image == null ) { image = layerImage ; graphics = layeredGraphics [ layer ] ; } else { graphics . drawImage ( layerImage , 0 , 0 , null ) ; layeredGraphics [ layer ] . dispose ( ) ; layerImage . flush ( ) ; } layeredImage [ layer ] = null ; layeredGraphics [ layer ] = null ; } } if ( graphics != null ) { graphics . dispose ( ) ; } return image ; }
|
Create the final image from the layers resets the layers
|
3,686
|
public void dispose ( ) { for ( int layer = 0 ; layer < 4 ; layer ++ ) { Graphics2D graphics = layeredGraphics [ layer ] ; if ( graphics != null ) { graphics . dispose ( ) ; layeredGraphics [ layer ] = null ; } BufferedImage image = layeredImage [ layer ] ; if ( image != null ) { image . flush ( ) ; layeredImage [ layer ] = null ; } } }
|
Dispose of the layered graphics and images
|
3,687
|
private BufferedImage getImage ( int layer ) { BufferedImage image = layeredImage [ layer ] ; if ( image == null ) { createImageAndGraphics ( layer ) ; image = layeredImage [ layer ] ; } return image ; }
|
Get the bitmap for the layer index
|
3,688
|
private Graphics2D getGraphics ( int layer ) { Graphics2D graphics = layeredGraphics [ layer ] ; if ( graphics == null ) { createImageAndGraphics ( layer ) ; graphics = layeredGraphics [ layer ] ; } return graphics ; }
|
Get the graphics for the layer index
|
3,689
|
private void createImageAndGraphics ( int layer ) { layeredImage [ layer ] = new BufferedImage ( tileWidth , tileHeight , BufferedImage . TYPE_INT_ARGB ) ; layeredGraphics [ layer ] = layeredImage [ layer ] . createGraphics ( ) ; layeredGraphics [ layer ] . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_ON ) ; }
|
Create a new empty Image and Graphics
|
3,690
|
public void resize ( int maxSize ) { this . maxSize = maxSize ; if ( cache . size ( ) > maxSize ) { int count = 0 ; Iterator < Long > rowIds = cache . keySet ( ) . iterator ( ) ; while ( rowIds . hasNext ( ) ) { rowIds . next ( ) ; if ( ++ count > maxSize ) { rowIds . remove ( ) ; } } } }
|
Resize the cache
|
3,691
|
private CoverageDataTileMatrixResults getResults ( BoundingBox requestProjectedBoundingBox , TileMatrix tileMatrix , int overlappingPixels ) { CoverageDataTileMatrixResults results = null ; BoundingBox paddedBoundingBox = padBoundingBox ( tileMatrix , requestProjectedBoundingBox , overlappingPixels ) ; TileResultSet tileResults = retrieveSortedTileResults ( paddedBoundingBox , tileMatrix ) ; if ( tileResults != null ) { if ( tileResults . getCount ( ) > 0 ) { results = new CoverageDataTileMatrixResults ( tileMatrix , tileResults ) ; } else { tileResults . close ( ) ; } } return results ; }
|
Get the coverage data tile results for a specified tile matrix
|
3,692
|
private TileResultSet retrieveSortedTileResults ( BoundingBox projectedRequestBoundingBox , TileMatrix tileMatrix ) { TileResultSet tileResults = null ; if ( tileMatrix != null ) { TileGrid tileGrid = TileBoundingBoxUtils . getTileGrid ( coverageBoundingBox , tileMatrix . getMatrixWidth ( ) , tileMatrix . getMatrixHeight ( ) , projectedRequestBoundingBox ) ; tileResults = tileDao . queryByTileGrid ( tileGrid , tileMatrix . getZoomLevel ( ) , TileTable . COLUMN_TILE_ROW + "," + TileTable . COLUMN_TILE_COLUMN ) ; } return tileResults ; }
|
Get the tile row results of coverage data tiles needed to create the requested bounding box coverage data sorted by row and then column
|
3,693
|
public List < MediaRow > getRows ( List < Long > ids ) { List < MediaRow > mediaRows = new ArrayList < > ( ) ; for ( long id : ids ) { UserCustomRow userCustomRow = queryForIdRow ( id ) ; if ( userCustomRow != null ) { mediaRows . add ( getRow ( userCustomRow ) ) ; } } return mediaRows ; }
|
Get the media rows that exist with the provided ids
|
3,694
|
private static Color getColor ( String colorString ) { Color color = null ; String [ ] colorParts = colorString . split ( "," ) ; try { switch ( colorParts . length ) { case 1 : Field field = Color . class . getField ( colorString ) ; color = ( Color ) field . get ( null ) ; break ; case 3 : color = new Color ( Integer . parseInt ( colorParts [ 0 ] ) , Integer . parseInt ( colorParts [ 1 ] ) , Integer . parseInt ( colorParts [ 2 ] ) ) ; break ; case 4 : color = new Color ( Integer . parseInt ( colorParts [ 0 ] ) , Integer . parseInt ( colorParts [ 1 ] ) , Integer . parseInt ( colorParts [ 2 ] ) , Integer . parseInt ( colorParts [ 3 ] ) ) ; break ; default : throw new GeoPackageException ( "Unexpected color arguments: " + colorParts . length + ", color: " + colorString ) ; } } catch ( Exception e ) { throw new GeoPackageException ( "Invalid color: " + colorString + ", Allowable Formats: colorName | r,g,b | r,g,b,a" , e ) ; } return color ; }
|
Get the color from the string
|
3,695
|
private static String colorString ( Color color ) { return color . getRed ( ) + "," + color . getGreen ( ) + "," + color . getBlue ( ) + "," + color . getAlpha ( ) ; }
|
Get a r g b a color string from the color
|
3,696
|
public Integer getIntegerProperty ( String property , boolean required ) { Integer integerValue = null ; String value = getProperty ( property , required ) ; if ( value != null ) { try { integerValue = Integer . valueOf ( value ) ; } catch ( NumberFormatException e ) { throw new GeoPackageException ( GEOPACKAGE_PROPERTIES_FILE + " property file property '" + property + "' must be an integer" ) ; } } return integerValue ; }
|
Get the Integer property
|
3,697
|
public Double getDoubleProperty ( String property , boolean required ) { Double doubleValue = null ; String value = getProperty ( property , required ) ; if ( value != null ) { try { doubleValue = Double . valueOf ( value ) ; } catch ( NumberFormatException e ) { throw new GeoPackageException ( GEOPACKAGE_PROPERTIES_FILE + " property file property '" + property + "' must be a double" ) ; } } return doubleValue ; }
|
Get the Double property
|
3,698
|
public String getProperty ( String property , boolean required ) { if ( properties == null ) { throw new GeoPackageException ( "Properties must be loaded before reading" ) ; } String value = properties . getProperty ( property ) ; if ( value == null && required ) { throw new GeoPackageException ( GEOPACKAGE_PROPERTIES_FILE + " property file missing required property: " + property ) ; } return value ; }
|
Get the String property
|
3,699
|
public void writeFile ( TileDao tileDao ) { try { PrintWriter pw = new PrintWriter ( propertiesFile ) ; TileMatrixSet tileMatrixSet = tileDao . getTileMatrixSet ( ) ; pw . println ( GEOPACKAGE_PROPERTIES_EPSG + "=" + tileMatrixSet . getSrs ( ) . getOrganizationCoordsysId ( ) ) ; pw . println ( GEOPACKAGE_PROPERTIES_MIN_X + "=" + tileMatrixSet . getMinX ( ) ) ; pw . println ( GEOPACKAGE_PROPERTIES_MAX_X + "=" + tileMatrixSet . getMaxX ( ) ) ; pw . println ( GEOPACKAGE_PROPERTIES_MIN_Y + "=" + tileMatrixSet . getMinY ( ) ) ; pw . println ( GEOPACKAGE_PROPERTIES_MAX_Y + "=" + tileMatrixSet . getMaxY ( ) ) ; for ( TileMatrix tileMatrix : tileDao . getTileMatrices ( ) ) { long zoom = tileMatrix . getZoomLevel ( ) ; pw . println ( getMatrixWidthProperty ( zoom ) + "=" + tileMatrix . getMatrixWidth ( ) ) ; pw . println ( getMatrixHeightProperty ( zoom ) + "=" + tileMatrix . getMatrixHeight ( ) ) ; } pw . close ( ) ; } catch ( FileNotFoundException e ) { throw new GeoPackageException ( "GeoPackage file format properties file could not be created: " + propertiesFile , e ) ; } }
|
Write the properties file using the tile dao
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.