idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
22,600 | @ 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 . |
22,601 | 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 . |
22,602 | 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 . |
22,603 | 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 . |
22,604 | protected TextSymbolizer createTextSymbolizer ( final PJsonObject styleJson ) { final TextSymbolizer textSymbolizer = this . styleBuilder . createTextSymbolizer ( ) ; 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 . |
22,605 | 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 . |
22,606 | protected final StyleSupplier < FeatureSource > createStyleFunction ( final Template template , final String styleString ) { return new StyleSupplier < FeatureSource > ( ) { 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 . |
22,607 | 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 . |
22,608 | 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 . |
22,609 | 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 . |
22,610 | 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 . |
22,611 | public static SimpleFeatureType createGridFeatureType ( final MapfishMapContext mapContext , 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 . |
22,612 | 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 ) ) { return String . format ( "%1.0f %s" , value , unit ) ; } else if ( NonSI . DEGREE_ANGLE . toString ( ) . equals ( unit ) ) { return String . format ( "%1.6f %s" , value , unit ) ; } else { return String . format ( "%f %s" , value , unit ) ; } } } | Create the label for a grid line . |
22,613 | 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 . |
22,614 | protected URL getDefinitionsURL ( ) { try { URL url = CustomEPSGCodes . class . getResource ( CUSTOM_EPSG_CODES_FILE ) ; try ( InputStream stream = url . openStream ( ) ) { 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 . |
22,615 | public synchronized void addMapStats ( final MapfishMapContext mapContext , final MapAttribute . MapAttributeValues mapValues ) { this . mapStats . add ( new MapStats ( mapContext , mapValues ) ) ; } | Add statistics about a created map . |
22,616 | 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 . |
22,617 | 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 . |
22,618 | 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 . |
22,619 | 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 . |
22,620 | 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 . |
22,621 | 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 . |
22,622 | 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 . |
22,623 | 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 . |
22,624 | 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 . |
22,625 | 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 . |
22,626 | 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 . |
22,627 | 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 . |
22,628 | 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 . |
22,629 | 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 . |
22,630 | 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 . |
22,631 | 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 . |
22,632 | 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 . |
22,633 | 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 . |
22,634 | 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 . |
22,635 | 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 . |
22,636 | 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 . |
22,637 | 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 . |
22,638 | 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 . |
22,639 | 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 . |
22,640 | 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 . |
22,641 | 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 . |
22,642 | 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 . |
22,643 | public static MfClientHttpRequestFactory createFactoryWrapper ( final MfClientHttpRequestFactory requestFactory , final UriMatchers matchers , final Map < String , List < String > > headers ) { return new AbstractMfClientHttpRequestFactoryWrapper ( requestFactory , matchers , false ) { 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 . |
22,644 | @ 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 ( ) ; 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 . |
22,645 | 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 . |
22,646 | public static String getInputValueName ( final String inputPrefix , final BiMap < String , String > inputMapper , 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 . |
22,647 | public static String getOutputValueName ( final String outputPrefix , final Map < String , String > outputMapper , 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 . |
22,648 | 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 . |
22,649 | 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 ) ; 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 . |
22,650 | 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 . |
22,651 | 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 ) { } 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 . |
22,652 | 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 . |
22,653 | 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 . |
22,654 | 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 . |
22,655 | 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 . |
22,656 | 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 . |
22,657 | 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 . |
22,658 | public SimpleFeatureCollection areaToFeatureCollection ( 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 . |
22,659 | 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 . |
22,660 | 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 . |
22,661 | 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 . |
22,662 | 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 . |
22,663 | 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 . |
22,664 | 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 . |
22,665 | 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 . |
22,666 | public final Style getDefaultStyle ( 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 . |
22,667 | 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 . |
22,668 | 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 . |
22,669 | 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 . |
22,670 | 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 . |
22,671 | 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 . |
22,672 | 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 . |
22,673 | 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 . |
22,674 | 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 . |
22,675 | 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 . |
22,676 | 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 . |
22,677 | 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 . |
22,678 | 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 . |
22,679 | protected static String createLabelText ( final DistanceUnit scaleUnit , final double value , final DistanceUnit intervalUnit ) { double scaledValue = scaleUnit . convertTo ( value , intervalUnit ) ; 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 . |
22,680 | 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 ) ; int digits = ( int ) Math . floor ( ( Math . log ( value * factor ) / Math . log ( 10 ) ) ) ; double pow10 = Math . pow ( 10 , digits ) ; double firstChar = value * factor / pow10 ; 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 ; } return barLen * pow10 / factor ; } | Reduce the given value to the nearest smaller 1 significant digit number starting with 1 2 or 5 . |
22,681 | 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 . |
22,682 | 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 .. |
22,683 | public final URI render ( final MapfishMapContext mapContext , final ScalebarAttributeValues scalebarParams , final File tempFolder , final Template template ) throws IOException , ParserConfigurationException { final double dpi = mapContext . getDPI ( ) ; 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 ; } 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 ) ) ; File path = null ; if ( template . getConfiguration ( ) . renderAsSvg ( scalebarParams . renderAsSvg ) ) { 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 { 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 . |
22,684 | 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 . |
22,685 | 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 . |
22,686 | 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 . |
22,687 | 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 . |
22,688 | 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 . |
22,689 | 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 . |
22,690 | public static Collection < Field > getAllAttributes ( final Class < ? > classToInspect ) { Set < Field > allFields = new HashSet < > ( ) ; getAllAttributes ( classToInspect , allFields , Function . identity ( ) , field -> true ) ; return allFields ; } | Inspects the object and all superclasses for public non - final accessible methods and returns a collection containing all the attributes found . |
22,691 | public static Collection < Field > getAttributes ( final Class < ? > classToInspect , final Predicate < Field > filter ) { Set < Field > allFields = new HashSet < > ( ) ; getAllAttributes ( classToInspect , allFields , Function . identity ( ) , filter ) ; return allFields ; } | Get a subset of the attributes of the provided class . An attribute is each public field in the class or super class . |
22,692 | private static URI createRaster ( final Dimension targetSize , final RasterReference rasterReference , final Double rotation , final Color backgroundColor , final File workingDir ) throws IOException { final File path = File . createTempFile ( "north-arrow-" , ".png" , workingDir ) ; final BufferedImage newImage = new BufferedImage ( targetSize . width , targetSize . height , BufferedImage . TYPE_4BYTE_ABGR ) ; final Graphics2D graphics2d = newImage . createGraphics ( ) ; try { final BufferedImage originalImage = ImageIO . read ( rasterReference . inputStream ) ; if ( originalImage == null ) { LOGGER . warn ( "Unable to load NorthArrow graphic: {}, it is not an image format that can be " + "decoded" , rasterReference . uri ) ; throw new IllegalArgumentException ( ) ; } graphics2d . setColor ( backgroundColor ) ; graphics2d . fillRect ( 0 , 0 , targetSize . width , targetSize . height ) ; int newWidth ; int newHeight ; if ( originalImage . getWidth ( ) > originalImage . getHeight ( ) ) { newWidth = targetSize . width ; newHeight = Math . min ( targetSize . height , ( int ) Math . ceil ( newWidth / ( originalImage . getWidth ( ) / ( double ) originalImage . getHeight ( ) ) ) ) ; } else { newHeight = targetSize . height ; newWidth = Math . min ( targetSize . width , ( int ) Math . ceil ( newHeight / ( originalImage . getHeight ( ) / ( double ) originalImage . getWidth ( ) ) ) ) ; } int deltaX = ( int ) Math . floor ( ( targetSize . width - newWidth ) / 2.0 ) ; int deltaY = ( int ) Math . floor ( ( targetSize . height - newHeight ) / 2.0 ) ; if ( ! FloatingPointUtil . equals ( rotation , 0.0 ) ) { final AffineTransform rotate = AffineTransform . getRotateInstance ( rotation , targetSize . width / 2.0 , targetSize . height / 2.0 ) ; graphics2d . setTransform ( rotate ) ; } graphics2d . setRenderingHint ( RenderingHints . KEY_INTERPOLATION , RenderingHints . VALUE_INTERPOLATION_BICUBIC ) ; graphics2d . drawImage ( originalImage , deltaX , deltaY , newWidth , newHeight , null ) ; ImageUtils . writeImage ( newImage , "png" , path ) ; } finally { graphics2d . dispose ( ) ; } return path . toURI ( ) ; } | Renders a given graphic into a new image scaled to fit the new size and rotated . |
22,693 | private static URI createSvg ( final Dimension targetSize , final RasterReference rasterReference , final Double rotation , final Color backgroundColor , final File workingDir ) throws IOException { final SVGElement svgRoot = parseSvg ( rasterReference . inputStream ) ; DOMImplementation impl = SVGDOMImplementation . getDOMImplementation ( ) ; Document newDocument = impl . createDocument ( SVG_NS , "svg" , null ) ; SVGElement newSvgRoot = ( SVGElement ) newDocument . getDocumentElement ( ) ; newSvgRoot . setAttributeNS ( null , "width" , Integer . toString ( targetSize . width ) ) ; newSvgRoot . setAttributeNS ( null , "height" , Integer . toString ( targetSize . height ) ) ; setSvgBackground ( backgroundColor , targetSize , newDocument , newSvgRoot ) ; embedSvgGraphic ( svgRoot , newSvgRoot , newDocument , targetSize , rotation ) ; File path = writeSvgToFile ( newDocument , workingDir ) ; return path . toURI ( ) ; } | With the Batik SVG library it is only possible to create new SVG graphics but you can not modify an existing graphic . So we are loading the SVG file as plain XML and doing the modifications by hand . |
22,694 | private static void embedSvgGraphic ( final SVGElement svgRoot , final SVGElement newSvgRoot , final Document newDocument , final Dimension targetSize , final Double rotation ) { final String originalWidth = svgRoot . getAttributeNS ( null , "width" ) ; final String originalHeight = svgRoot . getAttributeNS ( null , "height" ) ; if ( ! StringUtils . isEmpty ( originalWidth ) && ! StringUtils . isEmpty ( originalHeight ) ) { Element wrapperContainer = newDocument . createElementNS ( SVG_NS , "g" ) ; wrapperContainer . setAttributeNS ( null , SVGConstants . SVG_TRANSFORM_ATTRIBUTE , getRotateTransformation ( targetSize , rotation ) ) ; newSvgRoot . appendChild ( wrapperContainer ) ; Element wrapperSvg = newDocument . createElementNS ( SVG_NS , "svg" ) ; wrapperSvg . setAttributeNS ( null , "width" , "100%" ) ; wrapperSvg . setAttributeNS ( null , "height" , "100%" ) ; wrapperSvg . setAttributeNS ( null , "viewBox" , "0 0 " + originalWidth + " " + originalHeight ) ; wrapperContainer . appendChild ( wrapperSvg ) ; Node svgRootImported = newDocument . importNode ( svgRoot , true ) ; wrapperSvg . appendChild ( svgRootImported ) ; } else if ( StringUtils . isEmpty ( originalWidth ) && StringUtils . isEmpty ( originalHeight ) ) { Element wrapperContainer = newDocument . createElementNS ( SVG_NS , "g" ) ; wrapperContainer . setAttributeNS ( null , SVGConstants . SVG_TRANSFORM_ATTRIBUTE , getRotateTransformation ( targetSize , rotation ) ) ; newSvgRoot . appendChild ( wrapperContainer ) ; Node svgRootImported = newDocument . importNode ( svgRoot , true ) ; wrapperContainer . appendChild ( svgRootImported ) ; } else { throw new IllegalArgumentException ( "Unsupported or invalid north-arrow SVG graphic: The same unit (px, em, %, ...) must be" + " " + "used for `width` and `height`." ) ; } } | Embeds the given SVG element into a new SVG element scaling the graphic to the given dimension and applying the given rotation . |
22,695 | public void setDirectory ( final String directory ) { this . directory = new File ( this . configuration . getDirectory ( ) , directory ) ; if ( ! this . directory . exists ( ) ) { throw new IllegalArgumentException ( String . format ( "Directory does not exist: %s.\n" + "Configuration contained value %s which is supposed to be relative to " + "configuration directory." , this . directory , directory ) ) ; } if ( ! this . directory . getAbsolutePath ( ) . startsWith ( this . configuration . getDirectory ( ) . getAbsolutePath ( ) ) ) { throw new IllegalArgumentException ( String . format ( "All files and directories must be contained in the configuration directory the " + "directory provided in the configuration breaks that contract: %s in config " + "file resolved to %s." , directory , this . directory ) ) ; } } | Set the directory and test that the directory exists and is contained within the Configuration directory . |
22,696 | public void setAttribute ( final String name , final Attribute attribute ) { if ( name . equals ( MAP_KEY ) ) { this . mapAttribute = ( MapAttribute ) attribute ; } } | Set the map attribute . |
22,697 | public Map < String , Attribute > getAttributes ( ) { Map < String , Attribute > result = new HashMap < > ( ) ; DataSourceAttribute datasourceAttribute = new DataSourceAttribute ( ) ; Map < String , Attribute > dsResult = new HashMap < > ( ) ; dsResult . put ( MAP_KEY , this . mapAttribute ) ; datasourceAttribute . setAttributes ( dsResult ) ; result . put ( "datasource" , datasourceAttribute ) ; return result ; } | Gets the attributes provided by the processor . |
22,698 | public final void printClientConfig ( final JSONWriter json ) throws JSONException { json . key ( "attributes" ) ; json . array ( ) ; for ( Map . Entry < String , Attribute > entry : this . attributes . entrySet ( ) ) { Attribute attribute = entry . getValue ( ) ; if ( attribute . getClass ( ) . getAnnotation ( InternalAttribute . class ) == null ) { json . object ( ) ; attribute . printClientConfig ( json , this ) ; json . endObject ( ) ; } } json . endArray ( ) ; } | Print out the template information that the client needs for performing a request . |
22,699 | public final void setAttributes ( final Map < String , Attribute > attributes ) { for ( Map . Entry < String , Attribute > entry : attributes . entrySet ( ) ) { Object attribute = entry . getValue ( ) ; if ( ! ( attribute instanceof Attribute ) ) { final String msg = "Attribute: '" + entry . getKey ( ) + "' is not an attribute. It is a: " + attribute ; LOGGER . error ( "Error setting the Attributes: {}" , msg ) ; throw new IllegalArgumentException ( msg ) ; } else { ( ( Attribute ) attribute ) . setConfigName ( entry . getKey ( ) ) ; } } this . attributes = attributes ; } | Set the attributes for this template . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.