idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
146,000
private int findAvailablePortNumber ( Integer portNumberStartingPoint , List < Integer > reservedPorts ) { assert portNumberStartingPoint != null ; int candidate = portNumberStartingPoint ; while ( reservedPorts . contains ( candidate ) ) { candidate ++ ; } return candidate ; }
Returns the first number available starting at portNumberStartingPoint that s not already in the reservedPorts list .
58
22
146,001
public void populateFromAttributes ( @ Nonnull final Template template , @ Nonnull final Map < String , Attribute > attributes , @ Nonnull final PObject requestJsonAttributes ) { if ( requestJsonAttributes . has ( JSON_REQUEST_HEADERS ) && requestJsonAttributes . getObject ( JSON_REQUEST_HEADERS ) . has ( JSON_REQUEST_HEADERS ) && ! attributes . containsKey ( JSON_REQUEST_HEADERS ) ) { attributes . put ( JSON_REQUEST_HEADERS , new HttpRequestHeadersAttribute ( ) ) ; } for ( Map . Entry < String , Attribute > attribute : attributes . entrySet ( ) ) { try { put ( attribute . getKey ( ) , attribute . getValue ( ) . getValue ( template , attribute . getKey ( ) , requestJsonAttributes ) ) ; } catch ( ObjectMissingException | IllegalArgumentException e ) { throw e ; } catch ( Throwable e ) { String templateName = "unknown" ; for ( Map . Entry < String , Template > entry : template . getConfiguration ( ) . getTemplates ( ) . entrySet ( ) ) { if ( entry . getValue ( ) == template ) { templateName = entry . getKey ( ) ; break ; } } String defaults = "" ; if ( attribute instanceof ReflectiveAttribute < ? > ) { ReflectiveAttribute < ? > reflectiveAttribute = ( ReflectiveAttribute < ? > ) attribute ; defaults = "\n\n The attribute defaults are: " + reflectiveAttribute . getDefaultValue ( ) ; } String errorMsg = "An error occurred when creating a value from the '" + attribute . getKey ( ) + "' attribute for the '" + templateName + "' template.\n\nThe JSON is: \n" + requestJsonAttributes + defaults + "\n" + e . toString ( ) ; throw new AttributeParsingException ( errorMsg , e ) ; } } if ( template . getConfiguration ( ) . isThrowErrorOnExtraParameters ( ) ) { final List < String > extraProperties = new ArrayList <> ( ) ; for ( Iterator < String > it = requestJsonAttributes . keys ( ) ; it . hasNext ( ) ; ) { final String attributeName = it . next ( ) ; if ( ! attributes . containsKey ( attributeName ) ) { extraProperties . add ( attributeName ) ; } } if ( ! extraProperties . isEmpty ( ) ) { throw new ExtraPropertyException ( "Extra properties found in the request attributes" , extraProperties , attributes . keySet ( ) ) ; } } }
Process the requestJsonAttributes using the attributes and the MapfishParser and add all resulting values to this values object .
559
24
146,002
public void addRequiredValues ( @ Nonnull final Values sourceValues ) { Object taskDirectory = sourceValues . getObject ( TASK_DIRECTORY_KEY , Object . class ) ; MfClientHttpRequestFactoryProvider requestFactoryProvider = sourceValues . getObject ( CLIENT_HTTP_REQUEST_FACTORY_KEY , MfClientHttpRequestFactoryProvider . class ) ; Template template = sourceValues . getObject ( TEMPLATE_KEY , Template . class ) ; PDFConfig pdfConfig = sourceValues . getObject ( PDF_CONFIG_KEY , PDFConfig . class ) ; String subReportDir = sourceValues . getString ( SUBREPORT_DIR_KEY ) ; this . values . put ( TASK_DIRECTORY_KEY , taskDirectory ) ; this . values . put ( CLIENT_HTTP_REQUEST_FACTORY_KEY , requestFactoryProvider ) ; this . values . put ( TEMPLATE_KEY , template ) ; this . values . put ( PDF_CONFIG_KEY , pdfConfig ) ; this . values . put ( SUBREPORT_DIR_KEY , subReportDir ) ; this . values . put ( VALUES_KEY , this ) ; this . values . put ( JOB_ID_KEY , sourceValues . getString ( JOB_ID_KEY ) ) ; this . values . put ( LOCALE_KEY , sourceValues . getObject ( LOCALE_KEY , Locale . class ) ) ; }
Add the elements that all values objects require from the provided values object .
314
14
146,003
public void put ( final String key , final Object value ) { if ( TASK_DIRECTORY_KEY . equals ( key ) && this . values . keySet ( ) . contains ( TASK_DIRECTORY_KEY ) ) { // ensure that no one overwrites the task directory throw new IllegalArgumentException ( "Invalid key: " + key ) ; } if ( value == null ) { throw new IllegalArgumentException ( "A null value was attempted to be put into the values object under key: " + key ) ; } this . values . put ( key , value ) ; }
Put a new value in map .
128
7
146,004
public < V > V getObject ( final String key , final Class < V > type ) { final Object obj = this . values . get ( key ) ; return type . cast ( obj ) ; }
Get a value as a string .
42
7
146,005
@ Nullable public Boolean getBoolean ( @ Nonnull final String key ) { return ( Boolean ) this . values . get ( key ) ; }
Get a boolean value from the values or null .
31
10
146,006
@ SuppressWarnings ( "unchecked" ) public < T > Map < String , T > find ( final Class < T > valueTypeToFind ) { return ( Map < String , T > ) this . values . entrySet ( ) . stream ( ) . filter ( input -> valueTypeToFind . isInstance ( input . getValue ( ) ) ) . collect ( Collectors . toMap ( Map . Entry :: getKey , Map . Entry :: getValue ) ) ; }
Find all the values of the requested type .
103
9
146,007
@ Override public ConfigurableRequest createRequest ( @ Nonnull final URI uri , @ Nonnull final HttpMethod httpMethod ) throws IOException { HttpRequestBase httpRequest = ( HttpRequestBase ) createHttpUriRequest ( httpMethod , uri ) ; return new Request ( getHttpClient ( ) , httpRequest , createHttpContext ( httpMethod , uri ) ) ; }
allow extension only for testing
84
5
146,008
public final PJsonObject toJSON ( ) { try { JSONObject json = new JSONObject ( ) ; for ( String key : this . obj . keySet ( ) ) { Object opt = opt ( key ) ; if ( opt instanceof PYamlObject ) { opt = ( ( PYamlObject ) opt ) . toJSON ( ) . getInternalObj ( ) ; } else if ( opt instanceof PYamlArray ) { opt = ( ( PYamlArray ) opt ) . toJSON ( ) . getInternalArray ( ) ; } json . put ( key , opt ) ; } return new PJsonObject ( json , this . getContextName ( ) ) ; } catch ( Throwable e ) { throw ExceptionUtils . getRuntimeException ( e ) ; } }
Convert this object to a json object .
165
9
146,009
public static MatchInfo fromUri ( final URI uri , final HttpMethod method ) { int newPort = uri . getPort ( ) ; if ( newPort < 0 ) { try { newPort = uri . toURL ( ) . getDefaultPort ( ) ; } catch ( MalformedURLException | IllegalArgumentException e ) { newPort = ANY_PORT ; } } return new MatchInfo ( uri . getScheme ( ) , uri . getHost ( ) , newPort , uri . getPath ( ) , uri . getQuery ( ) , uri . getFragment ( ) , ANY_REALM , method ) ; }
Create an info object from a uri and the http method object .
145
14
146,010
@ SuppressWarnings ( "StringEquality" ) public static MatchInfo fromAuthScope ( final AuthScope authscope ) { String newScheme = StringUtils . equals ( authscope . getScheme ( ) , AuthScope . ANY_SCHEME ) ? ANY_SCHEME : authscope . getScheme ( ) ; String newHost = StringUtils . equals ( authscope . getHost ( ) , AuthScope . ANY_HOST ) ? ANY_HOST : authscope . getHost ( ) ; int newPort = authscope . getPort ( ) == AuthScope . ANY_PORT ? ANY_PORT : authscope . getPort ( ) ; String newRealm = StringUtils . equals ( authscope . getRealm ( ) , AuthScope . ANY_REALM ) ? ANY_REALM : authscope . getRealm ( ) ; return new MatchInfo ( newScheme , newHost , newPort , ANY_PATH , ANY_QUERY , ANY_FRAGMENT , newRealm , ANY_METHOD ) ; }
Create an info object from an authscope object .
231
10
146,011
public Style createStyle ( final List < Rule > styleRules ) { final Rule [ ] rulesArray = styleRules . toArray ( new Rule [ 0 ] ) ; final FeatureTypeStyle featureTypeStyle = this . styleBuilder . createFeatureTypeStyle ( null , rulesArray ) ; final Style style = this . styleBuilder . createStyle ( ) ; style . featureTypeStyles ( ) . add ( featureTypeStyle ) ; return style ; }
Create a style from a list of rules .
92
9
146,012
@ VisibleForTesting @ Nullable protected LineSymbolizer createLineSymbolizer ( final PJsonObject styleJson ) { final Stroke stroke = createStroke ( styleJson , true ) ; if ( stroke == null ) { return null ; } else { return this . styleBuilder . createLineSymbolizer ( stroke ) ; } }
Add a line symbolizer definition to the rule .
75
10
146,013
@ Nullable @ VisibleForTesting protected PolygonSymbolizer createPolygonSymbolizer ( final PJsonObject styleJson ) { if ( this . allowNullSymbolizer && ! styleJson . has ( JSON_FILL_COLOR ) ) { return null ; } final PolygonSymbolizer symbolizer = this . styleBuilder . createPolygonSymbolizer ( ) ; symbolizer . setFill ( createFill ( styleJson ) ) ; symbolizer . setStroke ( createStroke ( styleJson , false ) ) ; return symbolizer ; }
Add a polygon symbolizer definition to the rule .
124
11
146,014
@ VisibleForTesting protected TextSymbolizer createTextSymbolizer ( final PJsonObject styleJson ) { final TextSymbolizer textSymbolizer = this . styleBuilder . createTextSymbolizer ( ) ; // make sure that labels are also rendered if a part of the text would be outside // the view context, see http://docs.geoserver.org/stable/en/user/styling/sld-reference/labeling // .html#partials textSymbolizer . getOptions ( ) . put ( "partials" , "true" ) ; if ( styleJson . has ( JSON_LABEL ) ) { final Expression label = parseExpression ( null , styleJson , JSON_LABEL , ( final String labelValue ) -> labelValue . replace ( "${" , "" ) . replace ( "}" , "" ) ) ; textSymbolizer . setLabel ( label ) ; } else { return null ; } textSymbolizer . setFont ( createFont ( textSymbolizer . getFont ( ) , styleJson ) ) ; if ( styleJson . has ( JSON_LABEL_ANCHOR_POINT_X ) || styleJson . has ( JSON_LABEL_ANCHOR_POINT_Y ) || styleJson . has ( JSON_LABEL_ALIGN ) || styleJson . has ( JSON_LABEL_X_OFFSET ) || styleJson . has ( JSON_LABEL_Y_OFFSET ) || styleJson . has ( JSON_LABEL_ROTATION ) || styleJson . has ( JSON_LABEL_PERPENDICULAR_OFFSET ) ) { textSymbolizer . setLabelPlacement ( createLabelPlacement ( styleJson ) ) ; } if ( ! StringUtils . isEmpty ( styleJson . optString ( JSON_HALO_RADIUS ) ) || ! StringUtils . isEmpty ( styleJson . optString ( JSON_HALO_COLOR ) ) || ! StringUtils . isEmpty ( styleJson . optString ( JSON_HALO_OPACITY ) ) || ! StringUtils . isEmpty ( styleJson . optString ( JSON_LABEL_OUTLINE_WIDTH ) ) || ! StringUtils . isEmpty ( styleJson . optString ( JSON_LABEL_OUTLINE_COLOR ) ) ) { textSymbolizer . setHalo ( createHalo ( styleJson ) ) ; } if ( ! StringUtils . isEmpty ( styleJson . optString ( JSON_FONT_COLOR ) ) || ! StringUtils . isEmpty ( styleJson . optString ( JSON_FONT_OPACITY ) ) ) { textSymbolizer . setFill ( addFill ( styleJson . optString ( JSON_FONT_COLOR , "black" ) , styleJson . optString ( JSON_FONT_OPACITY , "1.0" ) ) ) ; } this . addVendorOptions ( JSON_LABEL_ALLOW_OVERRUNS , styleJson , textSymbolizer ) ; this . addVendorOptions ( JSON_LABEL_AUTO_WRAP , styleJson , textSymbolizer ) ; this . addVendorOptions ( JSON_LABEL_CONFLICT_RESOLUTION , styleJson , textSymbolizer ) ; this . addVendorOptions ( JSON_LABEL_FOLLOW_LINE , styleJson , textSymbolizer ) ; this . addVendorOptions ( JSON_LABEL_GOODNESS_OF_FIT , styleJson , textSymbolizer ) ; this . addVendorOptions ( JSON_LABEL_GROUP , styleJson , textSymbolizer ) ; this . addVendorOptions ( JSON_LABEL_MAX_DISPLACEMENT , styleJson , textSymbolizer ) ; this . addVendorOptions ( JSON_LABEL_SPACE_AROUND , styleJson , textSymbolizer ) ; return textSymbolizer ; }
Add a text symbolizer definition to the rule .
886
10
146,015
public static void configureProtocolHandler ( ) { final String pkgs = System . getProperty ( "java.protocol.handler.pkgs" ) ; String newValue = "org.mapfish.print.url" ; if ( pkgs != null && ! pkgs . contains ( newValue ) ) { newValue = newValue + "|" + pkgs ; } else if ( pkgs != null ) { newValue = pkgs ; } System . setProperty ( "java.protocol.handler.pkgs" , newValue ) ; }
Adds the parent package to the java . protocol . handler . pkgs system property .
124
18
146,016
protected final StyleSupplier < FeatureSource > createStyleFunction ( final Template template , final String styleString ) { return new StyleSupplier < FeatureSource > ( ) { @ Override public Style load ( final MfClientHttpRequestFactory requestFactory , final FeatureSource featureSource ) { if ( featureSource == null ) { throw new IllegalArgumentException ( "Feature source cannot be null" ) ; } final String geomType = featureSource . getSchema ( ) == null ? Geometry . class . getSimpleName ( ) . toLowerCase ( ) : featureSource . getSchema ( ) . getGeometryDescriptor ( ) . getType ( ) . getBinding ( ) . getSimpleName ( ) ; final String styleRef = styleString != null ? styleString : geomType ; final StyleParser styleParser = AbstractFeatureSourceLayerPlugin . this . parser ; return OptionalUtils . or ( ( ) -> template . getStyle ( styleRef ) , ( ) -> styleParser . loadStyle ( template . getConfiguration ( ) , requestFactory , styleRef ) ) . orElseGet ( ( ) -> template . getConfiguration ( ) . getDefaultStyle ( geomType ) ) ; } } ; }
Create a function that will create the style on demand . This is called later in a separate thread so any blocking calls will not block the parsing of the layer attributes .
257
33
146,017
public static URI makeWmsGetLayerRequest ( final WmsLayerParam wmsLayerParam , final URI commonURI , final Dimension imageSize , final double dpi , final double angle , final ReferencedEnvelope bounds ) throws FactoryException , URISyntaxException , IOException { if ( commonURI == null || commonURI . getAuthority ( ) == null ) { throw new RuntimeException ( "Invalid WMS URI: " + commonURI ) ; } String [ ] authority = commonURI . getAuthority ( ) . split ( ":" ) ; URL url ; if ( authority . length == 2 ) { url = new URL ( commonURI . getScheme ( ) , authority [ 0 ] , Integer . parseInt ( authority [ 1 ] ) , commonURI . getPath ( ) ) ; } else { url = new URL ( commonURI . getScheme ( ) , authority [ 0 ] , commonURI . getPath ( ) ) ; } final GetMapRequest getMapRequest = WmsVersion . lookup ( wmsLayerParam . version ) . getGetMapRequest ( url ) ; getMapRequest . setBBox ( bounds ) ; getMapRequest . setDimensions ( imageSize . width , imageSize . height ) ; getMapRequest . setFormat ( wmsLayerParam . imageFormat ) ; getMapRequest . setSRS ( CRS . lookupIdentifier ( bounds . getCoordinateReferenceSystem ( ) , false ) ) ; for ( int i = wmsLayerParam . layers . length - 1 ; i > - 1 ; i -- ) { String layer = wmsLayerParam . layers [ i ] ; String style = "" ; if ( wmsLayerParam . styles != null ) { style = wmsLayerParam . styles [ i ] ; } getMapRequest . addLayer ( layer , style ) ; } final URI getMapUri = getMapRequest . getFinalURL ( ) . toURI ( ) ; Multimap < String , String > extraParams = HashMultimap . create ( ) ; if ( commonURI . getQuery ( ) != null ) { for ( NameValuePair pair : URLEncodedUtils . parse ( commonURI , Charset . forName ( "UTF-8" ) ) ) { extraParams . put ( pair . getName ( ) , pair . getValue ( ) ) ; } } extraParams . putAll ( wmsLayerParam . getMergeableParams ( ) ) ; extraParams . putAll ( wmsLayerParam . getCustomParams ( ) ) ; if ( wmsLayerParam . serverType != null ) { addDpiParam ( extraParams , ( int ) Math . round ( dpi ) , wmsLayerParam . serverType ) ; if ( wmsLayerParam . useNativeAngle && angle != 0.0 ) { addAngleParam ( extraParams , angle , wmsLayerParam . serverType ) ; } } return URIUtils . addParams ( getMapUri , extraParams , Collections . emptySet ( ) ) ; }
Make a WMS getLayer request and return the image read from the server .
654
16
146,018
private static boolean isDpiSet ( final Multimap < String , String > extraParams ) { String searchKey = "FORMAT_OPTIONS" ; for ( String key : extraParams . keys ( ) ) { if ( key . equalsIgnoreCase ( searchKey ) ) { for ( String value : extraParams . get ( key ) ) { if ( value . toLowerCase ( ) . contains ( "dpi:" ) ) { return true ; } } } } return false ; }
Checks if the DPI value is already set for GeoServer .
108
14
146,019
private static void setDpiValue ( final Multimap < String , String > extraParams , final int dpi ) { String searchKey = "FORMAT_OPTIONS" ; for ( String key : extraParams . keys ( ) ) { if ( key . equalsIgnoreCase ( searchKey ) ) { Collection < String > values = extraParams . removeAll ( key ) ; List < String > newValues = new ArrayList <> ( ) ; for ( String value : values ) { if ( ! StringUtils . isEmpty ( value ) ) { value += ";dpi:" + Integer . toString ( dpi ) ; newValues . add ( value ) ; } } extraParams . putAll ( key , newValues ) ; return ; } } }
Set the DPI value for GeoServer if there are already FORMAT_OPTIONS .
166
19
146,020
public static Polygon calculateBounds ( final MapfishMapContext context ) { double rotation = context . getRootContext ( ) . getRotation ( ) ; ReferencedEnvelope env = context . getRootContext ( ) . toReferencedEnvelope ( ) ; Coordinate centre = env . centre ( ) ; AffineTransform rotateInstance = AffineTransform . getRotateInstance ( rotation , centre . x , centre . y ) ; double [ ] dstPts = new double [ 8 ] ; double [ ] srcPts = { env . getMinX ( ) , env . getMinY ( ) , env . getMinX ( ) , env . getMaxY ( ) , env . getMaxX ( ) , env . getMaxY ( ) , env . getMaxX ( ) , env . getMinY ( ) } ; rotateInstance . transform ( srcPts , 0 , dstPts , 0 , 4 ) ; return new GeometryFactory ( ) . createPolygon ( new Coordinate [ ] { new Coordinate ( dstPts [ 0 ] , dstPts [ 1 ] ) , new Coordinate ( dstPts [ 2 ] , dstPts [ 3 ] ) , new Coordinate ( dstPts [ 4 ] , dstPts [ 5 ] ) , new Coordinate ( dstPts [ 6 ] , dstPts [ 7 ] ) , new Coordinate ( dstPts [ 0 ] , dstPts [ 1 ] ) } ) ; }
Create a polygon that represents in world space the exact area that will be visible on the printed map .
317
21
146,021
public static SimpleFeatureType createGridFeatureType ( @ Nonnull final MapfishMapContext mapContext , @ Nonnull final Class < ? extends Geometry > geomClass ) { final SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder ( ) ; CoordinateReferenceSystem projection = mapContext . getBounds ( ) . getProjection ( ) ; typeBuilder . add ( Constants . Style . Grid . ATT_GEOM , geomClass , projection ) ; typeBuilder . setName ( Constants . Style . Grid . NAME_LINES ) ; return typeBuilder . buildFeatureType ( ) ; }
Create the grid feature type .
128
6
146,022
public static String createLabel ( final double value , final String unit , final GridLabelFormat format ) { final double zero = 0.000000001 ; if ( format != null ) { return format . format ( value , unit ) ; } else { if ( Math . abs ( value - Math . round ( value ) ) < zero ) { return String . format ( "%d %s" , Math . round ( value ) , unit ) ; } else if ( "m" . equals ( unit ) ) { // meter: no decimals return String . format ( "%1.0f %s" , value , unit ) ; } else if ( NonSI . DEGREE_ANGLE . toString ( ) . equals ( unit ) ) { // degree: by default 6 decimals return String . format ( "%1.6f %s" , value , unit ) ; } else { return String . format ( "%f %s" , value , unit ) ; } } }
Create the label for a grid line .
205
8
146,023
public static Object parsePrimitive ( final String fieldName , final PrimitiveAttribute < ? > pAtt , final PObject requestData ) { Class < ? > valueClass = pAtt . getValueClass ( ) ; Object value ; try { value = parseValue ( false , new String [ 0 ] , valueClass , fieldName , requestData ) ; } catch ( UnsupportedTypeException e ) { String type = e . type . getName ( ) ; if ( e . type . isArray ( ) ) { type = e . type . getComponentType ( ) . getName ( ) + "[]" ; } throw new RuntimeException ( "The type '" + type + "' is not a supported type when parsing json. " + "See documentation for supported types.\n\nUnsupported type found in attribute " + fieldName + "\n\nTo support more types add the type to " + "parseValue and parseArrayValue in this class and add a test to the test class" , e ) ; } pAtt . validateValue ( value ) ; return value ; }
Get the value of a primitive type from the request data .
226
12
146,024
@ Override protected URL getDefinitionsURL ( ) { try { URL url = CustomEPSGCodes . class . getResource ( CUSTOM_EPSG_CODES_FILE ) ; // quickly test url try ( InputStream stream = url . openStream ( ) ) { //noinspection ResultOfMethodCallIgnored stream . read ( ) ; } return url ; } catch ( Throwable e ) { throw new AssertionError ( "Unable to load /epsg.properties file from root of classpath." ) ; } }
Returns the URL to the property file that contains CRS definitions .
117
13
146,025
public synchronized void addMapStats ( final MapfishMapContext mapContext , final MapAttribute . MapAttributeValues mapValues ) { this . mapStats . add ( new MapStats ( mapContext , mapValues ) ) ; }
Add statistics about a created map .
46
7
146,026
public void addEmailStats ( final InternetAddress [ ] recipients , final boolean storageUsed ) { this . storageUsed = storageUsed ; for ( InternetAddress recipient : recipients ) { emailDests . add ( recipient . getAddress ( ) ) ; } }
Add statistics about sent emails .
52
6
146,027
public String calculateLabelUnit ( final CoordinateReferenceSystem mapCrs ) { String unit ; if ( this . labelProjection != null ) { unit = this . labelCRS . getCoordinateSystem ( ) . getAxis ( 0 ) . getUnit ( ) . toString ( ) ; } else { unit = mapCrs . getCoordinateSystem ( ) . getAxis ( 0 ) . getUnit ( ) . toString ( ) ; } return unit ; }
Determine which unit to use when creating grid labels .
100
12
146,028
public MathTransform calculateLabelTransform ( final CoordinateReferenceSystem mapCrs ) { MathTransform labelTransform ; if ( this . labelProjection != null ) { try { labelTransform = CRS . findMathTransform ( mapCrs , this . labelCRS , true ) ; } catch ( FactoryException e ) { throw new RuntimeException ( e ) ; } } else { labelTransform = IdentityTransform . create ( 2 ) ; } return labelTransform ; }
Determine which math transform to use when creating the coordinate of the label .
95
16
146,029
public static GridLabelFormat fromConfig ( final GridParam param ) { if ( param . labelFormat != null ) { return new GridLabelFormat . Simple ( param . labelFormat ) ; } else if ( param . valueFormat != null ) { return new GridLabelFormat . Detailed ( param . valueFormat , param . unitFormat , param . formatDecimalSeparator , param . formatGroupingSeparator ) ; } return null ; }
Create an instance from the given config .
93
8
146,030
@ Nullable public final Credentials toCredentials ( final AuthScope authscope ) { try { if ( ! matches ( MatchInfo . fromAuthScope ( authscope ) ) ) { return null ; } } catch ( UnknownHostException | MalformedURLException | SocketException e ) { throw new RuntimeException ( e ) ; } if ( this . username == null ) { return null ; } final String passwordString ; if ( this . password != null ) { passwordString = new String ( this . password ) ; } else { passwordString = null ; } return new UsernamePasswordCredentials ( this . username , passwordString ) ; }
Check if this applies to the provided authorization scope and return the credentials for that scope or null if it doesn t apply to the scope .
136
27
146,031
public final PJsonObject getJSONObject ( final int i ) { JSONObject val = this . array . optJSONObject ( i ) ; final String context = "[" + i + "]" ; if ( val == null ) { throw new ObjectMissingException ( this , context ) ; } return new PJsonObject ( this , val , context ) ; }
Get the element at the index as a json object .
74
11
146,032
public final PJsonArray getJSONArray ( final int i ) { JSONArray val = this . array . optJSONArray ( i ) ; final String context = "[" + i + "]" ; if ( val == null ) { throw new ObjectMissingException ( this , context ) ; } return new PJsonArray ( this , val , context ) ; }
Get the element at the index as a json array .
74
11
146,033
@ Override public final int getInt ( final int i ) { int val = this . array . optInt ( i , Integer . MIN_VALUE ) ; if ( val == Integer . MIN_VALUE ) { throw new ObjectMissingException ( this , "[" + i + "]" ) ; } return val ; }
Get the element at the index as an integer .
66
10
146,034
@ Override public final float getFloat ( final int i ) { double val = this . array . optDouble ( i , Double . MAX_VALUE ) ; if ( val == Double . MAX_VALUE ) { throw new ObjectMissingException ( this , "[" + i + "]" ) ; } return ( float ) val ; }
Get the element at the index as a float .
69
10
146,035
@ Override public final String getString ( final int i ) { String val = this . array . optString ( i , null ) ; if ( val == null ) { throw new ObjectMissingException ( this , "[" + i + "]" ) ; } return val ; }
Get the element at the index as a string .
58
10
146,036
@ Override public final boolean getBool ( final int i ) { try { return this . array . getBoolean ( i ) ; } catch ( JSONException e ) { throw new ObjectMissingException ( this , "[" + i + "]" ) ; } }
Get the element as a boolean .
56
7
146,037
@ Override public final String getString ( final String key ) { String result = optString ( key ) ; if ( result == null ) { throw new ObjectMissingException ( this , key ) ; } return result ; }
Get a property as a string or throw an exception .
46
11
146,038
@ Override public final String optString ( final String key , final String defaultValue ) { String result = optString ( key ) ; return result == null ? defaultValue : result ; }
Get a property as a string or defaultValue .
39
10
146,039
@ Override public final int getInt ( final String key ) { Integer result = optInt ( key ) ; if ( result == null ) { throw new ObjectMissingException ( this , key ) ; } return result ; }
Get a property as an int or throw an exception .
46
11
146,040
@ Override public final Integer optInt ( final String key , final Integer defaultValue ) { Integer result = optInt ( key ) ; return result == null ? defaultValue : result ; }
Get a property as an int or default value .
39
10
146,041
@ Override public final long getLong ( final String key ) { Long result = optLong ( key ) ; if ( result == null ) { throw new ObjectMissingException ( this , key ) ; } return result ; }
Get a property as an long or throw an exception .
46
11
146,042
@ Override public final long optLong ( final String key , final long defaultValue ) { Long result = optLong ( key ) ; return result == null ? defaultValue : result ; }
Get a property as an long or default value .
39
10
146,043
@ Override public final double getDouble ( final String key ) { Double result = optDouble ( key ) ; if ( result == null ) { throw new ObjectMissingException ( this , key ) ; } return result ; }
Get a property as a double or throw an exception .
46
11
146,044
@ Override public final Double optDouble ( final String key , final Double defaultValue ) { Double result = optDouble ( key ) ; return result == null ? defaultValue : result ; }
Get a property as a double or defaultValue .
39
10
146,045
@ Override public final float getFloat ( final String key ) { Float result = optFloat ( key ) ; if ( result == null ) { throw new ObjectMissingException ( this , key ) ; } return result ; }
Get a property as a float or throw an exception .
46
11
146,046
@ Override public final Float optFloat ( final String key , final Float defaultValue ) { Float result = optFloat ( key ) ; return result == null ? defaultValue : result ; }
Get a property as a float or Default value .
39
10
146,047
@ Override public final boolean getBool ( final String key ) { Boolean result = optBool ( key ) ; if ( result == null ) { throw new ObjectMissingException ( this , key ) ; } return result ; }
Get a property as a boolean or throw exception .
48
10
146,048
@ Override public final Boolean optBool ( final String key , final Boolean defaultValue ) { Boolean result = optBool ( key ) ; return result == null ? defaultValue : result ; }
Get a property as a boolean or default value .
41
10
146,049
@ Override public final PObject getObject ( final String key ) { PObject result = optObject ( key ) ; if ( result == null ) { throw new ObjectMissingException ( this , key ) ; } return result ; }
Get a property as a object or throw exception .
48
10
146,050
@ Override public final PArray getArray ( final String key ) { PArray result = optArray ( key ) ; if ( result == null ) { throw new ObjectMissingException ( this , key ) ; } return result ; }
Get a property as a array or throw exception .
48
10
146,051
public AccessAssertion unmarshal ( final JSONObject encodedAssertion ) { final String className ; try { className = encodedAssertion . getString ( JSON_CLASS_NAME ) ; final Class < ? > assertionClass = Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( className ) ; final AccessAssertion assertion = ( AccessAssertion ) this . applicationContext . getBean ( assertionClass ) ; assertion . unmarshal ( encodedAssertion ) ; return assertion ; } catch ( JSONException | ClassNotFoundException e ) { throw new RuntimeException ( e ) ; } }
Load assertion from the provided json or throw exception if not possible .
136
13
146,052
public JSONObject marshal ( final AccessAssertion assertion ) { final JSONObject jsonObject = assertion . marshal ( ) ; if ( jsonObject . has ( JSON_CLASS_NAME ) ) { throw new AssertionError ( "The toJson method in AccessAssertion: '" + assertion . getClass ( ) + "' defined a JSON field " + JSON_CLASS_NAME + " which is a reserved keyword and is not permitted to be used " + "in toJSON method" ) ; } try { jsonObject . put ( JSON_CLASS_NAME , assertion . getClass ( ) . getName ( ) ) ; } catch ( JSONException e ) { throw new RuntimeException ( e ) ; } return jsonObject ; }
Marshal the assertion as a JSON object .
156
9
146,053
public static MfClientHttpRequestFactory createFactoryWrapper ( final MfClientHttpRequestFactory requestFactory , final UriMatchers matchers , final Map < String , List < String > > headers ) { return new AbstractMfClientHttpRequestFactoryWrapper ( requestFactory , matchers , false ) { @ Override protected ClientHttpRequest createRequest ( final URI uri , final HttpMethod httpMethod , final MfClientHttpRequestFactory requestFactory ) throws IOException { final ClientHttpRequest request = requestFactory . createRequest ( uri , httpMethod ) ; request . getHeaders ( ) . putAll ( headers ) ; return request ; } } ; }
Create a MfClientHttpRequestFactory for adding the specified headers .
140
14
146,054
@ SuppressWarnings ( "unchecked" ) public void setHeaders ( final Map < String , Object > headers ) { this . headers . clear ( ) ; for ( Map . Entry < String , Object > entry : headers . entrySet ( ) ) { if ( entry . getValue ( ) instanceof List ) { List value = ( List ) entry . getValue ( ) ; // verify they are all strings for ( Object o : value ) { Assert . isTrue ( o instanceof String , o + " is not a string it is a: '" + o . getClass ( ) + "'" ) ; } this . headers . put ( entry . getKey ( ) , ( List < String > ) entry . getValue ( ) ) ; } else if ( entry . getValue ( ) instanceof String ) { final List < String > value = Collections . singletonList ( ( String ) entry . getValue ( ) ) ; this . headers . put ( entry . getKey ( ) , value ) ; } else { throw new IllegalArgumentException ( "Only strings and list of strings may be headers" ) ; } } }
A map of the header key value pairs . Keys are strings and values are either list of strings or a string .
241
23
146,055
public static void writeProcessorOutputToValues ( final Object output , final Processor < ? , ? > processor , final Values values ) { Map < String , String > mapper = processor . getOutputMapperBiMap ( ) ; if ( mapper == null ) { mapper = Collections . emptyMap ( ) ; } final Collection < Field > fields = getAllAttributes ( output . getClass ( ) ) ; for ( Field field : fields ) { String name = getOutputValueName ( processor . getOutputPrefix ( ) , mapper , field ) ; try { final Object value = field . get ( output ) ; if ( value != null ) { values . put ( name , value ) ; } else { values . remove ( name ) ; } } catch ( IllegalAccessException e ) { throw ExceptionUtils . getRuntimeException ( e ) ; } } }
Read the values from the output object and write them to the values object .
181
15
146,056
public static String getInputValueName ( @ Nullable final String inputPrefix , @ Nonnull final BiMap < String , String > inputMapper , @ Nonnull final String field ) { String name = inputMapper == null ? null : inputMapper . inverse ( ) . get ( field ) ; if ( name == null ) { if ( inputMapper != null && inputMapper . containsKey ( field ) ) { throw new RuntimeException ( "field in keys" ) ; } final String [ ] defaultValues = { Values . TASK_DIRECTORY_KEY , Values . CLIENT_HTTP_REQUEST_FACTORY_KEY , Values . TEMPLATE_KEY , Values . PDF_CONFIG_KEY , Values . SUBREPORT_DIR_KEY , Values . OUTPUT_FORMAT_KEY , Values . JOB_ID_KEY } ; if ( inputPrefix == null || Arrays . asList ( defaultValues ) . contains ( field ) ) { name = field ; } else { name = inputPrefix . trim ( ) + Character . toUpperCase ( field . charAt ( 0 ) ) + field . substring ( 1 ) ; } } return name ; }
Calculate the name of the input value .
257
10
146,057
public static String getOutputValueName ( @ Nullable final String outputPrefix , @ Nonnull final Map < String , String > outputMapper , @ Nonnull final Field field ) { String name = outputMapper . get ( field . getName ( ) ) ; if ( name == null ) { name = field . getName ( ) ; if ( ! StringUtils . isEmpty ( outputPrefix ) && ! outputPrefix . trim ( ) . isEmpty ( ) ) { name = outputPrefix . trim ( ) + Character . toUpperCase ( name . charAt ( 0 ) ) + name . substring ( 1 ) ; } } return name ; }
Calculate the name of the output value .
142
10
146,058
public static Dimension rectangleDoubleToDimension ( final Rectangle2D . Double rectangle ) { return new Dimension ( ( int ) Math . round ( rectangle . width ) , ( int ) Math . round ( rectangle . height ) ) ; }
Round the size of a rectangle with double values .
49
10
146,059
public MapBounds getRotatedBounds ( final Rectangle2D . Double paintAreaPrecise , final Rectangle paintArea ) { final MapBounds rotatedBounds = this . getRotatedBounds ( ) ; if ( rotatedBounds instanceof CenterScaleMapBounds ) { return rotatedBounds ; } final ReferencedEnvelope envelope = ( ( BBoxMapBounds ) rotatedBounds ) . toReferencedEnvelope ( null ) ; // the paint area size and the map bounds are rotated independently. because // the paint area size is rounded to integers, the map bounds have to be adjusted // to these rounding changes. final double widthRatio = paintArea . getWidth ( ) / paintAreaPrecise . getWidth ( ) ; final double heightRatio = paintArea . getHeight ( ) / paintAreaPrecise . getHeight ( ) ; final double adaptedWidth = envelope . getWidth ( ) * widthRatio ; final double adaptedHeight = envelope . getHeight ( ) * heightRatio ; final double widthDiff = adaptedWidth - envelope . getWidth ( ) ; final double heigthDiff = adaptedHeight - envelope . getHeight ( ) ; envelope . expandBy ( widthDiff / 2.0 , heigthDiff / 2.0 ) ; return new BBoxMapBounds ( envelope ) ; }
Return the map bounds rotated with the set rotation . The bounds are adapted to rounding changes of the size of the paint area .
283
25
146,060
public MapBounds getRotatedBoundsAdjustedForPreciseRotatedMapSize ( ) { Rectangle2D . Double paintAreaPrecise = getRotatedMapSizePrecise ( ) ; Rectangle paintArea = new Rectangle ( MapfishMapContext . rectangleDoubleToDimension ( paintAreaPrecise ) ) ; return getRotatedBounds ( paintAreaPrecise , paintArea ) ; }
Return the map bounds rotated with the set rotation . The bounds are adapted to rounding changes of the size of the set paint area .
86
26
146,061
@ VisibleForTesting public static void runMain ( final String [ ] args ) throws Exception { final CliHelpDefinition helpCli = new CliHelpDefinition ( ) ; try { Args . parse ( helpCli , args ) ; if ( helpCli . help ) { printUsage ( 0 ) ; return ; } } catch ( IllegalArgumentException invalidOption ) { // Ignore because it is probably one of the non-help options. } final CliDefinition cli = new CliDefinition ( ) ; try { List < String > unusedArguments = Args . parse ( cli , args ) ; if ( ! unusedArguments . isEmpty ( ) ) { System . out . println ( "\n\nThe following arguments are not recognized: " + unusedArguments ) ; printUsage ( 1 ) ; return ; } } catch ( IllegalArgumentException invalidOption ) { System . out . println ( "\n\n" + invalidOption . getMessage ( ) ) ; printUsage ( 1 ) ; return ; } configureLogs ( cli . verbose ) ; AbstractXmlApplicationContext context = new ClassPathXmlApplicationContext ( DEFAULT_SPRING_CONTEXT ) ; if ( cli . springConfig != null ) { context = new ClassPathXmlApplicationContext ( DEFAULT_SPRING_CONTEXT , cli . springConfig ) ; } try { context . getBean ( Main . class ) . run ( cli ) ; } finally { context . close ( ) ; } }
Runs the print .
323
5
146,062
public GridCoverage2D call ( ) { try { BufferedImage coverageImage = this . tiledLayer . createBufferedImage ( this . tilePreparationInfo . getImageWidth ( ) , this . tilePreparationInfo . getImageHeight ( ) ) ; Graphics2D graphics = coverageImage . createGraphics ( ) ; try { for ( SingleTilePreparationInfo tileInfo : this . tilePreparationInfo . getSingleTiles ( ) ) { final TileTask task ; if ( tileInfo . getTileRequest ( ) != null ) { task = new SingleTileLoaderTask ( tileInfo . getTileRequest ( ) , this . errorImage , tileInfo . getTileIndexX ( ) , tileInfo . getTileIndexY ( ) , this . failOnError , this . registry , this . context ) ; } else { task = new PlaceHolderImageTask ( this . tiledLayer . getMissingTileImage ( ) , tileInfo . getTileIndexX ( ) , tileInfo . getTileIndexY ( ) ) ; } Tile tile = task . call ( ) ; if ( tile . getImage ( ) != null ) { graphics . drawImage ( tile . getImage ( ) , tile . getxIndex ( ) * this . tiledLayer . getTileSize ( ) . width , tile . getyIndex ( ) * this . tiledLayer . getTileSize ( ) . height , null ) ; } } } finally { graphics . dispose ( ) ; } GridCoverageFactory factory = CoverageFactoryFinder . getGridCoverageFactory ( null ) ; GeneralEnvelope gridEnvelope = new GeneralEnvelope ( this . tilePreparationInfo . getMapProjection ( ) ) ; gridEnvelope . setEnvelope ( this . tilePreparationInfo . getGridCoverageOrigin ( ) . x , this . tilePreparationInfo . getGridCoverageOrigin ( ) . y , this . tilePreparationInfo . getGridCoverageMaxX ( ) , this . tilePreparationInfo . getGridCoverageMaxY ( ) ) ; return factory . create ( this . tiledLayer . createCommonUrl ( ) , coverageImage , gridEnvelope , null , null , null ) ; } catch ( Exception e ) { throw ExceptionUtils . getRuntimeException ( e ) ; } }
Call the Coverage Task .
500
5
146,063
@ PreDestroy public final void shutdown ( ) { this . timer . shutdownNow ( ) ; this . executor . shutdownNow ( ) ; if ( this . cleanUpTimer != null ) { this . cleanUpTimer . shutdownNow ( ) ; } }
Called by spring when application context is being destroyed .
53
11
146,064
private boolean isAbandoned ( final SubmittedPrintJob printJob ) { final long duration = ThreadPoolJobManager . this . jobQueue . timeSinceLastStatusCheck ( printJob . getEntry ( ) . getReferenceId ( ) ) ; final boolean abandoned = duration > TimeUnit . SECONDS . toMillis ( ThreadPoolJobManager . this . abandonedTimeout ) ; if ( abandoned ) { LOGGER . info ( "Job {} is abandoned (no status check within the last {} seconds)" , printJob . getEntry ( ) . getReferenceId ( ) , ThreadPoolJobManager . this . abandonedTimeout ) ; } return abandoned ; }
If the status of a print job is not checked for a while we assume that the user is no longer interested in the report and we cancel the job .
135
31
146,065
private boolean isAcceptingNewJobs ( ) { if ( this . requestedToStop ) { return false ; } else if ( new File ( this . workingDirectories . getWorking ( ) , "stop" ) . exists ( ) ) { LOGGER . info ( "The print has been requested to stop" ) ; this . requestedToStop = true ; notifyIfStopped ( ) ; return false ; } else { return true ; } }
Check if the print has not been asked to stop taking new jobs .
93
14
146,066
private void notifyIfStopped ( ) { if ( isAcceptingNewJobs ( ) || ! this . runningTasksFutures . isEmpty ( ) ) { return ; } final File stoppedFile = new File ( this . workingDirectories . getWorking ( ) , "stopped" ) ; try { LOGGER . info ( "The print has finished processing jobs and can now stop" ) ; stoppedFile . createNewFile ( ) ; } catch ( IOException e ) { LOGGER . warn ( "Cannot create the {} file" , stoppedFile , e ) ; } }
Add a file to notify the script that asked to stop the print that it is now done processing the remain jobs .
124
23
146,067
public void postConstruct ( ) { parseGeometry ( ) ; Assert . isTrue ( this . polygon != null , "Polygon is null. 'area' string is: '" + this . area + "'" ) ; Assert . isTrue ( this . display != null , "'display' is null" ) ; Assert . isTrue ( this . style == null || this . display == AoiDisplay . RENDER , "'style' does not make sense unless 'display' == RENDER. In this case 'display' == " + this . display ) ; }
Tests that the area is valid geojson the style ref is valid or null and the display is non - null .
124
25
146,068
public SimpleFeatureCollection areaToFeatureCollection ( @ Nonnull final MapAttribute . MapAttributeValues mapAttributes ) { Assert . isTrue ( mapAttributes . areaOfInterest == this , "map attributes passed in does not contain this area of interest object" ) ; final SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder ( ) ; typeBuilder . setName ( "aoi" ) ; CoordinateReferenceSystem crs = mapAttributes . getMapBounds ( ) . getProjection ( ) ; typeBuilder . add ( "geom" , this . polygon . getClass ( ) , crs ) ; final SimpleFeature feature = SimpleFeatureBuilder . build ( typeBuilder . buildFeatureType ( ) , new Object [ ] { this . polygon } , "aoi" ) ; final DefaultFeatureCollection features = new DefaultFeatureCollection ( ) ; features . add ( feature ) ; return features ; }
Return the area polygon as the only feature in the feature collection .
190
14
146,069
public AreaOfInterest copy ( ) { AreaOfInterest aoi = new AreaOfInterest ( ) ; aoi . display = this . display ; aoi . area = this . area ; aoi . polygon = this . polygon ; aoi . style = this . style ; aoi . renderAsSvg = this . renderAsSvg ; return aoi ; }
Make a copy of this Area of Interest .
79
9
146,070
public static void fillProcessorAttributes ( final List < Processor > processors , final Map < String , Attribute > initialAttributes ) { Map < String , Attribute > currentAttributes = new HashMap <> ( initialAttributes ) ; for ( Processor processor : processors ) { if ( processor instanceof RequireAttributes ) { for ( ProcessorDependencyGraphFactory . InputValue inputValue : ProcessorDependencyGraphFactory . getInputs ( processor ) ) { if ( inputValue . type == Values . class ) { if ( processor instanceof CustomDependencies ) { for ( String attributeName : ( ( CustomDependencies ) processor ) . getDependencies ( ) ) { Attribute attribute = currentAttributes . get ( attributeName ) ; if ( attribute != null ) { ( ( RequireAttributes ) processor ) . setAttribute ( attributeName , currentAttributes . get ( attributeName ) ) ; } } } else { for ( Map . Entry < String , Attribute > attribute : currentAttributes . entrySet ( ) ) { ( ( RequireAttributes ) processor ) . setAttribute ( attribute . getKey ( ) , attribute . getValue ( ) ) ; } } } else { try { ( ( RequireAttributes ) processor ) . setAttribute ( inputValue . internalName , currentAttributes . get ( inputValue . name ) ) ; } catch ( ClassCastException e ) { throw new IllegalArgumentException ( String . format ( "The processor '%s' requires " + "the attribute '%s' " + "(%s) but he has the " + "wrong type:\n%s" , processor , inputValue . name , inputValue . internalName , e . getMessage ( ) ) , e ) ; } } } } if ( processor instanceof ProvideAttributes ) { Map < String , Attribute > newAttributes = ( ( ProvideAttributes ) processor ) . getAttributes ( ) ; for ( ProcessorDependencyGraphFactory . OutputValue ouputValue : ProcessorDependencyGraphFactory . getOutputValues ( processor ) ) { currentAttributes . put ( ouputValue . name , newAttributes . get ( ouputValue . internalName ) ) ; } } } }
Fill the attributes in the processor .
457
7
146,071
public void checkAllGroupsSatisfied ( final String currentPath ) { StringBuilder errors = new StringBuilder ( ) ; for ( OneOfGroup group : this . mapping . values ( ) ) { if ( group . satisfiedBy . isEmpty ( ) ) { errors . append ( "\n" ) ; errors . append ( "\t* The OneOf choice: " ) . append ( group . name ) . append ( " was not satisfied. One (and only one) of the " ) ; errors . append ( "following fields is required in the request data: " ) . append ( toNames ( group . choices ) ) ; } Collection < OneOfSatisfier > oneOfSatisfiers = Collections2 . filter ( group . satisfiedBy , input -> ! input . isCanSatisfy ) ; if ( oneOfSatisfiers . size ( ) > 1 ) { errors . append ( "\n" ) ; errors . append ( "\t* The OneOf choice: " ) . append ( group . name ) . append ( " was satisfied by too many fields. Only one choice " ) ; errors . append ( "may be in the request data. The fields found were: " ) . append ( toNames ( toFields ( group . satisfiedBy ) ) ) ; } } Assert . equals ( 0 , errors . length ( ) , "\nErrors were detected when analysing the @OneOf dependencies of '" + currentPath + "': \n" + errors ) ; }
Check that each group is satisfied by one and only one field .
315
13
146,072
@ PostConstruct public final void addMetricsAppenderToLogback ( ) { final LoggerContext factory = ( LoggerContext ) LoggerFactory . getILoggerFactory ( ) ; final Logger root = factory . getLogger ( Logger . ROOT_LOGGER_NAME ) ; final InstrumentedAppender metrics = new InstrumentedAppender ( this . metricRegistry ) ; metrics . setContext ( root . getLoggerContext ( ) ) ; metrics . start ( ) ; root . addAppender ( metrics ) ; }
Add an appender to Logback logging framework that will track the types of log messages made .
114
19
146,073
public void checkAllRequirementsSatisfied ( final String currentPath ) { StringBuilder errors = new StringBuilder ( ) ; for ( Field field : this . dependantsInJson ) { final Collection < String > requirements = this . dependantToRequirementsMap . get ( field ) ; if ( ! requirements . isEmpty ( ) ) { errors . append ( "\n" ) ; String type = field . getType ( ) . getName ( ) ; if ( field . getType ( ) . isArray ( ) ) { type = field . getType ( ) . getComponentType ( ) . getName ( ) + "[]" ; } errors . append ( "\t* " ) . append ( type ) . append ( ' ' ) . append ( field . getName ( ) ) . append ( " depends on " ) . append ( requirements ) ; } } Assert . equals ( 0 , errors . length ( ) , "\nErrors were detected when analysing the @Requires dependencies of '" + currentPath + "': " + errors ) ; }
Check that each requirement is satisfied .
220
7
146,074
public final void printClientConfig ( final JSONWriter json ) throws JSONException { json . key ( "layouts" ) ; json . array ( ) ; final Map < String , Template > accessibleTemplates = getTemplates ( ) ; accessibleTemplates . entrySet ( ) . stream ( ) . sorted ( Comparator . comparing ( Map . Entry :: getKey ) ) . forEach ( entry -> { json . object ( ) ; json . key ( "name" ) . value ( entry . getKey ( ) ) ; entry . getValue ( ) . printClientConfig ( json ) ; json . endObject ( ) ; } ) ; json . endArray ( ) ; json . key ( "smtp" ) . object ( ) ; json . key ( "enabled" ) . value ( smtp != null ) ; if ( smtp != null ) { json . key ( "storage" ) . object ( ) ; json . key ( "enabled" ) . value ( smtp . getStorage ( ) != null ) ; json . endObject ( ) ; } json . endObject ( ) ; }
Print out the configuration that the client needs to make a request .
230
13
146,075
public final Template getTemplate ( final String name ) { final Template template = this . templates . get ( name ) ; if ( template != null ) { this . accessAssertion . assertAccess ( "Configuration" , this ) ; template . assertAccessible ( name ) ; } else { throw new IllegalArgumentException ( String . format ( "Template '%s' does not exist. Options are: " + "%s" , name , this . templates . keySet ( ) ) ) ; } return template ; }
Retrieve the configuration of the named template .
108
9
146,076
@ Nonnull public final Style getDefaultStyle ( @ Nonnull final String geometryType ) { String normalizedGeomName = GEOMETRY_NAME_ALIASES . get ( geometryType . toLowerCase ( ) ) ; if ( normalizedGeomName == null ) { normalizedGeomName = geometryType . toLowerCase ( ) ; } Style style = this . defaultStyle . get ( normalizedGeomName . toLowerCase ( ) ) ; if ( style == null ) { style = this . namedStyles . get ( normalizedGeomName . toLowerCase ( ) ) ; } if ( style == null ) { StyleBuilder builder = new StyleBuilder ( ) ; final Symbolizer symbolizer ; if ( isPointType ( normalizedGeomName ) ) { symbolizer = builder . createPointSymbolizer ( ) ; } else if ( isLineType ( normalizedGeomName ) ) { symbolizer = builder . createLineSymbolizer ( Color . black , 2 ) ; } else if ( isPolygonType ( normalizedGeomName ) ) { symbolizer = builder . createPolygonSymbolizer ( Color . lightGray , Color . black , 2 ) ; } else if ( normalizedGeomName . equalsIgnoreCase ( Constants . Style . Raster . NAME ) ) { symbolizer = builder . createRasterSymbolizer ( ) ; } else if ( normalizedGeomName . startsWith ( Constants . Style . OverviewMap . NAME ) ) { symbolizer = createMapOverviewStyle ( normalizedGeomName , builder ) ; } else { final Style geomStyle = this . defaultStyle . get ( Geometry . class . getSimpleName ( ) . toLowerCase ( ) ) ; if ( geomStyle != null ) { return geomStyle ; } else { symbolizer = builder . createPointSymbolizer ( ) ; } } style = builder . createStyle ( symbolizer ) ; } return style ; }
Get a default style . If null a simple black line style will be returned .
409
16
146,077
public final void setDefaultStyle ( final Map < String , Style > defaultStyle ) { this . defaultStyle = new HashMap <> ( defaultStyle . size ( ) ) ; for ( Map . Entry < String , Style > entry : defaultStyle . entrySet ( ) ) { String normalizedName = GEOMETRY_NAME_ALIASES . get ( entry . getKey ( ) . toLowerCase ( ) ) ; if ( normalizedName == null ) { normalizedName = entry . getKey ( ) . toLowerCase ( ) ; } this . defaultStyle . put ( normalizedName , entry . getValue ( ) ) ; } }
Set the default styles . the case of the keys are not important . The retrieval will be case insensitive .
134
21
146,078
public final List < Throwable > validate ( ) { List < Throwable > validationErrors = new ArrayList <> ( ) ; this . accessAssertion . validate ( validationErrors , this ) ; for ( String jdbcDriver : this . jdbcDrivers ) { try { Class . forName ( jdbcDriver ) ; } catch ( ClassNotFoundException e ) { try { Configuration . class . getClassLoader ( ) . loadClass ( jdbcDriver ) ; } catch ( ClassNotFoundException e1 ) { validationErrors . add ( new ConfigurationException ( String . format ( "Unable to load JDBC driver: %s ensure that the web application has the jar " + "on its classpath" , jdbcDriver ) ) ) ; } } } if ( this . configurationFile == null ) { validationErrors . add ( new ConfigurationException ( "Configuration file is field on configuration " + "object is null" ) ) ; } if ( this . templates . isEmpty ( ) ) { validationErrors . add ( new ConfigurationException ( "There are not templates defined." ) ) ; } for ( Template template : this . templates . values ( ) ) { template . validate ( validationErrors , this ) ; } for ( HttpProxy proxy : this . proxies ) { proxy . validate ( validationErrors , this ) ; } try { ColorParser . toColor ( this . opaqueTileErrorColor ) ; } catch ( RuntimeException ex ) { validationErrors . add ( new ConfigurationException ( "Cannot parse opaqueTileErrorColor" , ex ) ) ; } try { ColorParser . toColor ( this . transparentTileErrorColor ) ; } catch ( RuntimeException ex ) { validationErrors . add ( new ConfigurationException ( "Cannot parse transparentTileErrorColor" , ex ) ) ; } if ( smtp != null ) { smtp . validate ( validationErrors , this ) ; } return validationErrors ; }
Validate that the configuration is valid .
415
8
146,079
public void addDependency ( final ProcessorGraphNode node ) { Assert . isTrue ( node != this , "A processor can't depends on himself" ) ; this . dependencies . add ( node ) ; node . addRequirement ( this ) ; }
Add a dependency to this node .
54
7
146,080
@ Nonnull public BiMap < String , String > getOutputMapper ( ) { final BiMap < String , String > outputMapper = this . processor . getOutputMapperBiMap ( ) ; if ( outputMapper == null ) { return HashBiMap . create ( ) ; } return outputMapper ; }
Get the output mapper from processor .
68
8
146,081
@ Nonnull public BiMap < String , String > getInputMapper ( ) { final BiMap < String , String > inputMapper = this . processor . getInputMapperBiMap ( ) ; if ( inputMapper == null ) { return HashBiMap . create ( ) ; } return inputMapper ; }
Return input mapper from processor .
68
7
146,082
public Set < ? extends Processor < ? , ? > > getAllProcessors ( ) { IdentityHashMap < Processor < ? , ? > , Void > all = new IdentityHashMap <> ( ) ; all . put ( this . getProcessor ( ) , null ) ; for ( ProcessorGraphNode < ? , ? > dependency : this . dependencies ) { for ( Processor < ? , ? > p : dependency . getAllProcessors ( ) ) { all . put ( p , null ) ; } } return all . keySet ( ) ; }
Create a set containing all the processor at the current node and the entire subgraph .
115
17
146,083
public static String findReplacement ( final String variableName , final Date date ) { if ( variableName . equalsIgnoreCase ( "date" ) ) { return cleanUpName ( DateFormat . getDateInstance ( ) . format ( date ) ) ; } else if ( variableName . equalsIgnoreCase ( "datetime" ) ) { return cleanUpName ( DateFormat . getDateTimeInstance ( ) . format ( date ) ) ; } else if ( variableName . equalsIgnoreCase ( "time" ) ) { return cleanUpName ( DateFormat . getTimeInstance ( ) . format ( date ) ) ; } else { try { return new SimpleDateFormat ( variableName ) . format ( date ) ; } catch ( Exception e ) { LOGGER . error ( "Unable to format timestamp according to pattern: {}" , variableName , e ) ; return "${" + variableName + "}" ; } } }
Update a variable name with a date if the variable is detected as being a date .
195
17
146,084
protected static void error ( final HttpServletResponse httpServletResponse , final String message , final HttpStatus code ) { try { httpServletResponse . setContentType ( "text/plain" ) ; httpServletResponse . setStatus ( code . value ( ) ) ; setNoCache ( httpServletResponse ) ; try ( PrintWriter out = httpServletResponse . getWriter ( ) ) { out . println ( "Error while processing request:" ) ; out . println ( message ) ; } LOGGER . error ( "Error while processing request: {}" , message ) ; } catch ( IOException ex ) { throw ExceptionUtils . getRuntimeException ( ex ) ; } }
Send an error to the client with a message .
146
10
146,085
protected final void error ( final HttpServletResponse httpServletResponse , final Throwable e ) { httpServletResponse . setContentType ( "text/plain" ) ; httpServletResponse . setStatus ( HttpStatus . INTERNAL_SERVER_ERROR . value ( ) ) ; try ( PrintWriter out = httpServletResponse . getWriter ( ) ) { out . println ( "Error while processing request:" ) ; LOGGER . error ( "Error while processing request" , e ) ; } catch ( IOException ex ) { throw ExceptionUtils . getRuntimeException ( ex ) ; } }
Send an error to the client with an exception .
130
10
146,086
protected final StringBuilder getBaseUrl ( final HttpServletRequest httpServletRequest ) { StringBuilder baseURL = new StringBuilder ( ) ; if ( httpServletRequest . getContextPath ( ) != null && ! httpServletRequest . getContextPath ( ) . isEmpty ( ) ) { baseURL . append ( httpServletRequest . getContextPath ( ) ) ; } if ( httpServletRequest . getServletPath ( ) != null && ! httpServletRequest . getServletPath ( ) . isEmpty ( ) ) { baseURL . append ( httpServletRequest . getServletPath ( ) ) ; } return baseURL ; }
Returns the base URL of the print servlet .
141
10
146,087
@ VisibleForTesting protected static Dimension getSize ( final ScalebarAttributeValues scalebarParams , final ScaleBarRenderSettings settings , final Dimension maxLabelSize ) { final float width ; final float height ; if ( scalebarParams . getOrientation ( ) . isHorizontal ( ) ) { width = 2 * settings . getPadding ( ) + settings . getIntervalLengthInPixels ( ) * scalebarParams . intervals + settings . getLeftLabelMargin ( ) + settings . getRightLabelMargin ( ) ; height = 2 * settings . getPadding ( ) + settings . getBarSize ( ) + settings . getLabelDistance ( ) + Label . getRotatedHeight ( maxLabelSize , scalebarParams . getLabelRotation ( ) ) ; } else { width = 2 * settings . getPadding ( ) + settings . getLabelDistance ( ) + settings . getBarSize ( ) + Label . getRotatedWidth ( maxLabelSize , scalebarParams . getLabelRotation ( ) ) ; height = 2 * settings . getPadding ( ) + settings . getTopLabelMargin ( ) + settings . getIntervalLengthInPixels ( ) * scalebarParams . intervals + settings . getBottomLabelMargin ( ) ; } return new Dimension ( ( int ) Math . ceil ( width ) , ( int ) Math . ceil ( height ) ) ; }
Get the size of the painting area required to draw the scalebar with labels .
302
16
146,088
@ VisibleForTesting protected static Dimension getMaxLabelSize ( final ScaleBarRenderSettings settings ) { float maxLabelHeight = 0.0f ; float maxLabelWidth = 0.0f ; for ( final Label label : settings . getLabels ( ) ) { maxLabelHeight = Math . max ( maxLabelHeight , label . getHeight ( ) ) ; maxLabelWidth = Math . max ( maxLabelWidth , label . getWidth ( ) ) ; } return new Dimension ( ( int ) Math . ceil ( maxLabelWidth ) , ( int ) Math . ceil ( maxLabelHeight ) ) ; }
Get the maximum width and height of the labels .
129
10
146,089
@ VisibleForTesting protected static String createLabelText ( final DistanceUnit scaleUnit , final double value , final DistanceUnit intervalUnit ) { double scaledValue = scaleUnit . convertTo ( value , intervalUnit ) ; // assume that there is no interval smaller then 0.0001 scaledValue = Math . round ( scaledValue * 10000 ) / 10000 ; String decimals = Double . toString ( scaledValue ) . split ( "\\." ) [ 1 ] ; if ( Double . valueOf ( decimals ) == 0 ) { return Long . toString ( Math . round ( scaledValue ) ) ; } else { return Double . toString ( scaledValue ) ; } }
Format the label text .
141
5
146,090
@ VisibleForTesting protected static double getNearestNiceValue ( final double value , final DistanceUnit scaleUnit , final boolean lockUnits ) { DistanceUnit bestUnit = bestUnit ( scaleUnit , value , lockUnits ) ; double factor = scaleUnit . convertTo ( 1.0 , bestUnit ) ; // nearest power of 10 lower than value int digits = ( int ) Math . floor ( ( Math . log ( value * factor ) / Math . log ( 10 ) ) ) ; double pow10 = Math . pow ( 10 , digits ) ; // ok, find first character double firstChar = value * factor / pow10 ; // right, put it into the correct bracket int barLen ; if ( firstChar >= 10.0 ) { barLen = 10 ; } else if ( firstChar >= 5.0 ) { barLen = 5 ; } else if ( firstChar >= 2.0 ) { barLen = 2 ; } else { barLen = 1 ; } // scale it up the correct power of 10 return barLen * pow10 / factor ; }
Reduce the given value to the nearest smaller 1 significant digit number starting with 1 2 or 5 .
223
20
146,091
@ VisibleForTesting protected static int getBarSize ( final ScaleBarRenderSettings settings ) { if ( settings . getParams ( ) . barSize != null ) { return settings . getParams ( ) . barSize ; } else { if ( settings . getParams ( ) . getOrientation ( ) . isHorizontal ( ) ) { return settings . getMaxSize ( ) . height / 4 ; } else { return settings . getMaxSize ( ) . width / 4 ; } } }
Get the bar size .
107
5
146,092
@ VisibleForTesting protected static int getLabelDistance ( final ScaleBarRenderSettings settings ) { if ( settings . getParams ( ) . labelDistance != null ) { return settings . getParams ( ) . labelDistance ; } else { if ( settings . getParams ( ) . getOrientation ( ) . isHorizontal ( ) ) { return settings . getMaxSize ( ) . width / 40 ; } else { return settings . getMaxSize ( ) . height / 40 ; } } }
Get the label distance ..
107
5
146,093
public final URI render ( final MapfishMapContext mapContext , final ScalebarAttributeValues scalebarParams , final File tempFolder , final Template template ) throws IOException , ParserConfigurationException { final double dpi = mapContext . getDPI ( ) ; // get the map bounds final Rectangle paintArea = new Rectangle ( mapContext . getMapSize ( ) ) ; MapBounds bounds = mapContext . getBounds ( ) ; final DistanceUnit mapUnit = getUnit ( bounds ) ; final Scale scale = bounds . getScale ( paintArea , PDF_DPI ) ; final double scaleDenominator = scale . getDenominator ( scalebarParams . geodetic , bounds . getProjection ( ) , dpi , bounds . getCenter ( ) ) ; DistanceUnit scaleUnit = scalebarParams . getUnit ( ) ; if ( scaleUnit == null ) { scaleUnit = mapUnit ; } // adjust scalebar width and height to the DPI value final double maxLengthInPixel = ( scalebarParams . getOrientation ( ) . isHorizontal ( ) ) ? scalebarParams . getSize ( ) . width : scalebarParams . getSize ( ) . height ; final double maxIntervalLengthInWorldUnits = DistanceUnit . PX . convertTo ( maxLengthInPixel , scaleUnit ) * scaleDenominator / scalebarParams . intervals ; final double niceIntervalLengthInWorldUnits = getNearestNiceValue ( maxIntervalLengthInWorldUnits , scaleUnit , scalebarParams . lockUnits ) ; final ScaleBarRenderSettings settings = new ScaleBarRenderSettings ( ) ; settings . setParams ( scalebarParams ) ; settings . setMaxSize ( scalebarParams . getSize ( ) ) ; settings . setPadding ( getPadding ( settings ) ) ; // start the rendering File path = null ; if ( template . getConfiguration ( ) . renderAsSvg ( scalebarParams . renderAsSvg ) ) { // render scalebar as SVG final SVGGraphics2D graphics2D = CreateMapProcessor . createSvgGraphics ( scalebarParams . getSize ( ) ) ; try { tryLayout ( graphics2D , scaleUnit , scaleDenominator , niceIntervalLengthInWorldUnits , settings , 0 ) ; path = File . createTempFile ( "scalebar-graphic-" , ".svg" , tempFolder ) ; CreateMapProcessor . saveSvgFile ( graphics2D , path ) ; } finally { graphics2D . dispose ( ) ; } } else { // render scalebar as raster graphic double dpiRatio = mapContext . getDPI ( ) / PDF_DPI ; final BufferedImage bufferedImage = new BufferedImage ( ( int ) Math . round ( scalebarParams . getSize ( ) . width * dpiRatio ) , ( int ) Math . round ( scalebarParams . getSize ( ) . height * dpiRatio ) , TYPE_4BYTE_ABGR ) ; final Graphics2D graphics2D = bufferedImage . createGraphics ( ) ; try { AffineTransform saveAF = new AffineTransform ( graphics2D . getTransform ( ) ) ; graphics2D . scale ( dpiRatio , dpiRatio ) ; tryLayout ( graphics2D , scaleUnit , scaleDenominator , niceIntervalLengthInWorldUnits , settings , 0 ) ; graphics2D . setTransform ( saveAF ) ; path = File . createTempFile ( "scalebar-graphic-" , ".png" , tempFolder ) ; ImageUtils . writeImage ( bufferedImage , "png" , path ) ; } finally { graphics2D . dispose ( ) ; } } return path . toURI ( ) ; }
Render the scalebar .
819
5
146,094
public static PJsonObject parseSpec ( final String spec ) { final JSONObject jsonSpec ; try { jsonSpec = new JSONObject ( spec ) ; } catch ( JSONException e ) { throw new RuntimeException ( "Cannot parse the spec file: " + spec , e ) ; } return new PJsonObject ( jsonSpec , "spec" ) ; }
Parse the JSON string and return the object . The string is expected to be the JSON print data from the client .
75
24
146,095
public final OutputFormat getOutputFormat ( final PJsonObject specJson ) { final String format = specJson . getString ( MapPrinterServlet . JSON_OUTPUT_FORMAT ) ; final boolean mapExport = this . configuration . getTemplate ( specJson . getString ( Constants . JSON_LAYOUT_KEY ) ) . isMapExport ( ) ; final String beanName = format + ( mapExport ? MAP_OUTPUT_FORMAT_BEAN_NAME_ENDING : OUTPUT_FORMAT_BEAN_NAME_ENDING ) ; if ( ! this . outputFormat . containsKey ( beanName ) ) { throw new RuntimeException ( "Format '" + format + "' with mapExport '" + mapExport + "' is not supported." ) ; } return this . outputFormat . get ( beanName ) ; }
Get the object responsible for printing to the correct output format .
184
12
146,096
public final Processor . ExecutionContext print ( final String jobId , final PJsonObject specJson , final OutputStream out ) throws Exception { final OutputFormat format = getOutputFormat ( specJson ) ; final File taskDirectory = this . workingDirectories . getTaskDirectory ( ) ; try { return format . print ( jobId , specJson , getConfiguration ( ) , this . configFile . getParentFile ( ) , taskDirectory , out ) ; } finally { this . workingDirectories . removeDirectory ( taskDirectory ) ; } }
Start a print .
114
4
146,097
public final Set < String > getOutputFormatsNames ( ) { SortedSet < String > formats = new TreeSet <> ( ) ; for ( String formatBeanName : this . outputFormat . keySet ( ) ) { int endingIndex = formatBeanName . indexOf ( MAP_OUTPUT_FORMAT_BEAN_NAME_ENDING ) ; if ( endingIndex < 0 ) { endingIndex = formatBeanName . indexOf ( OUTPUT_FORMAT_BEAN_NAME_ENDING ) ; } formats . add ( formatBeanName . substring ( 0 , endingIndex ) ) ; } return formats ; }
Return the available format ids .
138
7
146,098
public Scale getNearestScale ( final ZoomLevels zoomLevels , final double tolerance , final ZoomLevelSnapStrategy zoomLevelSnapStrategy , final boolean geodetic , final Rectangle paintArea , final double dpi ) { final Scale scale = getScale ( paintArea , dpi ) ; final Scale correctedScale ; final double scaleRatio ; if ( geodetic ) { final double currentScaleDenominator = scale . getGeodeticDenominator ( getProjection ( ) , dpi , getCenter ( ) ) ; scaleRatio = scale . getDenominator ( dpi ) / currentScaleDenominator ; correctedScale = scale . toResolution ( scale . getResolution ( ) / scaleRatio ) ; } else { scaleRatio = 1 ; correctedScale = scale ; } DistanceUnit unit = DistanceUnit . fromProjection ( getProjection ( ) ) ; final ZoomLevelSnapStrategy . SearchResult result = zoomLevelSnapStrategy . search ( correctedScale , tolerance , zoomLevels ) ; final Scale newScale ; if ( geodetic ) { newScale = new Scale ( result . getScale ( unit ) . getDenominator ( PDF_DPI ) * scaleRatio , getProjection ( ) , dpi ) ; } else { newScale = result . getScale ( unit ) ; } return newScale ; }
Get the nearest scale .
290
5
146,099
@ PostConstruct public final void init ( ) { this . cleanUpTimer = Executors . newScheduledThreadPool ( 1 , timerTask -> { final Thread thread = new Thread ( timerTask , "Clean up old job records" ) ; thread . setDaemon ( true ) ; return thread ; } ) ; this . cleanUpTimer . scheduleAtFixedRate ( this :: cleanup , this . cleanupInterval , this . cleanupInterval , TimeUnit . SECONDS ) ; }
Called by spring on initialization .
103
7