Class LineStringExtracter

 1  
 2 /*
 3  * Copyright (c) 2016 Vivid Solutions.
 4  *
 5  * All rights reserved. This program and the accompanying materials
 6  * are made available under the terms of the Eclipse Public License 2.0
 7  * and Eclipse Distribution License v. 1.0 which accompanies this distribution.
 8  * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v20.html
 9  * and the Eclipse Distribution License is available at
10  *
11  * http://www.eclipse.org/org/documents/edl-v10.php.
12  */
13 package org.locationtech.jts.geom.util;
14  
15 import java.util.ArrayList;
16 import java.util.List;
17  
18 import org.locationtech.jts.geom.Geometry;
19 import org.locationtech.jts.geom.GeometryCollection;
20 import org.locationtech.jts.geom.GeometryFilter;
21 import org.locationtech.jts.geom.LineString;
22 import org.locationtech.jts.geom.MultiLineString;
23  
24 /**
25  * Extracts all the {@link LineString} elements from a {@link Geometry}.
26  *
27  * @version 1.7
28  * @see GeometryExtracter
29  */
30 public class LineStringExtracter
31   implements GeometryFilter
32 {
33   /**
34    * Extracts the {@link LineString} elements from a single {@link Geometry}
35    * and adds them to the provided {@link List}.
36    * 
37    * @param geom the geometry from which to extract
38    * @param lines the list to add the extracted LineStrings to
39    * @return the list argument
40    */
41   public static List getLines(Geometry geom, List lines)
42   {
43       if (geom instanceof LineString) {
44           lines.add(geom);
45       }
46       else if (geom instanceof GeometryCollection) {
47           geom.apply(new LineStringExtracter(lines));
48       }
49       // skip non-LineString elemental geometries
50       
51     return lines;
52   }
53  
54   /**
55    * Extracts the {@link LineString} elements from a single {@link Geometry}
56    * and returns them in a {@link List}.
57    * 
58    * @param geom the geometry from which to extract
59    * @return a list containing the linear elements
60    */
61   public static List getLines(Geometry geom)
62   {
63     return getLines(geom, new ArrayList());
64   }
65  
66   /**
67    * Extracts the {@link LineString} elements from a single {@link Geometry}
68    * and returns them as either a {@link LineString} or {@link MultiLineString}.
69    * 
70    * @param geom the geometry from which to extract
71    * @return a linear geometry
72   */
73   public static Geometry getGeometry(Geometry geom)
74   {
75     return geom.getFactory().buildGeometry(getLines(geom));
76   }
77  
78   private List comps;
79   
80   /**
81    * Constructs a filter with a list in which to store the elements found.
82    */
83   public LineStringExtracter(List comps)
84   {
85     this.comps = comps;
86   }
87  
88   public void filter(Geometry geom)
89   {
90     if (geom instanceof LineString) comps.add(geom);
91   }
92  
93 }
94