idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
146,100
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 .
67
26
146,101
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 .
72
24
146,102
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 ( ) ; } // set background color graphics2d . setColor ( backgroundColor ) ; graphics2d . fillRect ( 0 , 0 , targetSize . width , targetSize . height ) ; // scale the original image to fit the new size 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 ( ) ) ) ) ; } // position the original image in the center of the new 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 .
612
18
146,103
private static URI createSvg ( final Dimension targetSize , final RasterReference rasterReference , final Double rotation , final Color backgroundColor , final File workingDir ) throws IOException { // load SVG graphic final SVGElement svgRoot = parseSvg ( rasterReference . inputStream ) ; // create a new SVG graphic in which the existing graphic is embedded (scaled and rotated) 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 .
264
41
146,104
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" ) ; /* * To scale the SVG graphic and to apply the rotation, we distinguish two * cases: width and height is set on the original SVG or not. * * Case 1: Width and height is set * If width and height is set, we wrap the original SVG into 2 new SVG elements * and a container element. * * Example: * Original SVG: * <svg width="100" height="100"></svg> * * New SVG (scaled to 300x300 and rotated by 90 degree): * <svg width="300" height="300"> * <g transform="rotate(90.0 150 150)"> * <svg width="100%" height="100%" viewBox="0 0 100 100"> * <svg width="100" height="100"></svg> * </svg> * </g> * </svg> * * The requested size is set on the outermost <svg>. Then, the rotation is applied to the * <g> container and the scaling is achieved with the viewBox parameter on the 2nd <svg>. * * * Case 2: Width and height is not set * In this case the original SVG is wrapped into just one container and one new SVG element. * The rotation is set on the container, and the scaling happens automatically. * * Example: * Original SVG: * <svg viewBox="0 0 61.06 91.83"></svg> * * New SVG (scaled to 300x300 and rotated by 90 degree): * <svg width="300" height="300"> * <g transform="rotate(90.0 150 150)"> * <svg viewBox="0 0 61.06 91.83"></svg> * </g> * </svg> */ 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 .
869
24
146,105
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 .
190
17
146,106
public void setAttribute ( final String name , final Attribute attribute ) { if ( name . equals ( MAP_KEY ) ) { this . mapAttribute = ( MapAttribute ) attribute ; } }
Set the map attribute .
40
5
146,107
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 .
110
9
146,108
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 .
122
14
146,109
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 .
150
7
146,110
public final ProcessorDependencyGraph getProcessorGraph ( ) { if ( this . processorGraph == null ) { synchronized ( this ) { if ( this . processorGraph == null ) { final Map < String , Class < ? > > attcls = new HashMap <> ( ) ; for ( Map . Entry < String , Attribute > attribute : this . attributes . entrySet ( ) ) { attcls . put ( attribute . getKey ( ) , attribute . getValue ( ) . getValueType ( ) ) ; } this . processorGraph = this . processorGraphFactory . build ( this . processors , attcls ) ; } } } return this . processorGraph ; }
Get the processor graph to use for executing all the processors for the template .
144
15
146,111
@ SuppressWarnings ( "unchecked" ) @ Nonnull public final java . util . Optional < Style > getStyle ( final String styleName ) { final String styleRef = this . styles . get ( styleName ) ; Optional < Style > style ; if ( styleRef != null ) { style = ( Optional < Style > ) this . styleParser . loadStyle ( getConfiguration ( ) , this . httpRequestFactory , styleRef ) ; } else { style = Optional . empty ( ) ; } return or ( style , this . configuration . getStyle ( styleName ) ) ; }
Look for a style in the named styles provided in the configuration .
124
13
146,112
@ PostConstruct public void init ( ) { this . metricRegistry . register ( name ( "gc" ) , new GarbageCollectorMetricSet ( ) ) ; this . metricRegistry . register ( name ( "memory" ) , new MemoryUsageGaugeSet ( ) ) ; this . metricRegistry . register ( name ( "thread-states" ) , new ThreadStatesGaugeSet ( ) ) ; this . metricRegistry . register ( name ( "fd-usage" ) , new FileDescriptorRatioGauge ( ) ) ; }
Add several jvm metrics .
122
6
146,113
public void postConstruct ( ) throws URISyntaxException { WmsVersion . lookup ( this . version ) ; Assert . isTrue ( validateBaseUrl ( ) , "invalid baseURL" ) ; Assert . isTrue ( this . layers . length > 0 , "There must be at least one layer defined for a WMS request" + " to make sense" ) ; // OpenLayers 2 compatibility. It will post a single empty style no matter how many layers there are if ( this . styles != null && this . styles . length != this . layers . length && this . styles . length == 1 && this . styles [ 0 ] . trim ( ) . isEmpty ( ) ) { this . styles = null ; } else { Assert . isTrue ( this . styles == null || this . layers . length == this . styles . length , String . format ( "If styles are defined then there must be one for each layer. Number of" + " layers: %s\nStyles: %s" , this . layers . length , Arrays . toString ( this . styles ) ) ) ; } if ( this . imageFormat . indexOf ( ' ' ) < 0 ) { LOGGER . warn ( "The format {} should be a mime type" , this . imageFormat ) ; this . imageFormat = "image/" + this . imageFormat ; } Assert . isTrue ( this . method == HttpMethod . GET || this . method == HttpMethod . POST , String . format ( "Unsupported method %s for WMS layer" , this . method . toString ( ) ) ) ; }
Validate some of the properties of this layer .
345
10
146,114
@ Nonnull public BufferedImage createBufferedImage ( final int imageWidth , final int imageHeight ) { return new BufferedImage ( imageWidth , imageHeight , BufferedImage . TYPE_4BYTE_ABGR ) ; }
Create a buffered image with the correct image bands etc ... for the tiles being loaded .
50
18
146,115
public void setKeywords ( final List < String > keywords ) { StringBuilder builder = new StringBuilder ( ) ; for ( String keyword : keywords ) { if ( builder . length ( ) > 0 ) { builder . append ( ' ' ) ; } builder . append ( keyword . trim ( ) ) ; } this . keywords = Optional . of ( builder . toString ( ) ) ; }
The keywords to include in the PDF metadata .
81
9
146,116
protected String getKey ( final String ref , final String filename , final String extension ) { return prefix + ref + "/" + filename + "." + extension ; }
Compute the key to use .
34
7
146,117
private Object tryConvert ( final MfClientHttpRequestFactory clientHttpRequestFactory , final Object rowValue ) throws URISyntaxException , IOException { if ( this . converters . isEmpty ( ) ) { return rowValue ; } String value = String . valueOf ( rowValue ) ; for ( TableColumnConverter < ? > converter : this . converters ) { if ( converter . canConvert ( value ) ) { return converter . resolve ( clientHttpRequestFactory , value ) ; } } return rowValue ; }
If converters are set on a table this function tests if these can convert a cell value . The first converter which claims that it can convert will be used to do the conversion .
113
36
146,118
@ Override public final Integer optInt ( final String key ) { final int result = this . obj . optInt ( key , Integer . MIN_VALUE ) ; return result == Integer . MIN_VALUE ? null : result ; }
Get a property as a int or null .
48
9
146,119
@ Override public final Double optDouble ( final String key ) { double result = this . obj . optDouble ( key , Double . NaN ) ; if ( Double . isNaN ( result ) ) { return null ; } return result ; }
Get a property as a double or null .
52
9
146,120
@ Override public final Boolean optBool ( final String key ) { if ( this . obj . optString ( key , null ) == null ) { return null ; } else { return this . obj . optBoolean ( key ) ; } }
Get a property as a boolean or null .
52
9
146,121
public final PJsonObject optJSONObject ( final String key ) { final JSONObject val = this . obj . optJSONObject ( key ) ; return val != null ? new PJsonObject ( this , val , key ) : null ; }
Get a property as a json object or null .
50
10
146,122
public final PJsonArray getJSONArray ( final String key ) { final JSONArray val = this . obj . optJSONArray ( key ) ; if ( val == null ) { throw new ObjectMissingException ( this , key ) ; } return new PJsonArray ( this , val , key ) ; }
Get a property as a json array or throw exception .
63
11
146,123
public final PJsonArray optJSONArray ( final String key , final PJsonArray defaultValue ) { PJsonArray result = optJSONArray ( key ) ; return result != null ? result : defaultValue ; }
Get a property as a json array or default .
44
10
146,124
@ Override public final boolean has ( final String key ) { String result = this . obj . optString ( key , null ) ; return result != null ; }
Check if the object has a property with the key .
34
11
146,125
public void setAttributes ( final Map < String , Attribute > attributes ) { this . internalAttributes = attributes ; this . allAttributes . putAll ( attributes ) ; }
All the attributes needed either by the processors for each datasource row or by the jasper template .
35
20
146,126
public void setAttribute ( final String name , final Attribute attribute ) { if ( name . equals ( "datasource" ) ) { this . allAttributes . putAll ( ( ( DataSourceAttribute ) attribute ) . getAttributes ( ) ) ; } else if ( this . copyAttributes . contains ( name ) ) { this . allAttributes . put ( name , attribute ) ; } }
All the sub - level attributes .
81
7
146,127
@ Nonnull public String getBody ( ) { if ( body == null ) { return storage == null ? DEFAULT_BODY : DEFAULT_BODY_STORAGE ; } else { return body ; } }
Returns the configured body or the default value .
46
9
146,128
private boolean isTileVisible ( final ReferencedEnvelope tileBounds ) { if ( FloatingPointUtil . equals ( this . transformer . getRotation ( ) , 0.0 ) ) { return true ; } final GeometryFactory gfac = new GeometryFactory ( ) ; final Optional < Geometry > rotatedMapBounds = getRotatedMapBounds ( gfac ) ; if ( rotatedMapBounds . isPresent ( ) ) { return rotatedMapBounds . get ( ) . intersects ( gfac . toGeometry ( tileBounds ) ) ; } else { // in case of an error, we simply load the tile return true ; } }
When using a map rotation there might be tiles that are outside the rotated map area . To avoid to load these tiles this method checks if a tile is really required to draw the map .
143
37
146,129
private List < Rule > getStyleRules ( final String styleProperty ) { final List < Rule > styleRules = new ArrayList <> ( this . json . size ( ) ) ; for ( Iterator < String > iterator = this . json . keys ( ) ; iterator . hasNext ( ) ; ) { String styleKey = iterator . next ( ) ; if ( styleKey . equals ( JSON_STYLE_PROPERTY ) || styleKey . equals ( MapfishStyleParserPlugin . JSON_VERSION ) ) { continue ; } PJsonObject styleJson = this . json . getJSONObject ( styleKey ) ; final List < Rule > currentRules = createStyleRule ( styleKey , styleJson , styleProperty ) ; for ( Rule currentRule : currentRules ) { if ( currentRule != null ) { styleRules . add ( currentRule ) ; } } } return styleRules ; }
Creates SLD rules for each old style .
189
10
146,130
public void setHeaders ( final Set < String > names ) { // transform to lower-case because header names should be case-insensitive Set < String > lowerCaseNames = new HashSet <> ( ) ; for ( String name : names ) { lowerCaseNames . add ( name . toLowerCase ( ) ) ; } this . headerNames = lowerCaseNames ; }
Set the header names to forward from the request . Should not be defined if all is set to true
79
20
146,131
public static Multimap < String , String > convertToMultiMap ( final PObject objectParams ) { Multimap < String , String > params = HashMultimap . create ( ) ; if ( objectParams != null ) { Iterator < String > customParamsIter = objectParams . keys ( ) ; while ( customParamsIter . hasNext ( ) ) { String key = customParamsIter . next ( ) ; if ( objectParams . isArray ( key ) ) { final PArray array = objectParams . optArray ( key ) ; for ( int i = 0 ; i < array . size ( ) ; i ++ ) { params . put ( key , array . getString ( i ) ) ; } } else { params . put ( key , objectParams . optString ( key , "" ) ) ; } } } return params ; }
convert a param object to a multimap .
186
10
146,132
public Envelope getMaxExtent ( ) { final int minX = 0 ; final int maxX = 1 ; final int minY = 2 ; final int maxY = 3 ; return new Envelope ( this . maxExtent [ minX ] , this . maxExtent [ minY ] , this . maxExtent [ maxX ] , this . maxExtent [ maxY ] ) ; }
Get the max extent as a envelop object .
87
9
146,133
public final void setConfigurationFiles ( final Map < String , String > configurationFiles ) throws URISyntaxException { this . configurationFiles . clear ( ) ; this . configurationFileLastModifiedTimes . clear ( ) ; for ( Map . Entry < String , String > entry : configurationFiles . entrySet ( ) ) { if ( ! entry . getValue ( ) . contains ( ":/" ) ) { // assume is a file this . configurationFiles . put ( entry . getKey ( ) , new File ( entry . getValue ( ) ) . toURI ( ) ) ; } else { this . configurationFiles . put ( entry . getKey ( ) , new URI ( entry . getValue ( ) ) ) ; } } if ( this . configFileLoader != null ) { this . validateConfigurationFiles ( ) ; } }
The setter for setting configuration file . It will convert the value to a URI .
173
17
146,134
public final ZoomToFeatures copy ( ) { ZoomToFeatures obj = new ZoomToFeatures ( ) ; obj . zoomType = this . zoomType ; obj . minScale = this . minScale ; obj . minMargin = this . minMargin ; return obj ; }
Make a copy .
57
4
146,135
public String getFullContentType ( ) { final String url = this . url . toExternalForm ( ) . substring ( "data:" . length ( ) ) ; final int endIndex = url . indexOf ( ' ' ) ; if ( endIndex >= 0 ) { final String contentType = url . substring ( 0 , endIndex ) ; if ( ! contentType . isEmpty ( ) ) { return contentType ; } } return "text/plain;charset=US-ASCII" ; }
Get the content - type including the optional ; base64 .
108
12
146,136
@ Override public final Optional < Boolean > tryOverrideValidation ( final MatchInfo matchInfo ) throws SocketException , UnknownHostException , MalformedURLException { for ( AddressHostMatcher addressHostMatcher : this . matchersForHost ) { if ( addressHostMatcher . matches ( matchInfo ) ) { return Optional . empty ( ) ; } } return Optional . of ( false ) ; }
Check the given URI to see if it matches .
86
10
146,137
public final void setHost ( final String host ) throws UnknownHostException { this . host = host ; final InetAddress [ ] inetAddresses = InetAddress . getAllByName ( host ) ; for ( InetAddress address : inetAddresses ) { final AddressHostMatcher matcher = new AddressHostMatcher ( ) ; matcher . setIp ( address . getHostAddress ( ) ) ; this . matchersForHost . add ( matcher ) ; } }
Set the host .
104
4
146,138
@ SuppressWarnings ( "unchecked" ) public Multimap < String , Processor > getAllRequiredAttributes ( ) { Multimap < String , Processor > requiredInputs = HashMultimap . create ( ) ; for ( ProcessorGraphNode root : this . roots ) { final BiMap < String , String > inputMapper = root . getInputMapper ( ) ; for ( String attr : inputMapper . keySet ( ) ) { requiredInputs . put ( attr , root . getProcessor ( ) ) ; } final Object inputParameter = root . getProcessor ( ) . createInputParameter ( ) ; if ( inputParameter instanceof Values ) { continue ; } else if ( inputParameter != null ) { final Class < ? > inputParameterClass = inputParameter . getClass ( ) ; final Set < String > requiredAttributesDefinedInInputParameter = getAttributeNames ( inputParameterClass , FILTER_ONLY_REQUIRED_ATTRIBUTES ) ; for ( String attName : requiredAttributesDefinedInInputParameter ) { try { if ( inputParameterClass . getField ( attName ) . getType ( ) == Values . class ) { continue ; } } catch ( NoSuchFieldException e ) { throw new RuntimeException ( e ) ; } String mappedName = ProcessorUtils . getInputValueName ( root . getProcessor ( ) . getInputPrefix ( ) , inputMapper , attName ) ; requiredInputs . put ( mappedName , root . getProcessor ( ) ) ; } } } return requiredInputs ; }
Get all the names of inputs that are required to be in the Values object when this graph is executed .
337
21
146,139
public Set < Processor < ? , ? > > getAllProcessors ( ) { IdentityHashMap < Processor < ? , ? > , Void > all = new IdentityHashMap <> ( ) ; for ( ProcessorGraphNode < ? , ? > root : this . roots ) { for ( Processor p : root . getAllProcessors ( ) ) { all . put ( p , null ) ; } } return all . keySet ( ) ; }
Create a set containing all the processors in the graph .
93
11
146,140
public void validate ( final List < Throwable > validationErrors ) { if ( this . matchers == null ) { validationErrors . add ( new IllegalArgumentException ( "Matchers cannot be null. There should be at least a !acceptAll matcher" ) ) ; } if ( this . matchers != null && this . matchers . isEmpty ( ) ) { validationErrors . add ( new IllegalArgumentException ( "There are no url matchers defined. There should be at least a " + "!acceptAll matcher" ) ) ; } }
Validate the configuration .
121
5
146,141
@ PostConstruct public final void init ( ) throws URISyntaxException { final String address = getConfig ( ADDRESS , null ) ; if ( address != null ) { final URI uri = new URI ( "udp://" + address ) ; final String prefix = getConfig ( PREFIX , "mapfish-print" ) . replace ( "%h" , getHostname ( ) ) ; final int period = Integer . parseInt ( getConfig ( PERIOD , "10" ) ) ; LOGGER . info ( "Starting a StatsD reporter targeting {} with prefix {} and period {}s" , uri , prefix , period ) ; this . reporter = StatsDReporter . forRegistry ( this . metricRegistry ) . prefixedWith ( prefix ) . build ( uri . getHost ( ) , uri . getPort ( ) ) ; this . reporter . start ( period , TimeUnit . SECONDS ) ; } }
Start the StatsD reporter if configured .
201
8
146,142
public static MapBounds adjustBoundsToScaleAndMapSize ( final GenericMapAttributeValues mapValues , final Rectangle paintArea , final MapBounds bounds , final double dpi ) { MapBounds newBounds = bounds ; if ( mapValues . isUseNearestScale ( ) ) { newBounds = newBounds . adjustBoundsToNearestScale ( mapValues . getZoomLevels ( ) , mapValues . getZoomSnapTolerance ( ) , mapValues . getZoomLevelSnapStrategy ( ) , mapValues . getZoomSnapGeodetic ( ) , paintArea , dpi ) ; } newBounds = new BBoxMapBounds ( newBounds . toReferencedEnvelope ( paintArea ) ) ; if ( mapValues . isUseAdjustBounds ( ) ) { newBounds = newBounds . adjustedEnvelope ( paintArea ) ; } return newBounds ; }
If requested adjust the bounds to the nearest scale and the map size .
202
14
146,143
public static SVGGraphics2D createSvgGraphics ( final Dimension size ) throws ParserConfigurationException { DocumentBuilderFactory dbf = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder db = dbf . newDocumentBuilder ( ) ; Document document = db . getDOMImplementation ( ) . createDocument ( null , "svg" , null ) ; SVGGeneratorContext ctx = SVGGeneratorContext . createDefault ( document ) ; ctx . setStyleHandler ( new OpacityAdjustingStyleHandler ( ) ) ; ctx . setComment ( "Generated by GeoTools2 with Batik SVG Generator" ) ; SVGGraphics2D g2d = new SVGGraphics2D ( ctx , true ) ; g2d . setSVGCanvasSize ( size ) ; return g2d ; }
Create a SVG graphic with the give dimensions .
174
9
146,144
public static void saveSvgFile ( final SVGGraphics2D graphics2d , final File path ) throws IOException { try ( FileOutputStream fs = new FileOutputStream ( path ) ; OutputStreamWriter outputStreamWriter = new OutputStreamWriter ( fs , StandardCharsets . UTF_8 ) ; Writer osw = new BufferedWriter ( outputStreamWriter ) ) { graphics2d . stream ( osw , true ) ; } }
Save a SVG graphic to the given path .
94
9
146,145
@ Nonnull private ReferencedEnvelope getFeatureBounds ( final MfClientHttpRequestFactory clientHttpRequestFactory , final MapAttributeValues mapValues , final ExecutionContext context ) { final MapfishMapContext mapContext = createMapContext ( mapValues ) ; String layerName = mapValues . zoomToFeatures . layer ; ReferencedEnvelope bounds = new ReferencedEnvelope ( ) ; for ( MapLayer layer : mapValues . getLayers ( ) ) { context . stopIfCanceled ( ) ; if ( ( ! StringUtils . isEmpty ( layerName ) && layerName . equals ( layer . getName ( ) ) ) || ( StringUtils . isEmpty ( layerName ) && layer instanceof AbstractFeatureSourceLayer ) ) { AbstractFeatureSourceLayer featureLayer = ( AbstractFeatureSourceLayer ) layer ; FeatureSource < ? , ? > featureSource = featureLayer . getFeatureSource ( clientHttpRequestFactory , mapContext ) ; FeatureCollection < ? , ? > features ; try { features = featureSource . getFeatures ( ) ; } catch ( IOException e ) { throw ExceptionUtils . getRuntimeException ( e ) ; } if ( ! features . isEmpty ( ) ) { final ReferencedEnvelope curBounds = features . getBounds ( ) ; bounds . expandToInclude ( curBounds ) ; } } } return bounds ; }
Get the bounding - box containing all features of all layers .
296
13
146,146
public final File getJasperCompilation ( final Configuration configuration ) { File jasperCompilation = new File ( getWorking ( configuration ) , "jasper-bin" ) ; createIfMissing ( jasperCompilation , "Jasper Compilation" ) ; return jasperCompilation ; }
Get the directory where the compiled jasper reports should be put .
61
13
146,147
public final File getTaskDirectory ( ) { createIfMissing ( this . working , "Working" ) ; try { return Files . createTempDirectory ( this . working . toPath ( ) , TASK_DIR_PREFIX ) . toFile ( ) ; } catch ( IOException e ) { throw new AssertionError ( "Unable to create temporary directory in '" + this . working + "'" ) ; } }
Creates and returns a temporary directory for a printing task .
92
12
146,148
public final void removeDirectory ( final File directory ) { try { FileUtils . deleteDirectory ( directory ) ; } catch ( IOException e ) { LOGGER . error ( "Unable to delete directory '{}'" , directory ) ; } }
Deletes the given directory .
52
6
146,149
public final File getBuildFileFor ( final Configuration configuration , final File jasperFileXml , final String extension , final Logger logger ) { final String configurationAbsolutePath = configuration . getDirectory ( ) . getPath ( ) ; final int prefixToConfiguration = configurationAbsolutePath . length ( ) + 1 ; final String parentDir = jasperFileXml . getAbsoluteFile ( ) . getParent ( ) ; final String relativePathToFile ; if ( configurationAbsolutePath . equals ( parentDir ) ) { relativePathToFile = FilenameUtils . getBaseName ( jasperFileXml . getName ( ) ) ; } else { final String relativePathToContainingDirectory = parentDir . substring ( prefixToConfiguration ) ; relativePathToFile = relativePathToContainingDirectory + File . separator + FilenameUtils . getBaseName ( jasperFileXml . getName ( ) ) ; } final File buildFile = new File ( getJasperCompilation ( configuration ) , relativePathToFile + extension ) ; if ( ! buildFile . getParentFile ( ) . exists ( ) && ! buildFile . getParentFile ( ) . mkdirs ( ) ) { logger . error ( "Unable to create directory for containing compiled jasper report templates: {}" , buildFile . getParentFile ( ) ) ; } return buildFile ; }
Calculate the file to compile a jasper report template to .
293
14
146,150
public static URI createRestURI ( final String matrixId , final int row , final int col , final WMTSLayerParam layerParam ) throws URISyntaxException { String path = layerParam . baseURL ; if ( layerParam . dimensions != null ) { for ( int i = 0 ; i < layerParam . dimensions . length ; i ++ ) { String dimension = layerParam . dimensions [ i ] ; String value = layerParam . dimensionParams . optString ( dimension ) ; if ( value == null ) { value = layerParam . dimensionParams . getString ( dimension . toUpperCase ( ) ) ; } path = path . replace ( "{" + dimension + "}" , value ) ; } } path = path . replace ( "{TileMatrixSet}" , layerParam . matrixSet ) ; path = path . replace ( "{TileMatrix}" , matrixId ) ; path = path . replace ( "{TileRow}" , String . valueOf ( row ) ) ; path = path . replace ( "{TileCol}" , String . valueOf ( col ) ) ; path = path . replace ( "{style}" , layerParam . style ) ; path = path . replace ( "{Layer}" , layerParam . layer ) ; return new URI ( path ) ; }
Prepare the baseURL to make a request .
264
10
146,151
public final String getPath ( final String key ) { StringBuilder result = new StringBuilder ( ) ; addPathTo ( result ) ; result . append ( "." ) ; result . append ( getPathElement ( key ) ) ; return result . toString ( ) ; }
Gets the string representation of the path to the current JSON element .
57
14
146,152
protected final void addPathTo ( final StringBuilder result ) { if ( this . parent != null ) { this . parent . addPathTo ( result ) ; if ( ! ( this . parent instanceof PJsonArray ) ) { result . append ( "." ) ; } } result . append ( getPathElement ( this . contextName ) ) ; }
Append the path to the StringBuilder .
74
9
146,153
public static void main ( final String [ ] args ) { if ( System . getProperty ( "db.name" ) == null ) { System . out . println ( "Not running in multi-instance mode: no DB to connect to" ) ; System . exit ( 1 ) ; } while ( true ) { try { Class . forName ( "org.postgresql.Driver" ) ; DriverManager . getConnection ( "jdbc:postgresql://" + System . getProperty ( "db.host" ) + ":5432/" + System . getProperty ( "db.name" ) , System . getProperty ( "db.username" ) , System . getProperty ( "db.password" ) ) ; System . out . println ( "Opened database successfully. Running in multi-instance mode" ) ; System . exit ( 0 ) ; return ; } catch ( Exception e ) { System . out . println ( "Failed to connect to the DB: " + e . toString ( ) ) ; try { Thread . sleep ( 1000 ) ; } catch ( InterruptedException e1 ) { //ignored } } } }
A comment .
243
3
146,154
private void started ( final ProcessorGraphNode processorGraphNode ) { this . processorLock . lock ( ) ; try { this . runningProcessors . put ( processorGraphNode . getProcessor ( ) , null ) ; } finally { this . processorLock . unlock ( ) ; } }
Flag that the processor has started execution .
59
8
146,155
public boolean isRunning ( final ProcessorGraphNode processorGraphNode ) { this . processorLock . lock ( ) ; try { return this . runningProcessors . containsKey ( processorGraphNode . getProcessor ( ) ) ; } finally { this . processorLock . unlock ( ) ; } }
Return true if the processor of the node is currently being executed .
60
13
146,156
public boolean isFinished ( final ProcessorGraphNode processorGraphNode ) { this . processorLock . lock ( ) ; try { return this . executedProcessors . containsKey ( processorGraphNode . getProcessor ( ) ) ; } finally { this . processorLock . unlock ( ) ; } }
Return true if the processor of the node has previously been executed .
61
13
146,157
public void finished ( final ProcessorGraphNode processorGraphNode ) { this . processorLock . lock ( ) ; try { this . runningProcessors . remove ( processorGraphNode . getProcessor ( ) ) ; this . executedProcessors . put ( processorGraphNode . getProcessor ( ) , null ) ; } finally { this . processorLock . unlock ( ) ; } }
Flag that the processor has completed execution .
78
8
146,158
public final void draw ( ) { AffineTransform transform = new AffineTransform ( this . transform ) ; transform . concatenate ( getAlignmentTransform ( ) ) ; // draw the background box this . graphics2d . setTransform ( transform ) ; this . graphics2d . setColor ( this . params . getBackgroundColor ( ) ) ; this . graphics2d . fillRect ( 0 , 0 , this . settings . getSize ( ) . width , this . settings . getSize ( ) . height ) ; //draw the labels this . graphics2d . setColor ( this . params . getFontColor ( ) ) ; drawLabels ( transform , this . params . getOrientation ( ) , this . params . getLabelRotation ( ) ) ; //sets the transformation for drawing the bar and do it final AffineTransform lineTransform = new AffineTransform ( transform ) ; setLineTranslate ( lineTransform ) ; if ( this . params . getOrientation ( ) == Orientation . VERTICAL_LABELS_LEFT || this . params . getOrientation ( ) == Orientation . VERTICAL_LABELS_RIGHT ) { final AffineTransform rotate = AffineTransform . getQuadrantRotateInstance ( 1 ) ; lineTransform . concatenate ( rotate ) ; } this . graphics2d . setTransform ( lineTransform ) ; this . graphics2d . setStroke ( new BasicStroke ( this . settings . getLineWidth ( ) ) ) ; this . graphics2d . setColor ( this . params . getColor ( ) ) ; drawBar ( ) ; }
Start the rendering of the scalebar .
347
8
146,159
private AffineTransform getAlignmentTransform ( ) { final int offsetX ; switch ( this . settings . getParams ( ) . getAlign ( ) ) { case LEFT : offsetX = 0 ; break ; case RIGHT : offsetX = this . settings . getMaxSize ( ) . width - this . settings . getSize ( ) . width ; break ; case CENTER : default : offsetX = ( int ) Math . floor ( this . settings . getMaxSize ( ) . width / 2.0 - this . settings . getSize ( ) . width / 2.0 ) ; break ; } final int offsetY ; switch ( this . settings . getParams ( ) . getVerticalAlign ( ) ) { case TOP : offsetY = 0 ; break ; case BOTTOM : offsetY = this . settings . getMaxSize ( ) . height - this . settings . getSize ( ) . height ; break ; case MIDDLE : default : offsetY = ( int ) Math . floor ( this . settings . getMaxSize ( ) . height / 2.0 - this . settings . getSize ( ) . height / 2.0 ) ; break ; } return AffineTransform . getTranslateInstance ( Math . round ( offsetX ) , Math . round ( offsetY ) ) ; }
Create a transformation which takes the alignment settings into account .
277
11
146,160
protected final MapfishMapContext getLayerTransformer ( final MapfishMapContext transformer ) { MapfishMapContext layerTransformer = transformer ; if ( ! FloatingPointUtil . equals ( transformer . getRotation ( ) , 0.0 ) && ! this . supportsNativeRotation ( ) ) { // if a rotation is set and the rotation can not be handled natively // by the layer, we have to adjust the bounds and map size layerTransformer = new MapfishMapContext ( transformer , transformer . getRotatedBoundsAdjustedForPreciseRotatedMapSize ( ) , transformer . getRotatedMapSize ( ) , 0 , transformer . getDPI ( ) , transformer . isForceLongitudeFirst ( ) , transformer . isDpiSensitiveStyle ( ) ) ; } return layerTransformer ; }
If the layer transformer has not been prepared yet do it .
172
12
146,161
public static void log ( final String templateName , final Template template , final Values values ) { new ValuesLogger ( ) . doLog ( templateName , template , values ) ; }
Log the values for the provided template .
38
8
146,162
private static String getFileName ( @ Nullable final MapPrinter mapPrinter , final PJsonObject spec ) { String fileName = spec . optString ( Constants . OUTPUT_FILENAME_KEY ) ; if ( fileName != null ) { return fileName ; } if ( mapPrinter != null ) { final Configuration config = mapPrinter . getConfiguration ( ) ; final String templateName = spec . getString ( Constants . JSON_LAYOUT_KEY ) ; final Template template = config . getTemplate ( templateName ) ; if ( template . getOutputFilename ( ) != null ) { return template . getOutputFilename ( ) ; } if ( config . getOutputFilename ( ) != null ) { return config . getOutputFilename ( ) ; } } return "mapfish-print-report" ; }
Read filename from spec .
175
5
146,163
protected PrintResult withOpenOutputStream ( final PrintAction function ) throws Exception { final File reportFile = getReportFile ( ) ; final Processor . ExecutionContext executionContext ; try ( FileOutputStream out = new FileOutputStream ( reportFile ) ; BufferedOutputStream bout = new BufferedOutputStream ( out ) ) { executionContext = function . run ( bout ) ; } return new PrintResult ( reportFile . length ( ) , executionContext ) ; }
Open an OutputStream and execute the function using the OutputStream .
95
13
146,164
static Style get ( final GridParam params ) { final StyleBuilder builder = new StyleBuilder ( ) ; final Symbolizer pointSymbolizer = crossSymbolizer ( "shape://plus" , builder , CROSS_SIZE , params . gridColor ) ; final Style style = builder . createStyle ( pointSymbolizer ) ; final List < Symbolizer > symbolizers = style . featureTypeStyles ( ) . get ( 0 ) . rules ( ) . get ( 0 ) . symbolizers ( ) ; if ( params . haloRadius > 0.0 ) { Symbolizer halo = crossSymbolizer ( "cross" , builder , CROSS_SIZE + params . haloRadius * 2.0 , params . haloColor ) ; symbolizers . add ( 0 , halo ) ; } return style ; }
Create the Grid Point style .
174
6
146,165
public Scale get ( final int index , final DistanceUnit unit ) { return new Scale ( this . scaleDenominators [ index ] , unit , PDF_DPI ) ; }
Get the scale at the given index .
37
8
146,166
public double [ ] getScaleDenominators ( ) { double [ ] dest = new double [ this . scaleDenominators . length ] ; System . arraycopy ( this . scaleDenominators , 0 , dest , 0 , this . scaleDenominators . length ) ; return dest ; }
Return a copy of the zoom level scale denominators . Scales are sorted greatest to least .
62
19
146,167
public final SimpleFeatureCollection autoTreat ( final Template template , final String features ) throws IOException { SimpleFeatureCollection featuresCollection = treatStringAsURL ( template , features ) ; if ( featuresCollection == null ) { featuresCollection = treatStringAsGeoJson ( features ) ; } return featuresCollection ; }
Get the features collection from a GeoJson inline string or URL .
65
14
146,168
public final SimpleFeatureCollection treatStringAsURL ( final Template template , final String geoJsonUrl ) throws IOException { URL url ; try { url = FileUtils . testForLegalFileUrl ( template . getConfiguration ( ) , new URL ( geoJsonUrl ) ) ; } catch ( MalformedURLException e ) { return null ; } final String geojsonString ; if ( url . getProtocol ( ) . equalsIgnoreCase ( "file" ) ) { geojsonString = IOUtils . toString ( url , Constants . DEFAULT_CHARSET . name ( ) ) ; } else { geojsonString = URIUtils . toString ( this . httpRequestFactory , url ) ; } return treatStringAsGeoJson ( geojsonString ) ; }
Get the features collection from a GeoJson URL .
174
11
146,169
@ Override public boolean supportsNativeRotation ( ) { return this . params . useNativeAngle && ( this . params . serverType == WmsLayerParam . ServerType . MAPSERVER || this . params . serverType == WmsLayerParam . ServerType . GEOSERVER ) ; }
If supported by the WMS server a parameter angle can be set on customParams or mergeableParams . In this case the rotation will be done natively by the WMS .
64
38
146,170
protected static File platformIndependentUriToFile ( final URI fileURI ) { File file ; try { file = new File ( fileURI ) ; } catch ( IllegalArgumentException e ) { if ( fileURI . toString ( ) . startsWith ( "file://" ) ) { file = new File ( fileURI . toString ( ) . substring ( "file://" . length ( ) ) ) ; } else { throw e ; } } return file ; }
Convert a url to a file object . No checks are made to see if file exists but there are some hacks that are needed to convert uris to files across platforms .
99
35
146,171
public static String getContext ( final PObject [ ] objs ) { StringBuilder result = new StringBuilder ( "(" ) ; boolean first = true ; for ( PObject obj : objs ) { if ( ! first ) { result . append ( ' ' ) ; } first = false ; result . append ( obj . getCurrentPath ( ) ) ; } result . append ( ' ' ) ; return result . toString ( ) ; }
Build the context name .
92
5
146,172
public final void save ( final PrintJobStatusExtImpl entry ) { getSession ( ) . merge ( entry ) ; getSession ( ) . flush ( ) ; getSession ( ) . evict ( entry ) ; }
Save Job Record .
44
4
146,173
public final Object getValue ( final String id , final String property ) { final CriteriaBuilder builder = getSession ( ) . getCriteriaBuilder ( ) ; final CriteriaQuery < Object > criteria = builder . createQuery ( Object . class ) ; final Root < PrintJobStatusExtImpl > root = criteria . from ( PrintJobStatusExtImpl . class ) ; criteria . select ( root . get ( property ) ) ; criteria . where ( builder . equal ( root . get ( "referenceId" ) , id ) ) ; return getSession ( ) . createQuery ( criteria ) . uniqueResult ( ) ; }
get specific property value of job .
128
7
146,174
public final void cancelOld ( final long starttimeThreshold , final long checkTimeThreshold , final String message ) { final CriteriaBuilder builder = getSession ( ) . getCriteriaBuilder ( ) ; final CriteriaUpdate < PrintJobStatusExtImpl > update = builder . createCriteriaUpdate ( PrintJobStatusExtImpl . class ) ; final Root < PrintJobStatusExtImpl > root = update . from ( PrintJobStatusExtImpl . class ) ; update . where ( builder . and ( builder . equal ( root . get ( "status" ) , PrintJobStatus . Status . WAITING ) , builder . or ( builder . lessThan ( root . get ( "entry" ) . get ( "startTime" ) , starttimeThreshold ) , builder . and ( builder . isNotNull ( root . get ( "lastCheckTime" ) ) , builder . lessThan ( root . get ( "lastCheckTime" ) , checkTimeThreshold ) ) ) ) ) ; update . set ( root . get ( "status" ) , PrintJobStatus . Status . CANCELLED ) ; update . set ( root . get ( "error" ) , message ) ; getSession ( ) . createQuery ( update ) . executeUpdate ( ) ; }
Cancel old waiting jobs .
268
6
146,175
public final void updateLastCheckTime ( final String id , final long lastCheckTime ) { final CriteriaBuilder builder = getSession ( ) . getCriteriaBuilder ( ) ; final CriteriaUpdate < PrintJobStatusExtImpl > update = builder . createCriteriaUpdate ( PrintJobStatusExtImpl . class ) ; final Root < PrintJobStatusExtImpl > root = update . from ( PrintJobStatusExtImpl . class ) ; update . where ( builder . equal ( root . get ( "referenceId" ) , id ) ) ; update . set ( root . get ( "lastCheckTime" ) , lastCheckTime ) ; getSession ( ) . createQuery ( update ) . executeUpdate ( ) ; }
Update the lastCheckTime of the given record .
149
10
146,176
public final int deleteOld ( final long checkTimeThreshold ) { final CriteriaBuilder builder = getSession ( ) . getCriteriaBuilder ( ) ; final CriteriaDelete < PrintJobStatusExtImpl > delete = builder . createCriteriaDelete ( PrintJobStatusExtImpl . class ) ; final Root < PrintJobStatusExtImpl > root = delete . from ( PrintJobStatusExtImpl . class ) ; delete . where ( builder . and ( builder . isNotNull ( root . get ( "lastCheckTime" ) ) , builder . lessThan ( root . get ( "lastCheckTime" ) , checkTimeThreshold ) ) ) ; return getSession ( ) . createQuery ( delete ) . executeUpdate ( ) ; }
Delete old jobs .
154
4
146,177
public final List < PrintJobStatusExtImpl > poll ( final int size ) { final CriteriaBuilder builder = getSession ( ) . getCriteriaBuilder ( ) ; final CriteriaQuery < PrintJobStatusExtImpl > criteria = builder . createQuery ( PrintJobStatusExtImpl . class ) ; final Root < PrintJobStatusExtImpl > root = criteria . from ( PrintJobStatusExtImpl . class ) ; root . alias ( "pj" ) ; criteria . where ( builder . equal ( root . get ( "status" ) , PrintJobStatus . Status . WAITING ) ) ; criteria . orderBy ( builder . asc ( root . get ( "entry" ) . get ( "startTime" ) ) ) ; final Query < PrintJobStatusExtImpl > query = getSession ( ) . createQuery ( criteria ) ; query . setMaxResults ( size ) ; // LOCK but don't wait for release (since this is run continuously // anyway, no wait prevents deadlock) query . setLockMode ( "pj" , LockMode . UPGRADE_NOWAIT ) ; try { return query . getResultList ( ) ; } catch ( PessimisticLockException ex ) { // Another process was polling at the same time. We can ignore this error return Collections . emptyList ( ) ; } }
Poll for the next N waiting jobs in line .
279
10
146,178
public final PrintJobResultExtImpl getResult ( final URI reportURI ) { final CriteriaBuilder builder = getSession ( ) . getCriteriaBuilder ( ) ; final CriteriaQuery < PrintJobResultExtImpl > criteria = builder . createQuery ( PrintJobResultExtImpl . class ) ; final Root < PrintJobResultExtImpl > root = criteria . from ( PrintJobResultExtImpl . class ) ; criteria . where ( builder . equal ( root . get ( "reportURI" ) , reportURI . toString ( ) ) ) ; return getSession ( ) . createQuery ( criteria ) . uniqueResult ( ) ; }
Get result report .
131
4
146,179
public void delete ( final String referenceId ) { final CriteriaBuilder builder = getSession ( ) . getCriteriaBuilder ( ) ; final CriteriaDelete < PrintJobStatusExtImpl > delete = builder . createCriteriaDelete ( PrintJobStatusExtImpl . class ) ; final Root < PrintJobStatusExtImpl > root = delete . from ( PrintJobStatusExtImpl . class ) ; delete . where ( builder . equal ( root . get ( "referenceId" ) , referenceId ) ) ; getSession ( ) . createQuery ( delete ) . executeUpdate ( ) ; }
Delete a record .
121
4
146,180
public final void configureAccess ( final Template template , final ApplicationContext context ) { final Configuration configuration = template . getConfiguration ( ) ; AndAccessAssertion accessAssertion = context . getBean ( AndAccessAssertion . class ) ; accessAssertion . setPredicates ( configuration . getAccessAssertion ( ) , template . getAccessAssertion ( ) ) ; this . access = accessAssertion ; }
Configure the access permissions required to access this print job .
92
12
146,181
protected final < T > StyleSupplier < T > createStyleSupplier ( final Template template , final String styleRef ) { return new StyleSupplier < T > ( ) { @ Override public Style load ( final MfClientHttpRequestFactory requestFactory , final T featureSource ) { final StyleParser parser = AbstractGridCoverageLayerPlugin . this . styleParser ; return OptionalUtils . or ( ( ) -> template . getStyle ( styleRef ) , ( ) -> parser . loadStyle ( template . getConfiguration ( ) , requestFactory , styleRef ) ) . orElse ( template . getConfiguration ( ) . getDefaultStyle ( NAME ) ) ; } } ; }
Common method for creating styles .
141
6
146,182
private void store ( final PrintJobStatus printJobStatus ) throws JSONException { JSONObject metadata = new JSONObject ( ) ; metadata . put ( JSON_REQUEST_DATA , printJobStatus . getEntry ( ) . getRequestData ( ) . getInternalObj ( ) ) ; metadata . put ( JSON_STATUS , printJobStatus . getStatus ( ) . toString ( ) ) ; metadata . put ( JSON_START_DATE , printJobStatus . getStartTime ( ) ) ; metadata . put ( JSON_REQUEST_COUNT , printJobStatus . getRequestCount ( ) ) ; if ( printJobStatus . getCompletionDate ( ) != null ) { metadata . put ( JSON_COMPLETION_DATE , printJobStatus . getCompletionTime ( ) ) ; } metadata . put ( JSON_ACCESS_ASSERTION , this . assertionPersister . marshal ( printJobStatus . getAccess ( ) ) ) ; if ( printJobStatus . getError ( ) != null ) { metadata . put ( JSON_ERROR , printJobStatus . getError ( ) ) ; } if ( printJobStatus . getResult ( ) != null ) { metadata . put ( JSON_REPORT_URI , printJobStatus . getResult ( ) . getReportURIString ( ) ) ; metadata . put ( JSON_FILENAME , printJobStatus . getResult ( ) . getFileName ( ) ) ; metadata . put ( JSON_FILE_EXT , printJobStatus . getResult ( ) . getFileExtension ( ) ) ; metadata . put ( JSON_MIME_TYPE , printJobStatus . getResult ( ) . getMimeType ( ) ) ; } this . registry . put ( RESULT_METADATA + printJobStatus . getReferenceId ( ) , metadata ) ; }
Store the data of a print job in the registry .
387
11
146,183
public static boolean canParseColor ( final String colorString ) { try { return ColorParser . toColor ( colorString ) != null ; } catch ( Exception exc ) { return false ; } }
Check if the given color string can be parsed .
41
10
146,184
private static Dimension adaptTileDimensions ( final Dimension pixels , final int maxWidth , final int maxHeight ) { return new Dimension ( adaptTileDimension ( pixels . width , maxWidth ) , adaptTileDimension ( pixels . height , maxHeight ) ) ; }
Adapt the size of the tiles so that we have the same amount of tiles as we would have had with maxWidth and maxHeight but with the smallest tiles as possible .
55
34
146,185
public static Multimap < String , String > getParameters ( final String rawQuery ) { Multimap < String , String > result = HashMultimap . create ( ) ; if ( rawQuery == null ) { return result ; } StringTokenizer tokens = new StringTokenizer ( rawQuery , "&" ) ; while ( tokens . hasMoreTokens ( ) ) { String pair = tokens . nextToken ( ) ; int pos = pair . indexOf ( ' ' ) ; String key ; String value ; if ( pos == - 1 ) { key = pair ; value = "" ; } else { try { key = URLDecoder . decode ( pair . substring ( 0 , pos ) , "UTF-8" ) ; value = URLDecoder . decode ( pair . substring ( pos + 1 ) , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { throw ExceptionUtils . getRuntimeException ( e ) ; } } result . put ( key , value ) ; } return result ; }
Parse the URI and get all the parameters in map form . Query name - &gt ; List of Query values .
217
24
146,186
public static URI setQueryParams ( final URI initialUri , final Multimap < String , String > queryParams ) { StringBuilder queryString = new StringBuilder ( ) ; for ( Map . Entry < String , String > entry : queryParams . entries ( ) ) { if ( queryString . length ( ) > 0 ) { queryString . append ( "&" ) ; } queryString . append ( entry . getKey ( ) ) . append ( "=" ) . append ( entry . getValue ( ) ) ; } try { if ( initialUri . getHost ( ) == null && initialUri . getAuthority ( ) != null ) { return new URI ( initialUri . getScheme ( ) , initialUri . getAuthority ( ) , initialUri . getPath ( ) , queryString . toString ( ) , initialUri . getFragment ( ) ) ; } else { return new URI ( initialUri . getScheme ( ) , initialUri . getUserInfo ( ) , initialUri . getHost ( ) , initialUri . getPort ( ) , initialUri . getPath ( ) , queryString . toString ( ) , initialUri . getFragment ( ) ) ; } } catch ( URISyntaxException e ) { throw ExceptionUtils . getRuntimeException ( e ) ; } }
Construct a new uri by replacing query parameters in initialUri with the query parameters provided .
292
19
146,187
public static URI setPath ( final URI initialUri , final String path ) { String finalPath = path ; if ( ! finalPath . startsWith ( "/" ) ) { finalPath = ' ' + path ; } try { if ( initialUri . getHost ( ) == null && initialUri . getAuthority ( ) != null ) { return new URI ( initialUri . getScheme ( ) , initialUri . getAuthority ( ) , finalPath , initialUri . getQuery ( ) , initialUri . getFragment ( ) ) ; } else { return new URI ( initialUri . getScheme ( ) , initialUri . getUserInfo ( ) , initialUri . getHost ( ) , initialUri . getPort ( ) , finalPath , initialUri . getQuery ( ) , initialUri . getFragment ( ) ) ; } } catch ( URISyntaxException e ) { throw ExceptionUtils . getRuntimeException ( e ) ; } }
Set the replace of the uri and return the new URI .
215
13
146,188
public final PJsonArray toJSON ( ) { JSONArray jsonArray = new JSONArray ( ) ; final int size = this . array . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { final Object o = get ( i ) ; if ( o instanceof PYamlObject ) { PYamlObject pYamlObject = ( PYamlObject ) o ; jsonArray . put ( pYamlObject . toJSON ( ) . getInternalObj ( ) ) ; } else if ( o instanceof PYamlArray ) { PYamlArray pYamlArray = ( PYamlArray ) o ; jsonArray . put ( pYamlArray . toJSON ( ) . getInternalArray ( ) ) ; } else { jsonArray . put ( o ) ; } } return new PJsonArray ( null , jsonArray , getContextName ( ) ) ; }
Convert this object to a json array .
191
9
146,189
@ PostConstruct public void checkUniqueSchemes ( ) { Multimap < String , ConfigFileLoaderPlugin > schemeToPluginMap = HashMultimap . create ( ) ; for ( ConfigFileLoaderPlugin plugin : getLoaderPlugins ( ) ) { schemeToPluginMap . put ( plugin . getUriScheme ( ) , plugin ) ; } StringBuilder violations = new StringBuilder ( ) ; for ( String scheme : schemeToPluginMap . keySet ( ) ) { final Collection < ConfigFileLoaderPlugin > plugins = schemeToPluginMap . get ( scheme ) ; if ( plugins . size ( ) > 1 ) { violations . append ( "\n\n* " ) . append ( "There are has multiple " ) . append ( ConfigFileLoaderPlugin . class . getSimpleName ( ) ) . append ( " plugins that support the scheme: '" ) . append ( scheme ) . append ( ' ' ) . append ( ":\n\t" ) . append ( plugins ) ; } } if ( violations . length ( ) > 0 ) { throw new IllegalStateException ( violations . toString ( ) ) ; } }
Method is called by spring and verifies that there is only one plugin per URI scheme .
237
18
146,190
public Set < String > getSupportedUriSchemes ( ) { Set < String > schemes = new HashSet <> ( ) ; for ( ConfigFileLoaderPlugin loaderPlugin : this . getLoaderPlugins ( ) ) { schemes . add ( loaderPlugin . getUriScheme ( ) ) ; } return schemes ; }
Return all URI schemes that are supported in the system .
68
11
146,191
public static CoordinateReferenceSystem parseProjection ( final String projection , final Boolean longitudeFirst ) { try { if ( longitudeFirst == null ) { return CRS . decode ( projection ) ; } else { return CRS . decode ( projection , longitudeFirst ) ; } } catch ( NoSuchAuthorityCodeException e ) { throw new RuntimeException ( projection + " was not recognized as a crs code" , e ) ; } catch ( FactoryException e ) { throw new RuntimeException ( "Error occurred while parsing: " + projection , e ) ; } }
Parse the given projection .
119
6
146,192
public final double [ ] getDpiSuggestions ( ) { if ( this . dpiSuggestions == null ) { List < Double > list = new ArrayList <> ( ) ; for ( double suggestion : DEFAULT_DPI_VALUES ) { if ( suggestion <= this . maxDpi ) { list . add ( suggestion ) ; } } double [ ] suggestions = new double [ list . size ( ) ] ; for ( int i = 0 ; i < suggestions . length ; i ++ ) { suggestions [ i ] = list . get ( i ) ; } return suggestions ; } return this . dpiSuggestions ; }
Get DPI suggestions .
132
5
146,193
protected BufferedImage createErrorImage ( final Rectangle area ) { final BufferedImage bufferedImage = new BufferedImage ( area . width , area . height , TYPE_INT_ARGB_PRE ) ; final Graphics2D graphics = bufferedImage . createGraphics ( ) ; try { graphics . setBackground ( ColorParser . toColor ( this . configuration . getTransparentTileErrorColor ( ) ) ) ; graphics . clearRect ( 0 , 0 , area . width , area . height ) ; return bufferedImage ; } finally { graphics . dispose ( ) ; } }
Create an error image .
122
5
146,194
protected BufferedImage fetchImage ( @ Nonnull final ClientHttpRequest request , @ Nonnull final MapfishMapContext transformer ) throws IOException { final String baseMetricName = getClass ( ) . getName ( ) + ".read." + StatsUtils . quotePart ( request . getURI ( ) . getHost ( ) ) ; final Timer . Context timerDownload = this . registry . timer ( baseMetricName ) . time ( ) ; try ( ClientHttpResponse httpResponse = request . execute ( ) ) { if ( httpResponse . getStatusCode ( ) != HttpStatus . OK ) { final String message = String . format ( "Invalid status code for %s (%d!=%d). The response was: '%s'" , request . getURI ( ) , httpResponse . getStatusCode ( ) . value ( ) , HttpStatus . OK . value ( ) , httpResponse . getStatusText ( ) ) ; this . registry . counter ( baseMetricName + ".error" ) . inc ( ) ; if ( getFailOnError ( ) ) { throw new RuntimeException ( message ) ; } else { LOGGER . info ( message ) ; return createErrorImage ( transformer . getPaintArea ( ) ) ; } } final List < String > contentType = httpResponse . getHeaders ( ) . get ( "Content-Type" ) ; if ( contentType == null || contentType . size ( ) != 1 ) { LOGGER . debug ( "The image {} didn't return a valid content type header." , request . getURI ( ) ) ; } else if ( ! contentType . get ( 0 ) . startsWith ( "image/" ) ) { final byte [ ] data ; try ( InputStream body = httpResponse . getBody ( ) ) { data = IOUtils . toByteArray ( body ) ; } LOGGER . debug ( "We get a wrong image for {}, content type: {}\nresult:\n{}" , request . getURI ( ) , contentType . get ( 0 ) , new String ( data , StandardCharsets . UTF_8 ) ) ; this . registry . counter ( baseMetricName + ".error" ) . inc ( ) ; return createErrorImage ( transformer . getPaintArea ( ) ) ; } final BufferedImage image = ImageIO . read ( httpResponse . getBody ( ) ) ; if ( image == null ) { LOGGER . warn ( "Cannot read image from %a" , request . getURI ( ) ) ; this . registry . counter ( baseMetricName + ".error" ) . inc ( ) ; if ( getFailOnError ( ) ) { throw new RuntimeException ( "Cannot read image from " + request . getURI ( ) ) ; } else { return createErrorImage ( transformer . getPaintArea ( ) ) ; } } timerDownload . stop ( ) ; return image ; } catch ( Throwable e ) { this . registry . counter ( baseMetricName + ".error" ) . inc ( ) ; throw e ; } }
Fetch the given image from the web .
650
9
146,195
@ SafeVarargs public static < T > Set < T > create ( final T ... values ) { Set < T > result = new HashSet <> ( values . length ) ; Collections . addAll ( result , values ) ; return result ; }
Create a HashSet with the given initial values .
52
10
146,196
@ SuppressWarnings ( { "deprecation" , "WeakerAccess" } ) protected void removeShutdownHook ( ClassLoaderLeakPreventor preventor , Thread shutdownHook ) { final String displayString = "'" + shutdownHook + "' of type " + shutdownHook . getClass ( ) . getName ( ) ; preventor . error ( "Removing shutdown hook: " + displayString ) ; Runtime . getRuntime ( ) . removeShutdownHook ( shutdownHook ) ; if ( executeShutdownHooks ) { // Shutdown hooks should be executed preventor . info ( "Executing shutdown hook now: " + displayString ) ; // Make sure it's from protected ClassLoader shutdownHook . start ( ) ; // Run cleanup immediately if ( shutdownHookWaitMs > 0 ) { // Wait for shutdown hook to finish try { shutdownHook . join ( shutdownHookWaitMs ) ; // Wait for thread to run } catch ( InterruptedException e ) { // Do nothing } if ( shutdownHook . isAlive ( ) ) { preventor . warn ( shutdownHook + "still running after " + shutdownHookWaitMs + " ms - Stopping!" ) ; shutdownHook . stop ( ) ; } } } }
Deregister shutdown hook and execute it immediately
271
10
146,197
protected static int getIntInitParameter ( ServletContext servletContext , String parameterName , int defaultValue ) { final String parameterString = servletContext . getInitParameter ( parameterName ) ; if ( parameterString != null && parameterString . trim ( ) . length ( ) > 0 ) { try { return Integer . parseInt ( parameterString ) ; } catch ( NumberFormatException e ) { // Do nothing, return default value } } return defaultValue ; }
Parse init parameter for integer value returning default if not found or invalid
97
14
146,198
@ SuppressWarnings ( "WeakerAccess" ) protected void clearRmiTargetsMap ( ClassLoaderLeakPreventor preventor , Map < ? , ? > rmiTargetsMap ) { try { final Field cclField = preventor . findFieldOfClass ( "sun.rmi.transport.Target" , "ccl" ) ; preventor . debug ( "Looping " + rmiTargetsMap . size ( ) + " RMI Targets to find leaks" ) ; for ( Iterator < ? > iter = rmiTargetsMap . values ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { Object target = iter . next ( ) ; // sun.rmi.transport.Target ClassLoader ccl = ( ClassLoader ) cclField . get ( target ) ; if ( preventor . isClassLoaderOrChild ( ccl ) ) { preventor . warn ( "Removing RMI Target: " + target ) ; iter . remove ( ) ; } } } catch ( Exception ex ) { preventor . error ( ex ) ; } }
Iterate RMI Targets Map and remove entries loaded by protected ClassLoader
241
15
146,199
@ SuppressWarnings ( "WeakerAccess" ) protected boolean isJettyWithJMX ( ClassLoaderLeakPreventor preventor ) { final ClassLoader classLoader = preventor . getClassLoader ( ) ; try { // If package org.eclipse.jetty is found, we may be running under jetty if ( classLoader . getResource ( "org/eclipse/jetty" ) == null ) { return false ; } Class . forName ( "org.eclipse.jetty.jmx.MBeanContainer" , false , classLoader . getParent ( ) ) ; // JMX enabled? Class . forName ( "org.eclipse.jetty.webapp.WebAppContext" , false , classLoader . getParent ( ) ) ; } catch ( Exception ex ) { // For example ClassNotFoundException return false ; } // Seems we are running in Jetty with JMX enabled return true ; }
Are we running in Jetty with JMX enabled?
202
11