From 0790087705ca9539b3042a878ebba8acb5c98063 Mon Sep 17 00:00:00 2001 From: Roger AIRES Date: Wed, 12 Aug 2020 15:43:28 +0200 Subject: [PATCH] Version 1.4.0 - Upgrade for PDI 9 - Add write to Geopackage, SVG and GPX - Add read from Geopackage, GPX - Other minor feature Change-Id: I8705fb3fdfe3932beec285b82383f9b70f56e814 --- .../java/com/atolcd/gis/dxf/DXFReader.java | 755 +++++++++----- .../java/com/atolcd/gis/dxf/DXFWriter.java | 92 ++ .../main/java/com/atolcd/gis/dxf/Entity.java | 37 +- .../java/com/atolcd/gis/dxf/ExtendedData.java | 39 + .../main/java/com/atolcd/gis/dxf/Layer.java | 2 +- .../michaelm/jump/drivers/dxf/DxfENTITY.java | 179 +++- .../fr/michaelm/jump/drivers/dxf/DxfFile.java | 247 +++-- .../michaelm/jump/drivers/dxf/DxfGroup.java | 144 ++- .../jump/drivers/dxf/DxfTABLE_LTYPE_ITEM.java | 91 +- .../jump/drivers/dxf/DxfTABLE_STYLE_ITEM.java | 102 +- .../michaelm/jump/drivers/dxf/DxfXDATA.java | 35 + dxf/src/main/java/org/kabeja/dxf/Bounds.java | 315 ++++++ .../main/java/org/kabeja/dxf/DXF3DFace.java | 41 + .../main/java/org/kabeja/dxf/DXF3DSolid.java | 31 + dxf/src/main/java/org/kabeja/dxf/DXFArc.java | 219 ++++ .../main/java/org/kabeja/dxf/DXFAttrib.java | 33 + .../main/java/org/kabeja/dxf/DXFBlock.java | 200 ++++ dxf/src/main/java/org/kabeja/dxf/DXFBody.java | 30 + .../main/java/org/kabeja/dxf/DXFCircle.java | 88 ++ .../main/java/org/kabeja/dxf/DXFColor.java | 127 +++ .../java/org/kabeja/dxf/DXFConstants.java | 346 +++++++ .../java/org/kabeja/dxf/DXFDimension.java | 354 +++++++ .../org/kabeja/dxf/DXFDimensionStyle.java | 208 ++++ .../main/java/org/kabeja/dxf/DXFDocument.java | 426 ++++++++ .../main/java/org/kabeja/dxf/DXFEllipse.java | 243 +++++ .../main/java/org/kabeja/dxf/DXFEntity.java | 260 +++++ .../java/org/kabeja/dxf/DXFExtendedData.java | 39 + .../java/org/kabeja/dxf/DXFExtrusion.java | 122 +++ .../main/java/org/kabeja/dxf/DXFHatch.java | 370 +++++++ .../java/org/kabeja/dxf/DXFHatchPattern.java | 91 ++ .../main/java/org/kabeja/dxf/DXFHeader.java | 73 ++ .../main/java/org/kabeja/dxf/DXFImage.java | 243 +++++ .../main/java/org/kabeja/dxf/DXFInsert.java | 281 +++++ .../java/org/kabeja/dxf/DXFLWPolyline.java | 48 + .../main/java/org/kabeja/dxf/DXFLayer.java | 260 +++++ .../main/java/org/kabeja/dxf/DXFLeader.java | 317 ++++++ dxf/src/main/java/org/kabeja/dxf/DXFLine.java | 80 ++ .../main/java/org/kabeja/dxf/DXFLineType.java | 112 ++ .../main/java/org/kabeja/dxf/DXFMLine.java | 147 +++ .../main/java/org/kabeja/dxf/DXFMText.java | 199 ++++ .../main/java/org/kabeja/dxf/DXFPoint.java | 109 ++ .../main/java/org/kabeja/dxf/DXFPolyline.java | 690 +++++++++++++ dxf/src/main/java/org/kabeja/dxf/DXFRay.java | 80 ++ .../main/java/org/kabeja/dxf/DXFRegion.java | 71 ++ .../main/java/org/kabeja/dxf/DXFShape.java | 149 +++ .../main/java/org/kabeja/dxf/DXFSolid.java | 119 +++ .../main/java/org/kabeja/dxf/DXFSpline.java | 253 +++++ .../main/java/org/kabeja/dxf/DXFStyle.java | 192 ++++ dxf/src/main/java/org/kabeja/dxf/DXFText.java | 463 +++++++++ .../java/org/kabeja/dxf/DXFTolerance.java | 109 ++ .../main/java/org/kabeja/dxf/DXFTrace.java | 30 + .../main/java/org/kabeja/dxf/DXFVPort.java | 335 ++++++ .../main/java/org/kabeja/dxf/DXFVariable.java | 67 ++ .../main/java/org/kabeja/dxf/DXFVertex.java | 219 ++++ dxf/src/main/java/org/kabeja/dxf/DXFView.java | 298 ++++++ .../main/java/org/kabeja/dxf/DXFViewport.java | 552 ++++++++++ .../main/java/org/kabeja/dxf/DXFXLine.java | 25 + .../kabeja/dxf/helpers/DXFMLineSegment.java | 63 ++ .../dxf/helpers/DXFMLineSegmentElement.java | 45 + ...XFMLineStyleElementDistanceComparator.java | 36 + .../dxf/helpers/DXFSplineConverter.java | 77 ++ .../org/kabeja/dxf/helpers/DXFTextParser.java | 662 ++++++++++++ .../java/org/kabeja/dxf/helpers/DXFUtils.java | 149 +++ .../java/org/kabeja/dxf/helpers/Edge.java | 58 ++ .../kabeja/dxf/helpers/HatchBoundaryLoop.java | 84 ++ .../kabeja/dxf/helpers/HatchLineFamily.java | 169 +++ .../kabeja/dxf/helpers/HatchLineIterator.java | 275 +++++ .../kabeja/dxf/helpers/HatchLineSegment.java | 129 +++ .../org/kabeja/dxf/helpers/HatchPattern.java | 24 + .../kabeja/dxf/helpers/MLineConverter.java | 104 ++ .../kabeja/dxf/helpers/ParametricLine.java | 97 ++ .../java/org/kabeja/dxf/helpers/Point.java | 103 ++ .../kabeja/dxf/helpers/PolylineSegment.java | 319 ++++++ .../org/kabeja/dxf/helpers/SplinePoint.java | 73 ++ .../dxf/helpers/StyledTextParagraph.java | 281 +++++ .../org/kabeja/dxf/helpers/TextDocument.java | 103 ++ .../java/org/kabeja/dxf/helpers/Vector.java | 46 + .../org/kabeja/dxf/objects/DXFDictionary.java | 202 ++++ .../kabeja/dxf/objects/DXFImageDefObject.java | 48 + .../org/kabeja/dxf/objects/DXFLayout.java | 141 +++ .../org/kabeja/dxf/objects/DXFMLineStyle.java | 138 +++ .../dxf/objects/DXFMLineStyleElement.java | 46 + .../org/kabeja/dxf/objects/DXFObject.java | 66 ++ .../kabeja/dxf/objects/DXFPlotSettings.java | 180 ++++ .../java/org/kabeja/io/StreamGenerator.java | 50 + .../main/java/org/kabeja/math/MathUtils.java | 334 ++++++ dxf/src/main/java/org/kabeja/math/NURBS.java | 163 +++ .../math/NURBSAutoStepPointIterator.java | 35 + .../math/NURBSFixedNTELSPointIterator.java | 112 ++ .../java/org/kabeja/math/ParametricPlane.java | 205 ++++ .../org/kabeja/math/TransformContext.java | 133 +++ .../kabeja/parser/AbstractSectionHandler.java | 34 + .../parser/DXFBlocksSectionHandler.java | 197 ++++ .../parser/DXFEntitiesSectionHandler.java | 142 +++ .../parser/DXFHeaderSectionHandler.java | 84 ++ .../parser/DXFObjectsSectionHandler.java | 110 ++ .../java/org/kabeja/parser/DXFParser.java | 297 ++++++ .../org/kabeja/parser/DXFSectionHandler.java | 44 + .../kabeja/parser/DXFTableSectionHandler.java | 128 +++ .../main/java/org/kabeja/parser/DXFValue.java | 81 ++ .../main/java/org/kabeja/parser/Handler.java | 35 + .../org/kabeja/parser/HandlerManager.java | 27 + .../org/kabeja/parser/ParseException.java | 36 + .../main/java/org/kabeja/parser/Parser.java | 89 ++ .../java/org/kabeja/parser/ParserBuilder.java | 309 ++++++ .../org/kabeja/parser/SAXParserBuilder.java | 265 +++++ .../org/kabeja/parser/dxf/DXFHandler.java | 25 + .../dxf/filter/AbstractDXFStreamFilter.java | 34 + .../dxf/filter/DXFStreamEntityFilter.java | 73 ++ .../parser/dxf/filter/DXFStreamFilter.java | 41 + .../dxf/filter/DXFStreamLayerFilter.java | 115 +++ .../dxf/filter/DXFStreamSectionFilter.java | 58 ++ .../parser/dxf/filter/FilterExample.java | 49 + .../entities/AbstractEntityHandler.java | 208 ++++ .../parser/entities/DXF3DFaceHandler.java | 39 + .../parser/entities/DXF3DSolidHandler.java | 45 + .../kabeja/parser/entities/DXFArcHandler.java | 136 +++ .../parser/entities/DXFAttribHandler.java | 69 ++ .../parser/entities/DXFBodyHandler.java | 45 + .../parser/entities/DXFCircleHandler.java | 123 +++ .../parser/entities/DXFDimensionHandler.java | 273 +++++ .../parser/entities/DXFEllipseHandler.java | 118 +++ .../parser/entities/DXFEntityHandler.java | 78 ++ .../parser/entities/DXFHatchHandler.java | 415 ++++++++ .../parser/entities/DXFImageHandler.java | 214 ++++ .../parser/entities/DXFInsertHandler.java | 166 +++ .../parser/entities/DXFLWPolylineHandler.java | 149 +++ .../parser/entities/DXFLeaderHandler.java | 208 ++++ .../parser/entities/DXFLineHandler.java | 134 +++ .../parser/entities/DXFMLineHandler.java | 197 ++++ .../parser/entities/DXFMTextHandler.java | 215 ++++ .../parser/entities/DXFPointHandler.java | 117 +++ .../parser/entities/DXFPolylineHandler.java | 249 +++++ .../kabeja/parser/entities/DXFRayHandler.java | 119 +++ .../parser/entities/DXFRegionHandler.java | 126 +++ .../parser/entities/DXFShapeHandler.java | 129 +++ .../parser/entities/DXFSolidHandler.java | 164 +++ .../parser/entities/DXFSplineHandler.java | 250 +++++ .../parser/entities/DXFTextHandler.java | 207 ++++ .../parser/entities/DXFToleranceHandler.java | 132 +++ .../parser/entities/DXFTraceHandler.java | 37 + .../parser/entities/DXFViewportHandler.java | 342 ++++++ .../parser/entities/DXFXLineHandler.java | 40 + .../org/kabeja/parser/header/HeaderModes.java | 25 + .../objects/AbstractDXFObjectHandler.java | 70 ++ .../parser/objects/DXFDictionaryHandler.java | 68 ++ .../parser/objects/DXFImageDefHandler.java | 89 ++ .../parser/objects/DXFLayoutHandler.java | 217 ++++ .../parser/objects/DXFMLineStyleHandler.java | 110 ++ .../parser/objects/DXFObjectHandler.java | 37 + .../objects/DXFPlotsettingsHandler.java | 193 ++++ .../parser/table/AbstractTableHandler.java | 41 + .../table/DXFDimensionStyleTableHandler.java | 81 ++ .../parser/table/DXFLayerTableHandler.java | 104 ++ .../parser/table/DXFLineTypeTableHandler.java | 120 +++ .../parser/table/DXFStyleTableHandler.java | 112 ++ .../kabeja/parser/table/DXFTableHandler.java | 37 + .../parser/table/DXFVPortTableHandler.java | 107 ++ .../parser/table/DXFViewTableHandler.java | 198 ++++ .../processing/AbstractConfigurable.java | 32 + .../processing/AbstractPostProcessor.java | 20 + .../org/kabeja/processing/BoundsDebugger.java | 176 ++++ .../org/kabeja/processing/BoundsFilter.java | 92 ++ .../org/kabeja/processing/Configurable.java | 35 + .../org/kabeja/processing/ImageFilter.java | 63 ++ .../org/kabeja/processing/LayerFilter.java | 106 ++ .../kabeja/processing/PolylineConverter.java | 191 ++++ .../kabeja/processing/PostProcessManager.java | 62 ++ .../org/kabeja/processing/PostProcessor.java | 44 + .../processing/PostProcessorConfig.java | 59 ++ .../kabeja/processing/ProcessPipeline.java | 225 ++++ .../kabeja/processing/ProcessingManager.java | 184 ++++ .../kabeja/processing/ProcessorException.java | 34 + .../org/kabeja/processing/ViewFilter.java | 108 ++ .../org/kabeja/processing/ViewportFilter.java | 101 ++ .../kabeja/processing/VisibilityFilter.java | 71 ++ .../processing/event/ProcessingEvent.java | 27 + .../processing/event/ProcessingListener.java | 27 + .../kabeja/processing/helper/MergeMap.java | 95 ++ .../processing/helper/PolylineQueue.java | 256 +++++ .../java/org/kabeja/tools/CodePageParser.java | 88 ++ .../java/org/kabeja/tools/ConfigHelper.java | 60 ++ .../java/org/kabeja/tools/FontManager.java | 115 +++ .../org/kabeja/tools/SAXFilterConfig.java | 59 ++ .../tools/SAXProcessingManagerBuilder.java | 358 +++++++ .../org/kabeja/tools/SAXSerializerConfig.java | 51 + .../main/java/org/kabeja/ui/Application.java | 35 + .../org/kabeja/ui/ApplicationMenuBar.java | 42 + .../org/kabeja/ui/ApplicationToolBar.java | 32 + .../main/java/org/kabeja/ui/Component.java | 24 + .../kabeja/ui/DXFDocumentViewComponent.java | 48 + .../org/kabeja/ui/ProcessingUIComponent.java | 33 + .../java/org/kabeja/ui/PropertiesEditor.java | 48 + .../org/kabeja/ui/PropertiesListener.java | 31 + .../java/org/kabeja/ui/ServiceManager.java | 32 + .../main/java/org/kabeja/ui/Serviceable.java | 29 + .../main/java/org/kabeja/ui/Startable.java | 28 + .../main/java/org/kabeja/ui/UIException.java | 26 + .../java/org/kabeja/ui/ViewComponent.java | 39 + .../event/DXFDocumentChangeEventProvider.java | 32 + .../ui/event/DXFDocumentChangeListener.java | 34 + .../ui/model/AbstractProcessingTreeNode.java | 93 ++ .../org/kabeja/ui/model/ParserTreeNode.java | 47 + .../org/kabeja/ui/model/ParsersTreeNode.java | 48 + .../org/kabeja/ui/model/PipelineTreeNode.java | 42 + .../kabeja/ui/model/PipelinesTreeNode.java | 48 + .../ui/model/PostProcessorTreeNode.java | 42 + .../ui/model/PostProcessorsTreeNode.java | 48 + .../model/ProcessingTreeModelPresenter.java | 104 ++ .../kabeja/ui/model/PropertiesTreeNode.java | 49 + .../org/kabeja/ui/model/PropertyTreeNode.java | 48 + .../kabeja/ui/model/SAXFilterTreeNode.java | 44 + .../kabeja/ui/model/SAXFiltersTreeNode.java | 47 + .../kabeja/ui/model/SAXGeneratorTreeNode.java | 62 ++ .../ui/model/SAXGeneratorsTreeNode.java | 48 + .../ui/model/SAXSerializerTreeNode.java | 42 + .../ui/model/SAXSerializersTreeNode.java | 50 + .../org/kabeja/xml/AbstractSAXFilter.java | 42 + .../org/kabeja/xml/AbstractSAXGenerator.java | 47 + .../org/kabeja/xml/AbstractSAXSerializer.java | 22 + .../org/kabeja/xml/AggregatorGenerator.java | 79 ++ .../org/kabeja/xml/ConsoleSerializer.java | 22 + .../main/java/org/kabeja/xml/SAXFilter.java | 31 + .../java/org/kabeja/xml/SAXGenerator.java | 42 + .../org/kabeja/xml/SAXPrettyOutputter.java | 340 ++++++ .../java/org/kabeja/xml/SAXSerializer.java | 46 + gpx/.gitignore | 4 + gpx/pom.xml | 94 ++ .../atolcd/gis/gpx/AbstractReaderWriter.java | 45 + .../java/com/atolcd/gis/gpx/GpxReader.java | 228 ++++ .../java/com/atolcd/gis/gpx/GpxWriter.java | 277 +++++ .../java/com/atolcd/gis/gpx/IElement.java | 11 + .../com/atolcd/gis/gpx/ISpatialElement.java | 18 + .../atolcd/gis/gpx/type/AbstractElement.java | 29 + .../gis/gpx/type/AbstractSpatialElement.java | 48 + .../java/com/atolcd/gis/gpx/type/Author.java | 72 ++ .../com/atolcd/gis/gpx/type/Document.java | 130 +++ .../com/atolcd/gis/gpx/type/Metadata.java | 48 + .../java/com/atolcd/gis/gpx/type/Route.java | 95 ++ .../java/com/atolcd/gis/gpx/type/Track.java | 107 ++ .../com/atolcd/gis/gpx/type/TrackSegment.java | 44 + .../com/atolcd/gis/gpx/type/WayPoint.java | 83 ++ pentaho-gis-plugins/pom.xml | 78 +- .../di/core/row/value/ValueMetaGeometry.java | 102 +- .../pentaho/di/gis/io/AbstractFileReader.java | 13 + .../atolcd/pentaho/di/gis/io/DXFReader.java | 26 +- .../atolcd/pentaho/di/gis/io/DXFWriter.java | 177 ++-- .../atolcd/pentaho/di/gis/io/GPXReader.java | 157 +++ .../atolcd/pentaho/di/gis/io/GPXWriter.java | 321 ++++++ .../pentaho/di/gis/io/GeoPackageReader.java | 592 +++++++++++ .../pentaho/di/gis/io/GeoPackageWriter.java | 974 ++++++++++++++++++ .../atolcd/pentaho/di/gis/io/SVGWriter.java | 704 +++++++++++++ .../pentaho/di/gis/io/SpatialiteReader.java | 146 ++- .../di/gis/io/features/FeatureConverter.java | 28 +- .../pentaho/di/gis/utils/GeometryUtils.java | 95 +- .../GisCoordinateTransformation.java | 13 +- .../GisCoordinateTransformationData.java | 3 +- .../steps/gisfileinput/GisFileInput.java | 49 +- .../steps/gisfileinput/GisFileInputData.java | 3 +- .../steps/gisfileinput/GisFileInputMeta.java | 56 +- .../steps/gisfileoutput/GisFileOutput.java | 271 ++++- .../gisfileoutput/GisFileOutputData.java | 3 +- .../gisfileoutput/GisFileOutputMeta.java | 76 +- .../gisgeometryinfo/GisGeometryInfo.java | 11 +- .../gisgeometryinfo/GisGeometryInfoData.java | 3 +- .../gisgeometryinfo/GisGeometryInfoMeta.java | 32 +- .../gisgeoprocessing/GisGeoprocessing.java | 290 +++++- .../GisGeoprocessingData.java | 3 +- .../GisGeoprocessingMeta.java | 10 +- .../di/trans/steps/gisgroupby/GisGroupBy.java | 60 +- .../steps/gisgroupby/GisGroupByData.java | 3 +- .../steps/gisgroupby/GisGroupByMeta.java | 16 +- .../di/trans/steps/gisrelate/GisRelate.java | 15 +- .../trans/steps/gisrelate/GisRelateData.java | 3 +- .../trans/steps/gisrelate/GisRelateMeta.java | 6 +- .../gisfileinput/GisFileInputDialog.java | 33 +- .../gisfileoutput/GisFileOutputDialog.java | 47 +- .../GisGeometryInfoDialog.java | 4 +- .../GisGeoprocessingDialog.java | 8 +- .../steps/gisgroupby/GisGroupByDialog.java | 2 +- .../steps/gisrelate/GisRelateDialog.java | 8 +- .../messages/messages_fr_FR.properties | 2 +- .../messages/messages_en_US.properties | 6 +- .../messages/messages_fr_FR.properties | 6 +- .../messages/messages_en_US.properties | 121 ++- .../messages/messages_fr_FR.properties | 113 +- .../messages/messages_en_US.properties | 53 +- .../messages/messages_fr_FR.properties | 55 +- .../messages/messages_en_US.properties | 43 +- .../messages/messages_fr_FR.properties | 47 +- pom.xml | 2 + svg/.gitignore | 4 + svg/pom.xml | 120 +++ .../main/java/com/atolcd/gis/svg/SvgUtil.java | 268 +++++ .../java/com/atolcd/gis/svg/SvgWriter.java | 309 ++++++ .../gis/svg/type/AbstractContainer.java | 27 + .../atolcd/gis/svg/type/AbstractElement.java | 72 ++ .../atolcd/gis/svg/type/AbstractGraphic.java | 14 + .../atolcd/gis/svg/type/AbstractStyle.java | 25 + .../com/atolcd/gis/svg/type/Document.java | 63 ++ .../com/atolcd/gis/svg/type/IElement.java | 19 + .../atolcd/gis/svg/type/container/Defs.java | 7 + .../atolcd/gis/svg/type/container/Group.java | 7 + .../atolcd/gis/svg/type/container/Link.java | 59 ++ .../atolcd/gis/svg/type/graphic/Circle.java | 29 + .../atolcd/gis/svg/type/graphic/Image.java | 69 ++ .../com/atolcd/gis/svg/type/graphic/Path.java | 17 + .../gis/svg/type/graphic/Rectangle.java | 57 + .../com/atolcd/gis/svg/type/graphic/Text.java | 43 + .../com/atolcd/gis/svg/type/graphic/Use.java | 95 ++ .../gis/svg/type/style/EmbeddedStyle.java | 49 + .../gis/svg/type/style/ExternalStyle.java | 18 + 312 files changed, 35450 insertions(+), 1091 deletions(-) create mode 100644 dxf/src/main/java/com/atolcd/gis/dxf/DXFWriter.java create mode 100644 dxf/src/main/java/com/atolcd/gis/dxf/ExtendedData.java create mode 100644 dxf/src/main/java/fr/michaelm/jump/drivers/dxf/DxfXDATA.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/Bounds.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXF3DFace.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXF3DSolid.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFArc.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFAttrib.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFBlock.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFBody.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFCircle.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFColor.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFConstants.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFDimension.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFDimensionStyle.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFDocument.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFEllipse.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFEntity.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFExtendedData.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFExtrusion.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFHatch.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFHatchPattern.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFHeader.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFImage.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFInsert.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFLWPolyline.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFLayer.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFLeader.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFLine.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFLineType.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFMLine.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFMText.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFPoint.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFPolyline.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFRay.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFRegion.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFShape.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFSolid.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFSpline.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFStyle.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFText.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFTolerance.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFTrace.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFVPort.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFVariable.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFVertex.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFView.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFViewport.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/DXFXLine.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/helpers/DXFMLineSegment.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/helpers/DXFMLineSegmentElement.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/helpers/DXFMLineStyleElementDistanceComparator.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/helpers/DXFSplineConverter.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/helpers/DXFTextParser.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/helpers/DXFUtils.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/helpers/Edge.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/helpers/HatchBoundaryLoop.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/helpers/HatchLineFamily.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/helpers/HatchLineIterator.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/helpers/HatchLineSegment.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/helpers/HatchPattern.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/helpers/MLineConverter.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/helpers/ParametricLine.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/helpers/Point.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/helpers/PolylineSegment.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/helpers/SplinePoint.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/helpers/StyledTextParagraph.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/helpers/TextDocument.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/helpers/Vector.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/objects/DXFDictionary.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/objects/DXFImageDefObject.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/objects/DXFLayout.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/objects/DXFMLineStyle.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/objects/DXFMLineStyleElement.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/objects/DXFObject.java create mode 100644 dxf/src/main/java/org/kabeja/dxf/objects/DXFPlotSettings.java create mode 100644 dxf/src/main/java/org/kabeja/io/StreamGenerator.java create mode 100644 dxf/src/main/java/org/kabeja/math/MathUtils.java create mode 100644 dxf/src/main/java/org/kabeja/math/NURBS.java create mode 100644 dxf/src/main/java/org/kabeja/math/NURBSAutoStepPointIterator.java create mode 100644 dxf/src/main/java/org/kabeja/math/NURBSFixedNTELSPointIterator.java create mode 100644 dxf/src/main/java/org/kabeja/math/ParametricPlane.java create mode 100644 dxf/src/main/java/org/kabeja/math/TransformContext.java create mode 100644 dxf/src/main/java/org/kabeja/parser/AbstractSectionHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/DXFBlocksSectionHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/DXFEntitiesSectionHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/DXFHeaderSectionHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/DXFObjectsSectionHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/DXFParser.java create mode 100644 dxf/src/main/java/org/kabeja/parser/DXFSectionHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/DXFTableSectionHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/DXFValue.java create mode 100644 dxf/src/main/java/org/kabeja/parser/Handler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/HandlerManager.java create mode 100644 dxf/src/main/java/org/kabeja/parser/ParseException.java create mode 100644 dxf/src/main/java/org/kabeja/parser/Parser.java create mode 100644 dxf/src/main/java/org/kabeja/parser/ParserBuilder.java create mode 100644 dxf/src/main/java/org/kabeja/parser/SAXParserBuilder.java create mode 100644 dxf/src/main/java/org/kabeja/parser/dxf/DXFHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/dxf/filter/AbstractDXFStreamFilter.java create mode 100644 dxf/src/main/java/org/kabeja/parser/dxf/filter/DXFStreamEntityFilter.java create mode 100644 dxf/src/main/java/org/kabeja/parser/dxf/filter/DXFStreamFilter.java create mode 100644 dxf/src/main/java/org/kabeja/parser/dxf/filter/DXFStreamLayerFilter.java create mode 100644 dxf/src/main/java/org/kabeja/parser/dxf/filter/DXFStreamSectionFilter.java create mode 100644 dxf/src/main/java/org/kabeja/parser/dxf/filter/FilterExample.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/AbstractEntityHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXF3DFaceHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXF3DSolidHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXFArcHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXFAttribHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXFBodyHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXFCircleHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXFDimensionHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXFEllipseHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXFEntityHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXFHatchHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXFImageHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXFInsertHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXFLWPolylineHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXFLeaderHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXFLineHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXFMLineHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXFMTextHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXFPointHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXFPolylineHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXFRayHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXFRegionHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXFShapeHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXFSolidHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXFSplineHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXFTextHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXFToleranceHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXFTraceHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXFViewportHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/entities/DXFXLineHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/header/HeaderModes.java create mode 100644 dxf/src/main/java/org/kabeja/parser/objects/AbstractDXFObjectHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/objects/DXFDictionaryHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/objects/DXFImageDefHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/objects/DXFLayoutHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/objects/DXFMLineStyleHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/objects/DXFObjectHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/objects/DXFPlotsettingsHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/table/AbstractTableHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/table/DXFDimensionStyleTableHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/table/DXFLayerTableHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/table/DXFLineTypeTableHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/table/DXFStyleTableHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/table/DXFTableHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/table/DXFVPortTableHandler.java create mode 100644 dxf/src/main/java/org/kabeja/parser/table/DXFViewTableHandler.java create mode 100644 dxf/src/main/java/org/kabeja/processing/AbstractConfigurable.java create mode 100644 dxf/src/main/java/org/kabeja/processing/AbstractPostProcessor.java create mode 100644 dxf/src/main/java/org/kabeja/processing/BoundsDebugger.java create mode 100644 dxf/src/main/java/org/kabeja/processing/BoundsFilter.java create mode 100644 dxf/src/main/java/org/kabeja/processing/Configurable.java create mode 100644 dxf/src/main/java/org/kabeja/processing/ImageFilter.java create mode 100644 dxf/src/main/java/org/kabeja/processing/LayerFilter.java create mode 100644 dxf/src/main/java/org/kabeja/processing/PolylineConverter.java create mode 100644 dxf/src/main/java/org/kabeja/processing/PostProcessManager.java create mode 100644 dxf/src/main/java/org/kabeja/processing/PostProcessor.java create mode 100644 dxf/src/main/java/org/kabeja/processing/PostProcessorConfig.java create mode 100644 dxf/src/main/java/org/kabeja/processing/ProcessPipeline.java create mode 100644 dxf/src/main/java/org/kabeja/processing/ProcessingManager.java create mode 100644 dxf/src/main/java/org/kabeja/processing/ProcessorException.java create mode 100644 dxf/src/main/java/org/kabeja/processing/ViewFilter.java create mode 100644 dxf/src/main/java/org/kabeja/processing/ViewportFilter.java create mode 100644 dxf/src/main/java/org/kabeja/processing/VisibilityFilter.java create mode 100644 dxf/src/main/java/org/kabeja/processing/event/ProcessingEvent.java create mode 100644 dxf/src/main/java/org/kabeja/processing/event/ProcessingListener.java create mode 100644 dxf/src/main/java/org/kabeja/processing/helper/MergeMap.java create mode 100644 dxf/src/main/java/org/kabeja/processing/helper/PolylineQueue.java create mode 100644 dxf/src/main/java/org/kabeja/tools/CodePageParser.java create mode 100644 dxf/src/main/java/org/kabeja/tools/ConfigHelper.java create mode 100644 dxf/src/main/java/org/kabeja/tools/FontManager.java create mode 100644 dxf/src/main/java/org/kabeja/tools/SAXFilterConfig.java create mode 100644 dxf/src/main/java/org/kabeja/tools/SAXProcessingManagerBuilder.java create mode 100644 dxf/src/main/java/org/kabeja/tools/SAXSerializerConfig.java create mode 100644 dxf/src/main/java/org/kabeja/ui/Application.java create mode 100644 dxf/src/main/java/org/kabeja/ui/ApplicationMenuBar.java create mode 100644 dxf/src/main/java/org/kabeja/ui/ApplicationToolBar.java create mode 100644 dxf/src/main/java/org/kabeja/ui/Component.java create mode 100644 dxf/src/main/java/org/kabeja/ui/DXFDocumentViewComponent.java create mode 100644 dxf/src/main/java/org/kabeja/ui/ProcessingUIComponent.java create mode 100644 dxf/src/main/java/org/kabeja/ui/PropertiesEditor.java create mode 100644 dxf/src/main/java/org/kabeja/ui/PropertiesListener.java create mode 100644 dxf/src/main/java/org/kabeja/ui/ServiceManager.java create mode 100644 dxf/src/main/java/org/kabeja/ui/Serviceable.java create mode 100644 dxf/src/main/java/org/kabeja/ui/Startable.java create mode 100644 dxf/src/main/java/org/kabeja/ui/UIException.java create mode 100644 dxf/src/main/java/org/kabeja/ui/ViewComponent.java create mode 100644 dxf/src/main/java/org/kabeja/ui/event/DXFDocumentChangeEventProvider.java create mode 100644 dxf/src/main/java/org/kabeja/ui/event/DXFDocumentChangeListener.java create mode 100644 dxf/src/main/java/org/kabeja/ui/model/AbstractProcessingTreeNode.java create mode 100644 dxf/src/main/java/org/kabeja/ui/model/ParserTreeNode.java create mode 100644 dxf/src/main/java/org/kabeja/ui/model/ParsersTreeNode.java create mode 100644 dxf/src/main/java/org/kabeja/ui/model/PipelineTreeNode.java create mode 100644 dxf/src/main/java/org/kabeja/ui/model/PipelinesTreeNode.java create mode 100644 dxf/src/main/java/org/kabeja/ui/model/PostProcessorTreeNode.java create mode 100644 dxf/src/main/java/org/kabeja/ui/model/PostProcessorsTreeNode.java create mode 100644 dxf/src/main/java/org/kabeja/ui/model/ProcessingTreeModelPresenter.java create mode 100644 dxf/src/main/java/org/kabeja/ui/model/PropertiesTreeNode.java create mode 100644 dxf/src/main/java/org/kabeja/ui/model/PropertyTreeNode.java create mode 100644 dxf/src/main/java/org/kabeja/ui/model/SAXFilterTreeNode.java create mode 100644 dxf/src/main/java/org/kabeja/ui/model/SAXFiltersTreeNode.java create mode 100644 dxf/src/main/java/org/kabeja/ui/model/SAXGeneratorTreeNode.java create mode 100644 dxf/src/main/java/org/kabeja/ui/model/SAXGeneratorsTreeNode.java create mode 100644 dxf/src/main/java/org/kabeja/ui/model/SAXSerializerTreeNode.java create mode 100644 dxf/src/main/java/org/kabeja/ui/model/SAXSerializersTreeNode.java create mode 100644 dxf/src/main/java/org/kabeja/xml/AbstractSAXFilter.java create mode 100644 dxf/src/main/java/org/kabeja/xml/AbstractSAXGenerator.java create mode 100644 dxf/src/main/java/org/kabeja/xml/AbstractSAXSerializer.java create mode 100644 dxf/src/main/java/org/kabeja/xml/AggregatorGenerator.java create mode 100644 dxf/src/main/java/org/kabeja/xml/ConsoleSerializer.java create mode 100644 dxf/src/main/java/org/kabeja/xml/SAXFilter.java create mode 100644 dxf/src/main/java/org/kabeja/xml/SAXGenerator.java create mode 100644 dxf/src/main/java/org/kabeja/xml/SAXPrettyOutputter.java create mode 100644 dxf/src/main/java/org/kabeja/xml/SAXSerializer.java create mode 100644 gpx/.gitignore create mode 100644 gpx/pom.xml create mode 100644 gpx/src/main/java/com/atolcd/gis/gpx/AbstractReaderWriter.java create mode 100644 gpx/src/main/java/com/atolcd/gis/gpx/GpxReader.java create mode 100644 gpx/src/main/java/com/atolcd/gis/gpx/GpxWriter.java create mode 100644 gpx/src/main/java/com/atolcd/gis/gpx/IElement.java create mode 100644 gpx/src/main/java/com/atolcd/gis/gpx/ISpatialElement.java create mode 100644 gpx/src/main/java/com/atolcd/gis/gpx/type/AbstractElement.java create mode 100644 gpx/src/main/java/com/atolcd/gis/gpx/type/AbstractSpatialElement.java create mode 100644 gpx/src/main/java/com/atolcd/gis/gpx/type/Author.java create mode 100644 gpx/src/main/java/com/atolcd/gis/gpx/type/Document.java create mode 100644 gpx/src/main/java/com/atolcd/gis/gpx/type/Metadata.java create mode 100644 gpx/src/main/java/com/atolcd/gis/gpx/type/Route.java create mode 100644 gpx/src/main/java/com/atolcd/gis/gpx/type/Track.java create mode 100644 gpx/src/main/java/com/atolcd/gis/gpx/type/TrackSegment.java create mode 100644 gpx/src/main/java/com/atolcd/gis/gpx/type/WayPoint.java create mode 100644 pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/GPXReader.java create mode 100644 pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/GPXWriter.java create mode 100644 pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/GeoPackageReader.java create mode 100644 pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/GeoPackageWriter.java create mode 100644 pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/SVGWriter.java create mode 100644 svg/.gitignore create mode 100644 svg/pom.xml create mode 100644 svg/src/main/java/com/atolcd/gis/svg/SvgUtil.java create mode 100644 svg/src/main/java/com/atolcd/gis/svg/SvgWriter.java create mode 100644 svg/src/main/java/com/atolcd/gis/svg/type/AbstractContainer.java create mode 100644 svg/src/main/java/com/atolcd/gis/svg/type/AbstractElement.java create mode 100644 svg/src/main/java/com/atolcd/gis/svg/type/AbstractGraphic.java create mode 100644 svg/src/main/java/com/atolcd/gis/svg/type/AbstractStyle.java create mode 100644 svg/src/main/java/com/atolcd/gis/svg/type/Document.java create mode 100644 svg/src/main/java/com/atolcd/gis/svg/type/IElement.java create mode 100644 svg/src/main/java/com/atolcd/gis/svg/type/container/Defs.java create mode 100644 svg/src/main/java/com/atolcd/gis/svg/type/container/Group.java create mode 100644 svg/src/main/java/com/atolcd/gis/svg/type/container/Link.java create mode 100644 svg/src/main/java/com/atolcd/gis/svg/type/graphic/Circle.java create mode 100644 svg/src/main/java/com/atolcd/gis/svg/type/graphic/Image.java create mode 100644 svg/src/main/java/com/atolcd/gis/svg/type/graphic/Path.java create mode 100644 svg/src/main/java/com/atolcd/gis/svg/type/graphic/Rectangle.java create mode 100644 svg/src/main/java/com/atolcd/gis/svg/type/graphic/Text.java create mode 100644 svg/src/main/java/com/atolcd/gis/svg/type/graphic/Use.java create mode 100644 svg/src/main/java/com/atolcd/gis/svg/type/style/EmbeddedStyle.java create mode 100644 svg/src/main/java/com/atolcd/gis/svg/type/style/ExternalStyle.java diff --git a/dxf/src/main/java/com/atolcd/gis/dxf/DXFReader.java b/dxf/src/main/java/com/atolcd/gis/dxf/DXFReader.java index 1d6f9b3..63243e8 100644 --- a/dxf/src/main/java/com/atolcd/gis/dxf/DXFReader.java +++ b/dxf/src/main/java/com/atolcd/gis/dxf/DXFReader.java @@ -1,5 +1,6 @@ package com.atolcd.gis.dxf; +import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -9,10 +10,14 @@ import org.kabeja.dxf.DXFConstants; import org.kabeja.dxf.DXFDocument; import org.kabeja.dxf.DXFEllipse; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.dxf.DXFExtendedData; +import org.kabeja.dxf.DXFInsert; import org.kabeja.dxf.DXFLWPolyline; import org.kabeja.dxf.DXFLayer; import org.kabeja.dxf.DXFLine; import org.kabeja.dxf.DXFMText; +import org.kabeja.dxf.DXFPoint; import org.kabeja.dxf.DXFPolyline; import org.kabeja.dxf.DXFSpline; import org.kabeja.dxf.DXFText; @@ -38,6 +43,7 @@ public class DXFReader { private static GeometryFactory geometryFactory = new GeometryFactory(); private String dxfFileName; + private boolean dxfFileExist; private List layers; private boolean circleAsPolygon; @@ -48,7 +54,19 @@ public DXFReader(String fileName) throws Exception { this.circleAsPolygon = false; this.ellipseAsPolygon = false; this.polylineAsPolygon = false; - this.dxfFileName = fileName; + + int pointIndex = fileName.lastIndexOf('.'); + if (pointIndex > 0) { + fileName = fileName.substring(0,pointIndex); + } + + this.dxfFileName = fileName.concat(".dxf"); + this.dxfFileExist = new File(this.dxfFileName).exists(); + + if(!this.dxfFileExist){ + throw new Exception("Missing " + this.dxfFileName + " file"); + } + this.layers = new ArrayList(); } @@ -73,6 +91,8 @@ public List getLayers() throws ParseException { entities.addAll(getCircles(dxfLayer)); entities.addAll(getEllipses(dxfLayer)); entities.addAll(getArcs(dxfLayer)); + entities.addAll(getBlocks(dxfLayer)); + entities.addAll(getPoints(dxfLayer)); layer.setEntities(entities); @@ -105,269 +125,478 @@ public void setPolylineAsPolygon(boolean polylineAsPolygon) { this.polylineAsPolygon = polylineAsPolygon; } - private List getMTexts(DXFLayer layer) { - List entities = new ArrayList(); - @SuppressWarnings("unchecked") - List dxfMTexts = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_MTEXT); - - if (dxfMTexts != null) { - for (DXFMText dxfMText : dxfMTexts) { - Entity entity = new Entity(); - - Point dxfInsertPoint = dxfMText.getInsertPoint(); - - entity.setType(Entity.TYPE_MTEXT); - entity.setGeometry(geometryFactory.createPoint(new Coordinate(dxfInsertPoint.getX(), dxfInsertPoint.getY()))); - entity.setText(dxfMText.getText()); - - entities.add(entity); - } - } - return entities; - } - - private List getTexts(DXFLayer layer) { - List entities = new ArrayList(); - @SuppressWarnings("unchecked") - List dxfMTexts = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_TEXT); - - if (dxfMTexts != null) { - for (DXFText dxfText : dxfMTexts) { - Entity entity = new Entity(); - - Point dxfInsertPoint = dxfText.getInsertPoint(); - - entity.setType(Entity.TYPE_TEXT); - entity.setGeometry(geometryFactory.createPoint(new Coordinate(dxfInsertPoint.getX(), dxfInsertPoint.getY()))); - entity.setText(dxfText.getText()); - entities.add(entity); - } - } - return entities; - } - - private List getLines(DXFLayer layer) { - List entities = new ArrayList(); - @SuppressWarnings("unchecked") - List dxfLines = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_LINE); - - if (dxfLines != null) { - for (DXFLine dxfLine : dxfLines) { - Entity entity = new Entity(); - - Point start = dxfLine.getStartPoint(); - Point end = dxfLine.getEndPoint(); - - entity.setType(Entity.TYPE_LINE); - entity.setGeometry(geometryFactory.createLineString(new Coordinate[] { new Coordinate(start.getX(), start.getY()), new Coordinate(end.getX(), end.getY()) })); - - entities.add(entity); - } - } - return entities; - } - - private List getPolylines(DXFLayer layer) { - List entities = new ArrayList(); - @SuppressWarnings("unchecked") - List dxfpolylines = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_POLYLINE); - - if (dxfpolylines != null) { - for (DXFPolyline dxfPolyline : dxfpolylines) { - Entity entity = new Entity(); - - CoordinateList coordinates = new CoordinateList(); - @SuppressWarnings("unchecked") - Iterator vertexIt = dxfPolyline.getVertexIterator(); - - while (vertexIt.hasNext()) { - DXFVertex vertex = vertexIt.next(); - if (!vertex.is2DSplineApproximationVertex() && !vertex.is2DSplineControlVertex() && !vertex.isCurveFitVertex()) { - coordinates.add(new Coordinate(vertex.getX(), vertex.getY()), false); - } - } - if (dxfPolyline.isClosed()) { - coordinates.add(coordinates.get(0), false); - } - Geometry geometry = geometryFactory.createLineString(coordinates.toCoordinateArray()); - if (((LineString) geometry).isClosed() && this.polylineAsPolygon) { - geometry = geometryFactory.createPolygon(geometry.getCoordinates()); - } - entity.setType(Entity.TYPE_POLYLINE); - entity.setGeometry(geometry); - entities.add(entity); - } - } - return entities; - } - - private List getLWPolylines(DXFLayer layer) { - List entities = new ArrayList(); - @SuppressWarnings("unchecked") - List dxfLwPolylines = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_LWPOLYLINE); - - if (dxfLwPolylines != null) { - for (DXFPolyline dxfLwPolyline : dxfLwPolylines) { - Entity entity = new Entity(); - - CoordinateList coordinates = new CoordinateList(); - @SuppressWarnings("unchecked") - Iterator vertexIt = dxfLwPolyline.getVertexIterator(); - - while (vertexIt.hasNext()) { - DXFVertex vertex = vertexIt.next(); - if (!vertex.is2DSplineApproximationVertex() && !vertex.is2DSplineControlVertex() && !vertex.isCurveFitVertex()) { - coordinates.add(new Coordinate(vertex.getX(), vertex.getY()), false); - } - } - if (dxfLwPolyline.isClosed()) { - coordinates.add(coordinates.get(0), false); - } - Geometry geometry = geometryFactory.createLineString(coordinates.toCoordinateArray()); - if (((LineString) geometry).isClosed() && this.polylineAsPolygon) { - geometry = geometryFactory.createPolygon(geometry.getCoordinates()); - } - entity.setType(Entity.TYPE_LWPOLYLINE); - entity.setGeometry(geometry); - entities.add(entity); - } - } - return entities; - } - - private List getSplines(DXFLayer layer) { - List entities = new ArrayList(); - @SuppressWarnings("unchecked") - List dxfSplines = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_SPLINE); - - if (dxfSplines != null) { - for (DXFSpline dxfSpline : dxfSplines) { - DXFPolyline dxfPolyline = DXFSplineConverter.toDXFPolyline(dxfSpline); - - Entity entity = new Entity(); - - CoordinateList coordinates = new CoordinateList(); - @SuppressWarnings("unchecked") - Iterator vertexIt = dxfPolyline.getVertexIterator(); - - while (vertexIt.hasNext()) { - DXFVertex vertex = vertexIt.next(); - if (!vertex.is2DSplineApproximationVertex() && !vertex.is2DSplineControlVertex() && !vertex.isCurveFitVertex()) { - coordinates.add(new Coordinate(vertex.getX(), vertex.getY()), false); - } - } - if (dxfPolyline.isClosed()) { - coordinates.add(coordinates.get(0), false); - } - Geometry geometry = geometryFactory.createLineString(coordinates.toCoordinateArray()); - if (((LineString) geometry).isClosed() && this.polylineAsPolygon) { - geometry = geometryFactory.createPolygon(geometry.getCoordinates()); - } - entity.setType(Entity.TYPE_LWPOLYLINE); - entity.setGeometry(geometry); - entities.add(entity); - } - } - return entities; - } - - private List getCircles(DXFLayer layer) { - List entities = new ArrayList(); - @SuppressWarnings("unchecked") - List dxfCircles = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_CIRCLE); - - if (dxfCircles != null) { - for (DXFCircle dxfCircle : dxfCircles) { - Entity entity = new Entity(); - - Point dxfCenter = dxfCircle.getCenterPoint(); - - GeometricShapeFactory geometricShapeFactory = new GeometricShapeFactory(); - geometricShapeFactory.setCentre(new Coordinate(dxfCenter.getX(), dxfCenter.getY())); - geometricShapeFactory.setWidth(dxfCircle.getRadius() * 2); - geometricShapeFactory.setHeight(dxfCircle.getRadius() * 2); - - Geometry geometry = geometricShapeFactory.createCircle(); - if (!this.circleAsPolygon) { - geometry = geometryFactory.createLineString(((Polygon) geometry).getExteriorRing().getCoordinates()); - } - - entity.setType(Entity.TYPE_CIRCLE); - entity.setGeometry(geometry); - entities.add(entity); - } - } - return entities; + private Entity addExtendedData(Entity entity, DXFEntity dxfEntity){ + for(DXFExtendedData dxfExtendedData : dxfEntity.getExtendedData()) { + + entity.AddExtendedData(dxfExtendedData.getName(),dxfExtendedData.getType(), dxfExtendedData.getValue()); + } + + return entity; } - - private List getEllipses(DXFLayer layer) { - List entities = new ArrayList(); - @SuppressWarnings("unchecked") - List dxfEllipses = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_ELLIPSE); - - if (dxfEllipses != null) { - for (DXFEllipse dxfEllipse : dxfEllipses) { - Entity entity = new Entity(); - - Point dxfCenter = dxfEllipse.getCenterPoint(); - // Bounds dxfBounds = dxfEllipse.getBounds(); - // Envelope dxfEnv = new Envelope(dxfBounds.getMinimumX(), - // dxfBounds.getMaximumX(), dxfBounds.getMinimumY(), - // dxfBounds.getMaximumY()); - - double width = dxfEllipse.getHalfMajorAxisLength() * 2; - double height = width * dxfEllipse.getRatio(); - GeometricShapeFactory geometricShapeFactory = new GeometricShapeFactory(); - geometricShapeFactory.setCentre(new Coordinate(dxfCenter.getX(), dxfCenter.getY())); - geometricShapeFactory.setWidth(width); - geometricShapeFactory.setHeight(height); - geometricShapeFactory.setRotation(dxfEllipse.getRotationAngle()); - - Geometry geometry = geometricShapeFactory.createEllipse(); - if (!this.ellipseAsPolygon) { - geometry = geometryFactory.createLineString(((Polygon) geometry).getExteriorRing().getCoordinates()); - } - - entity.setType(Entity.TYPE_ELLIPSE); - entity.setGeometry(geometry); - - entities.add(entity); - } - } - return entities; - } - - private List getArcs(DXFLayer layer) { - List entities = new ArrayList(); - @SuppressWarnings("unchecked") - List dxfArcs = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_ARC); - - if (dxfArcs != null) { - for (DXFArc dxfArc : dxfArcs) { - Entity entity = new Entity(); - - Point dxfCenter = dxfArc.getCenterPoint(); - double dxfStarAngle = dxfArc.getStartAngle(); - double dxfTotalAngle = dxfArc.getTotalAngle(); - - Coordinate center = new Coordinate(dxfCenter.getX(), dxfCenter.getY()); - - double startAngle = Angle.toRadians(dxfStarAngle); - double totalAngle = Angle.toRadians(dxfTotalAngle); - - GeometricShapeFactory geometricShapeFactory = new GeometricShapeFactory(); - geometricShapeFactory.setCentre(center); - geometricShapeFactory.setWidth(dxfArc.getRadius() * 2); - geometricShapeFactory.setHeight(dxfArc.getRadius() * 2); - Geometry geometry = geometricShapeFactory.createArc(startAngle, totalAngle); - - entity.setType(Entity.TYPE_ARC); - entity.setGeometry(geometry); - - entities.add(entity); - } - } - return entities; + + private List getPoints(DXFLayer layer){ + + List entities = new ArrayList(); + @SuppressWarnings("unchecked") + List dxfPoints = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_POINT); + + if(dxfPoints != null){ + + for(DXFPoint dxfPoint : dxfPoints){ + + Point dxfInsertPoint = dxfPoint.getPoint(); + + Entity entity = new Entity( + dxfPoint.getID(), + geometryFactory.createPoint( + new Coordinate( + dxfInsertPoint.getX(), + dxfInsertPoint.getY(), + dxfInsertPoint.getZ() + ) + ), + Entity.TYPE_POINT, + null + ); + + entities.add(addExtendedData(entity,dxfPoint)); + + } + } + + return entities; + } + + private List getBlocks(DXFLayer layer){ + + List entities = new ArrayList(); + @SuppressWarnings("unchecked") + List dxfInserts = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_INSERT); + + if(dxfInserts != null){ + + for(DXFInsert dxfInsert : dxfInserts){ + + Point dxfInsertPoint = dxfInsert.getPoint(); + + Entity entity = new Entity( + dxfInsert.getID(), + geometryFactory.createPoint( + new Coordinate( + dxfInsertPoint.getX(), + dxfInsertPoint.getY(), + dxfInsertPoint.getZ() + ) + ), + Entity.TYPE_BLOCK, + null + ); + + entities.add(addExtendedData(entity,dxfInsert)); + + } + } + + return entities; + + } + + private List getMTexts(DXFLayer layer){ + + List entities = new ArrayList(); + @SuppressWarnings("unchecked") + List dxfMTexts = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_MTEXT); + + if(dxfMTexts != null){ + + for(DXFMText dxfMText : dxfMTexts){ + + Point dxfInsertPoint = dxfMText.getInsertPoint(); + + Entity entity = new Entity( + dxfMText.getID(), + geometryFactory.createPoint( + new Coordinate( + dxfInsertPoint.getX(), + dxfInsertPoint.getY(), + dxfInsertPoint.getZ() + ) + ), + Entity.TYPE_MTEXT, + dxfMText.getText() + ); + + entities.add(addExtendedData(entity,dxfMText)); + + } + } + + return entities; + + } + + private List getTexts(DXFLayer layer){ + + List entities = new ArrayList(); + @SuppressWarnings("unchecked") + List dxfTexts = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_TEXT); + + if(dxfTexts != null){ + + for(DXFText dxfText : dxfTexts){ + + Point dxfInsertPoint = dxfText.getInsertPoint(); + + Entity entity = new Entity( + dxfText.getID(), + geometryFactory.createPoint( + new Coordinate( + dxfInsertPoint.getX(), + dxfInsertPoint.getY(), + dxfInsertPoint.getZ() + ) + ), + Entity.TYPE_TEXT, + dxfText.getText() + ); + + entities.add(addExtendedData(entity,dxfText)); + + } + } + + return entities; + + } + + private List getLines(DXFLayer layer){ + + List entities = new ArrayList(); + @SuppressWarnings("unchecked") + List dxfLines = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_LINE); + + if(dxfLines != null){ + + for(DXFLine dxfLine : dxfLines){ + + + Point start = dxfLine.getStartPoint(); + Point end = dxfLine.getEndPoint(); + + Entity entity = new Entity( + dxfLine.getID(), + geometryFactory.createLineString( + new Coordinate[]{ + new Coordinate(start.getX(),start.getY(),start.getZ()), + new Coordinate(end.getX(),end.getY(),end.getZ()) + } + ), + Entity.TYPE_LINE, + null + ); + + entities.add(addExtendedData(entity,dxfLine)); + } + } + + return entities; + + } + + private List getPolylines(DXFLayer layer){ + + List entities = new ArrayList(); + @SuppressWarnings("unchecked") + List dxfpolylines = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_POLYLINE); + + if(dxfpolylines != null){ + + for(DXFPolyline dxfPolyline : dxfpolylines){ + + CoordinateList coordinates = new CoordinateList(); + @SuppressWarnings("unchecked") + Iterator vertexIt = dxfPolyline.getVertexIterator(); + + while(vertexIt.hasNext()){ + + DXFVertex vertex = vertexIt.next(); + + if(!vertex.is2DSplineApproximationVertex() + && !vertex.is2DSplineControlVertex() + && !vertex.isCurveFitVertex()){ + + coordinates.add(new Coordinate(vertex.getX(),vertex.getY(),vertex.getZ()),false); + + } + + } + + if(dxfPolyline.isClosed()){ + coordinates.add(coordinates.get(0),false); + } + + Geometry geometry = geometryFactory.createLineString(coordinates.toCoordinateArray()); + if(((LineString)geometry).isClosed() && geometry.getCoordinates().length >= 4 && this.polylineAsPolygon){ + geometry = geometryFactory.createPolygon(geometry.getCoordinates()); + } + + Entity entity = new Entity( + dxfPolyline.getID(), + geometry, + Entity.TYPE_POLYLINE, + null + ); + + entities.add(addExtendedData(entity,dxfPolyline)); + + } + } + + return entities; + + } + + private List getLWPolylines(DXFLayer layer){ + + List entities = new ArrayList(); + @SuppressWarnings("unchecked") + List dxfLwPolylines = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_LWPOLYLINE); + + if(dxfLwPolylines != null){ + + for(DXFPolyline dxfLwPolyline : dxfLwPolylines){ + + CoordinateList coordinates = new CoordinateList(); + @SuppressWarnings("unchecked") + Iterator vertexIt = dxfLwPolyline.getVertexIterator(); + + while(vertexIt.hasNext()){ + + DXFVertex vertex = vertexIt.next(); + + if(!vertex.is2DSplineApproximationVertex() + && !vertex.is2DSplineControlVertex() + && !vertex.isCurveFitVertex()){ + + coordinates.add(new Coordinate(vertex.getX(),vertex.getY(), vertex.getZ()),false); + + } + + } + + if(dxfLwPolyline.isClosed()){ + coordinates.add(coordinates.get(0),false); + } + + Geometry geometry = geometryFactory.createLineString(coordinates.toCoordinateArray()); + if(((LineString)geometry).isClosed() && geometry.getCoordinates().length >= 4 && this.polylineAsPolygon){ + geometry = geometryFactory.createPolygon(geometry.getCoordinates()); + } + + Entity entity = new Entity( + dxfLwPolyline.getID(), + geometry, + Entity.TYPE_LWPOLYLINE, + null + ); + + entities.add(addExtendedData(entity,dxfLwPolyline)); + + } + } + + return entities; + + } + + private List getSplines(DXFLayer layer){ + + List entities = new ArrayList(); + @SuppressWarnings("unchecked") + List dxfSplines = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_SPLINE); + + if(dxfSplines != null){ + + for(DXFSpline dxfSpline : dxfSplines){ + + DXFPolyline dxfPolyline = DXFSplineConverter.toDXFPolyline(dxfSpline); + + CoordinateList coordinates = new CoordinateList(); + @SuppressWarnings("unchecked") + Iterator vertexIt = dxfPolyline.getVertexIterator(); + + while(vertexIt.hasNext()){ + + DXFVertex vertex = vertexIt.next(); + + if(!vertex.is2DSplineApproximationVertex() + && !vertex.is2DSplineControlVertex() + && !vertex.isCurveFitVertex()){ + + coordinates.add(new Coordinate(vertex.getX(),vertex.getY(),vertex.getZ()),false); + + } + + } + + if(dxfPolyline.isClosed()){ + coordinates.add(coordinates.get(0),false); + } + + Geometry geometry = geometryFactory.createLineString(coordinates.toCoordinateArray()); + if(((LineString)geometry).isClosed() && geometry.getCoordinates().length >= 4 && this.polylineAsPolygon){ + geometry = geometryFactory.createPolygon(geometry.getCoordinates()); + } + + Entity entity = new Entity( + dxfSpline.getID(), + geometry, + Entity.TYPE_LWPOLYLINE, + null + ); + + entities.add(addExtendedData(entity,dxfSpline)); + + } + } + + return entities; + + } + + private List getCircles(DXFLayer layer){ + + List entities = new ArrayList(); + @SuppressWarnings("unchecked") + List dxfCircles = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_CIRCLE); + + if(dxfCircles != null){ + + for(DXFCircle dxfCircle : dxfCircles){ + + + Point dxfCenter = dxfCircle.getCenterPoint(); + + GeometricShapeFactory geometricShapeFactory = new GeometricShapeFactory(); + geometricShapeFactory.setCentre(new Coordinate(dxfCenter.getX(),dxfCenter.getY())); + geometricShapeFactory.setWidth(dxfCircle.getRadius()*2); + geometricShapeFactory.setHeight(dxfCircle.getRadius()*2); + + Geometry geometry = geometricShapeFactory.createCircle(); + geometry = geometryFactory.createPolygon(setZ(geometry.getCoordinates(),dxfCenter.getZ())); + + if(!this.circleAsPolygon){ + geometry = geometryFactory.createLineString(((Polygon)geometry).getExteriorRing().getCoordinates()); + } + + Entity entity = new Entity( + dxfCircle.getID(), + geometry, + Entity.TYPE_CIRCLE, + null + ); + + entities.add(addExtendedData(entity,dxfCircle)); + + } + } + + return entities; + + } + + private List getEllipses(DXFLayer layer){ + + List entities = new ArrayList(); + @SuppressWarnings("unchecked") + List dxfEllipses = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_ELLIPSE); + + if(dxfEllipses != null){ + + for(DXFEllipse dxfEllipse : dxfEllipses){ + + Point dxfCenter = dxfEllipse.getCenterPoint(); + double width = dxfEllipse.getHalfMajorAxisLength() * 2; + double height = width * dxfEllipse.getRatio(); + GeometricShapeFactory geometricShapeFactory = new GeometricShapeFactory(); + geometricShapeFactory.setCentre(new Coordinate(dxfCenter.getX(),dxfCenter.getY())); + geometricShapeFactory.setWidth(width); + geometricShapeFactory.setHeight(height); + geometricShapeFactory.setRotation(dxfEllipse.getRotationAngle()); + + Geometry geometry = geometricShapeFactory.createEllipse(); + geometry = geometryFactory.createPolygon(setZ(geometry.getCoordinates(),dxfCenter.getZ())); + + if(!this.ellipseAsPolygon){ + geometry = geometryFactory.createLineString(((Polygon)geometry).getExteriorRing().getCoordinates()); + } + + Entity entity = new Entity( + dxfEllipse.getID(), + geometry, + Entity.TYPE_ELLIPSE, + null + ); + + entities.add(addExtendedData(entity,dxfEllipse)); + + } + } + + return entities; + + } + + private List getArcs(DXFLayer layer){ + + List entities = new ArrayList(); + @SuppressWarnings("unchecked") + List dxfArcs = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_ARC); + + if(dxfArcs != null){ + + for(DXFArc dxfArc : dxfArcs){ + + Point dxfCenter = dxfArc.getCenterPoint(); + double dxfStarAngle = dxfArc.getStartAngle(); + double dxfTotalAngle = dxfArc.getTotalAngle(); + + Coordinate center = new Coordinate(dxfCenter.getX(),dxfCenter.getY()); + + double startAngle = Angle.toRadians(dxfStarAngle); + double totalAngle = Angle.toRadians(dxfTotalAngle); + + GeometricShapeFactory geometricShapeFactory = new GeometricShapeFactory(); + geometricShapeFactory.setCentre(center); + geometricShapeFactory.setWidth(dxfArc.getRadius()*2); + geometricShapeFactory.setHeight(dxfArc.getRadius()*2); + Geometry geometry = geometricShapeFactory.createArc(startAngle, totalAngle); + geometry = geometryFactory.createLineString(setZ(geometry.getCoordinates(),dxfCenter.getZ())); + + Entity entity = new Entity( + dxfArc.getID(), + geometry, + Entity.TYPE_ARC, + null + ); + + entities.add(addExtendedData(entity,dxfArc)); + + } + } + + return entities; + + } + + private Coordinate[] setZ(Coordinate[] coordinates, double zValue){ + + for(Coordinate coordinate : coordinates){ + coordinate.z = zValue; + } + + return coordinates; + } } \ No newline at end of file diff --git a/dxf/src/main/java/com/atolcd/gis/dxf/DXFWriter.java b/dxf/src/main/java/com/atolcd/gis/dxf/DXFWriter.java new file mode 100644 index 0000000..e9d1c7a --- /dev/null +++ b/dxf/src/main/java/com/atolcd/gis/dxf/DXFWriter.java @@ -0,0 +1,92 @@ +package com.atolcd.gis.dxf; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import com.vividsolutions.jts.geom.Envelope; + +import fr.michaelm.jump.drivers.dxf.DxfENTITY; +import fr.michaelm.jump.drivers.dxf.DxfFile; +import fr.michaelm.jump.drivers.dxf.DxfXDATA; + +public class DXFWriter { + + private String dxfFileName; + private List layers; + + public DXFWriter(String fileName) { + + int pointIndex = fileName.lastIndexOf('.'); + if (pointIndex > 0) { + fileName = fileName.substring(0,pointIndex); + } + + this.dxfFileName = fileName.concat(".dxf"); + this.layers = new ArrayList(); + + } + + public void addLayer(Layer layer){ + this.layers.add(layer); + } + + public void write(int precision, boolean writeXData) throws IOException{ + + List layerNames = new ArrayList(); + Envelope extent = null; + List entities = new ArrayList(); + + for(Layer layer : this.layers){ + + //Alimente la liste des layers + layerNames.add(layer.getName()); + + //Calcul de l'extent globale + for (Entity entity:layer.getEntities()){ + + if(extent != null){ + extent.expandToInclude(entity.getGeometry().getEnvelopeInternal()); + }else{ + extent = entity.getGeometry().getEnvelopeInternal(); + } + + + //Conversion Entity -> DxfEntity + DxfENTITY dxfENTITY = new DxfENTITY(layer.getName(), entity.getGeometry()); + + for(ExtendedData extendedData : entity.getExtendedData()){ + + int code; + + if(extendedData.getType().equals(String.class)){ + code = DxfXDATA.GROUPCODE_XDATA_STRING; + + }else if(extendedData.getType().equals(Double.class)){ + code = DxfXDATA.GROUPCODE_XDATA_REAL; + + }else if(extendedData.getType().equals(Integer.class)){ + code = DxfXDATA.GROUPCODE_XDATA_INTEGER; + + }else if(extendedData.getType().equals(Long.class)){ + code = DxfXDATA.GROUPCODE_XDATA_LONG; + + }else{ + code = DxfXDATA.GROUPCODE_XDATA_STRING; + } + + dxfENTITY.addXData(new DxfXDATA(extendedData.getName(), code, extendedData.getValue())); + + } + + entities.add(dxfENTITY); + + } + + } + + DxfFile.write(this.dxfFileName, layerNames, extent, entities ,precision, writeXData); + + } + +} diff --git a/dxf/src/main/java/com/atolcd/gis/dxf/Entity.java b/dxf/src/main/java/com/atolcd/gis/dxf/Entity.java index dfbdb92..0088371 100644 --- a/dxf/src/main/java/com/atolcd/gis/dxf/Entity.java +++ b/dxf/src/main/java/com/atolcd/gis/dxf/Entity.java @@ -1,5 +1,8 @@ package com.atolcd.gis.dxf; +import java.util.ArrayList; +import java.util.List; + import com.vividsolutions.jts.geom.Geometry; public class Entity { @@ -12,10 +15,22 @@ public class Entity { public static String TYPE_CIRCLE = "CIRCLE"; public static String TYPE_ELLIPSE = "ELLIPSE"; public static String TYPE_ARC = "ARC"; + public static String TYPE_BLOCK = "BLOCK"; + public static String TYPE_POINT = "POINT"; + + private String id; + private Geometry geometry; + private String type; + private String text; + private List extendedData; - private Geometry geometry; - private String type; - private String text; + public Entity(String id, Geometry geometry,String type, String text){ + this.id = id; + this.geometry = geometry; + this.type = type; + this.text = text; + this.extendedData = new ArrayList(); + } public Geometry getGeometry() { return geometry; @@ -41,4 +56,20 @@ public void setText(String text) { this.text = text; } + public List getExtendedData() { + return extendedData; + } + + public void AddExtendedData(ExtendedData extendedData){ + this.getExtendedData().add(extendedData); + } + + public void AddExtendedData(String name, Class type, Object value){ + this.getExtendedData().add(new ExtendedData(name, type, value)); + } + + public String getId() { + return id; + } + } diff --git a/dxf/src/main/java/com/atolcd/gis/dxf/ExtendedData.java b/dxf/src/main/java/com/atolcd/gis/dxf/ExtendedData.java new file mode 100644 index 0000000..9e49186 --- /dev/null +++ b/dxf/src/main/java/com/atolcd/gis/dxf/ExtendedData.java @@ -0,0 +1,39 @@ +package com.atolcd.gis.dxf; + +public class ExtendedData { + + private String name; + private Class type; + private Object value; + + public ExtendedData(String name,Class type, Object value) { + this.name = name; + this.type = type; + this.value = value; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Class getType() { + return type; + } + + public void setType(Class type) { + this.type = type; + } + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + +} diff --git a/dxf/src/main/java/com/atolcd/gis/dxf/Layer.java b/dxf/src/main/java/com/atolcd/gis/dxf/Layer.java index 63f8543..5db4613 100644 --- a/dxf/src/main/java/com/atolcd/gis/dxf/Layer.java +++ b/dxf/src/main/java/com/atolcd/gis/dxf/Layer.java @@ -8,7 +8,7 @@ public class Layer { private String name; private List entities; - protected Layer(String name) { + public Layer(String name) { this.name = name; this.entities = new ArrayList(); } diff --git a/dxf/src/main/java/fr/michaelm/jump/drivers/dxf/DxfENTITY.java b/dxf/src/main/java/fr/michaelm/jump/drivers/dxf/DxfENTITY.java index 1d88c41..1510d9d 100644 --- a/dxf/src/main/java/fr/michaelm/jump/drivers/dxf/DxfENTITY.java +++ b/dxf/src/main/java/fr/michaelm/jump/drivers/dxf/DxfENTITY.java @@ -1,4 +1,6 @@ package fr.michaelm.jump.drivers.dxf; +import java.util.ArrayList; +import java.util.List; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; @@ -8,79 +10,143 @@ import com.vividsolutions.jts.geom.Polygon; public class DxfENTITY { + + private String layerName; + private Geometry geometry; + private List xData; + + public DxfENTITY(String layerName, Geometry geometry) { + this.layerName = layerName; + this.geometry = geometry; + this.xData = new ArrayList(); + } + + public String getLayerName() { + return layerName; + } + + public Geometry getGeometry() { + return geometry; + } + + public List getxData() { + return xData; + } + + public void addXData(DxfXDATA xData){ + this.xData.add(xData); + } + + public String toDXF(int precision, boolean writeXData){ + + StringBuffer sb = new StringBuffer(); + + if (this.geometry.getGeometryType().equals("Point")) { + + sb.append(pointToDXF(geometry, layerName, precision, this.xData)); + + } + else if (this.geometry.getGeometryType().equals("LineString")) { + + sb.append(lineStringToDXF(geometry, layerName, precision, this.xData)); + + } + else if (this.geometry.getGeometryType().equals("Polygon")) { + sb.append(polygonToDXF(geometry, layerName, precision, this.xData)); + + } else if (this.geometry instanceof GeometryCollection) { + + for (int i = 0 ; i < this.geometry.getNumGeometries() ; i++) { + + Geometry geometryN = this.geometry.getGeometryN(i); + + if (geometryN.getGeometryType().equals("Point")) { + sb.append(pointToDXF(geometryN, layerName, precision,this.xData)); + + } else if (geometryN.getGeometryType().equals("LineString")) { + sb.append(lineStringToDXF(geometryN, layerName, precision,this.xData)); + + } else if (geometryN.getGeometryType().equals("Polygon")) { + sb.append(polygonToDXF(geometryN, layerName, precision, this.xData)); + + } - public static String geometry2Dxf(Geometry geometry, String layerName, int precision) { - - Geometry g = geometry; - - if (g.getGeometryType().equals("Point")) { - return point2Dxf(geometry, layerName, precision); - } else if (g.getGeometryType().equals("LineString")) { - return lineString2Dxf(geometry, layerName, precision); - } else if (g.getGeometryType().equals("Polygon")) { - return polygon2Dxf(geometry, layerName, precision); - } else if (g instanceof GeometryCollection) { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < g.getNumGeometries(); i++) { - Geometry ff = g.getGeometryN(i); - sb.append(geometry2Dxf(ff, layerName, precision)); } - return sb.toString(); - } else { - return null; + } + + return sb.toString(); + } + + private static StringBuffer xDataToDXF(StringBuffer sb, List xDatas){ + + for(DxfXDATA xData : xDatas){ + sb.append(DxfGroup.toString(DxfXDATA.GROUPCODE_XDATA_APP_NAME, xData.getName())); + sb.append(DxfGroup.toString(xData.getCode(), xData.getValue().toString())); + } + return sb; + } + - public static String point2Dxf(Geometry geometry, String layerName, int precision) { + private static String pointToDXF(Geometry geometry, String layerName, int precision, List xDatas) { StringBuffer sb = new StringBuffer(DxfGroup.toString(0, "POINT")); sb.append(DxfGroup.toString(8, layerName)); - Coordinate coord = ((Point) geometry).getCoordinate(); + Coordinate coord = ((Point)geometry).getCoordinate(); sb.append(DxfGroup.toString(10, coord.x, precision)); sb.append(DxfGroup.toString(20, coord.y, precision)); - if (!Double.isNaN(coord.z)) { - sb.append(DxfGroup.toString(30, coord.z, precision)); + if (!Double.isNaN(coord.z)){ + sb.append(DxfGroup.toString(30, coord.z, precision)); } + + sb = xDataToDXF(sb,xDatas); + return sb.toString(); } - public static String lineString2Dxf(Geometry geometry, String layerName, int precision) { - LineString geom = (LineString) geometry; + private static String lineStringToDXF(Geometry geometry, String layerName,int precision, List xDatas) { + LineString geom = (LineString)geometry; Coordinate[] coords = geom.getCoordinates(); boolean isLine = (coords.length == 2); StringBuffer sb; if (!isLine) { - sb = new StringBuffer(DxfGroup.toString(0, "POLYLINE")); - } else { - sb = new StringBuffer(DxfGroup.toString(0, "LINE")); + sb = new StringBuffer(DxfGroup.toString(0, "POLYLINE")); + } + else { + sb = new StringBuffer(DxfGroup.toString(0, "LINE")); } sb.append(DxfGroup.toString(8, layerName)); - if (isLine) { + if (isLine){ sb.append(DxfGroup.toString(10, coords[0].x, precision)); sb.append(DxfGroup.toString(20, coords[0].y, precision)); - if (!Double.isNaN(coords[0].z)) { - sb.append(DxfGroup.toString(30, coords[0].z, precision)); - } + if (!Double.isNaN(coords[0].z)) { + sb.append(DxfGroup.toString(30, coords[0].z, precision)); + } sb.append(DxfGroup.toString(11, coords[1].x, precision)); sb.append(DxfGroup.toString(21, coords[1].y, precision)); - if (!Double.isNaN(coords[1].z)) { - sb.append(DxfGroup.toString(31, coords[1].z, precision)); - } - } else { + if (!Double.isNaN(coords[1].z)) { + sb.append(DxfGroup.toString(31, coords[1].z, precision)); + } + + sb = xDataToDXF(sb,xDatas); + + } + else { sb.append(DxfGroup.toString(66, 1)); sb.append(DxfGroup.toString(10, "0.0")); sb.append(DxfGroup.toString(20, "0.0")); - if (!Double.isNaN(coords[0].z)) - sb.append(DxfGroup.toString(30, "0.0")); + if (!Double.isNaN(coords[0].z)) sb.append(DxfGroup.toString(30, "0.0")); sb.append(DxfGroup.toString(70, 8)); - for (int i = 0; i < coords.length; i++) { + sb = xDataToDXF(sb,xDatas); + + for (int i = 0 ; i < coords.length ; i++) { sb.append(DxfGroup.toString(0, "VERTEX")); sb.append(DxfGroup.toString(8, layerName)); sb.append(DxfGroup.toString(10, coords[i].x, precision)); sb.append(DxfGroup.toString(20, coords[i].y, precision)); - if (!Double.isNaN(coords[i].z)) - sb.append(DxfGroup.toString(30, coords[i].z, precision)); + if (!Double.isNaN(coords[i].z)) sb.append(DxfGroup.toString(30, coords[i].z, precision)); sb.append(DxfGroup.toString(70, 32)); } sb.append(DxfGroup.toString(0, "SEQEND")); @@ -88,50 +154,53 @@ public static String lineString2Dxf(Geometry geometry, String layerName, int pre return sb.toString(); } - public static String polygon2Dxf(Geometry geometry, String layerName, int precision) { - Polygon geom = (Polygon) geometry; + private static String polygonToDXF(Geometry geometry, String layerName,int precision, List xDatas) { + Polygon geom = (Polygon)geometry; Coordinate[] coords = geom.getExteriorRing().getCoordinates(); StringBuffer sb = new StringBuffer(DxfGroup.toString(0, "POLYLINE")); sb.append(DxfGroup.toString(8, layerName)); sb.append(DxfGroup.toString(66, 1)); sb.append(DxfGroup.toString(10, "0.0")); sb.append(DxfGroup.toString(20, "0.0")); - if (!Double.isNaN(coords[0].z)) - sb.append(DxfGroup.toString(30, "0.0")); + if (!Double.isNaN(coords[0].z)) sb.append(DxfGroup.toString(30, "0.0")); sb.append(DxfGroup.toString(70, 9)); - for (int i = 0; i < coords.length; i++) { + + sb = xDataToDXF(sb,xDatas); + + for (int i = 0 ; i < coords.length ; i++) { sb.append(DxfGroup.toString(0, "VERTEX")); sb.append(DxfGroup.toString(8, layerName)); sb.append(DxfGroup.toString(10, coords[i].x, precision)); sb.append(DxfGroup.toString(20, coords[i].y, precision)); - if (!Double.isNaN(coords[i].z)) - sb.append(DxfGroup.toString(30, coords[i].z, precision)); + if (!Double.isNaN(coords[i].z)) sb.append(DxfGroup.toString(30, coords[i].z, precision)); sb.append(DxfGroup.toString(70, 32)); } sb.append(DxfGroup.toString(0, "SEQEND")); - for (int h = 0; h < geom.getNumInteriorRing(); h++) { + for (int h = 0 ; h < geom.getNumInteriorRing() ; h++) { sb.append(DxfGroup.toString(0, "POLYLINE")); sb.append(DxfGroup.toString(8, layerName)); sb.append(DxfGroup.toString(66, 1)); sb.append(DxfGroup.toString(10, "0.0")); sb.append(DxfGroup.toString(20, "0.0")); - if (!Double.isNaN(coords[0].z)) - sb.append(DxfGroup.toString(30, "0.0")); + if (!Double.isNaN(coords[0].z)) sb.append(DxfGroup.toString(30, "0.0")); sb.append(DxfGroup.toString(70, 9)); + + sb = xDataToDXF(sb,xDatas); + coords = geom.getInteriorRingN(h).getCoordinates(); - for (int i = 0; i < coords.length; i++) { + for (int i = 0 ; i < coords.length ; i++) { sb.append(DxfGroup.toString(0, "VERTEX")); sb.append(DxfGroup.toString(8, layerName)); sb.append(DxfGroup.toString(10, coords[i].x, precision)); sb.append(DxfGroup.toString(20, coords[i].y, precision)); - if (!Double.isNaN(coords[i].z)) - sb.append(DxfGroup.toString(30, coords[i].z, precision)); + if (!Double.isNaN(coords[i].z)) sb.append(DxfGroup.toString(30, coords[i].z, precision)); sb.append(DxfGroup.toString(70, 32)); } sb.append(DxfGroup.toString(0, "SEQEND")); } - + return sb.toString(); - } + + } } diff --git a/dxf/src/main/java/fr/michaelm/jump/drivers/dxf/DxfFile.java b/dxf/src/main/java/fr/michaelm/jump/drivers/dxf/DxfFile.java index add0beb..c0b4418 100644 --- a/dxf/src/main/java/fr/michaelm/jump/drivers/dxf/DxfFile.java +++ b/dxf/src/main/java/fr/michaelm/jump/drivers/dxf/DxfFile.java @@ -2,115 +2,220 @@ import java.io.FileWriter; import java.io.IOException; +import java.util.ArrayList; import java.util.List; -import com.vividsolutions.jts.geom.Envelope; +import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; +import com.vividsolutions.jts.geom.Envelope; import com.vividsolutions.jts.geom.GeometryFactory; +import com.vividsolutions.jts.geom.LineString; +import com.vividsolutions.jts.geom.Point; +import com.vividsolutions.jts.geom.Polygon; public class DxfFile { + + public static GeometryFactory geometryFactory = new GeometryFactory(); - public static GeometryFactory geometryFactory = new GeometryFactory(); - - public DxfFile() { - } - - public void write(List geometries, String[] layerNames, FileWriter fw, int precision) { - - Envelope envelope = geometryFactory.buildGeometry(geometries).getEnvelopeInternal(); - // Date date = new Date(System.currentTimeMillis()); + public static void write(String fileName, List layerNames, Envelope envelope, List entities, int precision, boolean writeXData) throws IOException { + + if(envelope == null){ + envelope = new Envelope(0, 0, 0, 0); + } + + if(layerNames== null){ + layerNames = new ArrayList(); + layerNames.add("0"); + } + + FileWriter fw = new FileWriter(fileName); + try { // ECRITURE DU HEADER fw.write(DxfGroup.toString(0, "SECTION")); fw.write(DxfGroup.toString(2, "HEADER")); fw.write(DxfGroup.toString(9, "$ACADVER")); - fw.write(DxfGroup.toString(1, "AC1009")); + fw.write(DxfGroup.toString(1, "AC1009")); fw.write(DxfGroup.toString(9, "$CECOLOR")); - fw.write(DxfGroup.toString(62, 256)); + fw.write(DxfGroup.toString(62, 256)); fw.write(DxfGroup.toString(9, "$CELTYPE")); - fw.write(DxfGroup.toString(6, "DUPLAN")); + fw.write(DxfGroup.toString(6, "DUPLAN")); fw.write(DxfGroup.toString(9, "$CLAYER")); - fw.write(DxfGroup.toString(8, "0")); + fw.write(DxfGroup.toString(8, "0")); fw.write(DxfGroup.toString(9, "$ELEVATION")); - fw.write(DxfGroup.toString(40, 0.0, 3)); + fw.write(DxfGroup.toString(40, 0.0, 3)); fw.write(DxfGroup.toString(9, "$EXTMAX")); - fw.write(DxfGroup.toString(10, envelope.getMaxX(), 6)); - fw.write(DxfGroup.toString(20, envelope.getMaxY(), 6)); + fw.write(DxfGroup.toString(10, envelope.getMaxX(), 6)); + fw.write(DxfGroup.toString(20, envelope.getMaxY(), 6)); fw.write(DxfGroup.toString(9, "$EXTMIN")); - fw.write(DxfGroup.toString(10, envelope.getMinX(), 6)); - fw.write(DxfGroup.toString(20, envelope.getMinY(), 6)); + fw.write(DxfGroup.toString(10, envelope.getMinX(), 6)); + fw.write(DxfGroup.toString(20, envelope.getMinY(), 6)); fw.write(DxfGroup.toString(9, "$INSBASE")); - fw.write(DxfGroup.toString(10, 0.0, 1)); - fw.write(DxfGroup.toString(20, 0.0, 1)); - fw.write(DxfGroup.toString(30, 0.0, 1)); + fw.write(DxfGroup.toString(10, 0.0, 1)); + fw.write(DxfGroup.toString(20, 0.0, 1)); + fw.write(DxfGroup.toString(30, 0.0, 1)); fw.write(DxfGroup.toString(9, "$LIMCHECK")); - fw.write(DxfGroup.toString(70, 1)); + fw.write(DxfGroup.toString(70, 1)); fw.write(DxfGroup.toString(9, "$LIMMAX")); - fw.write(DxfGroup.toString(10, envelope.getMaxX(), 6)); - fw.write(DxfGroup.toString(20, envelope.getMaxY(), 6)); + fw.write(DxfGroup.toString(10, envelope.getMaxX(), 6)); + fw.write(DxfGroup.toString(20, envelope.getMaxY(), 6)); fw.write(DxfGroup.toString(9, "$LIMMIN")); - fw.write(DxfGroup.toString(10, envelope.getMinX(), 6)); - fw.write(DxfGroup.toString(20, envelope.getMinY(), 6)); + fw.write(DxfGroup.toString(10, envelope.getMinX(), 6)); + fw.write(DxfGroup.toString(20, envelope.getMinY(), 6)); fw.write(DxfGroup.toString(9, "$LUNITS")); - fw.write(DxfGroup.toString(70, 2)); + fw.write(DxfGroup.toString(70, 2)); fw.write(DxfGroup.toString(9, "$LUPREC")); - fw.write(DxfGroup.toString(70, 2)); + fw.write(DxfGroup.toString(70, 2)); fw.write(DxfGroup.toString(0, "ENDSEC")); // ECRITURE DES TABLES fw.write(DxfGroup.toString(0, "SECTION")); fw.write(DxfGroup.toString(2, "TABLES")); - fw.write(DxfGroup.toString(0, "TABLE")); - fw.write(DxfGroup.toString(2, "STYLE")); - fw.write(DxfGroup.toString(70, 1)); - fw.write(DxfGroup.toString(0, "STYLE")); // added by L. Becker on - // 2006-11-08 - DxfTABLE_STYLE_ITEM style = new DxfTABLE_STYLE_ITEM("STANDARD", 0, 0f, 1f, 0f, 0, 1.0f, "xxx.txt", "yyy.txt"); - fw.write(style.toString()); - fw.write(DxfGroup.toString(0, "ENDTAB")); - fw.write(DxfGroup.toString(0, "TABLE")); - fw.write(DxfGroup.toString(2, "LTYPE")); - fw.write(DxfGroup.toString(70, 1)); - fw.write(DxfGroup.toString(0, "LTYPE")); // added by L. Becker on - // 2006-11-08 - DxfTABLE_LTYPE_ITEM ltype = new DxfTABLE_LTYPE_ITEM("CONTINUE", 0, "", 65, 0f, new float[0]); - fw.write(ltype.toString()); - fw.write(DxfGroup.toString(0, "ENDTAB")); - fw.write(DxfGroup.toString(0, "TABLE")); - fw.write(DxfGroup.toString(2, "LAYER")); - fw.write(DxfGroup.toString(70, 2)); - for (int i = 0; i < layerNames.length; i++) { - DxfTABLE_LAYER_ITEM layer = new DxfTABLE_LAYER_ITEM(layerNames[i], 0, 131, "CONTINUE"); - fw.write(DxfGroup.toString(0, "LAYER")); - fw.write(layer.toString()); - } - fw.write(DxfGroup.toString(0, "ENDTAB")); - fw.write(DxfGroup.toString(0, "ENDSEC")); - - // ECRITURE DES FEATURES - fw.write(DxfGroup.toString(0, "SECTION")); - fw.write(DxfGroup.toString(2, "ENTITIES")); - for (Geometry geometry : geometries) { - fw.write(DxfENTITY.geometry2Dxf(geometry, geometry.getUserData().toString(), precision)); - } - - fw.write(DxfGroup.toString(0, "ENDSEC")); + fw.write(DxfGroup.toString(0, "TABLE")); + fw.write(DxfGroup.toString(2, "STYLE")); + fw.write(DxfGroup.toString(70, 1)); + fw.write(DxfGroup.toString(0, "STYLE")); // added by L. Becker on 2006-11-08 + DxfTABLE_STYLE_ITEM style = + new DxfTABLE_STYLE_ITEM("STANDARD", 0, 0f, 1f, 0f, 0, 1.0f, "xxx.txt", "yyy.txt"); + fw.write(style.toString()); + fw.write(DxfGroup.toString(0, "ENDTAB")); + fw.write(DxfGroup.toString(0, "TABLE")); + fw.write(DxfGroup.toString(2, "LTYPE")); + fw.write(DxfGroup.toString(70, 1)); + fw.write(DxfGroup.toString(0, "LTYPE")); // added by L. Becker on 2006-11-08 + DxfTABLE_LTYPE_ITEM ltype = + new DxfTABLE_LTYPE_ITEM("CONTINUE", 0, "", 65, 0f, new float[0]); + fw.write(ltype.toString()); + fw.write(DxfGroup.toString(0, "ENDTAB")); + fw.write(DxfGroup.toString(0, "TABLE")); + fw.write(DxfGroup.toString(2, "LAYER")); + fw.write(DxfGroup.toString(70, 2)); + for (String layerName: layerNames){ + DxfTABLE_LAYER_ITEM layer = new DxfTABLE_LAYER_ITEM(layerName, 0, 131, "CONTINUE"); + fw.write(DxfGroup.toString(0, "LAYER")); + fw.write(layer.toString()); + } + fw.write(DxfGroup.toString(0, "ENDTAB")); + fw.write(DxfGroup.toString(0, "ENDSEC")); + + // ECRITURE DES FEATURES + fw.write(DxfGroup.toString(0, "SECTION")); + fw.write(DxfGroup.toString(2, "ENTITIES")); + for(DxfENTITY entity : entities){ + fw.write(entity.toDXF(precision, writeXData)); + } + fw.write(DxfGroup.toString(0, "ENDSEC")); + // FIN DE FICHIER fw.write(DxfGroup.toString(0, "EOF")); fw.flush(); - } catch (IOException ioe) { + } catch(IOException ioe) { ioe.printStackTrace(); } finally { - if (null != fw) - try { - fw.close(); - } catch (IOException ioe) { - } - ; + if (null != fw) try {fw.close();} catch(IOException ioe){}; } return; } + + public static String point2Dxf(Geometry geometry, String layerName, int precision) { + + StringBuffer sb = new StringBuffer(DxfGroup.toString(0, "POINT")); + sb.append(DxfGroup.toString(8, layerName)); + Coordinate coord = ((Point)geometry).getCoordinate(); + sb.append(DxfGroup.toString(10, coord.x, precision)); + sb.append(DxfGroup.toString(20, coord.y, precision)); + if (!Double.isNaN(coord.z)){ + sb.append(DxfGroup.toString(30, coord.z, precision)); + } + return sb.toString(); + } + + public static String lineString2Dxf(Geometry geometry, String layerName,int precision) { + LineString geom = (LineString)geometry; + Coordinate[] coords = geom.getCoordinates(); + boolean isLine = (coords.length == 2); + StringBuffer sb; + if (!isLine) { + sb = new StringBuffer(DxfGroup.toString(0, "POLYLINE")); + } + else { + sb = new StringBuffer(DxfGroup.toString(0, "LINE")); + } + sb.append(DxfGroup.toString(8, layerName)); + if (isLine){ + sb.append(DxfGroup.toString(10, coords[0].x, precision)); + sb.append(DxfGroup.toString(20, coords[0].y, precision)); + if (!Double.isNaN(coords[0].z)) { + sb.append(DxfGroup.toString(30, coords[0].z, precision)); + } + sb.append(DxfGroup.toString(11, coords[1].x, precision)); + sb.append(DxfGroup.toString(21, coords[1].y, precision)); + if (!Double.isNaN(coords[1].z)) { + sb.append(DxfGroup.toString(31, coords[1].z, precision)); + } + } + else { + sb.append(DxfGroup.toString(66, 1)); + sb.append(DxfGroup.toString(10, "0.0")); + sb.append(DxfGroup.toString(20, "0.0")); + if (!Double.isNaN(coords[0].z)) sb.append(DxfGroup.toString(30, "0.0")); + sb.append(DxfGroup.toString(70, 8)); + + for (int i = 0 ; i < coords.length ; i++) { + sb.append(DxfGroup.toString(0, "VERTEX")); + sb.append(DxfGroup.toString(8, layerName)); + sb.append(DxfGroup.toString(10, coords[i].x, precision)); + sb.append(DxfGroup.toString(20, coords[i].y, precision)); + if (!Double.isNaN(coords[i].z)) sb.append(DxfGroup.toString(30, coords[i].z, precision)); + sb.append(DxfGroup.toString(70, 32)); + } + sb.append(DxfGroup.toString(0, "SEQEND")); + } + return sb.toString(); + } + + public static String polygon2Dxf(Geometry geometry, String layerName,int precision) { + Polygon geom = (Polygon)geometry; + Coordinate[] coords = geom.getExteriorRing().getCoordinates(); + StringBuffer sb = new StringBuffer(DxfGroup.toString(0, "POLYLINE")); + sb.append(DxfGroup.toString(8, layerName)); + sb.append(DxfGroup.toString(66, 1)); + sb.append(DxfGroup.toString(10, "0.0")); + sb.append(DxfGroup.toString(20, "0.0")); + if (!Double.isNaN(coords[0].z)) sb.append(DxfGroup.toString(30, "0.0")); + sb.append(DxfGroup.toString(70, 9)); + for (int i = 0 ; i < coords.length ; i++) { + sb.append(DxfGroup.toString(0, "VERTEX")); + sb.append(DxfGroup.toString(8, layerName)); + sb.append(DxfGroup.toString(10, coords[i].x, precision)); + sb.append(DxfGroup.toString(20, coords[i].y, precision)); + if (!Double.isNaN(coords[i].z)) sb.append(DxfGroup.toString(30, coords[i].z, precision)); + sb.append(DxfGroup.toString(70, 32)); + } + sb.append(DxfGroup.toString(0, "SEQEND")); + for (int h = 0 ; h < geom.getNumInteriorRing() ; h++) { + sb.append(DxfGroup.toString(0, "POLYLINE")); + sb.append(DxfGroup.toString(8, layerName)); + sb.append(DxfGroup.toString(66, 1)); + sb.append(DxfGroup.toString(10, "0.0")); + sb.append(DxfGroup.toString(20, "0.0")); + if (!Double.isNaN(coords[0].z)) sb.append(DxfGroup.toString(30, "0.0")); + sb.append(DxfGroup.toString(70, 9)); + coords = geom.getInteriorRingN(h).getCoordinates(); + for (int i = 0 ; i < coords.length ; i++) { + sb.append(DxfGroup.toString(0, "VERTEX")); + sb.append(DxfGroup.toString(8, layerName)); + sb.append(DxfGroup.toString(10, coords[i].x, precision)); + sb.append(DxfGroup.toString(20, coords[i].y, precision)); + if (!Double.isNaN(coords[i].z)) sb.append(DxfGroup.toString(30, coords[i].z, precision)); + sb.append(DxfGroup.toString(70, 32)); + } + sb.append(DxfGroup.toString(0, "SEQEND")); + } + + return sb.toString(); + } } diff --git a/dxf/src/main/java/fr/michaelm/jump/drivers/dxf/DxfGroup.java b/dxf/src/main/java/fr/michaelm/jump/drivers/dxf/DxfGroup.java index 9349b72..f9b01dd 100644 --- a/dxf/src/main/java/fr/michaelm/jump/drivers/dxf/DxfGroup.java +++ b/dxf/src/main/java/fr/michaelm/jump/drivers/dxf/DxfGroup.java @@ -24,118 +24,101 @@ package fr.michaelm.jump.drivers.dxf; -import java.io.IOException; import java.io.RandomAccessFile; +import java.io.IOException; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Locale; /** - * DxfGroup is a group containing a dxf code and a dxf value. The class contains - * several utils to read and write groups an to format data. - * + * DxfGroup is a group containing a dxf code and a dxf value. + * The class contains several utils to read and write groups an to format data. * @author Michaël Michaud */ public class DxfGroup { // Write international decimal symbol (.), not the french one (,) private static final DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.US); - private static final DecimalFormat[] decimalFormats = new DecimalFormat[] { new DecimalFormat("#0", dfs), new DecimalFormat("#0.0", dfs), new DecimalFormat("#0.00", dfs), - new DecimalFormat("#0.000", dfs), new DecimalFormat("#0.0000", dfs), new DecimalFormat("#0.00000", dfs), new DecimalFormat("#0.000000", dfs), - new DecimalFormat("#0.0000000", dfs), new DecimalFormat("#0.00000000", dfs), new DecimalFormat("#0.000000000", dfs), new DecimalFormat("#0.0000000000", dfs), - new DecimalFormat("#0.00000000000", dfs), new DecimalFormat("#0.000000000000", dfs) }; + private static final DecimalFormat[] decimalFormats = new DecimalFormat[]{ + new DecimalFormat("#0", dfs), + new DecimalFormat("#0.0", dfs), + new DecimalFormat("#0.00", dfs), + new DecimalFormat("#0.000", dfs), + new DecimalFormat("#0.0000", dfs), + new DecimalFormat("#0.00000", dfs), + new DecimalFormat("#0.000000", dfs), + new DecimalFormat("#0.0000000", dfs), + new DecimalFormat("#0.00000000", dfs), + new DecimalFormat("#0.000000000", dfs), + new DecimalFormat("#0.0000000000", dfs), + new DecimalFormat("#0.00000000000", dfs), + new DecimalFormat("#0.000000000000", dfs)}; private int code = -1; private String value; private long address; - + public DxfGroup(int code, String value) { this.code = code; this.value = value; } - + public DxfGroup(String code, String value) { try { this.value = value; this.code = Integer.parseInt(code.trim()); - } catch (NumberFormatException nfe) { - System.out.println("Error reading group: \"" + code + "=" + value + "\" is not a valid code/value pair"); + } + catch(NumberFormatException nfe) { + System.out.println("Error reading group: \"" + code + "=" + + value + "\" is not a valid code/value pair"); } } - public int getCode() { - return code; - } - - public void setCode(int code) { - this.code = code; - } - - public String getValue() { - return value; - } - - public int getIntValue() { - return Integer.parseInt(value.trim()); - } - - public float getFloatValue() { - return Float.parseFloat(value.trim()); - } - - public double getDoubleValue() { - return Double.parseDouble(value.trim()); - } - - public void setValue(String value) { - this.value = value; - } - - public long getAddress() { - return address; - } - - private void setAddress(long address) { - this.address = address; - } - - public boolean equals(Object other) { - if (other instanceof DxfGroup && code == ((DxfGroup) other).getCode() && value.equals(((DxfGroup) other).getValue())) { + public int getCode() {return code;} + public void setCode(int code) {this.code = code;} + public String getValue() {return value;} + public int getIntValue() {return Integer.parseInt(value.trim());} + public float getFloatValue() {return Float.parseFloat(value.trim());} + public double getDoubleValue() {return Double.parseDouble(value.trim());} + public void setValue(String value) {this.value = value;} + public long getAddress() {return address;} + private void setAddress(long address) {this.address = address;} + + public boolean equals(Object other){ + if (other instanceof DxfGroup && + code==((DxfGroup)other).getCode() && + value.equals(((DxfGroup)other).getValue())) { return true; - } else - return false; + } + else return false; } - + public String toString() { String codeString = " " + Integer.toString(code); int stringLength = codeString.length(); - codeString = codeString.substring(stringLength - (code < 1000 ? 3 : 4), stringLength); + codeString = codeString.substring(stringLength-(code<1000?3:4), stringLength); return codeString + "\r\n" + value + "\r\n"; } - + public void print(int indent) { - for (int i = 0; i < indent; i++) - System.out.print(" "); + for (int i = 0 ; i < indent ; i++) System.out.print(" "); System.out.println("" + code + " = " + value); } - + public boolean isValid() { return code >= 0; } - + public static String int34car(int code) { - if (code < 10) - return " " + Integer.toString(code); - else if (code < 100) - return " " + Integer.toString(code); - else - return Integer.toString(code); + if (code<10) return " " + Integer.toString(code); + else if (code<100) return " " + Integer.toString(code); + else return Integer.toString(code); } - + public static String int6car(int value) { String s = " " + Integer.toString(value); - return s.substring(s.length() - 6, s.length()); + return s.substring(s.length()-6, s.length()); } - + public static String toString(int code, String value) { return int34car(code) + "\r\n" + value + "\r\n"; } @@ -145,36 +128,31 @@ public static String toString(int code, int value) { } public static String toString(int code, float value, int decimalPartLength) { - return int34car(code) + "\r\n" + decimalFormats[decimalPartLength].format((double) value) + "\r\n"; + return int34car(code) + "\r\n" + + decimalFormats[decimalPartLength].format((double)value) + "\r\n"; } public static String toString(int code, double value, int decimalPartLength) { - return int34car(code) + "\r\n" + decimalFormats[decimalPartLength].format(value) + "\r\n"; + return int34car(code) + "\r\n" + + decimalFormats[decimalPartLength].format(value) + "\r\n"; } public static String toString(int code, Object value) { - if (value instanceof String) { - return toString(code, (String) value); - } else if (value instanceof Integer) { - return toString(code, ((Integer) value).intValue()); - } else if (value instanceof Float) { - return toString(code, ((Float) value).floatValue(), 3); - } else if (value instanceof Double) { - return toString(code, ((Double) value).doubleValue(), 6); - } else - return toString(code, value.toString()); + if (value instanceof String) {return toString(code, (String)value);} + else if (value instanceof Integer) {return toString(code, ((Integer)value).intValue());} + else if (value instanceof Float) {return toString(code, ((Float)value).floatValue(), 3);} + else if (value instanceof Double) {return toString(code, ((Double)value).doubleValue(), 6);} + else return toString(code, value.toString()); } /** * Read a group from the current position in a RandomAccessFime. - * * @return a DxfGroup */ public static DxfGroup readGroup(RandomAccessFile raf) throws IOException { long pos = raf.getFilePointer(); DxfGroup dxfGroup = new DxfGroup(raf.readLine(), raf.readLine()); - if (dxfGroup != null) - dxfGroup.setAddress(pos); + if (dxfGroup != null) dxfGroup.setAddress(pos); return dxfGroup; } diff --git a/dxf/src/main/java/fr/michaelm/jump/drivers/dxf/DxfTABLE_LTYPE_ITEM.java b/dxf/src/main/java/fr/michaelm/jump/drivers/dxf/DxfTABLE_LTYPE_ITEM.java index e3a337f..e6e190d 100644 --- a/dxf/src/main/java/fr/michaelm/jump/drivers/dxf/DxfTABLE_LTYPE_ITEM.java +++ b/dxf/src/main/java/fr/michaelm/jump/drivers/dxf/DxfTABLE_LTYPE_ITEM.java @@ -24,15 +24,15 @@ package fr.michaelm.jump.drivers.dxf; -import java.io.IOException; import java.io.RandomAccessFile; -import java.util.LinkedHashMap; +import java.io.IOException; import java.util.Map; +import java.util.LinkedHashMap; /** - * The LTYPE item in the TABLES section There is a static reader to read the - * item in a DXF file and a toString method able to write it in a DXF form - * + * The LTYPE item in the TABLES section + * There is a static reader to read the item in a DXF file + * and a toString method able to write it in a DXF form * @author Michaël Michaud */ public class DxfTABLE_LTYPE_ITEM extends DxfTABLE_ITEM { @@ -46,7 +46,7 @@ public DxfTABLE_LTYPE_ITEM(String name, int flags) { this.description = ""; this.alignment = 0; this.patternLength = 1f; - this.pattern = new float[] { 1f }; + this.pattern = new float[]{1f}; } public DxfTABLE_LTYPE_ITEM(String name, int flags, String description, int alignment, float patternLength, float[] pattern) { @@ -56,70 +56,41 @@ public DxfTABLE_LTYPE_ITEM(String name, int flags, String description, int align this.patternLength = patternLength; this.pattern = pattern; } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public int getAlignment() { - return alignment; - } - - public void setAlignment(int alignment) { - this.alignment = alignment; - } - - public float getPatternLength() { - return patternLength; - } - - public void setPatternLength(float patternLength) { - this.patternLength = patternLength; - } - - public float[] getPattern() { - return pattern; - } - - public void setPattern(float[] pattern) { - this.pattern = pattern; - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public static Map readTable(RandomAccessFile raf) throws IOException { + + public String getDescription() {return description;} + public void setDescription(String description) {this.description = description;} + public int getAlignment() {return alignment;} + public void setAlignment(int alignment) {this.alignment = alignment;} + public float getPatternLength() {return patternLength;} + public void setPatternLength(float patternLength) {this.patternLength = patternLength;} + public float[] getPattern() {return pattern;} + public void setPattern(float[] pattern) {this.pattern = pattern;} + + public static Map readTable(RandomAccessFile raf) throws IOException { DxfTABLE_LTYPE_ITEM item = new DxfTABLE_LTYPE_ITEM("DEFAULT", 0); - Map table = new LinkedHashMap(); + Map table = new LinkedHashMap(); DxfGroup group = null; int patternDashCount = 0; while (group != null && !group.equals(ENDTAB)) { group = DxfGroup.readGroup(raf); if (group.equals(LTYPE)) { item = new DxfTABLE_LTYPE_ITEM("DEFAULT", 0); - } else if (group.getCode() == 2) { + } + else if (group.getCode()==2) { item.setName(group.getValue()); table.put(item.getName(), item); - } else if (group.getCode() == 5) { - } // tag appeared in version 13 of DXF - else if (group.getCode() == 100) { - } // tag appeared in version 13 of DXF - else if (group.getCode() == 70) { - item.setFlags(group.getIntValue()); - } else if (group.getCode() == 3) { - item.setDescription(group.getValue()); - } else if (group.getCode() == 72) { - item.setAlignment(group.getIntValue()); - } else if (group.getCode() == 73) { - item.setPattern(new float[group.getIntValue()]); - } else if (group.getCode() == 40) { - item.setPatternLength(group.getFloatValue()); - } else if (group.getCode() == 49 && patternDashCount < item.getPattern().length) { + } + else if (group.getCode()==5) {} // tag appeared in version 13 of DXF + else if (group.getCode()==100) {} // tag appeared in version 13 of DXF + else if (group.getCode()==70) {item.setFlags(group.getIntValue());} + else if (group.getCode()==3) {item.setDescription(group.getValue());} + else if (group.getCode()==72) {item.setAlignment(group.getIntValue());} + else if (group.getCode()==73) {item.setPattern(new float[group.getIntValue()]);} + else if (group.getCode()==40) {item.setPatternLength(group.getFloatValue());} + else if (group.getCode()==49 && patternDashCount < item.getPattern().length) { item.getPattern()[patternDashCount++] = group.getFloatValue(); - } else { } + else {} } return table; } @@ -130,7 +101,7 @@ public String toString() { sb.append(DxfGroup.toString(72, alignment)); sb.append(DxfGroup.toString(73, pattern.length)); sb.append(DxfGroup.toString(40, patternLength, 3)); - for (int i = 0; i < pattern.length; i++) { + for (int i = 0 ; i < pattern.length ; i++) { sb.append(DxfGroup.toString(49, pattern[i], 3)); } return sb.toString(); diff --git a/dxf/src/main/java/fr/michaelm/jump/drivers/dxf/DxfTABLE_STYLE_ITEM.java b/dxf/src/main/java/fr/michaelm/jump/drivers/dxf/DxfTABLE_STYLE_ITEM.java index 24e5b01..f9fb734 100644 --- a/dxf/src/main/java/fr/michaelm/jump/drivers/dxf/DxfTABLE_STYLE_ITEM.java +++ b/dxf/src/main/java/fr/michaelm/jump/drivers/dxf/DxfTABLE_STYLE_ITEM.java @@ -24,15 +24,15 @@ package fr.michaelm.jump.drivers.dxf; -import java.io.IOException; import java.io.RandomAccessFile; -import java.util.LinkedHashMap; +import java.io.IOException; import java.util.Map; +import java.util.LinkedHashMap; /** - * The STYLE item in the TABLES section There is a static reader to read the - * item from a DXF file and a toString method to write it in the DXF format - * + * The STYLE item in the TABLES section + * There is a static reader to read the item from a DXF file + * and a toString method to write it in the DXF format * @author Michaël Michaud */ public class DxfTABLE_STYLE_ITEM extends DxfTABLE_ITEM { @@ -55,8 +55,14 @@ public DxfTABLE_STYLE_ITEM(String name, int flags) { this.bigFontFileName = ""; } - public DxfTABLE_STYLE_ITEM(String name, int flags, float textHeight, float widthFactor, float obliqueAngle, int textGenerationFlags, float lastHeightUsed, - String primaryFontFileName, String bigFontFileName) { + public DxfTABLE_STYLE_ITEM(String name, int flags, + float textHeight, + float widthFactor, + float obliqueAngle, + int textGenerationFlags, + float lastHeightUsed, + String primaryFontFileName, + String bigFontFileName) { super(name, flags); this.textHeight = textHeight; this.widthFactor = widthFactor; @@ -67,96 +73,60 @@ public DxfTABLE_STYLE_ITEM(String name, int flags, float textHeight, float width this.bigFontFileName = bigFontFileName; } - public float getTextHeight() { - return textHeight; - } - - public float getWidthFactor() { - return widthFactor; - } - - public float getObliqueAngle() { - return obliqueAngle; - } - - public int getTextGenerationFlags() { - return textGenerationFlags; - } - - public float getLastHeightUsed() { - return lastHeightUsed; - } - - public String getPrimaryFontFileName() { - return primaryFontFileName; - } - - public String getBigFontFileName() { - return bigFontFileName; - } - + public float getTextHeight() {return textHeight;} + public float getWidthFactor() {return widthFactor;} + public float getObliqueAngle() {return obliqueAngle;} + public int getTextGenerationFlags() {return textGenerationFlags;} + public float getLastHeightUsed() {return lastHeightUsed;} + public String getPrimaryFontFileName() {return primaryFontFileName;} + public String getBigFontFileName() {return bigFontFileName;} + public void setTextHeight(float textHeight) { this.textHeight = textHeight; } - public void setWidthFactor(float widthFactor) { this.widthFactor = widthFactor; } - public void setObliqueAngle(float obliqueAngle) { this.obliqueAngle = obliqueAngle; } - public void setTextGenerationFlags(int textGenerationFlags) { this.textGenerationFlags = textGenerationFlags; } - public void setLastHeightUsed(float lastHeightUsed) { this.lastHeightUsed = lastHeightUsed; } - public void setPrimaryFontFileName(String primaryFontFileName) { this.primaryFontFileName = primaryFontFileName; } - public void setBigFontFileName(String bigFontFileName) { this.bigFontFileName = bigFontFileName; } - @SuppressWarnings({ "rawtypes", "unchecked" }) - public static Map readTable(RandomAccessFile raf) throws IOException { + public static Map readTable(RandomAccessFile raf) throws IOException { DxfTABLE_STYLE_ITEM item = new DxfTABLE_STYLE_ITEM("DEFAULT", 0); - Map table = new LinkedHashMap(); + Map table = new LinkedHashMap(); DxfGroup group = null; while (group != null && !group.equals(ENDTAB)) { group = DxfGroup.readGroup(raf); if (group.equals(STYLE)) { item = new DxfTABLE_STYLE_ITEM("DEFAULT", 0); - } else if (group.getCode() == 2) { + } + else if (group.getCode()==2) { item.setName(group.getValue()); table.put(item.getName(), item); - } else if (group.getCode() == 5) { - } // tag appeared in version 13 of DXF - else if (group.getCode() == 100) { - } // tag appeared in version 13 of DXF - else if (group.getCode() == 70) { - item.setFlags(group.getIntValue()); - } else if (group.getCode() == 40) { - item.setTextHeight(group.getFloatValue()); - } else if (group.getCode() == 41) { - item.setWidthFactor(group.getFloatValue()); - } else if (group.getCode() == 50) { - item.setObliqueAngle(group.getFloatValue()); - } else if (group.getCode() == 71) { - item.setTextGenerationFlags(group.getIntValue()); - } else if (group.getCode() == 42) { - item.setLastHeightUsed(group.getFloatValue()); - } else if (group.getCode() == 3) { - item.setPrimaryFontFileName(group.getValue()); - } else if (group.getCode() == 4) { - item.setBigFontFileName(group.getValue()); - } else { } + else if (group.getCode()==5) {} // tag appeared in version 13 of DXF + else if (group.getCode()==100) {} // tag appeared in version 13 of DXF + else if (group.getCode()==70) {item.setFlags(group.getIntValue());} + else if (group.getCode()==40) {item.setTextHeight(group.getFloatValue());} + else if (group.getCode()==41) {item.setWidthFactor(group.getFloatValue());} + else if (group.getCode()==50) {item.setObliqueAngle(group.getFloatValue());} + else if (group.getCode()==71) {item.setTextGenerationFlags(group.getIntValue());} + else if (group.getCode()==42) {item.setLastHeightUsed(group.getFloatValue());} + else if (group.getCode()==3) {item.setPrimaryFontFileName(group.getValue());} + else if (group.getCode()==4) {item.setBigFontFileName(group.getValue());} + else {} } return table; } diff --git a/dxf/src/main/java/fr/michaelm/jump/drivers/dxf/DxfXDATA.java b/dxf/src/main/java/fr/michaelm/jump/drivers/dxf/DxfXDATA.java new file mode 100644 index 0000000..eb2ef83 --- /dev/null +++ b/dxf/src/main/java/fr/michaelm/jump/drivers/dxf/DxfXDATA.java @@ -0,0 +1,35 @@ +package fr.michaelm.jump.drivers.dxf; + +public class DxfXDATA { + + public static int GROUPCODE_XDATA_APP_NAME = 1001; + public static int GROUPCODE_XDATA_STRING = 1000; + public static int GROUPCODE_XDATA_BINARY = 1004; + public static int GROUPCODE_XDATA_REAL = 1040; + public static int GROUPCODE_XDATA_INTEGER = 1070; + public static int GROUPCODE_XDATA_LONG = 1071; + + private String name; + private int code; + private Object value; + + public DxfXDATA(String name, int code, Object value) { + this.name = name; + this.code = code; + this.value = value; + } + + public String getName() { + return name; + } + + public int getCode() { + return code; + } + + public Object getValue() { + return value; + } + + +} diff --git a/dxf/src/main/java/org/kabeja/dxf/Bounds.java b/dxf/src/main/java/org/kabeja/dxf/Bounds.java new file mode 100644 index 0000000..8bec4c1 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/dxf/Bounds.java @@ -0,0 +1,315 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ +package org.kabeja.dxf; + +import org.kabeja.dxf.helpers.Point; + + +/** + * This class is a helper class and reflect a viewport of a entity/layer or + * document + * + * @author = this.max_x)) { + // the given bounds are on the left or right side of the bounds + return false; + } + + if ((bounds.getMaximumY() <= this.min_y) || + (bounds.getMinimumY() >= this.max_y)) { + // the given bounds are above or below + return false; + } + + return true; + } + + public boolean contains(Point p) { + if ((this.min_x <= p.getX()) && (this.max_x >= p.getX())) { + if ((this.min_y <= p.getY()) && (this.max_y >= p.getY())) { + return true; + } + } + + return false; + } + + /** + * Determines if the given bounds are enclosed. + * @param bounds + * @return + */ + public boolean enclose(Bounds bounds) { + if ((bounds.getMaximumX() <= this.max_x) && + (bounds.getMinimumX() >= this.min_x)) { + // the given bounds are on the left or right side of the bounds + if ((bounds.getMaximumY() <= this.max_y) && + (bounds.getMinimumY() >= this.min_y)) { + // the given bounds are above or below + return true; + } + } + + return false; + } +} diff --git a/dxf/src/main/java/org/kabeja/dxf/DXF3DFace.java b/dxf/src/main/java/org/kabeja/dxf/DXF3DFace.java new file mode 100644 index 0000000..d399c69 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/dxf/DXF3DFace.java @@ -0,0 +1,41 @@ +/* + * Created on 29.09.2005 + * + */ +package org.kabeja.dxf; + +import org.kabeja.math.MathUtils; + + +/** + * @author simon + * + */ +public class DXF3DFace extends DXFSolid { + public String getType() { + return DXFConstants.ENTITY_TYPE_3DFACE; + } + + public double getLength() { + double length = 0.0; + int flag = this.getFlags(); + + if ((flag & 1) == 0) { + length += MathUtils.distance(this.getPoint1(), this.getPoint2()); + } + + if ((flag & 2) == 0) { + length += MathUtils.distance(this.getPoint2(), this.getPoint3()); + } + + if ((flag & 4) == 0) { + length += MathUtils.distance(this.getPoint3(), this.getPoint4()); + } + + if ((flag & 8) == 0) { + length += MathUtils.distance(this.getPoint4(), this.getPoint1()); + } + + return length; + } +} diff --git a/dxf/src/main/java/org/kabeja/dxf/DXF3DSolid.java b/dxf/src/main/java/org/kabeja/dxf/DXF3DSolid.java new file mode 100644 index 0000000..1487429 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/dxf/DXF3DSolid.java @@ -0,0 +1,31 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.dxf; + + +/** + * @author Simon Mieth + * + */ +public class DXFArc extends DXFEntity { + private Point center; + private double radius; + private double start_angle; + private double end_angle; + private boolean counterclockwise = false; + + public DXFArc() { + center = new Point(); + } + + /** + * @return Returns the end_angle. + */ + public double getEndAngle() { + return end_angle; + } + + /** + * @param end_angle + * The end_angle to set. + */ + public void setEndAngle(double end_angle) { + this.end_angle = end_angle; + } + + /** + * @return Returns the radius. + */ + public double getRadius() { + return radius; + } + + /** + * @param radius + * The radius to set. + */ + public void setRadius(double radius) { + this.radius = radius; + } + + /** + * @return Returns the start_angle. + */ + public double getStartAngle() { + return start_angle; + } + + /** + * @param start_angle + * The start_angle to set. + */ + public void setStartAngle(double start_angle) { + this.start_angle = start_angle; + } + + /* + * (non-Javadoc) + * + * @see org.kabeja.dxf.DXFEntity#updateViewPort() + */ + public Bounds getBounds() { + Bounds bounds = new Bounds(); + Point start = this.getStartPoint(); + Point end = this.getEndPoint(); + bounds.addToBounds(start); + bounds.addToBounds(end); + + ParametricPlane plane = new ParametricPlane(this.getExtrusion()); + Point center = plane.getPoint(this.center.getX(), this.center.getY()); + int startQ = MathUtils.getQuadrant(start, center); + int endQ = MathUtils.getQuadrant(end, center); + + if (endQ < startQ) { + endQ += 4; + } + + while (endQ > startQ) { + switch (startQ) { + case 0: + bounds.addToBounds(center.getX(), center.getY() + radius, + center.getZ()); + + break; + + case 1: + bounds.addToBounds(center.getX() - radius, center.getY(), + center.getZ()); + + break; + + case 2: + bounds.addToBounds(center.getX(), center.getY() - radius, + center.getZ()); + + break; + + case 3: + bounds.addToBounds(center.getX() + radius, center.getY(), + center.getZ()); + endQ -= 4; + startQ -= 4; + + break; + } + + startQ++; + } + + return bounds; + } + + public void setCenterPoint(Point p) { + this.center = p; + } + + public Point getCenterPoint() { + return center; + } + + /** + * Calculate the start point of the arc (defined by the start parameter) + * + * @return the start point + */ + public Point getStartPoint() { + double angle = this.start_angle; + + // if (this.start_angle < 0) { + // angle += 360; + // } + return this.getPointAt(angle); + } + + /** + * Calculate the end point of the arc (defined by the end parameter) + * + * @return the end point + */ + public Point getEndPoint() { + double angle = this.end_angle; + + // if (this.end_angle < 0) { + // angle += 360; + // } + return this.getPointAt(angle); + } + + /** + * Calculate a point of the arc + * + * @param angle + * in degree + * @return Point on the circle + */ + public Point getPointAt(double angle) { + // the local part + double x = this.radius * Math.cos(Math.toRadians(angle)); + double y = radius * Math.sin(Math.toRadians(angle)); + + // the wcs part + ParametricPlane plane = new ParametricPlane(this.getExtrusion()); + Point p = plane.getPoint(x + this.center.getX(), y + + this.center.getY()); + + return p; + } + + /** + * + */ + public String getType() { + return DXFConstants.ENTITY_TYPE_ARC; + } + + public double getLength() { + double alpha = this.getTotalAngle(); + + return (alpha * Math.PI * this.radius) / 180.0; + } + + public double getTotalAngle() { + if (this.end_angle < this.start_angle) { + return (360 + this.end_angle) - this.start_angle; + } else { + return Math.abs(this.end_angle - this.start_angle); + } + } + + public double getChordLength() { + double s = 2 * this.radius * Math.sin(Math.toRadians( + this.getTotalAngle() / 2)); + + return s; + } + + public boolean isCounterClockwise() { + return counterclockwise; + } + + public void setCounterClockwise(boolean counterclockwise) { + this.counterclockwise = counterclockwise; + } +} diff --git a/dxf/src/main/java/org/kabeja/dxf/DXFAttrib.java b/dxf/src/main/java/org/kabeja/dxf/DXFAttrib.java new file mode 100644 index 0000000..15af4c3 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/dxf/DXFAttrib.java @@ -0,0 +1,33 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.dxf; + + +/** + * @author entities; + private DXFDocument doc; + + /** + * + */ + public DXFBlock() { + super(); + + this.entities = new ArrayList(); + this.referencePoint = new Point(); + } + + public Bounds getBounds() { + // first set the own point + Bounds bounds = new Bounds(); + Iterator i = entities.iterator(); + + if (i.hasNext()) { + while (i.hasNext()) { + DXFEntity entity = (DXFEntity) i.next(); + Bounds b = entity.getBounds(); + + if (b.isValid()) { + bounds.addToBounds(b); + } + } + } else { + bounds.setValid(false); + } + + return bounds; + } + + /** + * @return Returns the description. + */ + public String getDescription() { + return description; + } + + /** + * @param description + * The description to set. + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * @return Returns the p. + */ + public Point getReferencePoint() { + return referencePoint; + } + + /** + * @param p + * The p to set. + */ + public void setReferencePoint(Point p) { + this.referencePoint = p; + } + + public void addDXFEntity(DXFEntity entity) { + entities.add(entity); + } + + /** + * + * @return a iterator over all entities of this block + */ + public Iterator getDXFEntitiesIterator() { + return entities.iterator(); + } + + /** + * @return Returns the layerID. + */ + public String getLayerID() { + return layerID; + } + + /** + * @param layerID + * The layerID to set. + */ + public void setLayerID(String layerID) { + this.layerID = layerID; + } + + /** + * @return Returns the name. + */ + public String getName() { + return name; + } + + /** + * @param name + * The name to set. + */ + public void setName(String name) { + this.name = name; + } + + /** + * @param doc + * The doc to set. + */ + public void setDXFDocument(DXFDocument doc) { + this.doc = doc; + + Iterator i = entities.iterator(); + + while (i.hasNext()) { + DXFEntity entity = (DXFEntity) i.next(); + entity.setDXFDocument(doc); + } + } + + /** + * + * @return the parent document + */ + public DXFDocument getDXFDocument() { + return this.doc; + } + + public double getLength() { + double length = 0; + Iterator i = entities.iterator(); + + while (i.hasNext()) { + DXFEntity entity = (DXFEntity) i.next(); + length += entity.getLength(); + } + + return length; + } + + /** + * Gets the + * + * @see DXFEntity with the specified ID. + * @param id + * of the + * @see DXFEntity + * @return the + * @see DXFEntity with the specified ID or null if there is no + * @see DXFEntity with the specified ID + */ + public DXFEntity getDXFEntityByID(String id) { + DXFEntity entity = null; + Iterator i = this.entities.iterator(); + + while (i.hasNext()) { + DXFEntity e = (DXFEntity) i.next(); + + if (e.getID().equals(id)) { + return e; + } + } + + return entity; + } +} diff --git a/dxf/src/main/java/org/kabeja/dxf/DXFBody.java b/dxf/src/main/java/org/kabeja/dxf/DXFBody.java new file mode 100644 index 0000000..ccdc1d9 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/dxf/DXFBody.java @@ -0,0 +1,30 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.dxf; + + +/** + * @author 0) && ((dxfColorCode - 1) <= (rgbs.length - 1))) { + // the StringBuffer is faster then the String concat + StringBuffer buf = new StringBuffer(); + buf.append(rgbs[dxfColorCode - 1][0]); + buf.append(","); + buf.append(rgbs[dxfColorCode - 1][1]); + buf.append(","); + buf.append(rgbs[dxfColorCode - 1][2]); + + return buf.toString(); + } + + // default is black + return DEFAULT_COLOR; + } +} diff --git a/dxf/src/main/java/org/kabeja/dxf/DXFConstants.java b/dxf/src/main/java/org/kabeja/dxf/DXFConstants.java new file mode 100644 index 0000000..3724410 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/dxf/DXFConstants.java @@ -0,0 +1,346 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.dxf; + +import org.kabeja.dxf.helpers.Vector; + + +/** + * @author properties = new HashMap(); + private int flags = 0; + private String name = ""; + + public void setProperty(String key, String value) { + properties.put(key, value); + } + + public boolean hasProperty(String name) { + return properties.containsKey(name); + } + + public String getProperty(String name) { + return (String) properties.get(name); + } + + public int getIntegerProperty(String name) { + String value = (String) properties.get(name); + + return Integer.parseInt(value); + } + + public int getIntegerProperty(String name, int defaultValue) { + if (hasProperty(name)) { + String value = (String) properties.get(name); + + return Integer.parseInt(value); + } else { + return defaultValue; + } + } + + public double getDoubleProperty(String name) { + String value = (String) properties.get(name); + + return Double.parseDouble(value); + } + + public double getDoubleProperty(String name, double defaultValue) { + if (hasProperty(name)) { + String value = (String) properties.get(name); + + return Double.parseDouble(value); + } else { + return defaultValue; + } + } + + public boolean getBooleanProperty(String name) { + String value = (String) properties.get(name); + + if ("1".equals(value)) { + return true; + } else { + return false; + } + } + + public boolean getBooleanProperty(String name, boolean defaultValue) { + if (hasProperty(name)) { + String value = (String) properties.get(name); + + if ("1".equals(value)) { + return true; + } else { + return false; + } + } else { + return defaultValue; + } + } + + public Iterator getPropertyIterator() { + return properties.values().iterator(); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public void setFlags(int flags) { + this.flags = flags; + } + + public int getFlags() { + return flags; + } +} diff --git a/dxf/src/main/java/org/kabeja/dxf/DXFDocument.java b/dxf/src/main/java/org/kabeja/dxf/DXFDocument.java new file mode 100644 index 0000000..36fe8b2 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/dxf/DXFDocument.java @@ -0,0 +1,426 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ +package org.kabeja.dxf; + +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.List; + +import org.kabeja.dxf.objects.DXFDictionary; +import org.kabeja.dxf.objects.DXFObject; + + +/** + * @author search in the dictionaries + return this.rootDictionary.getDXFObjectByID(id); + } + + /** + * Gets the + * + * @see DXFEntity with the specified ID. + * @param id + * of the + * @see DXFEntity + * @return the + * @see DXFEntity with the specified ID or null if there is no + * @see DXFEntity with the specified ID + */ + public DXFEntity getDXFEntityByID(String id) { + DXFEntity entity = null; + Iterator i = this.getDXFLayerIterator(); + + while (i.hasNext()) { + DXFLayer layer = (DXFLayer) i.next(); + + if ((entity = layer.getDXFEntityByID(id)) != null) { + return entity; + } + } + + i = this.getDXFBlockIterator(); + + while (i.hasNext()) { + DXFBlock block = (DXFBlock) i.next(); + + if ((entity = block.getDXFEntityByID(id)) != null) { + return entity; + } + } + + return entity; + } + + /** + * Adds a DXFHatchPattern to the document. + * + * @param pattern + */ + public void addDXFHatchPattern(DXFHatchPattern pattern) { + this.patterns.put(pattern.getID(), pattern); + } + + /** + * + * @return java.util.Iterator over all DXFHatchPattern of the document + */ + public Iterator getDXFHatchPatternIterator() { + return this.patterns.values().iterator(); + } + + /** + * + * @param ID + * of the pattern (also called pattern name) + * @return the DXFHatchPattern or null + */ + public DXFHatchPattern getDXFHatchPattern(String id) { + return (DXFHatchPattern) this.patterns.get(id); + } +} diff --git a/dxf/src/main/java/org/kabeja/dxf/DXFEllipse.java b/dxf/src/main/java/org/kabeja/dxf/DXFEllipse.java new file mode 100644 index 0000000..15ac999 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/dxf/DXFEllipse.java @@ -0,0 +1,243 @@ +/* + * Created on Jul 15, 2004 + * + */ +package org.kabeja.dxf; + +import org.kabeja.dxf.helpers.Point; +import org.kabeja.dxf.helpers.Vector; +import org.kabeja.math.MathUtils; +import org.kabeja.math.ParametricPlane; + + +/** + * @author extendedData; + + /** + * From the DXF Specs default all entities are in model space. + */ + protected boolean modelSpace = true; + + public DXFEntity() { + this.extendedData = new LinkedHashMap(); + } + + public void setDXFDocument(DXFDocument doc) { + this.doc = doc; + } + + public DXFDocument getDXFDocument() { + return this.doc; + } + + /** + * Gives the name of the layer, which containts the entity. + * @return the name of the layer + */ + public String getLayerName() { + return this.layerID; + } + + /** + * Set the name of the layer, which containts the entity. + * @return the name of the layer + */ + public void setLayerName(String id) { + this.layerID = id; + } + + public DXFExtendedData getExtendedData(String name) { + return this.extendedData.get(name); + } + + + public List getExtendedData() { + return new ArrayList(this.extendedData.values()); + } + + public void addExtendedData(DXFExtendedData extendedData) { + this.extendedData.put(extendedData.getName(), extendedData); + } + + // public abstract void toSAX(ContentHandler handler, Map svgContext) + // throws SAXException; + public abstract Bounds getBounds(); + + /** + * @return Returns the lineType. + */ + public String getLineType() { + return lineType; + } + + /** + * @param lineType + * The lineType to set. + */ + public void setLineType(String lineType) { + this.lineType = lineType; + } + + /** + * @return Returns the visibile. + */ + public boolean isVisibile() { + return visibile; + } + + /** + * @param visibile + * The visibile to set. + */ + public void setVisibile(boolean visibile) { + this.visibile = visibile; + } + + /** + * @return Returns the flags. + */ + public int getFlags() { + return flags; + } + + /** + * @param flags + * The flags to set. + */ + public void setFlags(int flags) { + this.flags = flags; + } + + public void setBlockEntity(boolean b) { + this.block = b; + } + + public boolean isBlockEntity() { + return block; + } + + public void setExtrusion(DXFExtrusion extrusion) { + this.extrusion = extrusion; + } + + public DXFExtrusion getExtrusion() { + return extrusion; + } + + public double getLinetypeScaleFactor() { + return linetypeScaleFactor; + } + + public void setLinetypeScaleFactor(double linetypeScaleFactor) { + this.linetypeScaleFactor = linetypeScaleFactor; + } + + public int getColor() { + return color; + } + + public void setColor(int color) { + this.color = color; + } + + public byte[] getColorRGB() { + return colorRGB; + } + + public void setColorRGB(byte[] colorRGB) { + this.colorRGB = colorRGB; + } + + public int getLineWeight() { + return lineWeight; + } + + public void setLineWeight(int lineWeight) { + this.lineWeight = lineWeight; + } + + public double getTransparency() { + return transparency; + } + + public void setTransparency(double transparency) { + this.transparency = transparency; + } + + public void setID(String id) { + this.id = id; + } + + public String getID() { + return id; + } + + public void setExtrusionX(double x) { + extrusion.setX(x); + } + + public void setExtrusionY(double y) { + extrusion.setY(y); + } + + public void setExtrusionZ(double z) { + extrusion.setZ(z); + } + + public abstract String getType(); + + /** + * The thickness reflects the height of the entity. + * + * + * @return Returns the thickness. + */ + public double getThickness() { + return thickness; + } + + /** + * @param thickness + * The thickness /height of the entity to set. + */ + public void setThickness(double thickness) { + this.thickness = thickness; + } + + public boolean isOmitLineType() { + return false; + } + + /** + * @return Returns the modelSpace. + */ + public boolean isModelSpace() { + return modelSpace; + } + + /** + * @param modelSpace The modelSpace to set. + */ + public void setModelSpace(boolean modelSpace) { + this.modelSpace = modelSpace; + } + + /** + * Returns the length of the entity or 0 if the entity has no length + * @return + */ + public abstract double getLength(); +} diff --git a/dxf/src/main/java/org/kabeja/dxf/DXFExtendedData.java b/dxf/src/main/java/org/kabeja/dxf/DXFExtendedData.java new file mode 100644 index 0000000..01f3863 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/dxf/DXFExtendedData.java @@ -0,0 +1,39 @@ +package org.kabeja.dxf; + +public class DXFExtendedData { + + private String name; + private Class type; + private Object value; + + public DXFExtendedData(String name) { + this.name = name; + this.type = null; + this.value = null; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Class getType() { + return type; + } + + public void setType(Class type) { + this.type = type; + } + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + +} diff --git a/dxf/src/main/java/org/kabeja/dxf/DXFExtrusion.java b/dxf/src/main/java/org/kabeja/dxf/DXFExtrusion.java new file mode 100644 index 0000000..fb00cc9 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/dxf/DXFExtrusion.java @@ -0,0 +1,122 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.dxf; + +import org.kabeja.dxf.helpers.Point; +import org.kabeja.dxf.helpers.Vector; +import org.kabeja.math.MathUtils; + + +/** + * This class implements the arbitrary axis algorithm to extract the + * direction x,y,z of the plane defined by the extrusion. + * + * @author 0)) { + return true; + } + + return false; + } + + /** + * Returns the global linetype scale factor. + * + * @return the global scalefactor + */ + public double getLinetypeScale() { + double gscale = 1.0; + + if (hasVariable("$LTSCALE")) { + gscale = getVariable("$LTSCALE").getDoubleValue("40"); + } + + return gscale; + } +} diff --git a/dxf/src/main/java/org/kabeja/dxf/DXFImage.java b/dxf/src/main/java/org/kabeja/dxf/DXFImage.java new file mode 100644 index 0000000..a0af1fe --- /dev/null +++ b/dxf/src/main/java/org/kabeja/dxf/DXFImage.java @@ -0,0 +1,243 @@ +/* + * Created on 28.06.2005 + * + */ +package org.kabeja.dxf; + +import java.util.ArrayList; + +import org.kabeja.dxf.helpers.Point; +import org.kabeja.dxf.objects.DXFImageDefObject; + + +/** + * @author = 0) { + bounds.setMinimumX(bounds.getMinimumX() - width); + } else { + bounds.setMaximumX(bounds.getMaximumX() - width); + } + + if (height >= 0) { + bounds.setMinimumY(bounds.getMinimumY() - height); + } else { + bounds.setMaximumY(bounds.getMaximumY() - height); + } + + return bounds; + } + + /** + * @return Returns the blockID. + */ + public String getBlockID() { + return blockID; + } + + /** + * @param blockID + * The blockID to set. + */ + public void setBlockID(String blockID) { + this.blockID = blockID; + } + + /** + * @return Returns the column_spacing. + */ + public double getColumnSpacing() { + return column_spacing; + } + + /** + * @param column_spacing + * The column_spacing to set. + */ + public void setColumnSpacing(double column_spacing) { + this.column_spacing = column_spacing; + } + + /** + * @return Returns the columns. + */ + public int getColumns() { + return columns; + } + + /** + * @param columns + * The columns to set. + */ + public void setColumns(int columns) { + this.columns = columns; + } + + /** + * @return Returns the p. + */ + public Point getPoint() { + return insertPoint; + } + + /** + * @param p + * The p to set. + */ + public void setPoint(Point p) { + this.insertPoint = p; + } + + /** + * @return Returns the rotate. + */ + public double getRotate() { + return rotate; + } + + /** + * @param rotate + * The rotate to set. + */ + public void setRotate(double rotate) { + this.rotate = rotate; + } + + /** + * @return Returns the row_spacing. + */ + public double getRowSpacing() { + return row_spacing; + } + + /** + * @param row_spacing + * The row_spacing to set. + */ + public void setRowSpacing(double row_spacing) { + this.row_spacing = row_spacing; + } + + /** + * @return Returns the rows. + */ + public int getRows() { + return rows; + } + + /** + * @param rows + * The rows to set. + */ + public void setRows(int rows) { + this.rows = rows; + } + + /** + * @return Returns the scale_x. + */ + public double getScaleX() { + return scale_x; + } + + /** + * @param scale_x + * The scale_x to set. + */ + public void setScaleX(double scale_x) { + this.scale_x = scale_x; + } + + /** + * @return Returns the scale_y. + */ + public double getScaleY() { + return scale_y; + } + + /** + * @param scale_y + * The scale_y to set. + */ + public void setScaleY(double scale_y) { + this.scale_y = scale_y; + } + + /** + * @return Returns the scale_z. + */ + public double getScaleZ() { + return scale_z; + } + + /** + * @param scale_z + * The scale_z to set. + */ + public void setScaleZ(double scale_z) { + this.scale_z = scale_z; + } + + private Point rotatePoint(double x, double y) { + double phi = Math.toRadians(rotate); + Point point = new Point(); + + // the rotation matrix + point.setX((x * Math.cos(phi)) - (y * Math.sin(phi))); + point.setY((x * Math.sin(phi)) + (y * Math.cos(phi))); + + return point; + } + + public String getType() { + return DXFConstants.ENTITY_TYPE_INSERT; + } + + public double getLength() { + return this.doc.getDXFBlock(this.blockID).getLength(); + } +} diff --git a/dxf/src/main/java/org/kabeja/dxf/DXFLWPolyline.java b/dxf/src/main/java/org/kabeja/dxf/DXFLWPolyline.java new file mode 100644 index 0000000..f202034 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/dxf/DXFLWPolyline.java @@ -0,0 +1,48 @@ +/* + * Created on 13.04.2005 + * + */ +package org.kabeja.dxf; + + +/** + * @author polyline only after changes + DXFPolyline[] pl = toDXFPolylines(); + double l = 0; + + for (int i = 0; i < pl.length; i++) { + l += pl[i].getLength(); + } + + return l; + } + + public void addDXFMLineSegement(DXFMLineSegment seg) { + this.mlineSegments.add(seg); + } + + public int getDXFMLineSegmentCount() { + return this.mlineSegments.size(); + } + + public DXFMLineSegment getDXFMLineSegment(int index) { + return (DXFMLineSegment) this.mlineSegments.get(index); + } + + public double getScale() { + return scale; + } + + public void setScale(double scale) { + this.scale = scale; + } + + public Point getStartPoint() { + return startPoint; + } + + public void setStartPoint(Point startPoint) { + this.startPoint = startPoint; + } + + public int getLineCount() { + return lineCount; + } + + public void setLineCount(int lineCount) { + this.lineCount = lineCount; + } + + public String getMLineStyleID() { + return mLineStyleID; + } + + public void setMLineStyleID(String lineStyleID) { + mLineStyleID = lineStyleID; + } + + public int getJustification() { + return justification; + } + + public void setJustification(int justification) { + this.justification = justification; + } + + public String getMLineStyleName() { + return mLineStyleName; + } + + public void setMLineStyleName(String lineStyleName) { + mLineStyleName = lineStyleName; + } + + protected DXFPolyline[] toDXFPolylines() { + return MLineConverter.toDXFPolyline(this); + } + + public boolean isClosed() { + return (this.flags & 2) == 2; + } +} diff --git a/dxf/src/main/java/org/kabeja/dxf/DXFMText.java b/dxf/src/main/java/org/kabeja/dxf/DXFMText.java new file mode 100644 index 0000000..a1a9cb0 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/dxf/DXFMText.java @@ -0,0 +1,199 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.dxf; + +import org.kabeja.dxf.helpers.DXFTextParser; +import org.kabeja.dxf.helpers.DXFUtils; +import org.kabeja.dxf.helpers.TextDocument; + + +/** + * @author Simon Mieth + * + */ +public class DXFPolyline extends DXFEntity { + protected static final double QUARTER_CIRCLE_ANGLE = Math.tan(0.39269908169872414D); + protected ArrayList vertices = new ArrayList(); + protected double startWidth = 0.0; + protected double endWidth = 0.0; + protected boolean constantWidth = true; + protected int surefaceType = 0; + protected int surefaceDensityRows = 0; + protected int surefaceDensityColumns = 0; + protected int rows = 0; + protected int columns = 0; + + /** + * + */ + public DXFPolyline() { + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.dxf.DXFEntity#updateViewPort() + */ + public Bounds getBounds() { + Bounds bounds = new Bounds(); + + Iterator i = vertices.iterator(); + + if (i.hasNext()) { + DXFVertex last; + DXFVertex first; + DXFVertex v = null; + + last = first = (DXFVertex) i.next(); + bounds.addToBounds(last.getPoint()); + + while (i.hasNext()) { + v = (DXFVertex) i.next(); + addToBounds(last, v, bounds); + last = v; + } + + if ((v != null) && (v.getBulge() != 0.0)) { + addToBounds(v, first, bounds); + } + } else { + bounds.setValid(false); + } + + return bounds; + } + + public void addVertex(DXFVertex vertex) { + vertices.add(vertex); + + if (!vertex.isConstantWidth()) { + constantWidth = false; + } + } + + public int getVertexCount() { + return this.vertices.size(); + } + + public Iterator getVertexIterator() { + return this.vertices.iterator(); + } + + public void removeVertex(DXFVertex vertex) { + // remove and check the constantwidth + constantWidth = true; + + Iterator i = vertices.iterator(); + + while (i.hasNext()) { + DXFVertex v = (DXFVertex) i.next(); + + if (v == vertex) { + i.remove(); + } else if (!v.isConstantWidth()) { + constantWidth = false; + } + } + } + + public void removeVertex(int index) { + constantWidth = true; + + for (int i = 0; i < vertices.size(); i++) { + DXFVertex v = (DXFVertex) vertices.get(i); + + if (index == i) { + vertices.remove(i); + } else if (!v.isConstantWidth()) { + constantWidth = false; + } + } + } + + public DXFVertex getVertex(int i) { + return (DXFVertex) vertices.get(i); + } + + /** + * Returns the distance between 2 DXFPoints + * + * @param start + * @param end + * @return the length between the two points + */ + protected double getLength(DXFPoint start, DXFPoint end) { + double value = Math.sqrt(Math.pow(end.getX() - start.getX(), 2) + + Math.pow(end.getY() - start.getY(), 2)); + + return value; + } + + /** + * Caculate the radius of a cut circle segment between 2 DXFVertex + * + * @param bulge + * the vertex bulge + * @param length + * the length of the circle cut + */ + public double getRadius(double bulge, double length) { + double h = (bulge * length) / 2; + double value = (h / 2) + (Math.pow(length, 2) / (8 * h)); + + return Math.abs(value); + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.dxf.DXFEntity#getType() + */ + public String getType() { + return DXFConstants.ENTITY_TYPE_POLYLINE; + } + + /** + * @return Returns the endWidth. + */ + public double getEndWidth() { + return endWidth; + } + + /** + * @param endWidth + * The endWidth to set. + */ + public void setEndWidth(double endWidth) { + this.endWidth = endWidth; + } + + /** + * @return Returns the startWidth. + */ + public double getStartWidth() { + return startWidth; + } + + /** + * @param startWidth + * The startWidth to set. + */ + public void setStartWidth(double startWidth) { + this.startWidth = startWidth; + } + + public boolean isClosed() { + // the closed Flag + return (this.flags & 1) == 1; + } + + public boolean isCurveFitVerticesAdded() { + return (this.flags & 2) == 2; + } + + public boolean isSplineFitVerticesAdded() { + return (this.flags & 4) == 4; + } + + public boolean is3DPolygon() { + return (this.flags & 8) == 8; + } + + public boolean is3DPolygonMesh() { + return (this.flags & 16) == 16; + } + + public boolean isPolyfaceMesh() { + return (this.flags & 64) == 64; + } + + public boolean isClosedMeshNDirection() { + return (this.flags & 32) == 32; + } + + public boolean isClosedMeshMDirection() { + return (this.flags & 1) == 1; + } + + public boolean isQuadSpline() { + if (isSplineFitVerticesAdded()) { + return this.surefaceType == 5; + } + + return false; + } + + public boolean isCubicSpline() { + if (isSplineFitVerticesAdded()) { + return this.surefaceType == 6; + } + + return false; + } + + public boolean isConstantWidth() { + //TODO review to see if the + //property is always set correct + if (!this.constantWidth) { + return false; + } else { + this.constantWidth = true; + + Iterator i = vertices.iterator(); + + while (i.hasNext()) { + DXFVertex vertex = (DXFVertex) i.next(); + + if (!vertex.isConstantWidth()) { + this.constantWidth = false; + + return this.constantWidth; + } + } + } + + return this.constantWidth; + } + + /** + * @return Returns the surefaceType. + */ + public int getSurefaceType() { + return surefaceType; + } + + /** + * @param surefaceType + * The surefaceType to set. + */ + public void setSurefaceType(int surefaceType) { + this.surefaceType = surefaceType; + } + + /** + * @return Returns the columns. + */ + public int getSurefaceDensityColumns() { + return surefaceDensityColumns; + } + + /** + * @param columns + * The columns to set. + */ + public void setSurefaceDensityColumns(int columns) { + this.surefaceDensityColumns = columns; + } + + /** + * @return Returns the rows. + */ + public int getSurefaceDensityRows() { + return surefaceDensityRows; + } + + /** + * @param rows + * The rows to set. + */ + public void setSurefaceDensityRows(int rows) { + this.surefaceDensityRows = rows; + } + + protected void addToBounds(DXFVertex start, DXFVertex end, Bounds bounds) { + if (start.getBulge() != 0) { + // calculte the height + double l = MathUtils.distance(start.getPoint(), end.getPoint()); + + // double h = Math.abs(last.getBulge()) * l / 2; + double r = this.getRadius(start.getBulge(), l); + + double s = l / 2; + Vector edgeDirection = MathUtils.getVector(start.getPoint(), + end.getPoint()); + edgeDirection = MathUtils.normalize(edgeDirection); + + Point centerPoint = MathUtils.getPointOfStraightLine(start.getPoint(), + edgeDirection, s); + + Vector centerPointDirection = MathUtils.crossProduct(edgeDirection, + this.getExtrusion().getNormal()); + centerPointDirection = MathUtils.normalize(centerPointDirection); + + // double t = Math.sqrt(Math.pow(r, 2) - Math.pow(s, 2)); + // double t = 0; + double h = Math.abs(start.getBulge() * l) / 2; + + // if(Math.abs(start.getBulge())>=1.0){ + // t = h-r; + // }else{ + // //t = Math.sqrt(Math.pow(r, 2) - Math.pow(s, 2)); + // t=r-h; + // } + // the center point of the arc + int startQ = 0; + int endQ = 0; + + double bulge = start.getBulge(); + + if (bulge > 0) { + // the arc goes over the right side, but where is the center + // point? + if (bulge > 1.0) { + double t = h - r; + centerPoint = MathUtils.getPointOfStraightLine(centerPoint, + centerPointDirection, t); + } else { + double t = r - h; + centerPoint = MathUtils.getPointOfStraightLine(centerPoint, + centerPointDirection, (-1 * t)); + } + + endQ = MathUtils.getQuadrant(end.getPoint(), centerPoint); + startQ = MathUtils.getQuadrant(start.getPoint(), centerPoint); + } else { + // the arc goes over the left side, but where is the center + // point? + if (bulge < -1.0) { + double t = h - r; + centerPoint = MathUtils.getPointOfStraightLine(centerPoint, + centerPointDirection, (-1 * t)); + } else { + double t = r - h; + centerPoint = MathUtils.getPointOfStraightLine(centerPoint, + centerPointDirection, t); + } + + startQ = MathUtils.getQuadrant(end.getPoint(), centerPoint); + endQ = MathUtils.getQuadrant(start.getPoint(), centerPoint); + } + + if (endQ < startQ) { + endQ += 4; + } else if ((endQ == startQ) && + (Math.abs(start.getBulge()) > QUARTER_CIRCLE_ANGLE)) { + endQ += 4; + } + + while (endQ > startQ) { + switch (startQ) { + case 0: + bounds.addToBounds(centerPoint.getX(), + centerPoint.getY() + r, centerPoint.getZ()); + + break; + + case 1: + bounds.addToBounds(centerPoint.getX() - r, + centerPoint.getY(), centerPoint.getZ()); + + break; + + case 2: + bounds.addToBounds(centerPoint.getX(), + centerPoint.getY() - r, centerPoint.getZ()); + + break; + + case 3: + bounds.addToBounds(centerPoint.getX() + r, + centerPoint.getY(), centerPoint.getZ()); + endQ -= 4; + startQ -= 4; + + break; + } + + startQ++; + } + } + + bounds.addToBounds(start.getPoint()); + bounds.addToBounds(end.getPoint()); + } + + public DXFVertex getPolyFaceMeshVertex(int index) { + Iterator i = this.vertices.iterator(); + int count = 1; + + while (i.hasNext()) { + DXFVertex v = (DXFVertex) i.next(); + + if (v.isPolyFaceMeshVertex()) { + if (count == index) { + return v; + } else { + count++; + } + } + } + + return null; + } + + /** + * @return Returns the column. + */ + public int getColumns() { + return columns; + } + + /** + * @param column + * The column to set. + */ + public void setColumns(int column) { + this.columns = column; + } + + /** + * @return Returns the rows. + */ + public int getRows() { + return rows; + } + + /** + * @param rows + * The rows to set. + */ + public void setRows(int rows) { + this.rows = rows; + } + + public boolean isSimpleMesh() { + return (this.surefaceType == 0) && ((this.flags & 4) == 0); + } + + public boolean isQuadSurefaceMesh() { + return (this.surefaceType == 5) && ((this.flags & 4) == 4); + } + + public boolean isCubicSurefaceMesh() { + return (this.surefaceType == 6) && ((this.flags & 4) == 4); + } + + public boolean isBezierSurefaceMesh() { + return (this.surefaceType == 8) && ((this.flags & 4) == 4); + } + + public double getLength() { + double length = 0.0; + + if (isCubicSpline() || isQuadSpline()) { + return getSplineApproximationLength(); + } else if (isPolyfaceMesh()) { + return getPolyfaceLength(); + } else if (is3DPolygonMesh() || isBezierSurefaceMesh() || + isCubicSurefaceMesh()) { + return getMeshLength(); + } else { + // a normal polyline with or without bulges + Iterator i = this.vertices.iterator(); + DXFVertex first; + DXFVertex last = first = (DXFVertex) i.next(); + + while (i.hasNext()) { + DXFVertex v = (DXFVertex) i.next(); + length += this.getSegmentLength(last, v); + last = v; + } + + if (this.isClosed()) { + length += this.getSegmentLength(last, first); + } + } + + return length; + } + + protected double getSegmentLength(DXFVertex start, DXFVertex end) { + double l = MathUtils.distance(start.getPoint(), end.getPoint()); + + if (start.getBulge() == 0.0) { + return l; + } else { + double alpha = 4 * Math.atan(Math.abs(start.getBulge())); + + double r = l / (2 * Math.sin(alpha / 2)); + double d = (Math.PI * Math.toDegrees(alpha) * r) / 180; + + return d; + } + } + + protected double getSplineApproximationLength() { + double length = 0.0; + + // use the approximation + Iterator i = this.vertices.iterator(); + DXFVertex first; + DXFVertex last = first = null; + + while (i.hasNext()) { + DXFVertex v = (DXFVertex) i.next(); + + if (v.is2DSplineApproximationVertex()) { + if (first == null) { + first = last = v; + } else { + length += getSegmentLength(last, v); + last = v; + } + } + } + + if (this.isClosed()) { + length += getSegmentLength(last, first); + } + + return length; + } + + protected double getPolyfaceLength() { + double length = 0.0; + Iterator i = this.vertices.iterator(); + + while (i.hasNext()) { + DXFVertex v = (DXFVertex) i.next(); + + if (v.isFaceRecord()) { + DXFVertex v1 = getPolyFaceMeshVertex(v.getPolyFaceMeshVertex0()); + DXFVertex v2 = getPolyFaceMeshVertex(v.getPolyFaceMeshVertex1()); + DXFVertex v3 = getPolyFaceMeshVertex(v.getPolyFaceMeshVertex2()); + DXFVertex v4 = getPolyFaceMeshVertex(v.getPolyFaceMeshVertex3()); + + if (v.isPolyFaceEdge0Visible() && + (v.getPolyFaceMeshVertex0() != 0)) { + length += getSegmentLength(v1, v2); + } + + if (v.isPolyFaceEdge1Visible() && + (v.getPolyFaceMeshVertex1() != 0)) { + length += getSegmentLength(v2, v3); + } + + if (v.isPolyFaceEdge2Visible() && + (v.getPolyFaceMeshVertex2() != 0)) { + length += getSegmentLength(v3, v4); + } + + if (v.isPolyFaceEdge3Visible() && + (v.getPolyFaceMeshVertex3() != 0)) { + length += getSegmentLength(v4, v1); + } else if ((v4 == null) && (v3 != null)) { + // triangle + length += getSegmentLength(v3, v1); + } + } + } + + return length; + } + + protected double getMeshLength() { + double length = 0.0; + + if (isSimpleMesh()) { + DXFVertex[][] points = new DXFVertex[this.rows][this.columns]; + Iterator it = this.vertices.iterator(); + + // create a line for each row + for (int i = 0; i < this.rows; i++) { + for (int x = 0; x < this.columns; x++) { + DXFVertex v = (DXFVertex) it.next(); + points[i][x] = v; + + if (x > 0) { + length += getSegmentLength(points[i][x - 1], + points[i][x]); + } + } + + if (isClosedMeshNDirection()) { + length += getSegmentLength(points[i][points[i].length - 1], + points[i][0]); + } + } + + // create a line for each column + for (int i = 0; i < this.columns; i++) { + for (int x = 0; x < this.rows; x++) { + if (x > 0) { + length += getSegmentLength(points[x - 1][i], + points[x][i]); + } + } + + if (isClosedMeshMDirection()) { + length += getSegmentLength(points[points[i].length - 1][i], + points[0][i]); + } + } + } else { + DXFVertex[][] points = new DXFVertex[this.surefaceDensityRows][this.surefaceDensityColumns]; + Iterator vi = this.vertices.iterator(); + List appVertices = new ArrayList(); + + while (vi.hasNext()) { + DXFVertex v = (DXFVertex) vi.next(); + + if (v.isMeshApproximationVertex()) { + appVertices.add(v); + } + } + + Iterator it = appVertices.iterator(); + + // create a line for each row + for (int i = 0; i < this.surefaceDensityRows; i++) { + for (int x = 0; x < this.surefaceDensityColumns; x++) { + DXFVertex v = (DXFVertex) it.next(); + points[i][x] = v; + + if (x > 0) { + length += getSegmentLength(points[i][x - 1], + points[i][x]); + } + } + + if (isClosedMeshNDirection()) { + length += getSegmentLength(points[i][points[i].length - 1], + points[i][0]); + } + } + + // create a line for each column + for (int i = 0; i < this.surefaceDensityColumns; i++) { + for (int x = 0; x < this.surefaceDensityRows; x++) { + if (x > 0) { + length += getSegmentLength(points[x - 1][i], + points[x][i]); + } + } + + if (isClosedMeshMDirection()) { + length += getSegmentLength(points[points[i].length - 1][i], + points[0][i]); + } + } + } + + return length; + } +} diff --git a/dxf/src/main/java/org/kabeja/dxf/DXFRay.java b/dxf/src/main/java/org/kabeja/dxf/DXFRay.java new file mode 100644 index 0000000..abea129 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/dxf/DXFRay.java @@ -0,0 +1,80 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.dxf; + +import org.kabeja.dxf.helpers.Point; +import org.kabeja.dxf.helpers.Vector; + + +/** + * @author 0) { + // TODO calculate the real values + Point p = calculateAlignmentPoint(); + bounds.addToBounds(p); + + double h = getHeight(); + + double w = tl * h * 0.6; + + if (this.isBackward()) { + w = -1 * w; + } + + // we set the horizontal width + switch (this.align) { + case 0: + bounds.addToBounds(p.getX() + w, p.getY(), p.getZ()); + + break; + + case 1: + bounds.addToBounds(p.getX() + (w / 2), p.getY(), p.getZ()); + bounds.addToBounds(p.getX() - (w / 2), p.getY(), p.getZ()); + + break; + + case 2: + bounds.addToBounds(p.getX() - w, p.getY(), p.getZ()); + + break; + + case 3: + bounds.addToBounds(p.getX() - w, p.getY(), p.getZ()); + + break; + + case 4: + bounds.addToBounds(p.getX() + (w / 2), p.getY(), p.getZ()); + bounds.addToBounds(p.getX() - (w / 2), p.getY(), p.getZ()); + + break; + + case 5: + bounds.addToBounds(p.getX() + (w / 2), p.getY(), p.getZ()); + bounds.addToBounds(p.getX() - (w / 2), p.getY(), p.getZ()); + + break; + } + + // set the vertical height + switch (this.valign) { + case VALIGN_BASELINE: + bounds.addToBounds(p.getX(), p.getY() + (h * 0.75), p.getZ()); + + break; + + case VALIGN_BOTTOM: + bounds.addToBounds(p.getX(), p.getY() + h, p.getZ()); + + break; + + case VALIGN_CENTER: + bounds.addToBounds(p.getX(), p.getY() + (h * 0.5), p.getZ()); + bounds.addToBounds(p.getX(), p.getY() - (h * 0.5), p.getZ()); + + break; + + case VALIGN_TOP: + bounds.addToBounds(p.getX(), p.getY() - h, p.getZ()); + + break; + } + } else { + bounds.setValid(false); + } + + return bounds; + } + + /** + * @return Returns the align. + */ + public int getAlign() { + return align; + } + + /** + * @param align + * The align to set. + */ + public void setAlign(int align) { + this.align = align; + } + + /** + * @return Returns the align_x. + */ + public double getAlignX() { + return align_p1.getX(); + } + + /** + * @param align_x + * The align_x to set. + */ + public void setAlignX(double align_x) { + align_p1.setX(align_x); + } + + /** + * @return Returns the align_y. + */ + public double getAlignY() { + return align_p1.getY(); + } + + /** + * @param align_y + * The align_y to set. + */ + public void setAlignY(double align_y) { + align_p1.setY(align_y); + } + + /** + * @return Returns the align_z. + */ + public double getAlignZ() { + return align_p1.getZ(); + } + + /** + * @param align_z + * The align_z to set. + */ + public void setAlignZ(double align_z) { + align_p1.setZ(align_z); + } + + /** + * @return Returns the height. + */ + public double getHeight() { + if (height != 0.0) { + return height; + } else if (doc.getDXFStyle(this.textStyle) != null) { + return doc.getDXFStyle(this.textStyle).getTextHeight(); + } else { + return 0.0; + } + } + + /** + * @param height + * The height to set. + */ + public void setHeight(double height) { + this.height = height; + } + + /** + * @return Returns the oblique_angle. + */ + public double getObliqueAngle() { + return oblique_angle; + } + + /** + * @param oblique_angle + * The oblique_angle to set. + */ + public void setObliqueAngle(double oblique_angle) { + this.oblique_angle = oblique_angle; + } + + /** + * @return Returns the rotation. + */ + public double getRotation() { + return rotation; + } + + /** + * @param rotation + * The rotation to set. + */ + public void setRotation(double rotation) { + this.rotation = rotation; + } + + /** + * @return Returns the scale_x. + */ + public double getScaleX() { + return scale_x; + } + + /** + * @param scale_x + * The scale_x to set. + */ + public void setScaleX(double scale_x) { + this.scale_x = scale_x; + } + + /** + * @return Returns the text. + */ + public String getText() { + return text; + } + + /** + * @param text + * The text to set. + */ + public void setText(String text) { + this.text = text; + this.textDoc = DXFTextParser.parseDXFText(this); + } + + /** + * @return Returns the textStyle. + */ + public String getTextStyle() { + return textStyle; + } + + /** + * @param textStyle + * The textStyle to set. + */ + public void setTextStyle(String textStyle) { + this.textStyle = textStyle; + } + + /** + * @return Returns the valign. + */ + public int getValign() { + return valign; + } + + /** + * @param valign + * The valign to set. + */ + public void setValign(int valign) { + this.valign = valign; + } + + public void setX(double x) { + p.setX(x); + } + + public void setY(double y) { + p.setY(y); + } + + public void setZ(double z) { + p.setZ(z); + } + + public boolean isBackward() { + return backward; + } + + public void setBackward(boolean backward) { + this.backward = backward; + } + + public boolean isUpsideDown() { + return upsideDown; + } + + public void setUpsideDown(boolean upsideDown) { + this.upsideDown = upsideDown; + } + + public String getType() { + return DXFConstants.ENTITY_TYPE_TEXT; + } + + /** + * @return Returns the alignmentPointSet. + */ + public boolean isAlignmentPointSet() { + return alignmentPointSet; + } + + /** + * @param alignmentPointSet + * The alignmentPointSet to set. + */ + public void setAlignmentPoint(boolean alignmentPoint) { + this.alignmentPointSet = alignmentPoint; + } + + public TextDocument getTextDocument() { + return this.textDoc; + } + + public Point getInsertPoint() { + return p; + } + + public Point getAlignmentPoint() { + return align_p1; + } + + public Point calculateAlignmentPoint() { + Point alignmentPoint = new Point(p.getX(), p.getY(), p.getZ()); + + if (!isUpsideDown()) { + switch (align) { + case 1: + + if (alignmentPointSet) { + alignmentPoint.setX(align_p1.getX()); + } + + break; + + case 2: + + if (alignmentPointSet) { + alignmentPoint.setX(align_p1.getX()); + } + + break; + + case 3: + + if (alignmentPointSet) { + alignmentPoint.setX(align_p1.getX()); + } + + break; + + case 4: + + if (alignmentPointSet) { + alignmentPoint.setX(align_p1.getX()); + } + + break; + + case 5: + + if (alignmentPointSet) { + alignmentPoint.setX(align_p1.getX()); + } + + break; + } + + if (alignmentPointSet) { + alignmentPoint.setY(align_p1.getY()); + } + } + + return alignmentPoint; + } + + public boolean isOmitLineType() { + return true; + } + + public double getLength() { + return 0; + } +} diff --git a/dxf/src/main/java/org/kabeja/dxf/DXFTolerance.java b/dxf/src/main/java/org/kabeja/dxf/DXFTolerance.java new file mode 100644 index 0000000..cfd0d25 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/dxf/DXFTolerance.java @@ -0,0 +1,109 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.dxf; + +import org.kabeja.dxf.helpers.Point; +import org.kabeja.dxf.helpers.Vector; + + +/** + * @author 0) { + bounds.addToBounds(this.centerPoint.getX() - (this.width / 2), + this.centerPoint.getY() - (this.height / 2), 0.0); + bounds.addToBounds(this.centerPoint.getX() + (this.width / 2), + this.centerPoint.getY() + (this.height / 2), 0.0); + } + + return bounds; + } + + public double getLength() { + // TODO Auto-generated method stub + return 0; + } + + public String getType() { + return DXFConstants.ENTITY_TYPE_VIEWPORT; + } + + public double getWidth() { + return width; + } + + public void setWidth(double width) { + this.width = width; + } + + public void setRenderMode(int renderMode) { + this.renderMode = renderMode; + } + + public double getViewHeight() { + return viewHeight; + } + + public void setViewHeight(double viewHeight) { + this.viewHeight = viewHeight; + } + + public Vector getUcsOrigin() { + return ucsOrigin; + } + + public void setUcsOrigin(Vector ucsOrigin) { + this.ucsOrigin = ucsOrigin; + } + + public Vector getUcsXAxis() { + return ucsXAxis; + } + + public void setUcsXAxis(Vector ucsXAxis) { + this.ucsXAxis = ucsXAxis; + } + + public Vector getUcsYAxis() { + return ucsYAxis; + } + + public void setUcsYAxis(Vector ucsYAxis) { + this.ucsYAxis = ucsYAxis; + } + + public int getUcsType() { + return ucsType; + } + + public void setUcsType(int ucsType) { + this.ucsType = ucsType; + } + + public double getUcsElevation() { + return ucsElevation; + } + + public void setUcsElevation(double ucsElevation) { + this.ucsElevation = ucsElevation; + } + + public boolean isUseUCS() { + return useUCS; + } + + public void setUseUCS(boolean useUCS) { + this.useUCS = useUCS; + } + + public double getRatio() { + return ratio; + } + + public void setRatio(double ratio) { + this.ratio = ratio; + } + + public int getRenderMode() { + return renderMode; + } + + public double getSnapAngle() { + return snapAngle; + } + + public void setSnapAngle(double snapAngle) { + this.snapAngle = snapAngle; + } + + public Point getViewTargetPoint() { + return viewTargetPoint; + } + + public void setViewTargetPoint(Point viewTargetPoint) { + this.viewTargetPoint = viewTargetPoint; + } + + public Point getSnapSpacingPoint() { + return snapSpacingPoint; + } + + public void setSnapSpacingPoint(Point snapSpacingPoint) { + this.snapSpacingPoint = snapSpacingPoint; + } + + public String getPlotStyleName() { + return plotStyleName; + } + + public void setPlotStyleName(String plotStyleName) { + this.plotStyleName = plotStyleName; + } + + public int getViewportStatus() { + return viewportStatus; + } + + public void setViewportStatus(int viewportStatus) { + this.viewportStatus = viewportStatus; + } + + public double getTwistAngle() { + return twistAngle; + } + + public void addFrozenLayer(String layerName) { + this.frozenLayerSet.add(layerName); + } + + public boolean isFrozenLayer(String layerName) { + return this.frozenLayerSet.contains(layerName); + } + + public Iterator getFrozenLayerIterator() { + return this.frozenLayerSet.iterator(); + } + + public double getZoomXPFactor() { + if (this.viewHeight != 0.0) { + return this.height / this.viewHeight; + } else { + return this.calculateZoomXPFactor(); + } + } + + public double calculateZoomXPFactor() { + double c = (this.getViewDirectionVector().getLength() * 42) / this.lensLength; + double f = this.width / this.height; + double b = Math.sqrt((Math.pow(c, 2) / (Math.pow(f, 2) + 1))); + + return this.height / b; + } + + public Bounds getModelspaceViewBounds() { + double f = this.width / this.height; + + // the half of width and height + double modelH = (this.height / this.getZoomXPFactor()) / 2; + double modelW = (f * modelH); + double wf = modelW / modelH; + Vector directionX = null; + + if ((this.viewDirectionVector.getX() == 0.0) && + (this.viewDirectionVector.getY() == 0.0) && + (this.viewDirectionVector.getZ() == 1.0)) { + directionX = new Vector(1, 0, 0); + } else { + directionX = MathUtils.crossProduct(DXFConstants.DEFAULT_Z_AXIS_VECTOR, + this.viewDirectionVector); + } + + ParametricPlane plane = new ParametricPlane(this.viewTargetPoint, + directionX, + MathUtils.crossProduct(this.viewDirectionVector, directionX), + this.viewDirectionVector); + Bounds bounds = new Bounds(); + Point p = plane.getPoint(this.viewCenterPoint.getX() - modelW, + this.viewCenterPoint.getY() - modelH); + bounds.addToBounds(p); + p = plane.getPoint(this.viewCenterPoint.getX() + modelW, + this.viewCenterPoint.getY() + modelH); + bounds.addToBounds(p); + + return bounds; + } +} diff --git a/dxf/src/main/java/org/kabeja/dxf/DXFXLine.java b/dxf/src/main/java/org/kabeja/dxf/DXFXLine.java new file mode 100644 index 0000000..cea6b19 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/dxf/DXFXLine.java @@ -0,0 +1,25 @@ +/* + * Created on 17.10.2005 + * + */ +package org.kabeja.dxf; + + +/** + * @author elements = new ArrayList(); + + public Point getStartPoint() { + return startPoint; + } + + public void setStartPoint(Point startPoint) { + this.startPoint = startPoint; + } + + public Vector getDirection() { + return direction; + } + + public void setDirection(Vector direction) { + this.direction = direction; + } + + public Vector getMiterDirection() { + return miterDirection; + } + + public void setMiterDirection(Vector miterDirection) { + this.miterDirection = miterDirection; + } + + public void addDXFMLineSegmentElement(DXFMLineSegmentElement el) { + this.elements.add(el); + } + + public int getDXFMLineSegmentElementCount() { + return this.elements.size(); + } + + public DXFMLineSegmentElement getDXFMLineSegmentElement(int index) { + return (DXFMLineSegmentElement) this.elements.get(index); + } +} diff --git a/dxf/src/main/java/org/kabeja/dxf/helpers/DXFMLineSegmentElement.java b/dxf/src/main/java/org/kabeja/dxf/helpers/DXFMLineSegmentElement.java new file mode 100644 index 0000000..23a2285 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/dxf/helpers/DXFMLineSegmentElement.java @@ -0,0 +1,45 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.dxf.helpers; + +public class DXFMLineSegmentElement { + protected double[] lengthParameters; + protected double[] fillParameters; + + public double[] getLengthParameters() { + return lengthParameters; + } + + public void setLengthParameters(double[] lengthParameters) { + this.lengthParameters = lengthParameters; + } + + public void setLengthParameter(int index, double v) { + this.lengthParameters[index] = v; + } + + public double[] getFillParameters() { + return fillParameters; + } + + public void setFillParameters(double[] fillParameters) { + this.fillParameters = fillParameters; + } + + public void setFillParameter(int index, double v) { + this.fillParameters[index] = v; + } +} diff --git a/dxf/src/main/java/org/kabeja/dxf/helpers/DXFMLineStyleElementDistanceComparator.java b/dxf/src/main/java/org/kabeja/dxf/helpers/DXFMLineStyleElementDistanceComparator.java new file mode 100644 index 0000000..748f75c --- /dev/null +++ b/dxf/src/main/java/org/kabeja/dxf/helpers/DXFMLineStyleElementDistanceComparator.java @@ -0,0 +1,36 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.dxf.helpers; + +import java.util.Comparator; + +import org.kabeja.dxf.objects.DXFMLineStyleElement; + + +public class DXFMLineStyleElementDistanceComparator implements Comparator { + public int compare(Object arg0, Object arg1) { + DXFMLineStyleElement el1 = (DXFMLineStyleElement) arg0; + DXFMLineStyleElement el2 = (DXFMLineStyleElement) arg1; + + if (el1.getOffset() > el2.getOffset()) { + return 1; + } else if (el1.getOffset() < el2.getOffset()) { + return -1; + } + + return 0; + } +} diff --git a/dxf/src/main/java/org/kabeja/dxf/helpers/DXFSplineConverter.java b/dxf/src/main/java/org/kabeja/dxf/helpers/DXFSplineConverter.java new file mode 100644 index 0000000..86e0c9b --- /dev/null +++ b/dxf/src/main/java/org/kabeja/dxf/helpers/DXFSplineConverter.java @@ -0,0 +1,77 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.dxf.helpers; + +import java.util.ArrayList; +import java.util.Iterator; + +import org.kabeja.dxf.DXFPolyline; +import org.kabeja.dxf.DXFSpline; +import org.kabeja.dxf.DXFVertex; +import org.kabeja.math.NURBS; +import org.kabeja.math.NURBSFixedNTELSPointIterator; + + +public class DXFSplineConverter { + public static DXFPolyline toDXFPolyline(DXFSpline spline) { + DXFPolyline p = new DXFPolyline(); + p.setDXFDocument(spline.getDXFDocument()); + + if ((spline.getDegree() > 0) && (spline.getKnots().length > 0)) { + Iterator pi = new NURBSFixedNTELSPointIterator(toNurbs(spline), 30); + + while (pi.hasNext()) { + p.addVertex(new DXFVertex((Point) pi.next())); + } + } else { + // the curve is the controlpoint polygon + Iterator i = spline.getSplinePointIterator(); + + while (i.hasNext()) { + SplinePoint sp = (SplinePoint) i.next(); + + if (sp.isControlPoint()) { + p.addVertex(new DXFVertex(sp)); + } + } + } + + if (spline.isClosed()) { + p.setFlags(1); + } + + return p; + } + + public static NURBS toNurbs(DXFSpline spline) { + Iterator i = spline.getSplinePointIterator(); + ArrayList list = new ArrayList(); + + while (i.hasNext()) { + SplinePoint sp = (SplinePoint) i.next(); + + if (sp.isControlPoint()) { + list.add((Point) sp); + } + } + + NURBS n = new NURBS((Point[]) list.toArray(new Point[list.size()]), + spline.getKnots(), spline.getWeights(), spline.getDegree()); + n.setClosed(spline.isClosed()); + + return n; + } +} diff --git a/dxf/src/main/java/org/kabeja/dxf/helpers/DXFTextParser.java b/dxf/src/main/java/org/kabeja/dxf/helpers/DXFTextParser.java new file mode 100644 index 0000000..2a09daa --- /dev/null +++ b/dxf/src/main/java/org/kabeja/dxf/helpers/DXFTextParser.java @@ -0,0 +1,662 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.dxf.helpers; + +import java.util.Stack; +import java.util.StringTokenizer; + +import org.kabeja.dxf.DXFMText; +import org.kabeja.dxf.DXFText; + + +/** + * @author (i + 6)) && (text.charAt(i + 1) == 'U') && + (text.charAt(i + 2) == '+')) { + String part = text.substring(i + 3, i + 7); + int unicode = Integer.parseInt(part, 16); + buf.append((char) unicode); + i += 6; + } else { + buf.append('\\'); + } + } else { + if (marker == 0) { + buf.append(c); + } else if (marker == 1) { + // the control % self + buf.append('%'); + marker = 0; + } else if (marker == 2) { + switch (c) { + case 'd': + buf.append('\u00B0'); + + break; + + case 'c': + buf.append('\u2205'); + + break; + + case 'p': + buf.append('\u00B1'); + + break; + + default: + + if (Character.isDigit(c) && ((i + 2) < text.length())) { + String code = "" + c + text.charAt(i + 1) + + text.charAt(i + 2); + + try { + c = (char) Integer.parseInt(code); + buf.append(c); + i += 2; + } catch (NumberFormatException e) { + // TODO sometimes there is only one + // digit, so what should be the + //replacement??? + buf.append('?'); + i++; + } + } else { + //a style control write back + buf.append("%%"); + buf.append(c); + } + } + + marker = 0; + } else if (marker == 3) { + buf.append('%'); + marker = 0; + } + } + } + + if ((marker == 1) || (marker == 3)) { + buf.append('%'); + } + + return buf.toString(); + } +} diff --git a/dxf/src/main/java/org/kabeja/dxf/helpers/DXFUtils.java b/dxf/src/main/java/org/kabeja/dxf/helpers/DXFUtils.java new file mode 100644 index 0000000..c1bf7b2 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/dxf/helpers/DXFUtils.java @@ -0,0 +1,149 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ +package org.kabeja.dxf.helpers; + +import java.util.ArrayList; + +import org.kabeja.dxf.DXFLine; +import org.kabeja.dxf.DXFPolyline; +import org.kabeja.dxf.DXFVertex; +import org.kabeja.math.MathUtils; + + +/** + * @author startLength) { + this.currentLength = l - startLength; + + if (pattern[i] < 0) { + //System.out.println("is empty"); + this.currentLength *= (-1); + } + + //System.out.println("pattern startet bei="+i+" mit length="+this.currentLength); + this.index = i + 1; + + return; + } + } + } + + public boolean isSolid() { + return pattern.length == 0; + } +} diff --git a/dxf/src/main/java/org/kabeja/dxf/helpers/HatchPattern.java b/dxf/src/main/java/org/kabeja/dxf/helpers/HatchPattern.java new file mode 100644 index 0000000..baadec6 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/dxf/helpers/HatchPattern.java @@ -0,0 +1,24 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.dxf.helpers; + + +/** + * @author Lifecycle + * + *
    + *
  1. setProperties
  2. + *
  3. getSuffix()
  4. + *
  5. getMimeType()
  6. + *
  7. generate()
  8. + *
+ *@author
Simon Mieth + */ +public interface StreamGenerator { + public void setProperties(Map properties); + + public String getSuffix(); + + public String getMimeType(); + + /** + * Output the generation result to the given stream. + * @param doc the @see DXFDocument to output + * @param out + */ + public void generate(DXFDocument doc, OutputStream out); +} diff --git a/dxf/src/main/java/org/kabeja/math/MathUtils.java b/dxf/src/main/java/org/kabeja/math/MathUtils.java new file mode 100644 index 0000000..5fe53bd --- /dev/null +++ b/dxf/src/main/java/org/kabeja/math/MathUtils.java @@ -0,0 +1,334 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.math; + +import org.kabeja.dxf.helpers.Point; +import org.kabeja.dxf.helpers.Vector; + + +/** + * @author = this.knots[mid + 1])) { + if (u < this.knots[mid]) { + high = mid; + } else { + low = mid; + } + + mid = (low + high) / 2; + } + + return mid; + } + + public Point[] getControlPoints() { + return controlPoints; + } + + public void setControlPoints(Point[] controlPoints) { + this.controlPoints = controlPoints; + } + + public double[] getKnots() { + return knots; + } + + public void setKnots(double[] knots) { + this.knots = knots; + } + + public double[] getWeights() { + return weights; + } + + public void setWeights(double[] weights) { + this.weights = weights; + } + + public int getDegree() { + return degree; + } + + public void setDegree(int degree) { + this.degree = degree; + } + + public boolean isClosed() { + return closed; + } + + public void setClosed(boolean closed) { + this.closed = closed; + } +} diff --git a/dxf/src/main/java/org/kabeja/math/NURBSAutoStepPointIterator.java b/dxf/src/main/java/org/kabeja/math/NURBSAutoStepPointIterator.java new file mode 100644 index 0000000..dfa823c --- /dev/null +++ b/dxf/src/main/java/org/kabeja/math/NURBSAutoStepPointIterator.java @@ -0,0 +1,35 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.math; + +import java.util.Iterator; + + +public class NURBSAutoStepPointIterator implements Iterator { + public boolean hasNext() { + // TODO Auto-generated method stub + return false; + } + + public Object next() { + // TODO Auto-generated method stub + return null; + } + + public void remove() { + // TODO Auto-generated method stub + } +} diff --git a/dxf/src/main/java/org/kabeja/math/NURBSFixedNTELSPointIterator.java b/dxf/src/main/java/org/kabeja/math/NURBSFixedNTELSPointIterator.java new file mode 100644 index 0000000..4e28b1e --- /dev/null +++ b/dxf/src/main/java/org/kabeja/math/NURBSFixedNTELSPointIterator.java @@ -0,0 +1,112 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.math; + +import java.util.Iterator; + +import org.kabeja.dxf.helpers.Point; + + +public class NURBSFixedNTELSPointIterator implements Iterator { + private NURBS nurbs; + private int ntels; + private double dt = 0; + private double t = 0; + private int interval; + private int lastInterval; + + /** + * + * @param nurbs + * The NURBS curve to draw + * @param ntels + * the ntels per interval to use + */ + public NURBSFixedNTELSPointIterator(NURBS nurbs, int ntels) { + this.nurbs = nurbs; + this.ntels = ntels; + + if (this.nurbs.getKnots().length == (this.nurbs.getDegree() + + this.nurbs.controlPoints.length + 1)) { + this.lastInterval = this.nurbs.getKnots().length - + this.nurbs.getDegree() - 1; + this.interval = this.nurbs.getDegree(); + } else if (this.nurbs.getKnots().length > 0) { + // find self the start and end interval + this.interval = 0; + + double start = this.nurbs.getKnots()[0]; + + while (start == this.nurbs.getKnots()[this.interval + 1]) { + this.interval++; + } + + this.lastInterval = this.nurbs.getKnots().length - 1; + + double end = this.nurbs.getKnots()[this.lastInterval]; + + while (end == this.nurbs.getKnots()[this.lastInterval]) { + this.lastInterval--; + } + } + + //init t + this.t = this.nurbs.getKnots()[this.nurbs.getDegree()]; + this.nextInterval(); + + //fix for some broken nurbs + if ((this.interval - 1) < this.nurbs.getDegree()) { + this.interval = this.nurbs.getDegree() + 1; + } + } + + public boolean hasNext() { + if (this.t < this.nurbs.getKnots()[this.interval]) { + return true; + } else if (this.interval < this.lastInterval) { + this.nextInterval(); + + return hasNext(); + } + + return false; + } + + public Object next() { + Point p = this.nurbs.getPointAt(this.interval - 1, t); + // System.out.println("t="+t); + // Point p = this.nurbs.getPointAt(t); + this.t += this.dt; + + return p; + } + + public void remove() { + //nothing todo here + } + + protected void nextInterval() { + this.interval++; + + while ((this.t > this.nurbs.getKnots()[this.interval]) && + (this.interval < this.lastInterval)) { + this.interval++; + } + + double length = this.nurbs.getKnots()[this.interval] - this.t; + this.dt = length / this.ntels; + } +} diff --git a/dxf/src/main/java/org/kabeja/math/ParametricPlane.java b/dxf/src/main/java/org/kabeja/math/ParametricPlane.java new file mode 100644 index 0000000..829183b --- /dev/null +++ b/dxf/src/main/java/org/kabeja/math/ParametricPlane.java @@ -0,0 +1,205 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.math; + +import org.kabeja.dxf.DXFExtrusion; +import org.kabeja.dxf.helpers.Point; +import org.kabeja.dxf.helpers.Vector; + + +public class ParametricPlane { + protected Point base; + protected Vector directionX; + protected Vector directionY; + protected Vector normal; + + /** + * + * @param basePoint + * The base point of this plane + * @param directionX + * the x direction of this plane + * @param directionY + * the y direction of this plane + * @param normal + * the normal direction of this plane + */ + public ParametricPlane(Point basePoint, Vector directionX, + Vector directionY, Vector normal) { + this.base = basePoint; + this.directionX = directionX; + this.directionY = directionY; + this.normal = normal; + } + + /** + * + * @param basePoint + * The base point of this plane + * @param directionX + * the x direction of this plane + * @param directionY + * the y direction of this plane + */ + public ParametricPlane(Point basePoint, Vector directionX, Vector directionY) { + this(basePoint, directionX, directionY, + MathUtils.normalize(MathUtils.crossProduct(directionX, directionY))); + } + + /** + * Generates a plane with the base point and uses the vector from base point + * to b as x direction. The y direction is generated with the cross product + * of the normal with the x direction. + * + * @param basePoint + * @param b + * @param normal + */ + public ParametricPlane(Point basePoint, Point b, Vector normal) { + this(basePoint, MathUtils.normalize(MathUtils.getVector(basePoint, b)), + MathUtils.normalize(MathUtils.crossProduct(normal, + MathUtils.normalize(MathUtils.getVector(basePoint, b)))), + normal); + } + + public ParametricPlane(Point basePoint, Point b, Point c) { + this(basePoint, MathUtils.normalize(MathUtils.getVector(basePoint, b)), + MathUtils.normalize(MathUtils.getVector(basePoint, c))); + } + + public ParametricPlane(DXFExtrusion e) { + this(new Point(0.0, 0.0, 0.0), e.getDirectionX(), e.getDirectionY(), + e.getNormal()); + } + + /** + * Calculate the point in world coordinates for the given parameters + * + * @param x + * @param y + * @return + */ + public Point getPoint(double x, double y) { + Point p = new Point(); + p.setX(this.base.getX() + (this.directionX.getX() * x) + + (this.directionY.getX() * y)); + p.setY(this.base.getY() + (this.directionX.getY() * x) + + (this.directionY.getY() * y)); + p.setZ(this.base.getZ() + (this.directionX.getZ() * x) + + (this.directionY.getZ() * y)); + + return p; + } + + public Point getPoint(Point point) { + return getPoint(point.getX(), point.getY()); + } + + /** + * Calculates the plane parameters of the given point relative to the base + * point of the plane + * + * @param p + * @return double[]{parameter x direction, parameter y direction} + */ + public double[] getParameter(Point p) { + double u = 0.0; + double v = (this.directionX.getY() * this.directionY.getX()) - + (this.directionX.getX() * this.directionY.getY()); + + if (v != 0.0) { + v = ((p.getY() * this.directionY.getX()) - + (this.base.getY() * this.directionY.getX()) - + (this.directionY.getY() * p.getX()) + + (this.base.getX() * this.directionY.getY())) / v; + } + + if (this.directionY.getX() != 0.0) { + u = (p.getX() - this.base.getX() - (this.directionX.getX() * v)) / this.directionY.getX(); + } else if (this.directionY.getY() != 0.0) { + u = (p.getY() - this.base.getY() - (this.directionX.getY() * v)) / this.directionY.getY(); + } else if (this.directionY.getY() != 0.0) { + u = (p.getZ() - this.base.getZ() - (this.directionX.getZ() * v)) / this.directionY.getZ(); + } + + return new double[] { v, u }; + } + + /** + * Determines if the given point lies on the plane. + * + * @param p + * the point to determine + * @return true if the point lies on the plane, otherwise false. + */ + public boolean isOnPlane(Point p) { + double[] para = this.getParameter(p); + double v = this.base.getZ() + (this.directionX.getZ() * para[0]) + + (this.directionY.getZ() * para[1]); + + if (!(Math.abs((p.getZ() - v)) < MathUtils.DISTANCE_DELTA)) { + return false; + } + + v = this.base.getY() + (this.directionX.getY() * para[0]) + + (this.directionY.getY() * para[1]); + + if (!(Math.abs((p.getY() - v)) < MathUtils.DISTANCE_DELTA)) { + return false; + } + + v = this.base.getX() + (this.directionX.getX() * para[0]) + + (this.directionY.getX() * para[1]); + + if (!(Math.abs((p.getX() - v)) < MathUtils.DISTANCE_DELTA)) { + return false; + } + + return true; + } + + public Point getBasePoint() { + return base; + } + + public void setBasePoint(Point base) { + this.base = base; + } + + public Vector getDirectionX() { + return directionX; + } + + public void setDirectionX(Vector directionX) { + this.directionX = directionX; + this.normal = MathUtils.crossProduct(this.directionX, this.directionY); + this.normal.normalize(); + } + + public Vector getDirectionY() { + return directionY; + } + + public void setDirectionY(Vector directionY) { + this.directionY = directionY; + this.normal = MathUtils.crossProduct(this.directionX, this.directionY); + this.normal.normalize(); + } + + public Vector getNormal() { + return normal; + } +} diff --git a/dxf/src/main/java/org/kabeja/math/TransformContext.java b/dxf/src/main/java/org/kabeja/math/TransformContext.java new file mode 100644 index 0000000..c09a8be --- /dev/null +++ b/dxf/src/main/java/org/kabeja/math/TransformContext.java @@ -0,0 +1,133 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.math; + +import org.kabeja.dxf.helpers.Point; +import org.kabeja.dxf.helpers.Vector; + + +public class TransformContext { + private double[][] transformMatrix; + private double rotationAngle = 0.0; + private double scaleX = 1.0; + private double scaleY = 1.0; + private double scaleZ = 1.0; + private Vector translation = new Vector(1.0, 1.0, 1.0); + + public TransformContext() { + transformMatrix = new double[][] { + { 1.0, 0.0, 0.0, 0.0 }, + { 0.0, 1.0, 0.0, 0.0 }, + { 0.0, 0.0, 1.0, 0.0 }, + { 0.0, 0.0, 0.0, 1.0 } + }; + } + + public TransformContext(double[][] transformMatrix) + throws IllegalArgumentException { + if ((transformMatrix.length != 4) && (transformMatrix[0].length != 4)) { + throw new IllegalArgumentException( + "Not a valid tranformation matrix."); + } + + this.transformMatrix = transformMatrix; + } + + public double getRotationZAxis() { + return rotationAngle; + } + + public void setRotationZAxis(double rotationAngle) { + this.rotationAngle = rotationAngle; + } + + public void setScale(double s) { + this.setScale(s, s, s); + } + + public void setScale(double x, double y, double z) { + this.scaleX = x; + this.scaleY = y; + this.scaleZ = z; + + double[][] m = new double[][] { + { x, 0.0, 0.0, 0.0 }, + { 0.0, y, 0.0, 0.0 }, + { 0.0, 0.0, z, 0.0 }, + { 0.0, 0.0, 0.0, 1.0 } + }; + this.transformMatrix = MathUtils.multiplyMatrixByMatrix(this.transformMatrix, + m); + } + + public double getScaleX() { + return scaleX; + } + + public void setScaleX(double scaleX) { + this.setScale(scaleX, 1.0, 1.0); + } + + public double getScaleY() { + return scaleY; + } + + public void setScaleY(double scaleY) { + this.setScale(1.0, scaleY, 1.0); + } + + public double getScaleZ() { + return scaleZ; + } + + public void setScaleZ(double scaleZ) { + this.setScale(1.0, 1.0, scaleZ); + } + + public double[][] getTransformMatrix() { + return transformMatrix; + } + + public void setTransformMatrix(double[][] transformMatrix) { + this.transformMatrix = transformMatrix; + } + + public Vector getTranslation() { + return translation; + } + + public void setTranslation(Vector translation) { + this.translation = translation; + + double[][] m = new double[][] { + { 1.0, 0.0, 0.0, translation.getX() }, + { 0.0, 1.0, 0.0, translation.getY() }, + { 0.0, 0.0, 1.0, translation.getZ() }, + { 0.0, 0.0, 0.0, 1.0 } + }; + this.transformMatrix = MathUtils.multiplyMatrixByMatrix(this.transformMatrix, + m); + } + + public Point transform(Point a) { + double[] v = new double[] { a.getX(), a.getY(), a.getZ(), 1.0 }; + v = MathUtils.multiplyMatrixByVector(this.transformMatrix, v); + + Point p = new Point(v[0], v[1], v[2]); + + return p; + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/AbstractSectionHandler.java b/dxf/src/main/java/org/kabeja/parser/AbstractSectionHandler.java new file mode 100644 index 0000000..f5430c5 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/AbstractSectionHandler.java @@ -0,0 +1,34 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser; + +import org.kabeja.dxf.DXFDocument; + + +/** + * @author = 0; i--) { + DXFStreamFilter f = (DXFStreamFilter) this.streamFilters.get(i); + f.setDXFHandler(handler); + handler = f; + } + + // the first is used filter and if no filter + // the parser itself is the filter + this.filter = handler; + } + + public String getName() { + return PARSER_NAME; + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/DXFSectionHandler.java b/dxf/src/main/java/org/kabeja/parser/DXFSectionHandler.java new file mode 100644 index 0000000..13994b6 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/DXFSectionHandler.java @@ -0,0 +1,44 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser; + +import org.kabeja.dxf.DXFDocument; +import org.kabeja.parser.dxf.DXFHandler; + + +/** + * This interface descripe a Section Handler, which should handle a SECTION + * block. + *

Lifecycle

+ *
    + *
  1. setDXFDocument
  2. + *
  3. startSection
  4. + *
  5. parseGroup (multiple)
  6. + *
  7. endSection
  8. + * + * @author
    Simon Mieth + * + * + * + */ +public interface Handler { + public void setDXFDocument(DXFDocument doc); + + public void releaseDXFDocument(); +} diff --git a/dxf/src/main/java/org/kabeja/parser/HandlerManager.java b/dxf/src/main/java/org/kabeja/parser/HandlerManager.java new file mode 100644 index 0000000..6f2ad05 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/HandlerManager.java @@ -0,0 +1,27 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser; + + +/** + * @author Simon Mieth + * + * + * + */ +public interface HandlerManager extends Handler { + public void addHandler(Handler handler); +} diff --git a/dxf/src/main/java/org/kabeja/parser/ParseException.java b/dxf/src/main/java/org/kabeja/parser/ParseException.java new file mode 100644 index 0000000..fcdabbc --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/ParseException.java @@ -0,0 +1,36 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser; + + +/** + * @author Lifecycle + *
      + *
    1. supportedExtension()
    2. + *
    3. parse(...)
    4. + *
    5. getDXFDocument()
    6. + *
    + * + *
    Simon Mieth + * + */ +public interface Parser extends Handler { + + + /** + * Parse the given file. + * @param file the file to parse + * @throws ParseException + */ + + public abstract void parse(String file) throws ParseException; + + /** + * Parse the given file with the specific encoding. + * @param file + * @param encoding + * @throws ParseException + */ + + + public abstract void parse(String file, String encoding) + throws ParseException; + + + + /** + * Parse the given inputstream + * @param input + * @param encoding + * @throws ParseException + */ + public abstract void parse(InputStream input, String encoding) + throws ParseException; + + /** + * Gets the parsed DXFDocument after parsing. + * @return the parsed @see org.kabeja.dxf.DXFDocument after parsing. + */ + + public abstract DXFDocument getDocument(); + + /** + * + * @param extension + * @return + */ + + public abstract boolean supportedExtension(String extension); + + /** + * Gets the name of the parser. + * @return + */ + public abstract String getName(); +} diff --git a/dxf/src/main/java/org/kabeja/parser/ParserBuilder.java b/dxf/src/main/java/org/kabeja/parser/ParserBuilder.java new file mode 100644 index 0000000..cd9ef5d --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/ParserBuilder.java @@ -0,0 +1,309 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; + +import org.kabeja.parser.entities.DXF3DFaceHandler; +import org.kabeja.parser.entities.DXF3DSolidHandler; +import org.kabeja.parser.entities.DXFArcHandler; +import org.kabeja.parser.entities.DXFBodyHandler; +import org.kabeja.parser.entities.DXFCircleHandler; +import org.kabeja.parser.entities.DXFDimensionHandler; +import org.kabeja.parser.entities.DXFEllipseHandler; +import org.kabeja.parser.entities.DXFHatchHandler; +import org.kabeja.parser.entities.DXFImageHandler; +import org.kabeja.parser.entities.DXFInsertHandler; +import org.kabeja.parser.entities.DXFLWPolylineHandler; +import org.kabeja.parser.entities.DXFLeaderHandler; +import org.kabeja.parser.entities.DXFLineHandler; +import org.kabeja.parser.entities.DXFMLineHandler; +import org.kabeja.parser.entities.DXFMTextHandler; +import org.kabeja.parser.entities.DXFPointHandler; +import org.kabeja.parser.entities.DXFPolylineHandler; +import org.kabeja.parser.entities.DXFRayHandler; +import org.kabeja.parser.entities.DXFRegionHandler; +import org.kabeja.parser.entities.DXFSolidHandler; +import org.kabeja.parser.entities.DXFSplineHandler; +import org.kabeja.parser.entities.DXFTextHandler; +import org.kabeja.parser.entities.DXFToleranceHandler; +import org.kabeja.parser.entities.DXFTraceHandler; +import org.kabeja.parser.entities.DXFViewportHandler; +import org.kabeja.parser.entities.DXFXLineHandler; +import org.kabeja.parser.objects.DXFDictionaryHandler; +import org.kabeja.parser.objects.DXFImageDefHandler; +import org.kabeja.parser.objects.DXFLayoutHandler; +import org.kabeja.parser.objects.DXFMLineStyleHandler; +import org.kabeja.parser.objects.DXFPlotsettingsHandler; +import org.kabeja.parser.table.DXFDimensionStyleTableHandler; +import org.kabeja.parser.table.DXFLayerTableHandler; +import org.kabeja.parser.table.DXFLineTypeTableHandler; +import org.kabeja.parser.table.DXFStyleTableHandler; +import org.kabeja.parser.table.DXFVPortTableHandler; +import org.kabeja.parser.table.DXFViewTableHandler; + + +/** + * @author + * + * <?xml version="1.0"encoding="utf-8" ?> + * + * <parser class="org.kabeja.parser.DXFParser" xmlns="http://kabeja.org/parser/1.0"> + * <handler class="org.kabeja.parser.DXFHeaderSectionHandler"/> + * <handler class="org.kabeja.parser.DXFTableSectionHandler"> + * <handlers> + * <handler class="org.kabeja.parser.table.DXFLayerTableHandler"/> + * </handlers> + * </handler> + * + * <!--+ + * | The block and the entities handler use the same sub handlers. + * | If you have create a parser for an entity add the parser in + * | both sections. + * +--> + * + * <handler class="org.kabeja.parser.DXFBlocksSectionHandler"> + * <handlers> + * <handler class="org.kabeja.parser.entities.DXFArcHandler"/> + * <handler class="org.kabeja.parser.entities.DXFCircleHandler"/> + * </handlers> + * </handler> + * + * + * <handler class="org.kabeja.parser.DXFEntitiesSectionHandler"> + * <handlers> + * <handler class="org.kabeja.parser.entities.DXFArcHandler"/> + * <handler class="org.kabeja.parser.entities.DXFCircleHandler"/> + * <handler class="org.kabeja.parser.entities.DXFEllipseHandler"/> + * </handlers> + * </handler> + * </parser> + * + * + * + * + * @author Simon Mieth + * + */ +public class SAXParserBuilder implements ContentHandler { + public static String ELEMENT_PARSER = "parser"; + public static String ELEMENT_HANDLER = "handler"; + public static String ELEMENT_HANDLERS = "handlers"; + public static String ATTRIBUTE_CLASS = "class"; + public static String ATTRIBUTE_EXTENSIONS = "extensions"; + public static String XMLNS_KABEJA_PARSER = "http://kabeja.org/parser/1.0"; + private Parser parser; + private Stack stack = new Stack(); + private HandlerManager currentHandlerManager; + private Handler handler; + + public SAXParserBuilder() { + } + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#characters(char[], int, int) + */ + public void characters(char[] ch, int start, int length) + throws SAXException { + // TODO Auto-generated method stub + } + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#endDocument() + */ + public void endDocument() throws SAXException { + // TODO Auto-generated method stub + } + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#endElement(java.lang.String, + * java.lang.String, java.lang.String) + */ + public void endElement(String namespaceURI, String localName, String qName) + throws SAXException { + if (localName.equals(ELEMENT_HANDLERS) && + namespaceURI.equals(XMLNS_KABEJA_PARSER)) { + currentHandlerManager = (HandlerManager) stack.pop(); + } + } + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#endPrefixMapping(java.lang.String) + */ + public void endPrefixMapping(String prefix) throws SAXException { + // TODO Auto-generated method stub + } + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#ignorableWhitespace(char[], int, int) + */ + public void ignorableWhitespace(char[] ch, int start, int length) + throws SAXException { + // TODO Auto-generated method stub + } + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String, + * java.lang.String) + */ + public void processingInstruction(String target, String data) + throws SAXException { + // TODO Auto-generated method stub + } + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#setDocumentLocator(org.xml.sax.Locator) + */ + public void setDocumentLocator(Locator locator) { + // TODO Auto-generated method stub + } + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#skippedEntity(java.lang.String) + */ + public void skippedEntity(String name) throws SAXException { + } + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#startDocument() + */ + public void startDocument() throws SAXException { + } + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#startElement(java.lang.String, + * java.lang.String, java.lang.String, org.xml.sax.Attributes) + */ + public void startElement(String namespaceURI, String localName, + String qName, Attributes atts) throws SAXException { + if (namespaceURI.equals(XMLNS_KABEJA_PARSER)) { + if (localName.equals(ELEMENT_HANDLER)) { + String clazz = atts.getValue(ATTRIBUTE_CLASS); + + try { + // load the class and add to the currentHandlerManager + Class c = this.getClass().getClassLoader().loadClass(clazz); + handler = (Handler) c.newInstance(); + currentHandlerManager.addHandler(handler); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } catch (InstantiationException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + } else if (localName.equals(ELEMENT_HANDLERS)) { + stack.add(currentHandlerManager); + currentHandlerManager = (HandlerManager) handler; + } else if (localName.equals(ELEMENT_PARSER)) { + String clazz = atts.getValue(ATTRIBUTE_CLASS); + + try { + // load the class and add to the currentHandlerManager + Class c = this.getClass().getClassLoader().loadClass(clazz); + this.parser = (Parser) c.newInstance(); + + if (this.parser instanceof HandlerManager) { + this.currentHandlerManager = (HandlerManager) this.parser; + } + + this.stack = new Stack(); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } catch (InstantiationException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + } + } + } + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#startPrefixMapping(java.lang.String, + * java.lang.String) + */ + public void startPrefixMapping(String prefix, String uri) + throws SAXException { + // TODO Auto-generated method stub + } + + public Parser getParser() { + return parser; + } + + /** + * + * @param in + * the InputStream + * @return The DXFParser build from the XML description + */ + public static Parser buildFromStream(InputStream in) { + SAXParserBuilder builder = new SAXParserBuilder(); + + try { + XMLReader parser = XMLReaderFactory.createXMLReader(); + parser.setFeature("http://apache.org/xml/features/xinclude", true); + parser.setContentHandler(builder); + parser.parse(new InputSource(in)); + } catch (SAXException e) { + System.err.println(e.getMessage()); + } catch (IOException ioe) { + } + + return builder.getParser(); + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/dxf/DXFHandler.java b/dxf/src/main/java/org/kabeja/parser/dxf/DXFHandler.java new file mode 100644 index 0000000..298c8aa --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/dxf/DXFHandler.java @@ -0,0 +1,25 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.dxf; + +import org.kabeja.parser.DXFValue; +import org.kabeja.parser.ParseException; + + +public interface DXFHandler { + public void parseGroup(int groupCode, DXFValue value) + throws ParseException; +} diff --git a/dxf/src/main/java/org/kabeja/parser/dxf/filter/AbstractDXFStreamFilter.java b/dxf/src/main/java/org/kabeja/parser/dxf/filter/AbstractDXFStreamFilter.java new file mode 100644 index 0000000..3f12f28 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/dxf/filter/AbstractDXFStreamFilter.java @@ -0,0 +1,34 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.dxf.filter; + +import java.util.Map; + +import org.kabeja.parser.dxf.DXFHandler; + + +public abstract class AbstractDXFStreamFilter implements DXFStreamFilter { + protected Map properties; + protected DXFHandler handler; + + public void setProperties(Map properties) { + this.properties = properties; + } + + public void setDXFHandler(DXFHandler handler) { + this.handler = handler; + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/dxf/filter/DXFStreamEntityFilter.java b/dxf/src/main/java/org/kabeja/parser/dxf/filter/DXFStreamEntityFilter.java new file mode 100644 index 0000000..da586c2 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/dxf/filter/DXFStreamEntityFilter.java @@ -0,0 +1,73 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.dxf.filter; + +import org.kabeja.parser.DXFValue; +import org.kabeja.parser.ParseException; + + +abstract class DXFStreamEntityFilter extends DXFStreamSectionFilter { + private static String SECTION_KEY = "ENTITIES"; + public static final int ENTITY_START = 0; + protected boolean entitySection = false; + protected boolean parseEntity = false; + protected boolean parseHeader = false; + + protected void parseSection(int groupCode, DXFValue value) + throws ParseException { + if (parseHeader) { + if (value.getValue().equals(SECTION_KEY)) { + this.entitySection = true; + this.parseHeader = false; + } + } else if (entitySection) { + if (groupCode == ENTITY_START) { + if (parseEntity) { + endEntity(); + } else { + parseEntity = true; + } + + startEntity(value.getValue()); + } + + parseEntity(groupCode, value); + + return; + } + + handler.parseGroup(groupCode, value); + } + + protected void sectionEnd(String Section) throws ParseException { + if (section.equals(SECTION_KEY)) { + this.entitySection = false; + } + } + + protected void sectionStart(String Section) throws ParseException { + if (section.equals(SECTION_KEY)) { + this.parseHeader = true; + } + } + + protected abstract void startEntity(String type) throws ParseException; + + protected abstract void endEntity() throws ParseException; + + protected abstract void parseEntity(int groupCode, DXFValue value) + throws ParseException; +} diff --git a/dxf/src/main/java/org/kabeja/parser/dxf/filter/DXFStreamFilter.java b/dxf/src/main/java/org/kabeja/parser/dxf/filter/DXFStreamFilter.java new file mode 100644 index 0000000..5ff505f --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/dxf/filter/DXFStreamFilter.java @@ -0,0 +1,41 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.dxf.filter; + +import java.util.Map; + +import org.kabeja.parser.dxf.DXFHandler; + + +/** + * + * @author Simon Mieth + * + */ +public abstract class AbstractEntityHandler implements DXFEntityHandler { + public final static int ELEMENT_REFERENCE = 5; + public final static int GROUPCODE_START_X = 10; + public final static int GROUPCODE_START_Y = 20; + public final static int GROUPCODE_START_Z = 30; + public final static int END_X = 11; + public final static int END_Y = 21; + public final static int END_Z = 31; + public final static int LAYER_NAME = 8; + public final static int TRANSPARENCY = 440; + public final static int COLOR_CODE = 62; + public final static int COLORNAME = 430; + public final static int COLOR_24BIT = 420; + public final static int COLOR_TRANSPARENCY = 440; + public final static int FLAGS = 70; + public final static int EXTRUSION_X = 210; + public final static int EXTRUSION_Y = 220; + public final static int EXTRUSION_Z = 230; + public final static int VISIBILITY = 60; + public final static int LINE_TYPE = 6; + public final static int LINE_TYPE_SCALE = 48; + public final static int LINE_WEIGHT = 370; + public final static int GROUPCODE_THICKNESS = 39; + public final static int GROUPCODE_STYLENAME = 3; + public final static int GROUPCODE_TEXT = 1; + public final static int GROUPCODE_ROTATION_ANGLE = 50; + public final static int GROUPCODE_MODELSPACE = 67; + + public final static int GROUPCODE_XDATA_APP_NAME = 1001; + public final static int GROUPCODE_XDATA_STRING = 1000; + public final static int GROUPCODE_XDATA_BINARY = 1004; + public final static int GROUPCODE_XDATA_REAL = 1040; + public final static int GROUPCODE_XDATA_INTEGER = 1070; + public final static int GROUPCODE_XDATA_LONG = 1071; + + protected DXFDocument doc; + private DXFExtendedData currentExtendedData; + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#setDXFDocument(org.dxf2svg.xml.DXFDocument) + */ + public void setDXFDocument(DXFDocument doc) { + this.doc = doc; + } + + protected void parseCommonProperty(int groupCode, DXFValue value, + DXFEntity entity) { + + if(groupCode == GROUPCODE_XDATA_APP_NAME && this.currentExtendedData == null){ + + this.currentExtendedData = new DXFExtendedData(value.getValue()); + entity.addExtendedData(this.currentExtendedData); + + }else{ + + if (this.currentExtendedData != null){ + + if(groupCode == GROUPCODE_XDATA_STRING){ + + this.currentExtendedData.setType(String.class); + this.currentExtendedData.setValue(value.getValue()); + + }else if(groupCode == GROUPCODE_XDATA_BINARY){ + + this.currentExtendedData.setType(String.class); + this.currentExtendedData.setValue(value.getValue()); + + }else if(groupCode == GROUPCODE_XDATA_REAL){ + this.currentExtendedData.setType(Double.class); + this.currentExtendedData.setValue(Double.parseDouble(value.getValue())); + + }else if(groupCode == GROUPCODE_XDATA_INTEGER){ + this.currentExtendedData.setType(Integer.class); + this.currentExtendedData.setValue(new Integer(value.getIntegerValue())); + + }else if(groupCode == GROUPCODE_XDATA_LONG){ + this.currentExtendedData.setType(Long.class); + this.currentExtendedData.setValue(new Long(value.getIntegerValue())); + + }else{ + this.currentExtendedData.setType(String.class); + this.currentExtendedData.setValue(value.getValue()); + } + + this.currentExtendedData = null; + + } + } + + switch (groupCode) { + case ELEMENT_REFERENCE: + entity.setID(value.getValue()); + + break; + + case LAYER_NAME: + entity.setLayerName(value.getValue()); + + break; + + case FLAGS: + entity.setFlags(value.getIntegerValue()); + + break; + + case VISIBILITY: + entity.setVisibile(!value.getBooleanValue()); + + break; + + case LINE_TYPE: + entity.setLineType(value.getValue()); + + break; + + case LINE_TYPE_SCALE: + entity.setLinetypeScaleFactor(value.getDoubleValue()); + + break; + + case COLOR_CODE: + entity.setColor(value.getIntegerValue()); + + break; + + case EXTRUSION_X: + entity.setExtrusionX(value.getDoubleValue()); + + break; + + case EXTRUSION_Y: + entity.setExtrusionY(value.getDoubleValue()); + + break; + + case EXTRUSION_Z: + entity.setExtrusionZ(value.getDoubleValue()); + + break; + + case COLOR_24BIT: + break; + + case COLOR_TRANSPARENCY: + break; + + case LINE_WEIGHT: + entity.setLineWeight(value.getIntegerValue()); + + break; + + case GROUPCODE_THICKNESS: + entity.setThickness(value.getDoubleValue()); + + break; + + case GROUPCODE_MODELSPACE: + entity.setModelSpace(value.getBooleanValue()); + + break; + } + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#getEntityName() + */ + public abstract String getDXFEntityName(); + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.Handler#releaseDXFDocument() + */ + public void releaseDXFDocument() { + this.doc = null; + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXF3DFaceHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXF3DFaceHandler.java new file mode 100644 index 0000000..febb614 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXF3DFaceHandler.java @@ -0,0 +1,39 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.entities; + +import org.kabeja.dxf.DXF3DFace; +import org.kabeja.dxf.DXFConstants; + + +/** + * @author Simon Mieth + * + */ +public class DXF3DFaceHandler extends DXFSolidHandler { + protected String ENTITY_NAME = "TRACE"; + + public String getDXFEntityName() { + return DXFConstants.ENTITY_TYPE_3DFACE; + } + + /* (non-Javadoc) + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#startDXFEntity() + */ + public void startDXFEntity() { + solid = new DXF3DFace(); + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXF3DSolidHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXF3DSolidHandler.java new file mode 100644 index 0000000..7c8ee8d --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXF3DSolidHandler.java @@ -0,0 +1,45 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.entities; + +import org.kabeja.dxf.DXF3DSolid; +import org.kabeja.dxf.DXFConstants; + + +/** + * @author Simon Mieth + * + */ +public class DXF3DSolidHandler extends DXFRegionHandler { + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.AbstractEntityHandler#getDXFEntityName() + */ + public String getDXFEntityName() { + // TODO Auto-generated method stub + return DXFConstants.ENTITY_TYPE_3DSOLID; + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#startDXFEntity() + */ + public void startDXFEntity() { + region = new DXF3DSolid(); + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXFArcHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXFArcHandler.java new file mode 100644 index 0000000..d05136b --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXFArcHandler.java @@ -0,0 +1,136 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.entities; + +import org.kabeja.dxf.DXFArc; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + * + */ +public class DXFArcHandler extends AbstractEntityHandler { + public static final String ENTITY_NAME = "ARC"; + public static final int RADIUS = 40; + public static final int START_ANGLE = 50; + public static final int END_ANGLE = 51; + public static final int COUNTERCLOCKWISE = 73; + private DXFArc arc; + + /** + * + */ + public DXFArcHandler() { + super(); + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.DXFEntityHandler#endDXFEntity() + */ + public void endDXFEntity() { + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.DXFEntityHandler#getDXFEntity() + */ + public DXFEntity getDXFEntity() { + return arc; + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.DXFEntityHandler#getDXFEntityName() + */ + public String getDXFEntityName() { + return ENTITY_NAME; + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.DXFEntityHandler#isFollowSequence() + */ + public boolean isFollowSequence() { + return false; + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.DXFEntityHandler#parseGroup(int, + * org.dxf2svg.parser.DXFValue) + */ + public void parseGroup(int groupCode, DXFValue value) { + + switch (groupCode) { + + case GROUPCODE_START_X: + arc.getCenterPoint().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Y: + arc.getCenterPoint().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Z: + arc.getCenterPoint().setZ(value.getDoubleValue()); + + + case RADIUS: + arc.setRadius(value.getDoubleValue()); + + break; + + case START_ANGLE: + arc.setStartAngle(value.getDoubleValue()); + + break; + + case END_ANGLE: + arc.setEndAngle(value.getDoubleValue()); + + break; + + case COUNTERCLOCKWISE: + arc.setCounterClockwise(value.getBooleanValue()); + + break; + + default: + super.parseCommonProperty(groupCode, value, arc); + + break; + } + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.DXFEntityHandler#startDXFEntity() + */ + public void startDXFEntity() { + arc = new DXFArc(); + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXFAttribHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXFAttribHandler.java new file mode 100644 index 0000000..94af64d --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXFAttribHandler.java @@ -0,0 +1,69 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.entities; + +import org.kabeja.dxf.DXFAttrib; +import org.kabeja.dxf.DXFConstants; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + * + */ +public class DXFAttribHandler extends DXFTextHandler { + public static final int ATTRIB_VERTICAL_ALIGN = 74; + public static final int ATTRIB_TEXT_LENGTH = 73; + + + public DXFAttribHandler() { + super(); + } + + /* (non-Javadoc) + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#parseGroup(int, de.miethxml.kabeja.parser.DXFValue) + */ + public void parseGroup(int groupCode, DXFValue value) { + + switch (groupCode) { + + + case ATTRIB_TEXT_LENGTH: + + //ignore not used by + break; + + case ATTRIB_VERTICAL_ALIGN: + text.setValign(value.getIntegerValue()); + + break; + + default: + super.parseGroup(groupCode, value); + } + } + + public void startDXFEntity() { + text = new DXFAttrib(); + } + + /* (non-Javadoc) + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#getDXFEntityName() + */ + public String getDXFEntityName() { + return DXFConstants.ENTITY_TYPE_ATTRIB; + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXFBodyHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXFBodyHandler.java new file mode 100644 index 0000000..cf308e4 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXFBodyHandler.java @@ -0,0 +1,45 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.entities; + +import org.kabeja.dxf.DXFBody; +import org.kabeja.dxf.DXFConstants; + + +/** + * @author Simon Mieth + * + */ +public class DXFBodyHandler extends DXFRegionHandler { + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.AbstractEntityHandler#getDXFEntityName() + */ + public String getDXFEntityName() { + // TODO Auto-generated method stub + return DXFConstants.ENTITY_TYPE_BODY; + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#startDXFEntity() + */ + public void startDXFEntity() { + region = new DXFBody(); + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXFCircleHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXFCircleHandler.java new file mode 100644 index 0000000..6573a41 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXFCircleHandler.java @@ -0,0 +1,123 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.entities; + +import org.kabeja.dxf.DXFCircle; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.dxf.helpers.Point; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + * + */ +public class DXFCircleHandler extends AbstractEntityHandler { + public final static String ENTITY_NAME = "CIRCLE"; + public final static int RADIUS = 40; + private DXFCircle circle; + + /** + * + */ + public DXFCircleHandler() { + super(); + + // TODO Auto-generated constructor stub + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#endParsing() + */ + public void endDXFEntity() { + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#getEntity() + */ + public DXFEntity getDXFEntity() { + return circle; + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#getEntityName() + */ + public String getDXFEntityName() { + // TODO Auto-generated method stub + return ENTITY_NAME; + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#parseGroup(int, + * org.dxf2svg.parser.DXFValue) + */ + public void parseGroup(int groupCode, DXFValue value) { + + switch (groupCode) { + + case GROUPCODE_START_X: + circle.getCenterPoint().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Y: + circle.getCenterPoint().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Z: + circle.getCenterPoint().setZ(value.getDoubleValue()); + + break; + + case RADIUS: + circle.setRadius(value.getDoubleValue()); + + break; + + default: + super.parseCommonProperty(groupCode, value, circle); + + break; + } + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#startParsing() + */ + public void startDXFEntity() { + circle = new DXFCircle(); + circle.setCenterPoint(new Point()); + circle.setDXFDocument(doc); + } + + /* (non-Javadoc) + * @see org.dxf2svg.parser.entities.EntityHandler#isFollowSequence() + */ + public boolean isFollowSequence() { + return false; + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXFDimensionHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXFDimensionHandler.java new file mode 100644 index 0000000..95c2f93 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXFDimensionHandler.java @@ -0,0 +1,273 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.entities; + +import org.kabeja.dxf.DXFDimension; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + * + */ +public class DXFDimensionHandler extends AbstractEntityHandler { + protected final static int GROUPCODE_REFERENCE_POINT_X = 10; + protected final static int GROUPCODE_REFERENCE_POINT_Y = 20; + protected final static int GROUPCODE_REFERENCE_POINT_Z = 30; + protected final static int GROUPCODE_TEXT_POINT_X = 11; + protected final static int GROUPCODE_TEXT_POINT_Y = 21; + protected final static int GROUPCODE_TEXT_POINT_Z = 31; + protected final static int GROUPCODE_INSERT_POINT_X = 12; + protected final static int GROUPCODE_INSERT_POINT_Y = 22; + protected final static int GROUPCODE_INSERT_POINT_Z = 32; + protected final static int GROUPCODE_REFERENCE_POINT3_X = 13; + protected final static int GROUPCODE_REFERENCE_POINT3_Y = 23; + protected final static int GROUPCODE_REFERENCE_POINT3_Z = 33; + protected final static int GROUPCODE_REFERENCE_POINT4_X = 14; + protected final static int GROUPCODE_REFERENCE_POINT4_Y = 24; + protected final static int GROUPCODE_REFERENCE_POINT4_Z = 34; + protected final static int GROUPCODE_REFERENCE_POINT5_X = 15; + protected final static int GROUPCODE_REFERENCE_POINT5_Y = 25; + protected final static int GROUPCODE_REFERENCE_POINT5_Z = 35; + protected final static int GROUPCODE_REFERENCE_POINT6_X = 16; + protected final static int GROUPCODE_REFERENCE_POINT6_Y = 26; + protected final static int GROUPCODE_REFERENCE_POINT6_Z = 36; + protected final static int GROUPCODE_DIMENSION_STYLE = 3; + protected final static int GROUPCODE_DIMENSION_BLOCK = 2; + protected final static int GROUPCODE_DIMENSION_AREA = 67; + protected final static int GROUPCODE_DIMENSION_TEXT = 1; + protected final static int GROUPCODE_LEADINGLINE_LENGTH = 40; + protected final static int GROUPCODE_DIMENSION_ROTATE = 50; + protected final static int GROUPCODE_HORIZONTAL_ALIGNMENT = 51; + protected final static int GROUPCODE_INCLINATION_HELPLINE = 52; + protected final static int GROUPCODE_TEXT_ROTATION = 53; + protected final static int GROUPCODE_DIMENSION_TYPE = 70; + protected String ENTITY_NAME = "DIMENSION"; + protected DXFDimension dimension; + + public void endDXFEntity() { + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#getDXFEntity() + */ + public DXFEntity getDXFEntity() { + return dimension; + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#getDXFEntityName() + */ + public String getDXFEntityName() { + // TODO Auto-generated method stub + return ENTITY_NAME; + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#isFollowSequence() + */ + public boolean isFollowSequence() { + // TODO Auto-generated method stub + return false; + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#parseGroup(int, + * de.miethxml.kabeja.parser.DXFValue) + */ + public void parseGroup(int groupCode, DXFValue value) { + + + switch (groupCode) { + + case GROUPCODE_TEXT_POINT_X: + dimension.getTextPoint().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_TEXT_POINT_Y: + dimension.getTextPoint().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_TEXT_POINT_Z: + dimension.getTextPoint().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_INSERT_POINT_X: + dimension.getInsertPoint().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_INSERT_POINT_Y: + dimension.getInsertPoint().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_INSERT_POINT_Z: + dimension.getInsertPoint().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_REFERENCE_POINT_X: + dimension.getReferencePoint().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_REFERENCE_POINT_Y: + dimension.getReferencePoint().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_REFERENCE_POINT_Z: + dimension.getReferencePoint().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_REFERENCE_POINT3_X: + dimension.getReferencePoint3().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_REFERENCE_POINT3_Y: + dimension.getReferencePoint3().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_REFERENCE_POINT3_Z: + dimension.getReferencePoint3().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_REFERENCE_POINT4_X: + dimension.getReferencePoint4().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_REFERENCE_POINT4_Y: + dimension.getReferencePoint4().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_REFERENCE_POINT4_Z: + dimension.getReferencePoint4().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_REFERENCE_POINT5_X: + dimension.getReferencePoint5().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_REFERENCE_POINT5_Y: + dimension.getReferencePoint5().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_REFERENCE_POINT5_Z: + dimension.getReferencePoint5().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_REFERENCE_POINT6_X: + dimension.getReferencePoint6().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_REFERENCE_POINT6_Y: + dimension.getReferencePoint6().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_REFERENCE_POINT6_Z: + dimension.getReferencePoint6().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_DIMENSION_BLOCK: + dimension.setDimensionBlock(value.getValue()); + + break; + + case GROUPCODE_DIMENSION_STYLE: + dimension.setDimensionStyleID(value.getValue()); + + break; + + case GROUPCODE_DIMENSION_TYPE: + dimension.setDimensionType(value.getIntegerValue()); + + break; + + case GROUPCODE_DIMENSION_TEXT: + dimension.setDimensionText(value.getValue()); + + break; + + case GROUPCODE_HORIZONTAL_ALIGNMENT: + dimension.setHorizontalAlign(value.getDoubleValue()); + + break; + + case GROUPCODE_INCLINATION_HELPLINE: + dimension.setInclinationHelpLine(value.getDoubleValue()); + + break; + + case GROUPCODE_LEADINGLINE_LENGTH: + dimension.setLeadingLineLength(value.getDoubleValue()); + + break; + + case GROUPCODE_TEXT_ROTATION: + dimension.setTextRotation(value.getDoubleValue()); + + break; + + case GROUPCODE_DIMENSION_ROTATE: + dimension.setDimensionRotation(value.getDoubleValue()); + + break; + + case GROUPCODE_DIMENSION_AREA: + dimension.setDimensionArea(value.getIntegerValue()); + + break; + + default: + super.parseCommonProperty(groupCode, value, dimension); + } + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#startDXFEntity() + */ + public void startDXFEntity() { + dimension = new DXFDimension(); + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXFEllipseHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXFEllipseHandler.java new file mode 100644 index 0000000..e6a2986 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXFEllipseHandler.java @@ -0,0 +1,118 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.entities; + +import org.kabeja.dxf.DXFEllipse; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + * + * + * + */ +public class DXFEllipseHandler extends AbstractEntityHandler { + public final static String ENTITY_NAME = "ELLIPSE"; + public final static int RATIO = 40; + public final static int START_PARAMETER = 41; + public final static int END_PARAMTER = 42; + public static final int COUNTERCLOCKWISE = 73; + private DXFEllipse ellipse; + + public void endDXFEntity() { + } + + public DXFEntity getDXFEntity() { + return ellipse; + } + + public String getDXFEntityName() { + return ENTITY_NAME; + } + + public boolean isFollowSequence() { + return false; + } + + public void parseGroup(int groupCode, DXFValue value) { + + switch (groupCode) { + + case GROUPCODE_START_X: + ellipse.getCenterPoint().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Y: + ellipse.getCenterPoint().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Z: + ellipse.getCenterPoint().setZ(value.getDoubleValue()); + + break; + + case END_X: + ellipse.getMajorAxisDirection().setX(value.getDoubleValue()); + + break; + + case END_Y: + ellipse.getMajorAxisDirection().setY(value.getDoubleValue()); + + break; + + case END_Z: + ellipse.getMajorAxisDirection().setZ(value.getDoubleValue()); + + break; + + case RATIO: + ellipse.setRatio(value.getDoubleValue()); + + break; + + case START_PARAMETER: + ellipse.setStartParameter(value.getDoubleValue()); + + break; + + case END_PARAMTER: + ellipse.setEndParameter(value.getDoubleValue()); + + break; + + case COUNTERCLOCKWISE: + ellipse.setCounterClockwise(value.getBooleanValue()); + + break; + + default: + super.parseCommonProperty(groupCode, value, ellipse); + + break; + } + } + + public void startDXFEntity() { + //System.out.println("0\nELLIPSE"); + ellipse = new DXFEllipse(); + ellipse.setDXFDocument(doc); + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXFEntityHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXFEntityHandler.java new file mode 100644 index 0000000..1bbfeda --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXFEntityHandler.java @@ -0,0 +1,78 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.entities; + +import org.kabeja.dxf.DXFDocument; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.parser.DXFValue; +import org.kabeja.parser.Handler; + + +/** + * + * This interface descripe an Entity jandler, which should + * handle (parse) an DXF entity. + * + *

    Lifecycle

    + *
      + *
    1. setDXFDocument
    2. + *
    3. startDXFEntity
    4. + *
    5. parseGroup (multiple)
    6. + *
    7. isFollowSequence (need for polylines, where multiple vertices follow)
    8. + *
    9. endDXFEntity
    10. + *
    11. getDXFEntity
    12. + * + * @author Simon Mieth + * + * + * @author Simon Mieth + */ +public interface DXFEntityHandler extends Handler { + /** + * + * @return the DXFEntity name (LINE,POLYLINE,TEXT,...) + */ + public abstract String getDXFEntityName(); + + public void setDXFDocument(DXFDocument doc); + + /** + * Will called if the entity block starts. + * + */ + public abstract void startDXFEntity(); + + public abstract void parseGroup(int groupCode, DXFValue value); + + /** + * Called after endDXFEntity. + * @return the parsed Entity + */ + public abstract DXFEntity getDXFEntity(); + + /** + * Will called if the entity block ends. + * + */ + public abstract void endDXFEntity(); + + /** + * + * @return true if the this DXFEntityHandler have to parse the following entities (like POLYLINE), + * otherwise false (like TEXT,LINE). + */ + public abstract boolean isFollowSequence(); +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXFHatchHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXFHatchHandler.java new file mode 100644 index 0000000..df97acf --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXFHatchHandler.java @@ -0,0 +1,415 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ +package org.kabeja.parser.entities; + +import java.util.Hashtable; +import java.util.Iterator; + +import org.kabeja.dxf.DXFConstants; +import org.kabeja.dxf.DXFDocument; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.dxf.DXFHatch; +import org.kabeja.dxf.DXFHatchPattern; +import org.kabeja.dxf.DXFPolyline; +import org.kabeja.dxf.DXFVertex; +import org.kabeja.dxf.helpers.HatchBoundaryLoop; +import org.kabeja.dxf.helpers.HatchLineFamily; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + * + */ +public class DXFHatchHandler extends AbstractEntityHandler { + public static final String END_SEQUENCE = "SEQEND"; + public static final int END_SEQUENCE_CODE = -2; + public static final int GROUPCODE_ASSOSIATIVITY_FLAG = 71; + public static final int GROUPCODE_BOUNDARY_ANNOTATION = 73; + public static final int GROUPCODE_BOUNDARY_EDGE_COUNT = 93; + public static final int GROUPCODE_BOUNDARY_EDGE_TYPE = 72; + public static final int GROUPCODE_BOUNDARY_LOOP_COUNT = 91; + public static final int GROUPCODE_BOUNDAYY_LOOP_TYPE = 92; + public static final int GROUPCODE_DEFINITION_LINE_COUNT = 78; + public static final int GROUPCODE_DEGENERTE_BOUNDARY_PATH_COUNT = 99; + public static final int GROUPCODE_HATCH_DOUBLE_FLAG = 77; + public static final int GROUPCODE_HATCH_STYLE = 75; + public static final int GROUPCODE_NAME = 2; + public static final int GROUPCODE_OFFSET_VECTOR = 11; + public static final int GROUPCODE_PATTERN_ANGLE = 52; + public static final int GROUPCODE_PATTERN_BASE_X = 43; + public static final int GROUPCODE_PATTERN_BASE_Y = 44; + public static final int GROUPCODE_PATTERN_FILL_COLOR = 63; + public static final int GROUPCODE_PATTERN_LINE_ANGLE = 53; + public static final int GROUPCODE_PATTERN_LINE_COUNT = 79; + public static final int GROUPCODE_PATTERN_LINE_TYPE_DATA = 49; + public static final int GROUPCODE_PATTERN_OFFSET_X = 45; + public static final int GROUPCODE_PATTERN_OFFSET_Y = 46; + public static final int GROUPCODE_PATTERN_SCALE = 41; + public static final int GROUPCODE_PATTERN_TYPE = 76; + public static final int GROUPCODE_PIXEL_SIZE = 47; + public static final int GROUPCODE_SEED_POINTS_COUNT = 98; + public static final int GROUPCODE_SOLID_FILL_FLAG = 70; + protected DXFEntityHandler boundaryHandler; + protected Hashtable boundaryHandlers = new Hashtable(); + protected int count; + //private boolean follow = false; + private DXFHatch hatch; + protected HatchLineFamily linePattern = new HatchLineFamily(); + protected HatchBoundaryLoop loop; + protected double[] parameters = new double[0]; + private boolean parseBoundary = false; + protected DXFHatchPattern pattern; + protected DXFPolyline polyline; + private boolean polylineBoundary = false; + protected DXFVertex vertex; + protected int lastGroupCode; + + public DXFHatchHandler() { + init(); + } + + protected void endBoundaryElement() { + if (boundaryHandler != null) { + // get the last parsed entity + this.boundaryHandler.endDXFEntity(); + this.loop.addBoundaryEdge(boundaryHandler.getDXFEntity()); + this.boundaryHandler = null; + } + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#endDXFEntity() + */ + public void endDXFEntity() { + // this.linePattern.setPattern(this.parameters); + if (this.pattern != null) { + this.hatch.setDXFHatchPatternID(this.pattern.getID()); + } + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#getDXFEntity() + */ + public DXFEntity getDXFEntity() { + return hatch; + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.DXFEntityHandler#getDXFEntityName() + */ + public String getDXFEntityName() { + return DXFConstants.ENTITY_TYPE_HATCH; + } + + protected void init() { + DXFEntityHandler handler = new DXFSplineHandler(); + boundaryHandlers.put(handler.getDXFEntityName(), handler); + + handler = new DXFLineHandler(); + boundaryHandlers.put(handler.getDXFEntityName(), handler); + + handler = new DXFArcHandler(); + boundaryHandlers.put(handler.getDXFEntityName(), handler); + + handler = new DXFEllipseHandler(); + boundaryHandlers.put(handler.getDXFEntityName(), handler); + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#isFollowSequence() + */ + public boolean isFollowSequence() { + return false; + } + + protected void parseBoundary(int groupCode, DXFValue value) { + if (this.polylineBoundary) { + parsePolylineBoundary(groupCode, value); + } else { + // delegate to the entityhandler + this.boundaryHandler.parseGroup(groupCode, value); + } + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#parseGroup(int, + * de.miethxml.kabeja.parser.DXFValue) + */ + public void parseGroup(int groupCode, DXFValue value) { + + switch (groupCode) { + + case GROUPCODE_BOUNDARY_LOOP_COUNT: + break; + + case GROUPCODE_BOUNDARY_EDGE_COUNT: + break; + + case GROUPCODE_BOUNDARY_EDGE_TYPE: + + if (this.lastGroupCode == GROUPCODE_BOUNDAYY_LOOP_TYPE) { + this.polylineBoundary = true; + this.polyline = new DXFPolyline(); + this.polyline.setDXFDocument(this.doc); + this.loop.addBoundaryEdge(this.polyline); + + break; + } + + if (!this.polylineBoundary) { + this.endBoundaryElement(); + + switch (value.getIntegerValue()) { + case 1: + boundaryHandler = (DXFEntityHandler) boundaryHandlers.get(DXFConstants.ENTITY_TYPE_LINE); + boundaryHandler.startDXFEntity(); + + break; + + case 2: + boundaryHandler = (DXFEntityHandler) boundaryHandlers.get(DXFConstants.ENTITY_TYPE_ARC); + boundaryHandler.startDXFEntity(); + + break; + + case 3: + boundaryHandler = (DXFEntityHandler) boundaryHandlers.get(DXFConstants.ENTITY_TYPE_ELLIPSE); + boundaryHandler.startDXFEntity(); + + break; + + case 4: + boundaryHandler = (DXFEntityHandler) boundaryHandlers.get(DXFConstants.ENTITY_TYPE_SPLINE); + boundaryHandler.startDXFEntity(); + + break; + } + } + + break; + + case GROUPCODE_BOUNDAYY_LOOP_TYPE: + + // finish up last parsing + if (!this.polylineBoundary) { + this.endBoundaryElement(); + } + + // a new loop starts + this.loop = new HatchBoundaryLoop(); + this.hatch.addBoundaryLoop(loop); + + // set the flags + this.polylineBoundary = false; + this.parseBoundary = true; + + if ((value.getIntegerValue() & 2) == 2) { + } + + if ((value.getIntegerValue() & 1) == 1) { + // from external hatch + } + + if ((value.getIntegerValue() & 4) == 4) { + // from derivated hatch + } + + if ((value.getIntegerValue() & 16) == 16) { + // different from the DXF-Specs + // if bit is set the loop is not + this.loop.setOutermost(false); + } + + break; + + case GROUPCODE_NAME: + this.hatch.setName(value.getValue()); + + break; + + case GROUPCODE_START_X: + + if (parseBoundary) { + parseBoundary(groupCode, value); + } else { + this.hatch.getElevationPoint().setX(value.getDoubleValue()); + } + + break; + + case GROUPCODE_START_Y: + + if (parseBoundary) { + parseBoundary(groupCode, value); + } else { + this.hatch.getElevationPoint().setY(value.getDoubleValue()); + } + + break; + + case GROUPCODE_START_Z: + + if (parseBoundary) { + parseBoundary(groupCode, value); + } else { + this.hatch.getElevationPoint().setZ(value.getDoubleValue()); + } + + break; + + case GROUPCODE_HATCH_STYLE: + this.parseBoundary = false; + this.endBoundaryElement(); + + // This should be the end of a boundary entity + break; + + case GROUPCODE_PATTERN_LINE_ANGLE: + // set the previus parsed line data + this.parseBoundary = false; + this.linePattern = new HatchLineFamily(); + this.pattern.addLineFamily(this.linePattern); + + this.linePattern.setRotationAngle(value.getDoubleValue()); + this.count = 0; + + break; + + case GROUPCODE_PATTERN_BASE_X: + this.linePattern.setBaseX(value.getDoubleValue()); + + break; + + case GROUPCODE_PATTERN_BASE_Y: + this.linePattern.setBaseY(value.getDoubleValue()); + + break; + + case GROUPCODE_PATTERN_OFFSET_X: + this.linePattern.setOffsetX(value.getDoubleValue()); + + break; + + case GROUPCODE_PATTERN_OFFSET_Y: + this.linePattern.setOffsetY(value.getDoubleValue()); + + break; + + case GROUPCODE_PATTERN_LINE_COUNT: + this.parameters = new double[value.getIntegerValue()]; + this.linePattern.setPattern(this.parameters); + + break; + + case GROUPCODE_PATTERN_LINE_TYPE_DATA: + this.parameters[this.count] = value.getDoubleValue(); + this.count++; + + break; + + case GROUPCODE_PATTERN_SCALE: + this.hatch.setPatternScale(value.getDoubleValue()); + + break; + + default: + + if (parseBoundary) { + parseBoundary(groupCode, value); + } else { + super.parseCommonProperty(groupCode, value, this.hatch); + } + } + + this.lastGroupCode = groupCode; + } + + protected void parsePolylineBoundary(int groupCode, DXFValue value) { + switch (groupCode) { + case GROUPCODE_START_X: + this.vertex = new DXFVertex(); + this.polyline.addVertex(vertex); + this.vertex.setX(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Y: + this.vertex.setY(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Z: + this.vertex.setZ(value.getDoubleValue()); + + break; + + case DXFPolylineHandler.VERTEX_BULGE: + this.vertex.setBulge(value.getDoubleValue()); + + break; + + case 73: + this.polyline.setFlags(1); + + break; + } + } + + /* + * (non-Javadoc) + * + * @see org.kabeja.parser.Handler#setDXFDocument(org.kabeja.dxf.DXFDocument) + */ + public void setDXFDocument(DXFDocument doc) { + super.setDXFDocument(doc); + + Iterator i = this.boundaryHandlers.values().iterator(); + + while (i.hasNext()) { + DXFEntityHandler handler = (DXFEntityHandler) i.next(); + handler.setDXFDocument(doc); + } + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#startDXFEntity() + */ + public void startDXFEntity() { + this.hatch = new DXFHatch(); + this.pattern = new DXFHatchPattern(); + + this.pattern.setHatch(this.hatch); + this.doc.addDXFHatchPattern(pattern); + + // setup the flags + this.parseBoundary = false; + this.polylineBoundary = false; + boundaryHandler = null; + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXFImageHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXFImageHandler.java new file mode 100644 index 0000000..c68e9e2 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXFImageHandler.java @@ -0,0 +1,214 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.entities; + +import org.kabeja.dxf.DXFConstants; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.dxf.DXFImage; +import org.kabeja.dxf.helpers.Point; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + * + */ +public class DXFImageHandler extends AbstractEntityHandler { + public final static int GROUPCODE_IMAGEDEF_HARDREFERENCE = 340; + public final static int GROUPCODE_VECTOR_U_X = 11; + public final static int GROUPCODE_VECTOR_U_Y = 21; + public final static int GROUPCODE_VECTOR_U_Z = 31; + public final static int GROUPCODE_VECTOR_V_X = 12; + public final static int GROUPCODE_VECTOR_V_Y = 22; + public final static int GROUPCODE_VECTOR_V_Z = 32; + public final static int GROUPCODE_IAMGESIZE_U = 13; + public final static int GROUPCODE_IAMGESIZE_V = 23; + public final static int GROUPCODE_DISPLAY_PROPERTY = 70; + public final static int GROUPCODE_BRIGHTNESS = 281; + public final static int GROUPCODE_CONTRAST = 282; + public final static int GROUPCODE_FADE = 283; + public final static int GROUPCODE_NUMBER_CLIP_BOUNDARY = 91; + public final static int GROUPCODE_CLIP_BOUNDARY_X = 14; + public final static int GROUPCODE_CLIP_BOUNDARY_Y = 24; + public final static int GROUPCODE_CLIP_BOUNDARY_TYPE = 71; + public final static int GROUPCODE_CLIPPING_STATE = 280; + protected DXFImage image; + protected Point clippingPoint; + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#getDXFEntityName() + */ + public String getDXFEntityName() { + return DXFConstants.ENTITY_TYPE_IMAGE; + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#endDXFEntity() + */ + public void endDXFEntity() { + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#getDXFEntity() + */ + public DXFEntity getDXFEntity() { + // TODO Auto-generated method stub + return image; + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#isFollowSequence() + */ + public boolean isFollowSequence() { + return false; + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#parseGroup(int, + * de.miethxml.kabeja.parser.DXFValue) + */ + public void parseGroup(int groupCode, DXFValue value) { + + switch (groupCode) { + + + case GROUPCODE_START_X: + image.getInsertPoint().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Y: + image.getInsertPoint().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Z: + image.getInsertPoint().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_IMAGEDEF_HARDREFERENCE: + image.setImageDefObjectID(value.getValue()); + + break; + + case GROUPCODE_VECTOR_U_X: + image.getVectorU().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_VECTOR_U_Y: + image.getVectorU().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_VECTOR_U_Z: + image.getVectorU().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_VECTOR_V_X: + image.getVectorV().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_VECTOR_V_Y: + image.getVectorV().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_VECTOR_V_Z: + image.getVectorV().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_IAMGESIZE_U: + image.setImageSizeAlongU(value.getDoubleValue()); + + break; + + case GROUPCODE_IAMGESIZE_V: + image.setImageSizeAlongV(value.getDoubleValue()); + + break; + + case GROUPCODE_CLIPPING_STATE: + image.setClipping(value.getBooleanValue()); + + break; + + case GROUPCODE_CLIP_BOUNDARY_X: + clippingPoint = new Point(); + clippingPoint.setX(value.getDoubleValue()); + image.addClippingPoint(clippingPoint); + + break; + + case GROUPCODE_CLIP_BOUNDARY_Y: + clippingPoint.setY(value.getDoubleValue()); + + break; + + case GROUPCODE_BRIGHTNESS: + image.setBrightness(value.getDoubleValue()); + + break; + + case GROUPCODE_CONTRAST: + image.setContrast(value.getDoubleValue()); + + break; + + case GROUPCODE_FADE: + image.setFade(value.getDoubleValue()); + + break; + + case GROUPCODE_CLIP_BOUNDARY_TYPE: + + if (value.getIntegerValue() == 1) { + image.setRectangularClipping(true); + } else if (value.getIntegerValue() == 2) { + image.setPolygonalClipping(true); + } + + break; + + default: + super.parseCommonProperty(groupCode, value, image); + } + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#startDXFEntity() + */ + public void startDXFEntity() { + image = new DXFImage(); + image.setDXFDocument(doc); + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXFInsertHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXFInsertHandler.java new file mode 100644 index 0000000..7138778 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXFInsertHandler.java @@ -0,0 +1,166 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.entities; + +import org.kabeja.dxf.DXFConstants; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.dxf.DXFInsert; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + * + */ +public class DXFInsertHandler extends AbstractEntityHandler { + public static final int SCALE_X = 41; + public static final int SCALE_Y = 42; + public static final int SCALE_Z = 43; + public static final int ROTATE = 50; + public static final int COLUMN_COUNT = 70; + public static final int ROW_COUNT = 71; + public static final int COLUMN_SPACING = 44; + public static final int ROW_SPACING = 45; + public static final int BLOCK_NAME = 2; + private DXFInsert insert; + + /** + * + */ + public DXFInsertHandler() { + super(); + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.DXFEntityHandler#endDXFEntity() + */ + public void endDXFEntity() { + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.DXFEntityHandler#getDXFEntity() + */ + public DXFEntity getDXFEntity() { + return insert; + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.DXFEntityHandler#getDXFEntityName() + */ + public String getDXFEntityName() { + return DXFConstants.ENTITY_TYPE_INSERT; + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.DXFEntityHandler#isFollowSequence() + */ + public boolean isFollowSequence() { + return false; + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.DXFEntityHandler#parseGroup(int, + * org.dxf2svg.parser.DXFValue) + */ + public void parseGroup(int groupCode, DXFValue value) { + + switch (groupCode) { + + + case GROUPCODE_START_X: + insert.getPoint().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Y: + insert.getPoint().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Z: + insert.getPoint().setZ(value.getDoubleValue()); + + break; + + case SCALE_X: + insert.setScaleX(value.getDoubleValue()); + + break; + + case SCALE_Y: + insert.setScaleY(value.getDoubleValue()); + + break; + + case SCALE_Z: + insert.setScaleZ(value.getDoubleValue()); + + break; + + case ROTATE: + insert.setRotate(value.getDoubleValue()); + + break; + + case COLUMN_COUNT: + insert.setColumns(value.getIntegerValue()); + + break; + + case ROW_COUNT: + insert.setRows(value.getIntegerValue()); + + break; + + case COLUMN_SPACING: + insert.setColumnSpacing(value.getDoubleValue()); + + break; + + case ROW_SPACING: + insert.setRowSpacing(value.getDoubleValue()); + + break; + + case BLOCK_NAME: + insert.setBlockID(value.getValue()); + + break; + + default: + super.parseCommonProperty(groupCode, value, insert); + } + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.DXFEntityHandler#startDXFEntity() + */ + public void startDXFEntity() { + insert = new DXFInsert(); + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXFLWPolylineHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXFLWPolylineHandler.java new file mode 100644 index 0000000..a01afc2 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXFLWPolylineHandler.java @@ -0,0 +1,149 @@ +/* + * Created on 13.04.2005 + * + */ +package org.kabeja.parser.entities; + +import org.kabeja.dxf.DXFEntity; +import org.kabeja.dxf.DXFLWPolyline; +import org.kabeja.dxf.DXFVertex; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + * + */ +public class DXFLWPolylineHandler extends AbstractEntityHandler { + public static final String ENTITY_NAME = "LWPOLYLINE"; + public static final int VERTEX_BULGE = 42; + public static final int START_WIDTH = 40; + public static final int END_WIDTH = 41; + public static final int CONSTANT_WIDTH = 43; + public static final int ELEVATION = 38; + public static final int THICKNESS = 39; + private DXFVertex vertex; + private DXFLWPolyline lwpolyline; + + /** + * + */ + public DXFLWPolylineHandler() { + super(); + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#endParsing() + */ + public void endDXFEntity() { + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#getEntity() + */ + public DXFEntity getDXFEntity() { + return lwpolyline; + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#getEntityName() + */ + public String getDXFEntityName() { + return ENTITY_NAME; + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#isFollowSequence() + */ + public boolean isFollowSequence() { + return false; + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#parseGroup(int, + * org.dxf2svg.parser.DXFValue) + */ + public void parseGroup(int groupCode, DXFValue value) { + // the different between polyline and lwpolyline is, + // that the vertices comes not as sequence here. + + switch (groupCode) { + + + case GROUPCODE_START_X: + // every new vertex starts with 10 + createVertex(); + vertex.setX(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Y: + vertex.setY(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Z: + vertex.setZ(value.getDoubleValue()); + + break; + + case VERTEX_BULGE: + vertex.setBulge(value.getDoubleValue()); + + break; + + case START_WIDTH: + vertex.setStartWidth(value.getDoubleValue()); + + break; + + case END_WIDTH: + vertex.setEndWidth(value.getDoubleValue()); + + break; + + case CONSTANT_WIDTH: + lwpolyline.setConstantWidth(value.getDoubleValue()); + + break; + + case ELEVATION: + lwpolyline.setElevation(value.getDoubleValue()); + + break; + + case THICKNESS: + lwpolyline.setThickness(value.getDoubleValue()); + + break; + + default: + super.parseCommonProperty(groupCode, value, lwpolyline); + } + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#startParsing() + */ + public void startDXFEntity() { + lwpolyline = new DXFLWPolyline(); + } + + private void createVertex() { + vertex = new DXFVertex(); + vertex.setDXFDocument(doc); + lwpolyline.addVertex(vertex); + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXFLeaderHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXFLeaderHandler.java new file mode 100644 index 0000000..f48e980 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXFLeaderHandler.java @@ -0,0 +1,208 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.entities; + +import org.kabeja.dxf.DXFConstants; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.dxf.DXFLeader; +import org.kabeja.dxf.helpers.Point; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + * + */ +public class DXFLeaderHandler extends AbstractEntityHandler { + public static final int GROUPCODE_ARROW_HEAD_FLAG = 71; + public static final int GROUPCODE_LEADER_PATH_TYPE = 72; + public static final int GROUPCODE_LEADER_CREATION_FLAG = 73; + public static final int GROUPCODE_HOOKLINE_DIRECTION_FLAG = 74; + public static final int GROUPCODE_HOOKLINE_FLAG = 75; + public static final int GROUPCODE_TEXT_HEIGHT = 40; + public static final int GROUPCODE_TEXT_WIDTH = 41; + public static final int GROUPCODE_COLOR_LEADER = 77; + public static final int GROUPCODE_TEXT_ENTITY_REFERENCE = 340; + public static final int GROUPCODE_HORIZONTAL_DIRECTION_X = 211; + public static final int GROUPCODE_HORIZONTAL_DIRECTION_Y = 221; + public static final int GROUPCODE_HORIZONTAL_DIRECTION_Z = 231; + public static final int GROUPCODE_OFFSET_LAST_VERTEX_INSERTPOINT_X = 212; + public static final int GROUPCODE_OFFSET_LAST_VERTEX_INSERTPOINT_Y = 222; + public static final int GROUPCODE_OFFSET_LAST_VERTEX_INSERTPOINT_Z = 232; + public static final int GROUPCODE_OFFSET_LAST_VERTEX_PLACEMENT_POINT_X = 213; + public static final int GROUPCODE_OFFSET_LAST_VERTEX_PLACEMENT_POINT_Y = 223; + public static final int GROUPCODE_OFFSET_LAST_VERTEX_PLACEMENT_POINT_Z = 233; + protected DXFLeader leader; + protected Point vertex; + + /* (non-Javadoc) + * @see org.kabeja.parser.entities.AbstractEntityHandler#getDXFEntityName() + */ + public String getDXFEntityName() { + return DXFConstants.ENTITY_TYPE_LEADER; + } + + /* (non-Javadoc) + * @see org.kabeja.parser.entities.DXFEntityHandler#startDXFEntity() + */ + public void startDXFEntity() { + leader = new DXFLeader(); + } + + /* (non-Javadoc) + * @see org.kabeja.parser.entities.DXFEntityHandler#parseGroup(int, org.kabeja.parser.DXFValue) + */ + public void parseGroup(int groupCode, DXFValue value) { + + switch (groupCode) { + + case GROUPCODE_START_X: + vertex = new Point(); + leader.addCoordinate(vertex); + vertex.setX(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Y: + vertex.setY(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Z: + vertex.setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_STYLENAME: + leader.setStyleNameID(value.getValue()); + + break; + + case GROUPCODE_ARROW_HEAD_FLAG: + leader.setArrowEnabled(value.getBooleanValue()); + + break; + + case GROUPCODE_LEADER_PATH_TYPE: + leader.setPathType(value.getIntegerValue()); + + break; + + case GROUPCODE_LEADER_CREATION_FLAG: + leader.setCreationType(value.getIntegerValue()); + + break; + + case GROUPCODE_HOOKLINE_DIRECTION_FLAG: + leader.setHooklineDirecton(value.getIntegerValue()); + + break; + + case GROUPCODE_HOOKLINE_FLAG: + leader.setHookline(value.getBooleanValue()); + + break; + + case GROUPCODE_TEXT_HEIGHT: + leader.setTextHeight(value.getDoubleValue()); + + break; + + case GROUPCODE_TEXT_WIDTH: + leader.setTextWidth(value.getDoubleValue()); + + break; + + case GROUPCODE_HORIZONTAL_DIRECTION_X: + leader.getHorizontalDirection().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_HORIZONTAL_DIRECTION_Y: + leader.getHorizontalDirection().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_HORIZONTAL_DIRECTION_Z: + leader.getHorizontalDirection().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_OFFSET_LAST_VERTEX_INSERTPOINT_X: + leader.getLastOffsetInsertion().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_OFFSET_LAST_VERTEX_INSERTPOINT_Y: + leader.getLastOffsetInsertion().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_OFFSET_LAST_VERTEX_INSERTPOINT_Z: + leader.getLastOffsetInsertion().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_OFFSET_LAST_VERTEX_PLACEMENT_POINT_X: + leader.getLastOffsetText().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_OFFSET_LAST_VERTEX_PLACEMENT_POINT_Y: + leader.getLastOffsetText().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_OFFSET_LAST_VERTEX_PLACEMENT_POINT_Z: + leader.getLastOffsetText().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_TEXT_ENTITY_REFERENCE: + leader.setTextID(value.getValue()); + + break; + + case GROUPCODE_COLOR_LEADER: + leader.setColor(value.getIntegerValue()); + + break; + + default: + super.parseCommonProperty(groupCode, value, leader); + } + } + + /* (non-Javadoc) + * @see org.kabeja.parser.entities.DXFEntityHandler#getDXFEntity() + */ + public DXFEntity getDXFEntity() { + return leader; + } + + /* (non-Javadoc) + * @see org.kabeja.parser.entities.DXFEntityHandler#endDXFEntity() + */ + public void endDXFEntity() { + } + + /* (non-Javadoc) + * @see org.kabeja.parser.entities.DXFEntityHandler#isFollowSequence() + */ + public boolean isFollowSequence() { + return false; + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXFLineHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXFLineHandler.java new file mode 100644 index 0000000..f035599 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXFLineHandler.java @@ -0,0 +1,134 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.entities; + +import org.kabeja.dxf.DXFDocument; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.dxf.DXFLine; +import org.kabeja.dxf.helpers.Point; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + * + */ +public class DXFLineHandler extends AbstractEntityHandler { + public final static String ENTITY_NAME = "LINE"; + private DXFLine line; + //private DXFDocument doc; + //private String layerID = ""; + + public DXFLineHandler() { + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#getEntityName() + */ + public String getDXFEntityName() { + return ENTITY_NAME; + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#parseGroup(int, + * java.lang.String) + */ + public void parseGroup(int groupCode, DXFValue value) { + + switch (groupCode) { + + case GROUPCODE_START_X: + line.getStartPoint().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Y: + line.getStartPoint().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Z: + line.getStartPoint().setZ(value.getDoubleValue()); + + break; + + case END_X: + line.getEndPoint().setX(value.getDoubleValue()); + + break; + + case END_Y: + line.getEndPoint().setY(value.getDoubleValue()); + + break; + + case END_Z: + line.getEndPoint().setZ(value.getDoubleValue()); + + break; + } + + super.parseCommonProperty(groupCode, value, line); + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#getEntity() + */ + public DXFEntity getDXFEntity() { + return line; + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#startParsing() + */ + public void startDXFEntity() { + line = new DXFLine(); + line.setStartPoint(new Point()); + line.setEndPoint(new Point()); + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#endParsing() + */ + public void endDXFEntity() { + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#setDXFDocument(org.dxf2svg.xml.DXFDocument) + */ + public void setDXFDocument(DXFDocument doc) { + this.doc = doc; + } + + /* (non-Javadoc) + * @see org.dxf2svg.parser.entities.EntityHandler#isFollowSequence() + */ + public boolean isFollowSequence() { + return false; + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXFMLineHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXFMLineHandler.java new file mode 100644 index 0000000..45e6ae1 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXFMLineHandler.java @@ -0,0 +1,197 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.entities; + +import org.kabeja.dxf.DXFConstants; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.dxf.DXFMLine; +import org.kabeja.dxf.helpers.DXFMLineSegment; +import org.kabeja.dxf.helpers.DXFMLineSegmentElement; +import org.kabeja.parser.DXFValue; + + +public class DXFMLineHandler extends AbstractEntityHandler { + public final static int GROUPCODE_MLINE_STYLENAME = 2; + public final static int GROUPCODE_MLINE_STYLE_ID = 340; + public final static int GROUPCODE_MLINE_SCALE_FACTOR = 40; + public final static int GROUPCODE_MLINE_JUSTIFICATION = 70; + public final static int GROUPCODE_MLINE_FLAGS = 71; + public final static int GROUPCODE_MLINE_NUMBER_OF_VERTICES = 72; + public final static int GROUPCODE_MLINE_NUMBER_OF_LINESTYLEELEMENTS = 73; + public final static int GROUPCODE_MLINE_VERTEX_X = 11; + public final static int GROUPCODE_MLINE_VERTEX_Y = 21; + public final static int GROUPCODE_MLINE_VERTEX_Z = 31; + public final static int GROUPCODE_MLINE_DIRECTION_X = 12; + public final static int GROUPCODE_MLINE_DIRECTION_Y = 22; + public final static int GROUPCODE_MLINE_DIRECTION_Z = 32; + public final static int GROUPCODE_MLINE_MITER_DIRECTION_X = 13; + public final static int GROUPCODE_MLINE_MITER_DIRECTION_Y = 23; + public final static int GROUPCODE_MLINE_MITER_DIRECTION_Z = 33; + public final static int GROUPCODE_MLINE_ELEMENT_PARAMETER_COUNT = 74; + public final static int GROUPCODE_MLINE_ELEMENT_PARAMETER = 41; + public final static int GROUPCODE_MLINE_FILL_PARAMETER_COUNT = 75; + public final static int GROUPCODE_MLINE_FILL_PARAMETER = 42; + protected DXFMLine mLine; + protected DXFMLineSegment seg; + protected DXFMLineSegmentElement el; + protected int index = 0; + + public String getDXFEntityName() { + return DXFConstants.ENTITY_TYPE_MLINE; + } + + public void endDXFEntity() { + } + + public DXFEntity getDXFEntity() { + return this.mLine; + } + + public boolean isFollowSequence() { + return false; + } + + public void parseGroup(int groupCode, DXFValue value) { + + switch (groupCode) { + + case GROUPCODE_MLINE_VERTEX_X: + this.seg = new DXFMLineSegment(); + this.mLine.addDXFMLineSegement(this.seg); + this.seg.getStartPoint().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_MLINE_VERTEX_Y: + this.seg.getStartPoint().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_MLINE_VERTEX_Z: + this.seg.getStartPoint().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_MLINE_DIRECTION_X: + this.seg.getDirection().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_MLINE_DIRECTION_Y: + this.seg.getDirection().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_MLINE_DIRECTION_Z: + this.seg.getDirection().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_MLINE_MITER_DIRECTION_X: + this.seg.getMiterDirection().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_MLINE_MITER_DIRECTION_Y: + this.seg.getMiterDirection().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_MLINE_MITER_DIRECTION_Z: + this.seg.getMiterDirection().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_MLINE_ELEMENT_PARAMETER: + this.el.setLengthParameter(index, value.getDoubleValue()); + this.index++; + + break; + + case GROUPCODE_MLINE_ELEMENT_PARAMETER_COUNT: + this.el = new DXFMLineSegmentElement(); + this.seg.addDXFMLineSegmentElement(el); + this.el.setLengthParameters(new double[value.getIntegerValue()]); + this.index = 0; + + break; + + case GROUPCODE_MLINE_FILL_PARAMETER: + this.el.setFillParameter(index, value.getDoubleValue()); + this.index++; + + break; + + case GROUPCODE_MLINE_FILL_PARAMETER_COUNT: + this.el.setFillParameters(new double[value.getIntegerValue()]); + this.index = 0; + + break; + + case GROUPCODE_START_X: + this.mLine.getStartPoint().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Y: + this.mLine.getStartPoint().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Z: + this.mLine.getStartPoint().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_MLINE_FLAGS: + this.mLine.setFlags(value.getIntegerValue()); + + break; + + case GROUPCODE_MLINE_JUSTIFICATION: + this.mLine.setJustification(value.getIntegerValue()); + + break; + + case GROUPCODE_MLINE_NUMBER_OF_LINESTYLEELEMENTS: + this.mLine.setLineCount(value.getIntegerValue()); + + break; + + case GROUPCODE_MLINE_SCALE_FACTOR: + this.mLine.setScale(value.getDoubleValue()); + + break; + + case GROUPCODE_MLINE_STYLENAME: + this.mLine.setMLineStyleName(value.getValue()); + + break; + + case GROUPCODE_MLINE_STYLE_ID: + this.mLine.setMLineStyleID(value.getValue()); + + break; + + default: + super.parseCommonProperty(groupCode, value, this.mLine); + } + } + + public void startDXFEntity() { + this.mLine = new DXFMLine(); + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXFMTextHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXFMTextHandler.java new file mode 100644 index 0000000..b440369 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXFMTextHandler.java @@ -0,0 +1,215 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.entities; + +import org.kabeja.dxf.DXFEntity; +import org.kabeja.dxf.DXFMText; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + * + */ +public class DXFMTextHandler extends AbstractEntityHandler { + public static final String ENTITY_NAME = "MTEXT"; + public static final int TEXT_VALUE_END = 1; + public static final int TEXT_VALUE = 3; + public static final int TEXT_HEIGHT = 40; + public static final int TEXT_REF_WIDTH = 41; + public static final int TEXT_REF_HEIGHT = 43; + public static final int TEXT_DRAWING_DIRECTION_FLAG = 72; + public static final int TEXT_ATTACHMENT_POINT = 71; + public static final int TEXT_VALIGN = 73; + public static final int TEXT_ALIGN_X = 11; + public static final int TEXT_ALIGN_Y = 21; + public static final int TEXT_ALIGN_Z = 31; + public static final int TEXT_STYLE = 7; + public static final int TEXT_OBLIQUEANGLE = 51; + public static final int TEXT_ROTATION = 50; + private DXFMText mtext; + private StringBuffer buf = new StringBuffer(); + private int insert = 0; + + /** + * + */ + public DXFMTextHandler() { + super(); + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#endParsing() + */ + public void endDXFEntity() { + mtext.setText(buf.toString()); + buf.delete(0, buf.length()); + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#getEntity() + */ + public DXFEntity getDXFEntity() { + return mtext; + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#getEntityName() + */ + public String getDXFEntityName() { + return ENTITY_NAME; + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#isFollowSequence() + */ + public boolean isFollowSequence() { + // TODO Auto-generated method stub + return false; + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#parseGroup(int, + * org.dxf2svg.parser.DXFValue) + */ + public void parseGroup(int groupCode, DXFValue value) { + + switch (groupCode) { + + case TEXT_VALUE: + + String part = value.getValue(); + buf.insert(insert, part); + insert += part.length(); + + break; + + case TEXT_VALUE_END: + buf.insert(insert, value.getValue()); + + break; + + case TEXT_ATTACHMENT_POINT: + mtext.setAttachmentPoint(value.getIntegerValue()); + + break; + + case GROUPCODE_START_X: + mtext.setX(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Y: + mtext.setY(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Z: + mtext.setZ(value.getDoubleValue()); + + break; + + case TEXT_ALIGN_X: + mtext.setAlignX(value.getDoubleValue()); + mtext.setRotation(0.0); + + break; + + case TEXT_ALIGN_Y: + mtext.setAlignY(value.getDoubleValue()); + mtext.setRotation(0.0); + + break; + + case TEXT_ALIGN_Z: + mtext.setAlignZ(value.getDoubleValue()); + mtext.setRotation(0.0); + + break; + + case TEXT_HEIGHT: + mtext.setHeight(value.getDoubleValue()); + + break; + + case TEXT_DRAWING_DIRECTION_FLAG: + + switch (value.getIntegerValue()) { + case 2: + mtext.setBackward(true); + + break; + + case 4: + mtext.setUpsideDown(true); + + break; + } + + break; + + case TEXT_STYLE: + mtext.setTextStyle(value.getValue()); + + break; + + case TEXT_ROTATION: + mtext.setRotation(value.getDoubleValue()); + + break; + + case TEXT_REF_WIDTH: + mtext.setReferenceWidth(value.getDoubleValue()); + + break; + + case TEXT_REF_HEIGHT: + mtext.setReferenceHeight(value.getDoubleValue()); + + break; + + case TEXT_OBLIQUEANGLE: + mtext.setObliqueAngle(value.getDoubleValue()); + + break; + + default: + super.parseCommonProperty(groupCode, value, mtext); + + break; + } + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#startParsing() + */ + public void startDXFEntity() { + mtext = new DXFMText(); + insert = 0; + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXFPointHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXFPointHandler.java new file mode 100644 index 0000000..579070c --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXFPointHandler.java @@ -0,0 +1,117 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.entities; + +import org.kabeja.dxf.DXFCircle; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.dxf.DXFPoint; +import org.kabeja.dxf.helpers.Point; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + * + */ +public class DXFPointHandler extends AbstractEntityHandler { + public final static String ENTITY_NAME = "POINT"; + private DXFPoint point; + + /** + * + */ + public DXFPointHandler() { + super(); + + // TODO Auto-generated constructor stub + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#endParsing() + */ + public void endDXFEntity() { + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#getEntity() + */ + public DXFEntity getDXFEntity() { + return point; + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#getEntityName() + */ + public String getDXFEntityName() { + // TODO Auto-generated method stub + return ENTITY_NAME; + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#parseGroup(int, + * org.dxf2svg.parser.DXFValue) + */ + public void parseGroup(int groupCode, DXFValue value) { + + switch (groupCode) { + + case GROUPCODE_START_X: + point.setX(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Y: + point.setY(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Z: + point.setZ(value.getDoubleValue()); + + break; + + default: + super.parseCommonProperty(groupCode, value, point); + + break; + } + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#startParsing() + */ + public void startDXFEntity() { + point = new DXFPoint(); + point.setDXFDocument(doc); + } + + /* (non-Javadoc) + * @see org.dxf2svg.parser.entities.EntityHandler#isFollowSequence() + */ + public boolean isFollowSequence() { + return false; + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXFPolylineHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXFPolylineHandler.java new file mode 100644 index 0000000..f05feb8 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXFPolylineHandler.java @@ -0,0 +1,249 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ +package org.kabeja.parser.entities; + +import org.kabeja.dxf.DXFConstants; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.dxf.DXFPolyline; +import org.kabeja.dxf.DXFVertex; +import org.kabeja.parser.DXFEntitiesSectionHandler; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + * + */ +public class DXFPolylineHandler extends AbstractEntityHandler { + public static final String ENTITY_NAME = "POLYLINE"; + public static final String ENTITY_VERTEX = "VERTEX"; + public static final String END_SEQUENCE = "SEQEND"; + public static final int END_SEQUENCE_CODE = -2; + public static final int VERTEX_BULGE = 42; + public static final int START_WIDTH = 40; + public static final int END_WIDTH = 41; + public static final int THICKNESS = 39; + public static final int SURFACE_TYPE = 75; + public static final int SUREFACE_DENSITY_ROW_COUNT = 73; + public static final int SUREFACE_DENSITY_COLUMN_COUNT = 74; + public static final int ROW_COUNT = 71; + public static final int COLUMN_COUNT = 72; + private boolean follow = true; + private boolean parse_vertex = false; + private DXFVertex vertex; + private DXFPolyline polyline; + + /** + * + */ + public DXFPolylineHandler() { + super(); + + // TODO Auto-generated constructor stub + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#endParsing() + */ + public void endDXFEntity() { + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#getEntity() + */ + public DXFEntity getDXFEntity() { + return polyline; + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#getEntityName() + */ + public String getDXFEntityName() { + return DXFConstants.ENTITY_TYPE_POLYLINE; + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#isFollowSequence() + */ + public boolean isFollowSequence() { + return follow; + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#parseGroup(int, + * org.dxf2svg.parser.DXFValue) + */ + public void parseGroup(int groupCode, DXFValue value) { + + if ((groupCode == END_SEQUENCE_CODE) || + END_SEQUENCE.equals(value.getValue())) { + polyline.addVertex(vertex); + follow = false; + + return; + } + + switch (groupCode) { + + case DXFEntitiesSectionHandler.ENTITY_START: + + if (ENTITY_VERTEX.equals(value.getValue())) { + // store the old before + if (parse_vertex) { + polyline.addVertex(vertex); + } else { + parse_vertex = true; + } + + vertex = new DXFVertex(); + vertex.setDXFDocument(doc); + } + + break; + + case GROUPCODE_START_X: + + if (parse_vertex) { + vertex.setX(value.getDoubleValue()); + } + + break; + + case GROUPCODE_START_Y: + + if (parse_vertex) { + vertex.setY(value.getDoubleValue()); + } + + break; + + case GROUPCODE_START_Z: + + if (parse_vertex) { + vertex.setZ(value.getDoubleValue()); + } + + break; + + case VERTEX_BULGE: + + if (parse_vertex) { + vertex.setBulge(value.getDoubleValue()); + } + + break; + + case START_WIDTH: + + if (parse_vertex) { + vertex.setStartWidth(value.getDoubleValue()); + } else { + polyline.setStartWidth(value.getDoubleValue()); + } + + break; + + case END_WIDTH: + + if (parse_vertex) { + vertex.setEndWidth(value.getDoubleValue()); + } else { + polyline.setEndWidth(value.getDoubleValue()); + } + + break; + + case THICKNESS: + polyline.setThickness(value.getDoubleValue()); + + break; + + case SURFACE_TYPE: + polyline.setSurefaceType(value.getIntegerValue()); + + break; + + case ROW_COUNT: + + if (parse_vertex) { + vertex.setPolyFaceMeshVertex0(value.getIntegerValue()); + } else { + polyline.setRows(value.getIntegerValue()); + } + + break; + + case COLUMN_COUNT: + + if (parse_vertex) { + vertex.setPolyFaceMeshVertex1(value.getIntegerValue()); + } else { + polyline.setColumns(value.getIntegerValue()); + } + + break; + + case SUREFACE_DENSITY_ROW_COUNT: + + if (parse_vertex) { + vertex.setPolyFaceMeshVertex2(value.getIntegerValue()); + } else { + polyline.setSurefaceDensityRows(value.getIntegerValue()); + } + + break; + + case SUREFACE_DENSITY_COLUMN_COUNT: + + if (parse_vertex) { + vertex.setPolyFaceMeshVertex3(value.getIntegerValue()); + } else { + polyline.setSurefaceDensityColumns(value.getIntegerValue()); + } + + break; + + default: + + if (parse_vertex) { + super.parseCommonProperty(groupCode, value, vertex); + } else { + super.parseCommonProperty(groupCode, value, polyline); + } + } + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#startParsing() + */ + public void startDXFEntity() { + follow = true; + parse_vertex = false; + polyline = new DXFPolyline(); + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXFRayHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXFRayHandler.java new file mode 100644 index 0000000..acf5017 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXFRayHandler.java @@ -0,0 +1,119 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.entities; + +import org.kabeja.dxf.DXFConstants; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.dxf.DXFRay; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + * + */ +public class DXFRayHandler extends AbstractEntityHandler { + protected DXFRay ray; + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#getDXFEntityName() + */ + public String getDXFEntityName() { + return DXFConstants.ENTITY_TYPE_RAY; + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#endDXFEntity() + */ + public void endDXFEntity() { + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#getDXFEntity() + */ + public DXFEntity getDXFEntity() { + return this.ray; + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#isFollowSequence() + */ + public boolean isFollowSequence() { + return false; + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#parseGroup(int, + * de.miethxml.kabeja.parser.DXFValue) + */ + public void parseGroup(int groupCode, DXFValue value) { + + switch (groupCode) { + + case GROUPCODE_START_X: + this.ray.getBasePoint().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Y: + this.ray.getBasePoint().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Z: + this.ray.getBasePoint().setY(value.getDoubleValue()); + + break; + + case END_X: + this.ray.getDirection().setX(value.getDoubleValue()); + + break; + + case END_Y: + this.ray.getDirection().setY(value.getDoubleValue()); + + break; + + case END_Z: + this.ray.getDirection().setZ(value.getDoubleValue()); + + break; + + default: + super.parseCommonProperty(groupCode, value, ray); + } + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#startDXFEntity() + */ + public void startDXFEntity() { + this.ray = new DXFRay(); + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXFRegionHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXFRegionHandler.java new file mode 100644 index 0000000..b24aee8 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXFRegionHandler.java @@ -0,0 +1,126 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.entities; + +import org.kabeja.dxf.DXFConstants; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.dxf.DXFRegion; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + * + */ +public class DXFRegionHandler extends AbstractEntityHandler { + protected static final int DATA = 1; + protected static final int APPEND_DATA = 3; + protected DXFRegion region; + protected StringBuffer data = new StringBuffer(); + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.AbstractEntityHandler#getDXFEntityName() + */ + public String getDXFEntityName() { + // TODO Auto-generated method stub + return DXFConstants.ENTITY_TYPE_REGION; + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#startDXFEntity() + */ + public void startDXFEntity() { + region = new DXFRegion(); + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#parseGroup(int, + * de.miethxml.kabeja.parser.DXFValue) + */ + public void parseGroup(int groupCode, DXFValue value) { + + switch (groupCode) { + + case DATA: + //first cleanup + checkBuffer(); + data.append(value.getValue()); + + break; + + case APPEND_DATA: + data.append(value.getValue()); + + break; + } + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#getDXFEntity() + */ + public DXFEntity getDXFEntity() { + return region; + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#endDXFEntity() + */ + public void endDXFEntity() { + checkBuffer(); + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#isFollowSequence() + */ + public boolean isFollowSequence() { + return false; + } + + protected String decodeDATA(String s) { + char[] c = s.toCharArray(); + StringBuffer buf = new StringBuffer(); + + for (int i = 0; i < c.length; i++) { + if (Character.isWhitespace(c[i])) { + buf.append(' '); + } else { + int code = Math.abs(((int) c[i]) - 159); + buf.append((char) code); + } + } + + return buf.toString(); + } + + protected void checkBuffer() { + if (data.length() > 0) { + region.appendACISDATA(decodeDATA(data.toString())); + data.delete(0, data.length()); + } + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXFShapeHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXFShapeHandler.java new file mode 100644 index 0000000..95e3a23 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXFShapeHandler.java @@ -0,0 +1,129 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.entities; + +import org.kabeja.dxf.DXFConstants; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.dxf.DXFShape; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + * + */ +public class DXFShapeHandler extends AbstractEntityHandler { + public final static int GROUPCODE_NAME = 2; + public final static int GROUPCODE_SIZE = 40; + public final static int GROUPCODE_SCALE_X = 41; + public final static int GROUPCODE_OBLIQUE_ANGLE = 51; + protected DXFShape shape; + + /* + * (non-Javadoc) + * + * @see org.kabeja.parser.entities.DXFEntityHandler#getDXFEntityName() + */ + public String getDXFEntityName() { + return DXFConstants.ENTITY_TYPE_SHAPE; + } + + /* + * (non-Javadoc) + * + * @see org.kabeja.parser.entities.DXFEntityHandler#endDXFEntity() + */ + public void endDXFEntity() { + } + + /* + * (non-Javadoc) + * + * @see org.kabeja.parser.entities.DXFEntityHandler#getDXFEntity() + */ + public DXFEntity getDXFEntity() { + return shape; + } + + /* + * (non-Javadoc) + * + * @see org.kabeja.parser.entities.DXFEntityHandler#isFollowSequence() + */ + public boolean isFollowSequence() { + // TODO Auto-generated method stub + return false; + } + + /* + * (non-Javadoc) + * + * @see org.kabeja.parser.entities.DXFEntityHandler#parseGroup(int, + * org.kabeja.parser.DXFValue) + */ + public void parseGroup(int groupCode, DXFValue value) { + + switch (groupCode) { + + case GROUPCODE_START_X: + shape.getInsertPoint().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Y: + shape.getInsertPoint().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Z: + shape.getInsertPoint().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_OBLIQUE_ANGLE: + shape.setObliqueAngle(value.getDoubleValue()); + + break; + + case GROUPCODE_ROTATION_ANGLE: + shape.setRotation(value.getDoubleValue()); + + break; + + case GROUPCODE_NAME: + shape.setName(value.getValue()); + + break; + + case GROUPCODE_SIZE: + shape.setHeight(value.getDoubleValue()); + + break; + + default: + super.parseCommonProperty(groupCode, value, shape); + } + } + + /* + * (non-Javadoc) + * + * @see org.kabeja.parser.entities.DXFEntityHandler#startDXFEntity() + */ + public void startDXFEntity() { + shape = new DXFShape(); + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXFSolidHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXFSolidHandler.java new file mode 100644 index 0000000..2ed82a8 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXFSolidHandler.java @@ -0,0 +1,164 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.entities; + +import org.kabeja.dxf.DXFEntity; +import org.kabeja.dxf.DXFSolid; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + * + */ +public class DXFSolidHandler extends AbstractEntityHandler { + public final static int POINT2_X = 11; + public final static int POINT2_Y = 21; + public final static int POINT2_Z = 31; + public final static int POINT3_X = 12; + public final static int POINT3_Y = 22; + public final static int POINT3_Z = 32; + public final static int POINT4_X = 13; + public final static int POINT4_Y = 23; + public final static int POINT4_Z = 33; + protected String ENTITY_NAME = "SOLID"; + protected DXFSolid solid; + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#endDXFEntity() + */ + public void endDXFEntity() { + // TODO Auto-generated method stub + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#getDXFEntity() + */ + public DXFEntity getDXFEntity() { + return solid; + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#getDXFEntityName() + */ + public String getDXFEntityName() { + return ENTITY_NAME; + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#isFollowSequence() + */ + public boolean isFollowSequence() { + // TODO Auto-generated method stub + return false; + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#parseGroup(int, + * de.miethxml.kabeja.parser.DXFValue) + */ + public void parseGroup(int groupCode, DXFValue value) { + + switch (groupCode) { + + + //point 1 + case GROUPCODE_START_X: + solid.getPoint1().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Y: + solid.getPoint1().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Z: + solid.getPoint1().setZ(value.getDoubleValue()); + + break; + + //point 2 + case POINT2_X: + solid.getPoint2().setX(value.getDoubleValue()); + + break; + + case POINT2_Y: + solid.getPoint2().setY(value.getDoubleValue()); + + break; + + case POINT2_Z: + solid.getPoint2().setZ(value.getDoubleValue()); + + break; + + //point 3 + case POINT3_X: + solid.getPoint3().setX(value.getDoubleValue()); + + break; + + case POINT3_Y: + solid.getPoint3().setY(value.getDoubleValue()); + + break; + + case POINT3_Z: + solid.getPoint3().setZ(value.getDoubleValue()); + + break; + + //point 4 + case POINT4_X: + solid.getPoint4().setX(value.getDoubleValue()); + + break; + + case POINT4_Y: + solid.getPoint4().setY(value.getDoubleValue()); + + break; + + case POINT4_Z: + solid.getPoint4().setZ(value.getDoubleValue()); + + break; + + default: + super.parseCommonProperty(groupCode, value, solid); + } + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#startDXFEntity() + */ + public void startDXFEntity() { + solid = new DXFSolid(); + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXFSplineHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXFSplineHandler.java new file mode 100644 index 0000000..e3da586 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXFSplineHandler.java @@ -0,0 +1,250 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.entities; + +import org.kabeja.dxf.DXFConstants; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.dxf.DXFSpline; +import org.kabeja.dxf.helpers.SplinePoint; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + * + */ +public class DXFSplineHandler extends AbstractEntityHandler { + public static final int CONTROL_POINT_X = 10; + public static final int CONTROL_POINT_Y = 20; + public static final int CONTROL_POINT_Z = 30; + public static final int FIT_POINT_X = 11; + public static final int FIT_POINT_Y = 21; + public static final int FIT_POINT_Z = 31; + public static final int START_TANGENT_X = 12; + public static final int START_TANGENT_Y = 22; + public static final int START_TANGENT_Z = 32; + public static final int END_TANGENT_X = 13; + public static final int END_TANGENT_Y = 23; + public static final int END_TANGENT_Z = 33; + public static final int FIT_TOLERANCE = 44; + public static final int KNOTS = 40; + public static final int WEIGHTS = 41; + public static final int CONTROLPOINT_TOLERANCE = 42; + public static final int KNOT_TOLERANCE = 43; + public static final int NUMBER_OF_FIT_POINTS = 74; + public static final int NUMBER_OF_CONTROL_POINTS = 73; + public static final int NUMBER_OF_CONTROL_POINTS2 = 96; + public static final int NUMBER_OF_NODES = 72; + public static final int NUMBER_OF_NODES2 = 95; + public static final int DEGREE = 71; + private DXFSpline spline; + private SplinePoint point; + private double[] knots; + private double[] weights; + private int knotsCount; + private int controlPointCount; + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#getDXFEntityName() + */ + public String getDXFEntityName() { + return DXFConstants.ENTITY_TYPE_SPLINE; + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#endDXFEntity() + */ + public void endDXFEntity() { + spline.setKnots(knots); + spline.setWeights(weights); + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#getDXFEntity() + */ + public DXFEntity getDXFEntity() { + return spline; + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#isFollowSequence() + */ + public boolean isFollowSequence() { + return false; + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#parseGroup(int, + * de.miethxml.kabeja.parser.DXFValue) + */ + public void parseGroup(int groupCode, DXFValue value) { + + switch (groupCode) { + + case DEGREE: + spline.setDegree(value.getIntegerValue()); + + break; + + case NUMBER_OF_CONTROL_POINTS: + weights = new double[value.getIntegerValue()]; + controlPointCount = 0; + spline.setControlPointSize(value.getIntegerValue()); + + break; + + case NUMBER_OF_FIT_POINTS: + spline.setFitPointSize(value.getIntegerValue()); + + break; + + case NUMBER_OF_NODES: + knots = new double[value.getIntegerValue()]; + knotsCount = 0; + spline.setNodePointsSize(value.getIntegerValue()); + + break; + + case NUMBER_OF_NODES2: + knots = new double[value.getIntegerValue()]; + knotsCount = 0; + spline.setNodePointsSize(value.getIntegerValue()); + + break; + + case FIT_TOLERANCE: + spline.setFitTolerance(value.getDoubleValue()); + + break; + + case KNOTS: + knots[knotsCount] = value.getDoubleValue(); + knotsCount++; + + break; + + case KNOT_TOLERANCE: + spline.setKnotsTolerance(value.getDoubleValue()); + + break; + + case WEIGHTS: + weights[controlPointCount] = value.getDoubleValue(); + controlPointCount++; + + break; + + case CONTROLPOINT_TOLERANCE: + spline.setControlPointTolerance(value.getDoubleValue()); + + break; + + case FIT_POINT_X: + point = new SplinePoint(); + point.setType(SplinePoint.TYPE_FITPOINT); + point.setX(value.getDoubleValue()); + spline.addSplinePoint(point); + + break; + + case FIT_POINT_Y: + point.setY(value.getDoubleValue()); + + break; + + case FIT_POINT_Z: + point.setZ(value.getDoubleValue()); + + break; + + case CONTROL_POINT_X: + point = new SplinePoint(); + point.setType(SplinePoint.TYPE_CONTROLPOINT); + point.setX(value.getDoubleValue()); + spline.addSplinePoint(point); + + break; + + case CONTROL_POINT_Y: + point.setY(value.getDoubleValue()); + + break; + + case CONTROL_POINT_Z: + point.setZ(value.getDoubleValue()); + + break; + + case START_TANGENT_X: + point = new SplinePoint(); + point.setType(SplinePoint.TYPE_STARTTANGENT); + point.setX(value.getDoubleValue()); + spline.addSplinePoint(point); + + break; + + case START_TANGENT_Y: + point.setY(value.getDoubleValue()); + + break; + + case START_TANGENT_Z: + point.setZ(value.getDoubleValue()); + + break; + + case END_TANGENT_X: + point = new SplinePoint(); + point.setType(SplinePoint.TYPE_ENDTANGENT); + point.setX(value.getDoubleValue()); + spline.addSplinePoint(point); + + break; + + case END_TANGENT_Y: + point.setY(value.getDoubleValue()); + + break; + + case END_TANGENT_Z: + point.setZ(value.getDoubleValue()); + + break; + + default: + super.parseCommonProperty(groupCode, value, spline); + } + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#startDXFEntity() + */ + public void startDXFEntity() { + spline = new DXFSpline(); + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXFTextHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXFTextHandler.java new file mode 100644 index 0000000..4ac319f --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXFTextHandler.java @@ -0,0 +1,207 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.entities; + +import org.kabeja.dxf.DXFConstants; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.dxf.DXFText; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + * + */ +public class DXFTextHandler extends AbstractEntityHandler { + public static final int TEXT_VALUE = 1; + public static final int TEXT_HEIGHT = 40; + public static final int TEXT_SCALEX = 41; + public static final int TEXT_GENERATION_FLAG = 71; + public static final int TEXT_ALIGN = 72; + public static final int TEXT_VALIGN = 73; + public static final int TEXT_ALIGN_X = 11; + public static final int TEXT_ALIGN_Y = 21; + public static final int TEXT_ALIGN_Z = 31; + public static final int TEXT_STYLE = 7; + public static final int TEXT_OBLIQUEANGLE = 51; + public static final int TEXT_ROTATION = 50; + protected DXFText text; + protected String content; + + /** + * + */ + public DXFTextHandler() { + super(); + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#endParsing() + */ + public void endDXFEntity() { + text.setText(this.content); + this.content = ""; + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#getEntity() + */ + public DXFEntity getDXFEntity() { + return text; + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#getEntityName() + */ + public String getDXFEntityName() { + return DXFConstants.ENTITY_TYPE_TEXT; + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#isFollowSequence() + */ + public boolean isFollowSequence() { + // TODO Auto-generated method stub + return false; + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#parseGroup(int, + * org.dxf2svg.parser.DXFValue) + */ + public void parseGroup(int groupCode, DXFValue value) { + + switch (groupCode) { + + case TEXT_VALUE: + //we set the content after the + //parsing is finished, so the + //DXFParser will get all infos + this.content = value.getValue(); + + break; + + case TEXT_ALIGN: + text.setAlign(value.getIntegerValue()); + + break; + + case TEXT_VALIGN: + text.setValign(value.getIntegerValue()); + + break; + + case GROUPCODE_START_X: + text.setX(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Y: + text.setY(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Z: + text.setZ(value.getDoubleValue()); + + break; + + case TEXT_ALIGN_X: + text.setAlignX(value.getDoubleValue()); + text.setAlignmentPoint(true); + + break; + + case TEXT_ALIGN_Y: + text.setAlignY(value.getDoubleValue()); + text.setAlignmentPoint(true); + + break; + + case TEXT_ALIGN_Z: + text.setAlignZ(value.getDoubleValue()); + text.setAlignmentPoint(true); + + break; + + case TEXT_HEIGHT: + text.setHeight(value.getDoubleValue()); + + break; + + case TEXT_GENERATION_FLAG: + + switch (value.getIntegerValue()) { + case 2: + text.setBackward(true); + + break; + + case 4: + text.setUpsideDown(true); + + break; + } + + break; + + case TEXT_STYLE: + text.setTextStyle(value.getValue()); + + break; + + case TEXT_ROTATION: + text.setRotation(value.getDoubleValue()); + + break; + + case TEXT_SCALEX: + text.setScaleX(value.getDoubleValue()); + + break; + + case TEXT_OBLIQUEANGLE: + text.setObliqueAngle(value.getDoubleValue()); + + break; + + default: + super.parseCommonProperty(groupCode, value, text); + + break; + } + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.EntityHandler#startParsing() + */ + public void startDXFEntity() { + text = new DXFText(); + text.setDXFDocument(this.doc); + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXFToleranceHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXFToleranceHandler.java new file mode 100644 index 0000000..e0473b4 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXFToleranceHandler.java @@ -0,0 +1,132 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.entities; + +import org.kabeja.dxf.DXFConstants; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.dxf.DXFTolerance; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + * + */ +public class DXFToleranceHandler extends AbstractEntityHandler { + public final static int GROUPCODE_X_AXIS_DIRECTOPN_X = 11; + public final static int GROUPCODE_X_AXIS_DIRECTOPN_Y = 21; + public final static int GROUPCODE_X_AXIS_DIRECTOPN_Z = 31; + protected DXFTolerance tolerance; + + /* + * (non-Javadoc) + * + * @see org.kabeja.parser.entities.DXFEntityHandler#getDXFEntityName() + */ + public String getDXFEntityName() { + return DXFConstants.ENTITY_TYPE_TOLERANCE; + } + + /* + * (non-Javadoc) + * + * @see org.kabeja.parser.entities.DXFEntityHandler#endDXFEntity() + */ + public void endDXFEntity() { + } + + /* + * (non-Javadoc) + * + * @see org.kabeja.parser.entities.DXFEntityHandler#getDXFEntity() + */ + public DXFEntity getDXFEntity() { + return tolerance; + } + + /* + * (non-Javadoc) + * + * @see org.kabeja.parser.entities.DXFEntityHandler#isFollowSequence() + */ + public boolean isFollowSequence() { + return false; + } + + /* + * (non-Javadoc) + * + * @see org.kabeja.parser.entities.DXFEntityHandler#parseGroup(int, + * org.kabeja.parser.DXFValue) + */ + public void parseGroup(int groupCode, DXFValue value) { + + switch (groupCode) { + + case GROUPCODE_START_X: + tolerance.getInsertionPoint().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Y: + tolerance.getInsertionPoint().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_START_Z: + tolerance.getInsertionPoint().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_X_AXIS_DIRECTOPN_X: + tolerance.getXaxisDirection().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_X_AXIS_DIRECTOPN_Y: + tolerance.getXaxisDirection().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_X_AXIS_DIRECTOPN_Z: + tolerance.getXaxisDirection().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_TEXT: + tolerance.setText(value.getValue()); + + break; + + case GROUPCODE_STYLENAME: + tolerance.setStyleID(value.getValue()); + + break; + + default: + super.parseCommonProperty(groupCode, value, tolerance); + } + } + + /* + * (non-Javadoc) + * + * @see org.kabeja.parser.entities.DXFEntityHandler#startDXFEntity() + */ + public void startDXFEntity() { + tolerance = new DXFTolerance(); + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXFTraceHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXFTraceHandler.java new file mode 100644 index 0000000..343d171 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXFTraceHandler.java @@ -0,0 +1,37 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.entities; + +import org.kabeja.dxf.DXFConstants; +import org.kabeja.dxf.DXFTrace; + + +/** + * @author Simon Mieth + * + */ +public class DXFTraceHandler extends DXFSolidHandler { + public String getDXFEntityName() { + return DXFConstants.ENTITY_TYPE_TRACE; + } + + /* (non-Javadoc) + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#startDXFEntity() + */ + public void startDXFEntity() { + solid = new DXFTrace(); + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXFViewportHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXFViewportHandler.java new file mode 100644 index 0000000..5575b81 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXFViewportHandler.java @@ -0,0 +1,342 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ +package org.kabeja.parser.entities; + +import org.kabeja.dxf.DXFConstants; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.dxf.DXFViewport; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + * + */ +public class DXFViewportHandler extends AbstractEntityHandler { + public static final int GROUPCODE_CENTER_X = 10; + public static final int GROUPCODE_CENTER_Y = 20; + public static final int GROUPCODE_CENTER_Z = 30; + public static final int GROUPCODE_HEIGHT = 41; + public static final int GROUPCODE_WIDTH = 40; + public static final int GROUPCODE_VIEW_DIRECTION_X = 16; + public static final int GROUPCODE_VIEW_DIRECTION_Y = 26; + public static final int GROUPCODE_VIEW_DIRECTION_Z = 36; + public static final int GROUPCODE_VIEW_CENTER_X = 12; + public static final int GROUPCODE_VIEW_CENTER_Y = 22; + public static final int GROUPCODE_VIEW_CENTER_Z = 32; + public static final int GROUPCODE_VIEW_TARGET_X = 17; + public static final int GROUPCODE_VIEW_TARGET_Y = 27; + public static final int GROUPCODE_VIEW_TARGET_Z = 37; + public static final int GROUPCODE_SNAP_BASE_POINT_X = 13; + public static final int GROUPCODE_SNAP_BASE_POINT_Y = 23; + public static final int GROUPCODE_SNAP_SPACING_X = 14; + public static final int GROUPCODE_SNAP_SPACING_Y = 24; + public static final int GROUPCODE_GRID_SPACING_X = 15; + public static final int GROUPCODE_GRID_SPACING_Y = 25; + public static final int GROUPCODE_LENS_LENGTH = 42; + public static final int GROUPCODE_FRONT_CLIPPING = 43; + public static final int GROUPCODE_BACK_CLIPPING = 44; + public static final int GROUPCODE_VIEW_HEIGHT = 45; + public static final int GROUPCODE_SNAP_ANGLE = 50; + public static final int GROUPCODE_TWIST_ANGLE = 51; + public static final int GROUPCODE_RENDER_MODE = 281; + public static final int GROUPCODE_UCS_ORIGIN_X = 110; + public static final int GROUPCODE_UCS_ORIGIN_Y = 120; + public static final int GROUPCODE_UCS_ORIGIN_Z = 130; + public static final int GROUPCODE_UCS_X_AXIS_X = 111; + public static final int GROUPCODE_UCS_X_AXIS_Y = 121; + public static final int GROUPCODE_UCS_X_AXIS_Z = 131; + public static final int GROUPCODE_UCS_Y_AXIS_X = 112; + public static final int GROUPCODE_UCS_Y_AXIS_Y = 122; + public static final int GROUPCODE_UCS_Y_AXIS_Z = 132; + public static final int GROUPCODE_UCS_TYPE = 79; + public static final int GROUPCODE_UCS_ELEVATION = 146; + public static final int GROUPCODE_CIRCLE_ZOOM_PERCENT = 72; + public static final int GROUPCODE_VIEWPORT_ID = 69; + public static final int GROUPCODE_VIEWPORT_STATUS = 68; + public static final int GROUPCODE_PLOTSTYLE_NAME = 1; + public static final int GROUPCODE_FROZEN_LAYER = 341; + public static final int GROUPCODE_FROZEN_LAYER_XDATA = 1003; + private int[] xDataConvert = new int[] { + 1000, 1002, 1070, 17, 27, 37, 16, 26, 36, 51, 45, 12, 22, 42, 43, 44, + 90, 72, 90, 90, 90, 90, 90, 90, 50, 13, 23, 14, 24, 15, 25, 90, 1002 + }; + private DXFViewport viewport; + private boolean convertXDATA = false; + private int pos = 0; + + public void parseGroup(int groupCode, DXFValue value) { + //check for XDATA + if (convertXDATA && (pos < xDataConvert.length)) { + groupCode = xDataConvert[pos]; + pos++; + } else if ((groupCode == 1001) && value.getValue().equals("ACAD")) { + convertXDATA = true; + pos = 0; + } else { + convertXDATA = false; + } + + switch (groupCode) { + + case GROUPCODE_CENTER_X: + viewport.getCenterPoint().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_CENTER_Y: + viewport.getCenterPoint().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_CENTER_Z: + viewport.getCenterPoint().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_VIEW_CENTER_X: + viewport.getViewCenterPoint().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_VIEW_CENTER_Y: + viewport.getViewCenterPoint().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_VIEW_CENTER_Z: + viewport.getViewCenterPoint().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_VIEW_DIRECTION_X: + viewport.getViewDirectionVector().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_VIEW_DIRECTION_Y: + viewport.getViewDirectionVector().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_VIEW_DIRECTION_Z: + viewport.getViewDirectionVector().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_VIEW_TARGET_X: + viewport.getViewTargetPoint().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_VIEW_TARGET_Y: + viewport.getViewTargetPoint().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_VIEW_TARGET_Z: + viewport.getViewTargetPoint().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_SNAP_BASE_POINT_X: + viewport.getSnapBasePoint().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_SNAP_BASE_POINT_Y: + viewport.getSnapBasePoint().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_SNAP_SPACING_X: + viewport.getSnapSpacingPoint().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_SNAP_SPACING_Y: + viewport.getSnapSpacingPoint().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_GRID_SPACING_X: + viewport.getGridSpacingPoint().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_GRID_SPACING_Y: + viewport.getGridSpacingPoint().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_VIEWPORT_ID: + viewport.setViewportID(value.getValue()); + + break; + + case GROUPCODE_WIDTH: + viewport.setWidth(value.getDoubleValue()); + + break; + + case GROUPCODE_HEIGHT: + viewport.setHeight(value.getDoubleValue()); + + break; + + case GROUPCODE_FRONT_CLIPPING: + viewport.setFrontClippingPlane(value.getDoubleValue()); + + break; + + case GROUPCODE_BACK_CLIPPING: + viewport.setBackClippingPlane(value.getDoubleValue()); + + break; + + case GROUPCODE_LENS_LENGTH: + viewport.setLensLength(value.getDoubleValue()); + + break; + + case GROUPCODE_RENDER_MODE: + viewport.setRenderMode(value.getIntegerValue()); + + break; + + case GROUPCODE_TWIST_ANGLE: + viewport.setTwistAngle(value.getDoubleValue()); + + break; + + case GROUPCODE_SNAP_ANGLE: + viewport.setSnapAngle(value.getDoubleValue()); + + break; + + case GROUPCODE_CIRCLE_ZOOM_PERCENT: + viewport.setCircleZoom(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_ELEVATION: + viewport.setUcsElevation(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_ORIGIN_X: + viewport.getUcsOrigin().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_ORIGIN_Y: + viewport.getUcsOrigin().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_ORIGIN_Z: + viewport.getUcsOrigin().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_X_AXIS_X: + viewport.getUcsXAxis().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_X_AXIS_Y: + viewport.getUcsXAxis().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_X_AXIS_Z: + viewport.getUcsXAxis().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_Y_AXIS_X: + viewport.getUcsYAxis().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_Y_AXIS_Y: + viewport.getUcsYAxis().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_Y_AXIS_Z: + viewport.getUcsYAxis().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_TYPE: + viewport.setUcsType(value.getIntegerValue()); + + break; + + case GROUPCODE_VIEW_HEIGHT: + viewport.setViewHeight(value.getDoubleValue()); + + break; + + case GROUPCODE_VIEWPORT_STATUS: + viewport.setViewportStatus(value.getIntegerValue()); + + break; + + case GROUPCODE_PLOTSTYLE_NAME: + viewport.setPlotStyleName(value.getValue()); + + break; + + case GROUPCODE_FROZEN_LAYER: + viewport.addFrozenLayer(value.getValue()); + + break; + + case GROUPCODE_FROZEN_LAYER_XDATA: + viewport.addFrozenLayer(value.getValue()); + + break; + + default: + super.parseCommonProperty(groupCode, value, viewport); + + break; + } + } + + public String getDXFEntityName() { + return DXFConstants.ENTITY_TYPE_VIEWPORT; + } + + public void endDXFEntity() { + // nothing to do + } + + public DXFEntity getDXFEntity() { + return this.viewport; + } + + public boolean isFollowSequence() { + return false; + } + + public void startDXFEntity() { + this.viewport = new DXFViewport(); + this.viewport.setModelSpace(false); + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/entities/DXFXLineHandler.java b/dxf/src/main/java/org/kabeja/parser/entities/DXFXLineHandler.java new file mode 100644 index 0000000..73a30cc --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/entities/DXFXLineHandler.java @@ -0,0 +1,40 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.entities; + +import org.kabeja.dxf.DXFConstants; +import org.kabeja.dxf.DXFXLine; + + +/** + * @author Simon Mieth + * + */ +public class DXFXLineHandler extends DXFRayHandler { + /* (non-Javadoc) + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#getDXFEntityName() + */ + public String getDXFEntityName() { + return DXFConstants.ENTITY_TYPE_XLINE; + } + + /* (non-Javadoc) + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#startDXFEntity() + */ + public void startDXFEntity() { + this.ray = new DXFXLine(); + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/header/HeaderModes.java b/dxf/src/main/java/org/kabeja/parser/header/HeaderModes.java new file mode 100644 index 0000000..670efc3 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/header/HeaderModes.java @@ -0,0 +1,25 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.header; + + +/** + * @author Simon Mieth + * + */ +public class HeaderModes { + public static final int ACADVER = 1; +} diff --git a/dxf/src/main/java/org/kabeja/parser/objects/AbstractDXFObjectHandler.java b/dxf/src/main/java/org/kabeja/parser/objects/AbstractDXFObjectHandler.java new file mode 100644 index 0000000..9df8414 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/objects/AbstractDXFObjectHandler.java @@ -0,0 +1,70 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.objects; + +import org.kabeja.dxf.DXFDocument; +import org.kabeja.dxf.objects.DXFObject; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + * + */ +public abstract class AbstractDXFObjectHandler implements DXFObjectHandler { + public final static int GROUPCODE_SOFTPOINTER_ID = 330; + public final static int GROUPCODE_HARDOWNER_ID = 360; + public final static int GROUPCODE_HANDLE_ID = 5; + protected DXFDocument doc; + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.Handler#releaseDXFDocument() + */ + public void releaseDXFDocument() { + doc = null; + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.Handler#setDXFDocument(de.miethxml.kabeja.dxf.DXFDocument) + */ + public void setDXFDocument(DXFDocument doc) { + this.doc = doc; + } + + protected void parseCommonGroupCode(int groupCode, DXFValue value, + DXFObject obj) { + switch (groupCode) { + case GROUPCODE_HANDLE_ID: + obj.setID(value.getValue()); + + break; + + case GROUPCODE_HARDOWNER_ID: + obj.setHardOwnerID(value.getValue()); + + break; + + case GROUPCODE_SOFTPOINTER_ID: + obj.setSoftPointerID(value.getValue()); + + break; + } + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/objects/DXFDictionaryHandler.java b/dxf/src/main/java/org/kabeja/parser/objects/DXFDictionaryHandler.java new file mode 100644 index 0000000..8da002e --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/objects/DXFDictionaryHandler.java @@ -0,0 +1,68 @@ +/* + Copyright 2007 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.objects; + +import org.kabeja.dxf.DXFConstants; +import org.kabeja.dxf.objects.DXFDictionary; +import org.kabeja.dxf.objects.DXFObject; +import org.kabeja.parser.DXFValue; + + +public class DXFDictionaryHandler extends AbstractDXFObjectHandler { + public final int GROUPCODE_RECORD_NAME = 3; + public final int GROUPCODE_RECORD_ID = 350; + protected DXFDictionary dictionary; + protected String objectName; + protected boolean rootDictionaryParsed = false; + + public void endObject() { + } + + public DXFObject getDXFObject() { + return dictionary; + } + + public String getObjectType() { + return DXFConstants.OBJECT_TYPE_DICTIONARY; + } + + public void parseGroup(int groupCode, DXFValue value) { + switch (groupCode) { + case GROUPCODE_RECORD_NAME: + this.objectName = value.getValue(); + + break; + + case GROUPCODE_RECORD_ID: + this.dictionary.putDXFObjectRelation(this.objectName, + value.getValue()); + + break; + + default: + super.parseCommonGroupCode(groupCode, value, this.dictionary); + } + } + + public void startObject() { + if (this.rootDictionaryParsed) { + this.dictionary = new DXFDictionary(); + } else { + this.dictionary = this.doc.getRootDXFDictionary(); + this.rootDictionaryParsed = true; + } + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/objects/DXFImageDefHandler.java b/dxf/src/main/java/org/kabeja/parser/objects/DXFImageDefHandler.java new file mode 100644 index 0000000..23770cf --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/objects/DXFImageDefHandler.java @@ -0,0 +1,89 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.objects; + +import org.kabeja.dxf.DXFConstants; +import org.kabeja.dxf.objects.DXFImageDefObject; +import org.kabeja.dxf.objects.DXFObject; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + * + */ +public class DXFImageDefHandler extends AbstractDXFObjectHandler { + public final static int GROUPCODE_FILENAME = 1; + protected DXFImageDefObject imageDef; + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.objects.DXFObjectHandler#getObjectType() + */ + public String getObjectType() { + return DXFConstants.OBJECT_TYPE_IMAGEDEF; + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.objects.DXFObjectHandler#startObject() + */ + public void startObject() { + imageDef = new DXFImageDefObject(); + imageDef.setDXFDocument(this.doc); + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.objects.DXFObjectHandler#endObject() + */ + public void endObject() { + // TODO Auto-generated method stub + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.objects.DXFObjectHandler#getDXFObject() + */ + public DXFObject getDXFObject() { + // TODO Auto-generated method stub + return imageDef; + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.objects.DXFObjectHandler#parseGroup(int, + * de.miethxml.kabeja.parser.DXFValue) + */ + public void parseGroup(int groupCode, DXFValue value) { + switch (groupCode) { + case GROUPCODE_FILENAME: + imageDef.setFilename(value.getValue()); + + break; + + default: + super.parseCommonGroupCode(groupCode, value, imageDef); + + break; + } + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/objects/DXFLayoutHandler.java b/dxf/src/main/java/org/kabeja/parser/objects/DXFLayoutHandler.java new file mode 100644 index 0000000..90aee20 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/objects/DXFLayoutHandler.java @@ -0,0 +1,217 @@ +/* + Copyright 2007 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.objects; + +import org.kabeja.dxf.DXFConstants; +import org.kabeja.dxf.objects.DXFLayout; +import org.kabeja.dxf.objects.DXFObject; +import org.kabeja.parser.DXFValue; + + +public class DXFLayoutHandler extends DXFPlotsettingsHandler { + public final static int GROUPCODE_MINIMUM_LIMITS_X = 10; + public final static int GROUPCODE_MINIMUM_LIMITS_Y = 20; + public final static int GROUPCODE_MAXIMUM_LIMITS_X = 11; + public final static int GROUPCODE_MAXIMUM_LIMITS_Y = 21; + public final static int GROUPCODE_INSERT_POINT_X = 12; + public final static int GROUPCODE_INSERT_POINT_Y = 22; + public final static int GROUPCODE_INSERT_POINT_Z = 32; + public final static int GROUPCODE_MINIMUM_EXTENTS_X = 14; + public final static int GROUPCODE_MINIMUM_EXTENTS_Y = 24; + public final static int GROUPCODE_MINIMUM_EXTENTS_Z = 34; + public final static int GROUPCODE_MAXIMUM_EXTENTS_X = 15; + public final static int GROUPCODE_MAXIMUM_EXTENTS_Y = 25; + public final static int GROUPCODE_MAXIMUM_EXTENTS_Z = 35; + public final static int GROUPCODE_ELEVATION = 146; + public final static int GROUPCODE_UCS_ORIGIN_X = 13; + public final static int GROUPCODE_UCS_ORIGIN_Y = 23; + public final static int GROUPCODE_UCS_ORIGIN_Z = 33; + public final static int GROUPCODE_UCS_AXIS_X_X = 16; + public final static int GROUPCODE_UCS_AXIS_X_Y = 26; + public final static int GROUPCODE_UCS_AXIS_X_Z = 36; + public final static int GROUPCODE_UCS_AXIS_Y_X = 17; + public final static int GROUPCODE_UCS_AXIS_Y_Y = 27; + public final static int GROUPCODE_UCS_AXIS_Y_Z = 37; + public final static int GROUPCODE_UCS_ORTHOGRAPHIC_TYPE = 76; + public final static int GROUPCODE_PAPER_SPACE_BLOCK_RECORD_ID = 330; + public final static int GROUPCODE_LAST_ACTIVE_VIEWPORT_ID = 331; + public final static int GROUPCODE_UCS_ID = 345; + public final static int GROUPCODE_UCS_BASE_ID = 346; + protected DXFLayout layout; + + public void endObject() { + } + + public DXFObject getDXFObject() { + return this.layout; + } + + public String getObjectType() { + return DXFConstants.OBJECT_TYPE_LAYOUT; + } + + public void parseGroup(int groupCode, DXFValue value) { + switch (groupCode) { + case GROUPCODE_ELEVATION: + this.layout.setElevation(value.getDoubleValue()); + + break; + + case GROUPCODE_INSERT_POINT_X: + this.layout.getInsertPoint().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_INSERT_POINT_Y: + this.layout.getInsertPoint().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_INSERT_POINT_Z: + this.layout.getInsertPoint().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_LAST_ACTIVE_VIEWPORT_ID: + this.layout.setLastActiveViewportID(value.getValue()); + + break; + + case GROUPCODE_MAXIMUM_EXTENTS_X: + this.layout.getExtent().setMaximumX(value.getDoubleValue()); + + break; + + case GROUPCODE_MAXIMUM_EXTENTS_Y: + this.layout.getExtent().setMaximumY(value.getDoubleValue()); + + break; + + case GROUPCODE_MAXIMUM_EXTENTS_Z: + this.layout.getExtent().setMaximumZ(value.getDoubleValue()); + + break; + + case GROUPCODE_MAXIMUM_LIMITS_X: + this.layout.getLimits().setMaximumX(value.getDoubleValue()); + + break; + + case GROUPCODE_MAXIMUM_LIMITS_Y: + this.layout.getLimits().setMaximumY(value.getDoubleValue()); + + break; + + case GROUPCODE_MINIMUM_EXTENTS_X: + this.layout.getExtent().setMinimumX(value.getDoubleValue()); + + break; + + case GROUPCODE_MINIMUM_EXTENTS_Y: + this.layout.getExtent().setMinimumY(value.getDoubleValue()); + + break; + + case GROUPCODE_MINIMUM_EXTENTS_Z: + this.layout.getExtent().setMinimumZ(value.getDoubleValue()); + + break; + + case GROUPCODE_MINIMUM_LIMITS_X: + this.layout.getLimits().setMinimumX(value.getDoubleValue()); + + break; + + case GROUPCODE_MINIMUM_LIMITS_Y: + this.layout.getLimits().setMinimumY(value.getDoubleValue()); + + break; + + case GROUPCODE_PAPER_SPACE_BLOCK_RECORD_ID: + this.layout.setPaperSpaceBlockID(value.getValue()); + + break; + + case GROUPCODE_UCS_AXIS_X_X: + this.layout.getXAxisUCS().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_AXIS_X_Y: + this.layout.getXAxisUCS().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_AXIS_X_Z: + this.layout.getXAxisUCS().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_AXIS_Y_X: + this.layout.getYAxisUCS().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_AXIS_Y_Y: + this.layout.getYAxisUCS().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_AXIS_Y_Z: + this.layout.getYAxisUCS().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_BASE_ID: + this.layout.setBaseUCSID(value.getValue()); + + break; + + case GROUPCODE_UCS_ID: + this.layout.setNamedUCSID(value.getValue()); + + break; + + case GROUPCODE_UCS_ORIGIN_X: + this.layout.getOriginUCS().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_ORIGIN_Y: + this.layout.getOriginUCS().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_ORIGIN_Z: + this.layout.getOriginUCS().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_ORTHOGRAPHIC_TYPE: + this.layout.setOrthographicTypeOfUCS(value.getIntegerValue()); + + break; + + default: + super.parseGroup(groupCode, value); + } + } + + public void startObject() { + this.layout = new DXFLayout(); + this.plotSettings = this.layout; + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/objects/DXFMLineStyleHandler.java b/dxf/src/main/java/org/kabeja/parser/objects/DXFMLineStyleHandler.java new file mode 100644 index 0000000..a4f0e9a --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/objects/DXFMLineStyleHandler.java @@ -0,0 +1,110 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.objects; + +import org.kabeja.dxf.DXFConstants; +import org.kabeja.dxf.objects.DXFMLineStyle; +import org.kabeja.dxf.objects.DXFMLineStyleElement; +import org.kabeja.dxf.objects.DXFObject; +import org.kabeja.parser.DXFValue; + + +public class DXFMLineStyleHandler extends AbstractDXFObjectHandler { + public static final int GROUPCODE_MLINE_STYLE_NAME = 2; + public static final int GROUPCODE_MLINE_STYLE_FLAGS = 70; + public static final int GROUPCODE_MLINE_STYLE_DESCRIPTION = 3; + public static final int GROUPCODE_MLINE_STYLE_FILL_COLOR = 62; + public static final int GROUPCODE_MLINE_STYLE_START_ANGLE = 51; + public static final int GROUPCODE_MLINE_STYLE_END_ANGLE = 52; + public static final int GROUPCODE_MLINE_STYLE_ELEMENT_COUNT = 71; + public static final int GROUPCODE_MLINE_STYLE_ELEMENT_OFFSET = 49; + public static final int GROUPCODE_MLINE_STYLE_ELEMENT_COLOR = 62; + public static final int GROUPCODE_MLINE_STYLE_ELEMENT_LINE_STYLE = 6; + protected DXFMLineStyle style; + protected DXFMLineStyleElement element; + protected boolean processLineElement = false; + + public void endObject() { + } + + public DXFObject getDXFObject() { + return this.style; + } + + public String getObjectType() { + return DXFConstants.OBJECT_TYPE_MLINESTYLE; + } + + public void parseGroup(int groupCode, DXFValue value) { + switch (groupCode) { + case GROUPCODE_MLINE_STYLE_ELEMENT_OFFSET: + this.element = new DXFMLineStyleElement(); + this.element.setOffset(value.getDoubleValue()); + this.style.addDXFMLineStyleElement(element); + this.processLineElement = true; + + break; + + case GROUPCODE_MLINE_STYLE_ELEMENT_COLOR: + + if (this.processLineElement) { + this.element.setLineColor(value.getIntegerValue()); + } else { + this.style.setFillColor(value.getIntegerValue()); + } + + break; + + case GROUPCODE_MLINE_STYLE_ELEMENT_LINE_STYLE: + this.element.setLineType(value.getValue()); + + break; + + case GROUPCODE_MLINE_STYLE_NAME: + this.style.setName(value.getValue()); + + break; + + case GROUPCODE_MLINE_STYLE_DESCRIPTION: + this.style.setDescrition(value.getValue()); + + break; + + case GROUPCODE_MLINE_STYLE_START_ANGLE: + this.style.setStartAngle(value.getDoubleValue()); + + break; + + case GROUPCODE_MLINE_STYLE_END_ANGLE: + this.style.setEndAngle(value.getDoubleValue()); + + break; + + case GROUPCODE_MLINE_STYLE_FLAGS: + this.style.setFlags(value.getIntegerValue()); + + break; + + default: + super.parseCommonGroupCode(groupCode, value, this.style); + } + } + + public void startObject() { + this.style = new DXFMLineStyle(); + this.processLineElement = false; + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/objects/DXFObjectHandler.java b/dxf/src/main/java/org/kabeja/parser/objects/DXFObjectHandler.java new file mode 100644 index 0000000..5f03d6f --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/objects/DXFObjectHandler.java @@ -0,0 +1,37 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.objects; + +import org.kabeja.dxf.objects.DXFObject; +import org.kabeja.parser.DXFValue; +import org.kabeja.parser.Handler; + + +/** + * @author Simon Mieth + * + */ +public interface DXFObjectHandler extends Handler { + public String getObjectType(); + + public void startObject(); + + public void parseGroup(int groupCode, DXFValue value); + + public void endObject(); + + public DXFObject getDXFObject(); +} diff --git a/dxf/src/main/java/org/kabeja/parser/objects/DXFPlotsettingsHandler.java b/dxf/src/main/java/org/kabeja/parser/objects/DXFPlotsettingsHandler.java new file mode 100644 index 0000000..f7c5136 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/objects/DXFPlotsettingsHandler.java @@ -0,0 +1,193 @@ +/* + Copyright 2007 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.objects; + +import org.kabeja.dxf.DXFConstants; +import org.kabeja.dxf.objects.DXFObject; +import org.kabeja.dxf.objects.DXFPlotSettings; +import org.kabeja.parser.DXFValue; + + +public class DXFPlotsettingsHandler extends AbstractDXFObjectHandler { + public final static int GROUPCODE_NAME = 1; + public final static int GROUPCODE_PLOT_CONFIGURATION_FILE = 2; + public final static int GROUPCODE_PAPER_SIZE = 4; + public final static int GROUPCODE_PLOT_VIEW_NAME = 6; + public final static int GROUPCODE_MARGIN_LEFT = 40; + public final static int GROUPCODE_MARGIN_BOTTOM = 41; + public final static int GROUPCODE_MARGIN_RIGHT = 42; + public final static int GROUPCODE_MARGIN_TOP = 43; + public final static int GROUPCODE_PLOT_PAPER_WIDTH = 44; + public final static int GROUPCODE_PLOT_PAPER_HEIGHT = 45; + public final static int GROUPCODE_ORIGIN_X = 46; + public final static int GROUPCODE_ORIGIN_Y = 47; + public final static int GROUPCODE_PLOT_WINDOW_MIN_X = 48; + public final static int GROUPCODE_PLOT_WINDOWS_MIN_Y = 49; + public final static int GROUPCODE_PLOT_WINDOW_MAX_X = 140; + public final static int GROUPCODE_PLOT_WINDOWS_MAX_Y = 141; + public final static int GROUPCODE_CUSTOM_SCALE_NUMERATOR = 142; + public final static int GROUPCODE_CUSTOM_SCALE_DEOMINATOR = 143; + public final static int GROUPCODE_PAPER_UNITS = 72; + public final static int GROUPCODE_PLOT_ROTATION = 73; + public final static int GROUPCODE_PLOT_TYPE = 74; + public final static int GROUPCODE_CURRENT_STYLESHEET = 7; + public final static int GROUPCODE_STANDARD_SCALE_TYPE = 75; + protected DXFPlotSettings plotSettings; + + public void endObject() { + } + + public DXFObject getDXFObject() { + return this.plotSettings; + } + + public String getObjectType() { + return DXFConstants.OBJECT_TYPE_PLOTSETTINGS; + } + + public void parseGroup(int groupCode, DXFValue value) { + double[] m; + + switch (groupCode) { + case GROUPCODE_CURRENT_STYLESHEET: + this.plotSettings.setCurrentStylesheet(value.getValue()); + + break; + + case GROUPCODE_CUSTOM_SCALE_DEOMINATOR: + this.plotSettings.setCustomScaleDenominator(value.getDoubleValue()); + + break; + + case GROUPCODE_CUSTOM_SCALE_NUMERATOR: + this.plotSettings.setCustomScaleNumerator(value.getDoubleValue()); + + break; + + case GROUPCODE_MARGIN_BOTTOM: + m = this.plotSettings.getMargin(); + m[2] = value.getDoubleValue(); + this.plotSettings.setMargin(m); + + break; + + case GROUPCODE_MARGIN_LEFT: + m = this.plotSettings.getMargin(); + m[3] = value.getDoubleValue(); + this.plotSettings.setMargin(m); + + break; + + case GROUPCODE_MARGIN_RIGHT: + m = this.plotSettings.getMargin(); + m[1] = value.getDoubleValue(); + this.plotSettings.setMargin(m); + + break; + + case GROUPCODE_MARGIN_TOP: + m = this.plotSettings.getMargin(); + m[0] = value.getDoubleValue(); + this.plotSettings.setMargin(m); + + break; + + case GROUPCODE_ORIGIN_X: + this.plotSettings.getPlotOrigin().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_ORIGIN_Y: + this.plotSettings.getPlotOrigin().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_NAME: + this.plotSettings.setName(value.getValue()); + + break; + + case GROUPCODE_PAPER_SIZE: + + //this.plotSettings. + break; + + case GROUPCODE_PAPER_UNITS: + this.plotSettings.setPaperUnit(value.getIntegerValue()); + + break; + + case GROUPCODE_PLOT_CONFIGURATION_FILE: + break; + + case GROUPCODE_PLOT_PAPER_HEIGHT: + this.plotSettings.setPaperHeight(value.getDoubleValue()); + + break; + + case GROUPCODE_PLOT_PAPER_WIDTH: + this.plotSettings.setPaperWidth(value.getDoubleValue()); + + break; + + case GROUPCODE_PLOT_ROTATION: + this.plotSettings.setPlotRotation(value.getIntegerValue()); + + break; + + case GROUPCODE_PLOT_TYPE: + this.plotSettings.setPlotType(value.getIntegerValue()); + + break; + + case GROUPCODE_PLOT_VIEW_NAME: + this.plotSettings.setPlotViewName(value.getValue()); + + break; + + case GROUPCODE_PLOT_WINDOW_MAX_X: + this.plotSettings.getWindowToPlot() + .setMaximumX(value.getDoubleValue()); + + break; + + case GROUPCODE_PLOT_WINDOW_MIN_X: + this.plotSettings.getWindowToPlot() + .setMinimumX(value.getDoubleValue()); + + break; + + case GROUPCODE_PLOT_WINDOWS_MAX_Y: + this.plotSettings.getWindowToPlot() + .setMaximumY(value.getDoubleValue()); + + break; + + case GROUPCODE_PLOT_WINDOWS_MIN_Y: + this.plotSettings.getWindowToPlot() + .setMinimumY(value.getDoubleValue()); + + break; + + default: + super.parseCommonGroupCode(groupCode, value, this.plotSettings); + } + } + + public void startObject() { + this.plotSettings = new DXFPlotSettings(); + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/table/AbstractTableHandler.java b/dxf/src/main/java/org/kabeja/parser/table/AbstractTableHandler.java new file mode 100644 index 0000000..fdf58a2 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/table/AbstractTableHandler.java @@ -0,0 +1,41 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.table; + +import org.kabeja.dxf.DXFDocument; + + +/** + * @author Simon Mieth + * + */ +public abstract class AbstractTableHandler implements DXFTableHandler { + protected DXFDocument doc; + + /* (non-Javadoc) + * @see org.dxf2svg.parser.table.TableHandler#setDXFDocument(org.dxf2svg.xml.DXFDocument) + */ + public void setDXFDocument(DXFDocument doc) { + this.doc = doc; + } + + /* (non-Javadoc) + * @see de.miethxml.kabeja.parser.Handler#releaseDXFDocument() + */ + public void releaseDXFDocument() { + this.doc = null; + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/table/DXFDimensionStyleTableHandler.java b/dxf/src/main/java/org/kabeja/parser/table/DXFDimensionStyleTableHandler.java new file mode 100644 index 0000000..52e0c3e --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/table/DXFDimensionStyleTableHandler.java @@ -0,0 +1,81 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.table; + +import org.kabeja.dxf.DXFDimensionStyle; +import org.kabeja.parser.DXFValue; +import org.kabeja.parser.entities.AbstractEntityHandler; + + +/** + * @author Simon Mieth + * + */ +public class DXFDimensionStyleTableHandler extends AbstractTableHandler { + public final static int GROUPCODE_NAME = 2; + private DXFDimensionStyle style; + private String key = "DIMSTYLE"; + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.table.DXFTableHandler#endParsing() + */ + public void endParsing() { + doc.addDXFDimensionStyle(style); + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.table.DXFTableHandler#getTableKey() + */ + public String getTableKey() { + return key; + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.table.DXFTableHandler#parseGroup(int, + * de.miethxml.kabeja.parser.DXFValue) + */ + public void parseGroup(int groupCode, DXFValue value) { + switch (groupCode) { + case AbstractEntityHandler.FLAGS: + style.setFlags(value.getIntegerValue()); + + break; + + case GROUPCODE_NAME: + style.setName(value.getValue()); + + break; + + default: + style.setProperty("" + groupCode, value.getValue()); + } + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.table.DXFTableHandler#startParsing() + */ + public void startParsing() { + style = new DXFDimensionStyle(); + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/table/DXFLayerTableHandler.java b/dxf/src/main/java/org/kabeja/parser/table/DXFLayerTableHandler.java new file mode 100644 index 0000000..0f5c158 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/table/DXFLayerTableHandler.java @@ -0,0 +1,104 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.table; + +import org.kabeja.dxf.DXFConstants; +import org.kabeja.dxf.DXFLayer; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + * + */ +public class DXFLayerTableHandler extends AbstractTableHandler { + public final static String TABLE_KEY = "LAYER"; + public final static int GROUPCODE_LAYER_NAME = 2; + public final static int GROUPCODE_LAYER_LINETYPE = 6; + public final static int GROUPCODE_LAYER_COLORNUMBER = 62; + public final static int GROUPCODE_LAYER_PLOTTINGFLAG = 290; + public final static int GROUPCODE_LAYER_LINEWEIGHT = 370; + public final static int GROUPCODE_LAYER_PLOTSTYLENAME = 390; + private DXFLayer layer; + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.table.TableHandler#getTableKey() + */ + public String getTableKey() { + return TABLE_KEY; + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.table.TableHandler#parseGroup(int, + * java.lang.String) + */ + public void parseGroup(int groupCode, DXFValue value) { + switch (groupCode) { + case GROUPCODE_LAYER_NAME: + layer.setName(value.getValue()); + + break; + + case GROUPCODE_LAYER_COLORNUMBER: + layer.setColor(value.getIntegerValue()); + + break; + + case GROUPCODE_LAYER_LINETYPE: + layer.setLineType(value.getValue()); + + break; + + case DXFConstants.GROUPCODE_STANDARD_FLAGS: + layer.setFlags(value.getIntegerValue()); + + break; + + case GROUPCODE_LAYER_LINEWEIGHT: + layer.setLineWeight(value.getIntegerValue()); + + break; + + case GROUPCODE_LAYER_PLOTSTYLENAME: + layer.setPlotStyle(value.getValue()); + + break; + } + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.table.TableHandler#endParsing() + */ + public void endParsing() { + doc.addDXFLayer(layer); + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.table.TableHandler#startParsing() + */ + public void startParsing() { + layer = new DXFLayer(); + layer.setDXFDocument(doc); + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/table/DXFLineTypeTableHandler.java b/dxf/src/main/java/org/kabeja/parser/table/DXFLineTypeTableHandler.java new file mode 100644 index 0000000..4c7d800 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/table/DXFLineTypeTableHandler.java @@ -0,0 +1,120 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.table; + +import org.kabeja.dxf.DXFLineType; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + */ +public class DXFLineTypeTableHandler extends AbstractTableHandler { + public final static String TABLE_KEY = "LTYPE"; + public final static int GROUPCODE_LTYPE_NAME = 2; + public final static int GROUPCODE_LTYPE_DESCRIPTION = 3; + public final static int GROUPCODE_LTYPE_ALIGNMENT = 72; + public final static int GROUPCODE_LTYPE_SEGMENT = 49; + public final static int GROUPCODE_LTYPE_LENGTH = 40; + public final static int GROUPCODE_LTYPE_SEGMENT_COUNT = 73; + public final static int GROUPCODE_LTYPE_SCALE = 46; + private DXFLineType ltype; + private int segmentCount = 0; + private double[] pattern; + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.table.DXFTableHandler#endParsing() + */ + public void endParsing() { + ltype.setPattern(pattern); + doc.addDXFLineType(ltype); + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.table.DXFTableHandler#getTableKey() + */ + public String getTableKey() { + // TODO Auto-generated method stub + return TABLE_KEY; + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.table.DXFTableHandler#parseGroup(int, + * de.miethxml.kabeja.parser.DXFValue) + */ + public void parseGroup(int groupCode, DXFValue value) { + switch (groupCode) { + case GROUPCODE_LTYPE_NAME: + ltype.setName(value.getValue()); + + break; + + case GROUPCODE_LTYPE_DESCRIPTION: + ltype.setDescritpion(value.getValue()); + + break; + + case GROUPCODE_LTYPE_SEGMENT_COUNT: + + int count = value.getIntegerValue(); + pattern = new double[count]; + segmentCount = 0; + + break; + + case GROUPCODE_LTYPE_SEGMENT: + pattern[segmentCount] = value.getDoubleValue(); + segmentCount++; + + break; + + case GROUPCODE_LTYPE_LENGTH: + ltype.setPatternLength(value.getDoubleValue()); + + break; + + case GROUPCODE_LTYPE_ALIGNMENT: + ltype.setAlignment(value.getIntegerValue()); + + break; + + case GROUPCODE_LTYPE_SCALE: + ltype.setScale(value.getDoubleValue()); + + break; + + default: + break; + } + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.table.DXFTableHandler#startParsing() + */ + public void startParsing() { + ltype = new DXFLineType(); + segmentCount = 0; + pattern = null; + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/table/DXFStyleTableHandler.java b/dxf/src/main/java/org/kabeja/parser/table/DXFStyleTableHandler.java new file mode 100644 index 0000000..f86e971 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/table/DXFStyleTableHandler.java @@ -0,0 +1,112 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.table; + +import org.kabeja.dxf.DXFStyle; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + * + */ +public class DXFStyleTableHandler extends AbstractTableHandler { + public static String TABLE_KEY = "STYLE"; + public final static int GROUPCODE_NAME = 2; + public final static int GROUPCODE_TEXT_HEIGHT = 40; + public final static int GROUPCODE_WIDTH_FACTOR = 41; + public final static int GROUPCODE_OBLIQUE_ANGLE = 50; + public final static int GROUPCODE_TEXT_GENERATION_FLAG = 71; + public final static int GROUPCODE_FLAGS = 70; + public final static int GROUPCODE_LAST_HEIGHT = 42; + public final static int GROUPCODE_FONT_FILE = 3; + public final static int GROUPCODE_BIG_FONT_FILE = 4; + private DXFStyle style; + + /* (non-Javadoc) + * @see de.miethxml.kabeja.parser.table.DXFTableHandler#endParsing() + */ + public void endParsing() { + doc.addDXStyle(style); + } + + /* (non-Javadoc) + * @see de.miethxml.kabeja.parser.table.DXFTableHandler#getTableKey() + */ + public String getTableKey() { + // TODO Auto-generated method stub + return TABLE_KEY; + } + + /* (non-Javadoc) + * @see de.miethxml.kabeja.parser.table.DXFTableHandler#parseGroup(int, de.miethxml.kabeja.parser.DXFValue) + */ + public void parseGroup(int groupCode, DXFValue value) { + switch (groupCode) { + case GROUPCODE_NAME: + style.setName(value.getValue()); + + break; + + case GROUPCODE_TEXT_HEIGHT: + style.setTextHeight(value.getDoubleValue()); + + break; + + case GROUPCODE_WIDTH_FACTOR: + style.setWidthFactor(value.getDoubleValue()); + + break; + + case GROUPCODE_OBLIQUE_ANGLE: + style.setObliqueAngle(value.getDoubleValue()); + + break; + + case GROUPCODE_TEXT_GENERATION_FLAG: + style.setTextGenerationFlag(value.getIntegerValue()); + + break; + + case GROUPCODE_LAST_HEIGHT: + style.setLastHeight(value.getDoubleValue()); + + break; + + case GROUPCODE_FONT_FILE: + style.setFontFile(value.getValue()); + + break; + + case GROUPCODE_BIG_FONT_FILE: + style.setBigFontFile(value.getValue()); + + break; + + case GROUPCODE_FLAGS: + style.setFlags(value.getIntegerValue()); + + break; + } + } + + /* (non-Javadoc) + * @see de.miethxml.kabeja.parser.table.DXFTableHandler#startParsing() + */ + public void startParsing() { + style = new DXFStyle(); + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/table/DXFTableHandler.java b/dxf/src/main/java/org/kabeja/parser/table/DXFTableHandler.java new file mode 100644 index 0000000..a629994 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/table/DXFTableHandler.java @@ -0,0 +1,37 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.table; + +import org.kabeja.dxf.DXFDocument; +import org.kabeja.parser.DXFValue; +import org.kabeja.parser.Handler; + + +/** + * @author Simon Mieth + * + */ +public interface DXFTableHandler extends Handler { + public String getTableKey(); + + public void setDXFDocument(DXFDocument doc); + + public void startParsing(); + + public void parseGroup(int groupCode, DXFValue value); + + public void endParsing(); +} diff --git a/dxf/src/main/java/org/kabeja/parser/table/DXFVPortTableHandler.java b/dxf/src/main/java/org/kabeja/parser/table/DXFVPortTableHandler.java new file mode 100644 index 0000000..c29e911 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/table/DXFVPortTableHandler.java @@ -0,0 +1,107 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.table; + +import org.kabeja.dxf.DXFConstants; +import org.kabeja.dxf.DXFViewport; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + * + */ +public class DXFVPortTableHandler extends AbstractTableHandler { + public final static int GROUPCODE_VPORT_NAME = 2; + public final static int GROUPCODE_VPORT_LOWER_LEFT_X = 10; + public final static int GROUPCODE_VPORT_LOWER_LEFT_Y = 20; + public final static int GROUPCODE_VPORT_UPPER_RIGHT_X = 11; + public final static int GROUPCODE_VPORT_UPPER_RIGHT_Y = 21; + public final static int GROUPCODE_VPORT_CENTER_POINT_X = 12; + public final static int GROUPCODE_VPORT_CENTER_POINT_Y = 22; + public final static int GROUPCODE_VPORT_SNAP_BASE_POINT_X = 13; + public final static int GROUPCODE_VPORT_SNAP_BASE_POINT_Y = 23; + public final static int GROUPCODE_HEIGHT = 40; + public final static int GROUPCODE_ASPECT_RATIO = 41; + private DXFViewport viewport; + + /* (non-Javadoc) + * @see de.miethxml.kabeja.parser.table.DXFTableHandler#endParsing() + */ + public void endParsing() { + doc.addDXFViewport(viewport); + } + + /* (non-Javadoc) + * @see de.miethxml.kabeja.parser.table.DXFTableHandler#getTableKey() + */ + public String getTableKey() { + return DXFConstants.TABLE_KEY_VPORT; + } + + /* (non-Javadoc) + * @see de.miethxml.kabeja.parser.table.DXFTableHandler#parseGroup(int, de.miethxml.kabeja.parser.DXFValue) + */ + public void parseGroup(int groupCode, DXFValue value) { + switch (groupCode) { + case GROUPCODE_VPORT_NAME: + viewport.setViewportID(value.getValue()); + + if ("*active".equals(value.getValue().toLowerCase())) { + viewport.setActive(true); + } + + break; + + case GROUPCODE_VPORT_CENTER_POINT_X: + viewport.getCenterPoint().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_VPORT_CENTER_POINT_Y: + viewport.getCenterPoint().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_VPORT_LOWER_LEFT_X: + viewport.getLowerLeftCorner().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_VPORT_LOWER_LEFT_Y: + viewport.getLowerLeftCorner().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_HEIGHT: + viewport.setHeight(value.getDoubleValue()); + + break; + + case GROUPCODE_ASPECT_RATIO: + viewport.setAspectRatio(value.getDoubleValue()); + + break; + } + } + + /* (non-Javadoc) + * @see de.miethxml.kabeja.parser.table.DXFTableHandler#startParsing() + */ + public void startParsing() { + viewport = new DXFViewport(); + } +} diff --git a/dxf/src/main/java/org/kabeja/parser/table/DXFViewTableHandler.java b/dxf/src/main/java/org/kabeja/parser/table/DXFViewTableHandler.java new file mode 100644 index 0000000..9d2c62d --- /dev/null +++ b/dxf/src/main/java/org/kabeja/parser/table/DXFViewTableHandler.java @@ -0,0 +1,198 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.parser.table; + +import org.kabeja.dxf.DXFConstants; +import org.kabeja.dxf.DXFView; +import org.kabeja.parser.DXFValue; + + +/** + * @author Simon Mieth + * + */ +public class DXFViewTableHandler extends AbstractTableHandler { + public static final int GROUPCODE_NAME = 2; + public static final int GROUPCODE_CENTER_X = 10; + public static final int GROUPCODE_CENTER_Y = 20; + public static final int GROUPCODE_CENTER_Z = 30; + public static final int GROUPCODE_HEIGHT = 40; + public static final int GROUPCODE_WIDTH = 41; + public static final int GROUPCODE_VIEW_DIRECTION_X = 11; + public static final int GROUPCODE_VIEW_DIRECTION_Y = 21; + public static final int GROUPCODE_VIEW_DIRECTION_Z = 31; + public static final int GROUPCODE_VIEW_TARGET_X = 12; + public static final int GROUPCODE_VIEW_TARGET_Y = 22; + public static final int GROUPCODE_VIEW_TARGET_Z = 32; + public static final int GROUPCODE_LENS_LENGTH = 42; + public static final int GROUPCODE_FRONT_CLIPPING = 43; + public static final int GROUPCODE_BACK_CLIPPING = 44; + public static final int GROUPCODE_TWIST_ANGLE = 50; + public static final int GROUPCODE_RENDER_MODE = 281; + public static final int GROUPCODE_UCS_ORIGIN_X = 110; + public static final int GROUPCODE_UCS_ORIGIN_Y = 120; + public static final int GROUPCODE_UCS_ORIGIN_Z = 130; + public static final int GROUPCODE_UCS_X_AXIS_X = 111; + public static final int GROUPCODE_UCS_X_AXIS_Y = 121; + public static final int GROUPCODE_UCS_X_AXIS_Z = 131; + public static final int GROUPCODE_UCS_Y_AXIS_X = 112; + public static final int GROUPCODE_UCS_Y_AXIS_Y = 122; + public static final int GROUPCODE_UCS_Y_AXIS_Z = 132; + public static final int GROUPCODE_UCS_TYPE = 79; + public static final int GROUPCODE_UCS_ELEVATION = 146; + public static final int GROUPCODE_USE_UCS = 72; + private DXFView view; + + public void endParsing() { + this.doc.addDXFView(view); + } + + /* (non-Javadoc) + * @see org.kabeja.parser.table.DXFTableHandler#getTableKey() + */ + public String getTableKey() { + return DXFConstants.TABLE_KEY_VIEW; + } + + /* (non-Javadoc) + * @see org.kabeja.parser.table.DXFTableHandler#parseGroup(int, org.kabeja.parser.DXFValue) + */ + public void parseGroup(int groupCode, DXFValue value) { + switch (groupCode) { + case GROUPCODE_CENTER_X: + view.getCenterPoint().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_CENTER_Y: + view.getCenterPoint().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_CENTER_Z: + view.getCenterPoint().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_NAME: + view.setName(value.getValue()); + + break; + + case GROUPCODE_WIDTH: + view.setWidth(value.getDoubleValue()); + + break; + + case GROUPCODE_HEIGHT: + view.setHeight(value.getDoubleValue()); + + break; + + case GROUPCODE_FRONT_CLIPPING: + view.setFrontClipping(value.getDoubleValue()); + + break; + + case GROUPCODE_BACK_CLIPPING: + view.setBackClipping(value.getDoubleValue()); + + break; + + case GROUPCODE_LENS_LENGTH: + view.setLensLength(value.getDoubleValue()); + + break; + + case GROUPCODE_RENDER_MODE: + view.setRenderMode(value.getIntegerValue()); + + break; + + case GROUPCODE_TWIST_ANGLE: + view.setTwistAngle(value.getDoubleValue()); + + break; + + case GROUPCODE_USE_UCS: + view.setUseUCS(value.getBooleanValue()); + + break; + + case GROUPCODE_UCS_ELEVATION: + view.setUcsElevation(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_ORIGIN_X: + view.getUcsOrigin().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_ORIGIN_Y: + view.getUcsOrigin().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_ORIGIN_Z: + view.getUcsOrigin().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_X_AXIS_X: + view.getUcsXAxis().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_X_AXIS_Y: + view.getUcsXAxis().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_X_AXIS_Z: + view.getUcsXAxis().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_Y_AXIS_X: + view.getUcsYAxis().setX(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_Y_AXIS_Y: + view.getUcsYAxis().setY(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_Y_AXIS_Z: + view.getUcsYAxis().setZ(value.getDoubleValue()); + + break; + + case GROUPCODE_UCS_TYPE: + view.setUcsType(value.getIntegerValue()); + + break; + } + } + + /* (non-Javadoc) + * @see org.kabeja.parser.table.DXFTableHandler#startParsing() + */ + public void startParsing() { + view = new DXFView(); + } +} diff --git a/dxf/src/main/java/org/kabeja/processing/AbstractConfigurable.java b/dxf/src/main/java/org/kabeja/processing/AbstractConfigurable.java new file mode 100644 index 0000000..39cde05 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/processing/AbstractConfigurable.java @@ -0,0 +1,32 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.processing; + +import java.util.HashMap; +import java.util.Map; + + +public abstract class AbstractConfigurable implements Configurable { + protected Map properties = new HashMap(); + + public void setProperties(Map properties) { + this.properties = properties; + } + + public Map getProperties() { + return this.properties; + } +} diff --git a/dxf/src/main/java/org/kabeja/processing/AbstractPostProcessor.java b/dxf/src/main/java/org/kabeja/processing/AbstractPostProcessor.java new file mode 100644 index 0000000..f2bd3ed --- /dev/null +++ b/dxf/src/main/java/org/kabeja/processing/AbstractPostProcessor.java @@ -0,0 +1,20 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.processing; + +public abstract class AbstractPostProcessor extends AbstractConfigurable + implements PostProcessor { +} diff --git a/dxf/src/main/java/org/kabeja/processing/BoundsDebugger.java b/dxf/src/main/java/org/kabeja/processing/BoundsDebugger.java new file mode 100644 index 0000000..de6f009 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/processing/BoundsDebugger.java @@ -0,0 +1,176 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.processing; + +import java.util.Iterator; +import java.util.Map; + +import org.kabeja.dxf.Bounds; +import org.kabeja.dxf.DXF3DFace; +import org.kabeja.dxf.DXFBlock; +import org.kabeja.dxf.DXFDocument; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.dxf.DXFLayer; +import org.kabeja.dxf.DXFText; + + +/** + * @author Simon Mieth + * + */ +public class BoundsDebugger extends AbstractPostProcessor { + public static final String LAYER_NAME = "kabeja_bounds_debug"; + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.tools.PostProcessor#process(de.miethxml.kabeja.dxf.DXFDocument) + */ + public void process(DXFDocument doc, Map context) throws ProcessorException { + //set all blocks to color gray + Iterator i = doc.getDXFBlockIterator(); + + while (i.hasNext()) { + DXFBlock b = (DXFBlock) i.next(); + Iterator ie = b.getDXFEntitiesIterator(); + + while (ie.hasNext()) { + DXFEntity entity = (DXFEntity) ie.next(); + + //set to gray + entity.setColor(9); + } + } + + DXFEntity left = null; + DXFEntity top = null; + DXFEntity right = null; + DXFEntity bottom = null; + + Bounds b = doc.getBounds(); + double x = b.getMinimumX() + (b.getWidth() / 2); + double y = b.getMinimumY() + (b.getHeight() / 2); + + //starting at the center point of the draft + Bounds lBounds = new Bounds(x, x, y, y); + Bounds rBounds = new Bounds(x, x, y, y); + Bounds tBounds = new Bounds(x, x, y, y); + Bounds bBounds = new Bounds(x, x, y, y); + + i = doc.getDXFLayerIterator(); + + while (i.hasNext()) { + DXFLayer l = (DXFLayer) i.next(); + + //set color to gray + l.setColor(8); + + Iterator ti = l.getDXFEntityTypeIterator(); + + while (ti.hasNext()) { + String type = (String) ti.next(); + Iterator ei = l.getDXFEntities(type).iterator(); + + while (ei.hasNext()) { + DXFEntity entity = (DXFEntity) ei.next(); + + //set to gray + entity.setColor(8); + + Bounds currentBounds = entity.getBounds(); + + if (currentBounds.isValid()) { + if (currentBounds.getMinimumX() <= lBounds.getMinimumX()) { + lBounds = currentBounds; + left = entity; + } + + if (currentBounds.getMinimumY() <= bBounds.getMinimumY()) { + bBounds = currentBounds; + bottom = entity; + } + + if (currentBounds.getMaximumX() >= rBounds.getMaximumX()) { + rBounds = currentBounds; + right = entity; + } + + if (currentBounds.getMaximumY() >= tBounds.getMaximumY()) { + tBounds = currentBounds; + top = entity; + } + } + } + } + } + + //left -> red + left.setColor(0); + addBounds(lBounds, doc, 0, left.getType() + "=" + left.getID()); + + //right -> green + right.setColor(2); + addBounds(rBounds, doc, 2, right.getType() + "=" + right.getID()); + + //bottom blue + bottom.setColor(4); + addBounds(bBounds, doc, 4, bottom.getType() + "=" + bottom.getID()); + + //top color -> magenta + top.setColor(5); + addBounds(tBounds, doc, 5, top.getType() + "=" + top.getID()); + + //the color -> magenta + top.setColor(5); + addBounds(b, doc, 6, "ALL"); + } + + protected void addBounds(Bounds bounds, DXFDocument doc, int color, + String type) { + DXF3DFace face = new DXF3DFace(); + face.getPoint1().setX(bounds.getMinimumX()); + face.getPoint1().setY(bounds.getMinimumY()); + + face.getPoint2().setX(bounds.getMinimumX()); + face.getPoint2().setY(bounds.getMaximumY()); + + face.getPoint3().setX(bounds.getMaximumX()); + face.getPoint3().setY(bounds.getMaximumY()); + + face.getPoint4().setX(bounds.getMaximumX()); + face.getPoint4().setY(bounds.getMinimumY()); + + face.setColor(color); + face.setLayerName(LAYER_NAME); + + doc.addDXFEntity(face); + + DXFText t = new DXFText(); + t.setDXFDocument(doc); + t.setText("DEBUG-" + type); + t.getInsertPoint().setX(bounds.getMinimumX()); + t.getInsertPoint().setY(bounds.getMaximumY()); + t.setColor(color); + t.setLayerName(LAYER_NAME); + doc.addDXFEntity(t); + } + + /* (non-Javadoc) + * @see org.kabeja.tools.PostProcessor#setProperties(java.util.Map) + */ + public void setProperties(Map properties) { + } +} diff --git a/dxf/src/main/java/org/kabeja/processing/BoundsFilter.java b/dxf/src/main/java/org/kabeja/processing/BoundsFilter.java new file mode 100644 index 0000000..5833506 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/processing/BoundsFilter.java @@ -0,0 +1,92 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.processing; + +import java.util.Iterator; +import java.util.Map; + +import org.kabeja.dxf.Bounds; +import org.kabeja.dxf.DXFDocument; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.dxf.DXFLayer; + + +public class BoundsFilter extends AbstractPostProcessor { + public final static String PROPERTY_X = "boundsfilter.x"; + public final static String PROPERTY_Y = "boundsfilter.y"; + public final static String PROPERTY_WIDTH = "boundsfilter.width"; + public final static String PROPERTY_HEIGHT = "boundsfilter.height"; + public final static String PROPERTY_PROCESS = "boundsfilter.process"; + + public void process(DXFDocument doc, Map context) throws ProcessorException { + if (this.properties.containsKey(PROPERTY_PROCESS) && + Boolean.valueOf((String) this.properties.get(PROPERTY_PROCESS)) + .booleanValue()) { + Bounds bounds = new Bounds(); + + if (this.properties.containsKey(PROPERTY_X)) { + bounds.setMinimumX(Double.parseDouble( + (String) this.properties.get(PROPERTY_X))); + } + + if (this.properties.containsKey(PROPERTY_Y)) { + bounds.setMinimumY(Double.parseDouble( + (String) this.properties.get(PROPERTY_Y))); + } + + if (this.properties.containsKey(PROPERTY_WIDTH)) { + bounds.setMaximumX(bounds.getMinimumX() + + Double.parseDouble( + (String) this.properties.get(PROPERTY_WIDTH))); + } + + if (this.properties.containsKey(PROPERTY_WIDTH)) { + bounds.setMaximumY(bounds.getMinimumY() + + Double.parseDouble( + (String) this.properties.get(PROPERTY_HEIGHT))); + } + + // the bounds should be setup now + // we remove all entities which are + // not inside our bounds + Iterator i = doc.getDXFLayerIterator(); + + while (i.hasNext()) { + DXFLayer layer = (DXFLayer) i.next(); + filterLayer(layer, bounds); + } + } + } + + protected void filterLayer(DXFLayer layer, Bounds bounds) { + Iterator i = layer.getDXFEntityTypeIterator(); + + while (i.hasNext()) { + String type = (String) i.next(); + Iterator entities = layer.getDXFEntities(type).iterator(); + + while (entities.hasNext()) { + DXFEntity entity = (DXFEntity) entities.next(); + + if (!bounds.enclose(entity.getBounds())) { + // the bounds not contains this entity + // we remove it + entities.remove(); + } + } + } + } +} diff --git a/dxf/src/main/java/org/kabeja/processing/Configurable.java b/dxf/src/main/java/org/kabeja/processing/Configurable.java new file mode 100644 index 0000000..0886662 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/processing/Configurable.java @@ -0,0 +1,35 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.processing; + +import java.util.Map; + + +public interface Configurable { + /** + * Set configuration properties of the component + * + * @param properties + */ + public void setProperties(Map properties); + + /** + * Get the configuration Properties of the component. + * + * @return + */ + public Map getProperties(); +} diff --git a/dxf/src/main/java/org/kabeja/processing/ImageFilter.java b/dxf/src/main/java/org/kabeja/processing/ImageFilter.java new file mode 100644 index 0000000..0ba90aa --- /dev/null +++ b/dxf/src/main/java/org/kabeja/processing/ImageFilter.java @@ -0,0 +1,63 @@ +/* +Copyright 2005 Simon Mieth + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + */ +package org.kabeja.processing; + +import java.io.File; +import java.util.Iterator; +import java.util.Map; + +import org.kabeja.dxf.DXFConstants; +import org.kabeja.dxf.DXFDocument; +import org.kabeja.dxf.DXFImage; +import org.kabeja.dxf.DXFLayer; +import org.kabeja.dxf.objects.DXFImageDefObject; + + +/** + * + * @author Simon Mieth + */ +public class ImageFilter extends AbstractPostProcessor { + /* + * (non-Javadoc) + * + * @see org.kabeja.tools.PostProcessor#process(org.kabeja.dxf.DXFDocument, + * java.util.Map) + */ + public void process(DXFDocument doc, Map context) throws ProcessorException { + Iterator i = doc.getDXFLayerIterator(); + + while (i.hasNext()) { + DXFLayer l = (DXFLayer) i.next(); + + if (l.hasDXFEntities(DXFConstants.ENTITY_TYPE_IMAGE)) { + Iterator in = l.getDXFEntities(DXFConstants.ENTITY_TYPE_IMAGE) + .iterator(); + + while (in.hasNext()) { + DXFImage img = (DXFImage) in.next(); + String imgDef = img.getImageDefObjectID(); + DXFImageDefObject def = (DXFImageDefObject) doc.getDXFObjectByID(imgDef); + File f = new File(def.getFilename()); + + if (!f.exists()) { + in.remove(); + } + } + } + } + } +} diff --git a/dxf/src/main/java/org/kabeja/processing/LayerFilter.java b/dxf/src/main/java/org/kabeja/processing/LayerFilter.java new file mode 100644 index 0000000..d416c6b --- /dev/null +++ b/dxf/src/main/java/org/kabeja/processing/LayerFilter.java @@ -0,0 +1,106 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.processing; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.StringTokenizer; + +import org.kabeja.dxf.DXFDocument; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.dxf.DXFLayer; + + +public class LayerFilter extends AbstractPostProcessor { + public final static String PROPERTY_REMOVE_LAYERS = "layers.remove"; + public final static String PROPERTY_MERGE_LAYERS = "layers.merge"; + public final static String MERGED_LAYER_NAME = "ALL"; + protected boolean merge = false; + protected Set removableLayers = new HashSet(); + + public void setProperties(Map properties) { + super.setProperties(properties); + + if (properties.containsKey(PROPERTY_MERGE_LAYERS)) { + this.merge = Boolean.valueOf((String) properties.get( + PROPERTY_MERGE_LAYERS)).booleanValue(); + } + + if (properties.containsKey(PROPERTY_REMOVE_LAYERS)) { + this.removableLayers.clear(); + + StringTokenizer st = new StringTokenizer((String) properties.get( + PROPERTY_REMOVE_LAYERS), "|"); + + while (st.hasMoreTokens()) { + this.removableLayers.add(st.nextToken()); + } + } + } + + public void process(DXFDocument doc, Map context) throws ProcessorException { + DXFLayer mergeLayer = null; + + if (this.merge) { + if (doc.containsDXFLayer(MERGED_LAYER_NAME)) { + mergeLayer = doc.getDXFLayer(MERGED_LAYER_NAME); + } else { + mergeLayer = new DXFLayer(); + mergeLayer.setName(MERGED_LAYER_NAME); + doc.addDXFLayer(mergeLayer); + } + } + + // iterate over all layers + Iterator i = doc.getDXFLayerIterator(); + + while (i.hasNext()) { + DXFLayer layer = (DXFLayer) i.next(); + + if (this.removableLayers.contains(layer.getName())) { + i.remove(); + } else if (this.merge) { + if (layer != mergeLayer) { + Iterator types = layer.getDXFEntityTypeIterator(); + + while (types.hasNext()) { + String type = (String) types.next(); + Iterator entityIterator = layer.getDXFEntities(type) + .iterator(); + + while (entityIterator.hasNext()) { + DXFEntity e = (DXFEntity) entityIterator.next(); + // we set all entities to the merged layer + // and remove them from the last layer + e.setLayerName(MERGED_LAYER_NAME); + + // set again to the doc, which will + // place the entity on the right + // layer -> the LAYER = "ALL" + doc.addDXFEntity(e); + entityIterator.remove(); + } + } + + // remove the layer + i.remove(); + } + } + } + } +} diff --git a/dxf/src/main/java/org/kabeja/processing/PolylineConverter.java b/dxf/src/main/java/org/kabeja/processing/PolylineConverter.java new file mode 100644 index 0000000..c70c140 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/processing/PolylineConverter.java @@ -0,0 +1,191 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.processing; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.kabeja.dxf.DXFArc; +import org.kabeja.dxf.DXFConstants; +import org.kabeja.dxf.DXFDocument; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.dxf.DXFLWPolyline; +import org.kabeja.dxf.DXFLayer; +import org.kabeja.dxf.DXFLine; +import org.kabeja.dxf.DXFPolyline; +import org.kabeja.dxf.helpers.Point; +import org.kabeja.processing.helper.PolylineQueue; + + +public class PolylineConverter extends AbstractPostProcessor { + public final static String PROPERTY_POINT_DISTANCE = "point.distance"; + private List queues; + private double radius = DXFConstants.POINT_CONNECTION_RADIUS; + + public void process(DXFDocument doc, Map context) throws ProcessorException { + Iterator i = doc.getDXFLayerIterator(); + + while (i.hasNext()) { + DXFLayer layer = (DXFLayer) i.next(); + + processLayer(layer); + } + + // TODO process the blocks too + } + + public void setProperties(Map properties) { + if (properties.containsKey(PROPERTY_POINT_DISTANCE)) { + this.radius = Double.parseDouble((String) properties.get( + PROPERTY_POINT_DISTANCE)); + } + } + + protected void processLayer(DXFLayer layer) { + this.queues = new ArrayList(); + + // check the lines + if (layer.hasDXFEntities(DXFConstants.ENTITY_TYPE_LINE)) { + List l = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_LINE); + Iterator i = l.iterator(); + + while (i.hasNext()) { + DXFLine line = (DXFLine) i.next(); + Point start = line.getStartPoint(); + Point end = line.getEndPoint(); + checkDXFEntity(line, start, end); + } + } + + // check the polylines + if (layer.hasDXFEntities(DXFConstants.ENTITY_TYPE_POLYLINE)) { + List l = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_POLYLINE); + Iterator i = l.iterator(); + + while (i.hasNext()) { + DXFPolyline pl = (DXFPolyline) i.next(); + + if (!pl.isClosed() && !pl.is3DPolygonMesh() && + !pl.isClosedMeshMDirection() && + !pl.isClosedMeshNDirection() && + !pl.isCubicSurefaceMesh()) { + Point start = pl.getVertex(0).getPoint(); + Point end = pl.getVertex(pl.getVertexCount() - 1).getPoint(); + checkDXFEntity(pl, start, end); + } + } + } + + // check the lwpolylines + if (layer.hasDXFEntities(DXFConstants.ENTITY_TYPE_LWPOLYLINE)) { + List l = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_LWPOLYLINE); + Iterator i = l.iterator(); + + while (i.hasNext()) { + DXFLWPolyline pl = (DXFLWPolyline) i.next(); + + if (!pl.isClosed() && !pl.is3DPolygonMesh() && + !pl.isClosedMeshMDirection() && + !pl.isClosedMeshNDirection() && + !pl.isCubicSurefaceMesh()) { + Point start = pl.getVertex(0).getPoint(); + Point end = pl.getVertex(pl.getVertexCount() - 1).getPoint(); + checkDXFEntity(pl, start, end); + } + } + } + + // check the arcs + if (layer.hasDXFEntities(DXFConstants.ENTITY_TYPE_ARC)) { + List l = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_ARC); + Iterator i = l.iterator(); + + while (i.hasNext()) { + DXFArc arc = (DXFArc) i.next(); + + // note that this points are calculated + // and could be not connected to the rest + // even though they should in you CAD + Point start = arc.getStartPoint(); + Point end = arc.getEndPoint(); + checkDXFEntity(arc, start, end); + } + } + + // finish up the connection search + // and connect parts, if it is possible + connectPolylineQueues(); + + cleanUp(layer); + } + + protected void checkDXFEntity(DXFEntity e, Point start, Point end) { + Iterator i = this.queues.iterator(); + + while (i.hasNext()) { + PolylineQueue queue = (PolylineQueue) i.next(); + + if (queue.connectDXFEntity(e, start, end)) { + return; + } + } + + // nothing found create a new queue + PolylineQueue queue = new PolylineQueue(e, start, end, this.radius); + + this.queues.add(queue); + } + + protected void cleanUp(DXFLayer layer) { + Iterator i = this.queues.iterator(); + + while (i.hasNext()) { + PolylineQueue queue = (PolylineQueue) i.next(); + + if (queue.size() > 1) { + queue.createDXFPolyline(layer); + } else { + // ignore + i.remove(); + } + } + } + + /** + * Goes through all polylinequeues and connect them, if they have the same + * start and end points. + * + */ + protected void connectPolylineQueues() { + for (int i = 0; i < this.queues.size(); i++) { + PolylineQueue queue = (PolylineQueue) this.queues.get(i); + + boolean connected = false; + + //inner loop -> test all following polylines if + //we can connect + for (int x = i + 1; (x < this.queues.size()) && !connected; x++) { + if (((PolylineQueue) this.queues.get(x)).connect(queue)) { + this.queues.remove(i); + i--; + connected = true; + } + } + } + } +} diff --git a/dxf/src/main/java/org/kabeja/processing/PostProcessManager.java b/dxf/src/main/java/org/kabeja/processing/PostProcessManager.java new file mode 100644 index 0000000..3215b3d --- /dev/null +++ b/dxf/src/main/java/org/kabeja/processing/PostProcessManager.java @@ -0,0 +1,62 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.processing; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Map; + +import org.kabeja.dxf.DXFDocument; + + +/** + * @author Simon Mieth + * + */ +public class PostProcessManager { + private ArrayList processors = new ArrayList(); + + public void addPostProcessor(PostProcessor pp) { + processors.add(pp); + } + + public void addPostProcessor(String classname) { + try { + PostProcessor pp = (PostProcessor) this.getClass().getClassLoader() + .loadClass(classname) + .newInstance(); + addPostProcessor(pp); + } catch (InstantiationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (ClassNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public void process(DXFDocument doc, Map context) throws ProcessorException { + Iterator i = processors.iterator(); + + while (i.hasNext()) { + PostProcessor pp = (PostProcessor) i.next(); + pp.process(doc, context); + } + } +} diff --git a/dxf/src/main/java/org/kabeja/processing/PostProcessor.java b/dxf/src/main/java/org/kabeja/processing/PostProcessor.java new file mode 100644 index 0000000..4b2fd6c --- /dev/null +++ b/dxf/src/main/java/org/kabeja/processing/PostProcessor.java @@ -0,0 +1,44 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.processing; + +import java.util.Map; + +import org.kabeja.dxf.DXFDocument; + + +/** + * This interface describes a PostPorcessor, which will work direct with + * parsed CAD data. + * + *

      Lifecycle

      + *
        + *
      1. setProperties()
      2. + *
      3. process()
      4. + * + *
      + * @author Simon Mieth + * + */ +public interface PostProcessor extends Configurable { + /** + * Postprocess the given DXFDocument + * @param doc + * @param context + * @throws ProcessorException + */ + public void process(DXFDocument doc, Map context) throws ProcessorException; +} diff --git a/dxf/src/main/java/org/kabeja/processing/PostProcessorConfig.java b/dxf/src/main/java/org/kabeja/processing/PostProcessorConfig.java new file mode 100644 index 0000000..361e08e --- /dev/null +++ b/dxf/src/main/java/org/kabeja/processing/PostProcessorConfig.java @@ -0,0 +1,59 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.processing; + +import java.util.HashMap; +import java.util.Map; + + +/** + * @author Simon Mieth + * + */ +public class PostProcessorConfig { + private Map properties = new HashMap(); + private String postProcessorName; + + public PostProcessorConfig(Map properties) { + this.properties = properties; + } + + public PostProcessorConfig() { + this(new HashMap()); + } + + public Map getProperties() { + return this.properties; + } + + public void addProperty(String name, String value) { + this.properties.put(name, value); + } + + /** + * @return Returns the filterName. + */ + public String getPostProcessorName() { + return postProcessorName; + } + + /** + * @param filterName The filterName to set. + */ + public void setPostProcessorName(String filterName) { + this.postProcessorName = filterName; + } +} diff --git a/dxf/src/main/java/org/kabeja/processing/ProcessPipeline.java b/dxf/src/main/java/org/kabeja/processing/ProcessPipeline.java new file mode 100644 index 0000000..6f1b316 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/processing/ProcessPipeline.java @@ -0,0 +1,225 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ +package org.kabeja.processing; + +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.kabeja.dxf.DXFDocument; +import org.kabeja.processing.helper.MergeMap; +import org.kabeja.tools.SAXFilterConfig; +import org.kabeja.xml.SAXFilter; +import org.kabeja.xml.SAXGenerator; +import org.kabeja.xml.SAXSerializer; +import org.xml.sax.ContentHandler; +import org.xml.sax.SAXException; + +/** + * @author Simon Mieth + * + */ +public class ProcessPipeline { + private ProcessingManager manager; + private List postProcessorConfigs = new ArrayList(); + private List saxFilterConfigs = new ArrayList(); + private SAXGenerator generator; + private Map serializerProperties = new HashMap(); + private Map generatorProperties = new HashMap(); + private SAXSerializer serializer; + private String name; + private String description = ""; + + public void process(DXFDocument doc, Map context, OutputStream out) + throws ProcessorException { + ContentHandler handler = null; + + // postprocess + Iterator i = this.postProcessorConfigs.iterator(); + + while (i.hasNext()) { + PostProcessorConfig ppc = (PostProcessorConfig) i.next(); + PostProcessor pp = this.manager.getPostProcessor(ppc + .getPostProcessorName()); + + // backup the default props + Map oldProps = pp.getProperties(); + // setup the pipepine props + pp.setProperties(new MergeMap(ppc.getProperties(), context)); + pp.process(doc, context); + // restore the default props + pp.setProperties(oldProps); + } + + List saxFilterProperties = new ArrayList(); + + // setup saxfilters + if (this.saxFilterConfigs.size() > 0) { + i = saxFilterConfigs.iterator(); + SAXFilterConfig sc = (SAXFilterConfig) i.next(); + SAXFilter first = this.manager.getSAXFilter(sc.getFilterName()); + saxFilterProperties + .add(new MergeMap(first.getProperties(), context)); + + first.setContentHandler(this.serializer); + handler = first; + first.setProperties(sc.getProperties()); + + while (i.hasNext()) { + sc = (SAXFilterConfig) i.next(); + SAXFilter f = this.manager.getSAXFilter(sc.getFilterName()); + f.setContentHandler(first); + saxFilterProperties.add(f.getProperties()); + f.setProperties(sc.getProperties()); + first = f; + + } + + } else { + // no filter + handler = this.serializer; + } + + Map oldProbs = this.serializer.getProperties(); + this.serializer.setProperties(new MergeMap(this.serializerProperties, + context)); + + // invoke the filter and serializer + this.serializer.setOutput(out); + + try { + Map oldGenProps = this.generator.getProperties(); + this.generator.setProperties(this.generatorProperties); + this.generator.generate(doc, handler, context); + // restore the old props + this.generator.setProperties(oldGenProps); + } catch (SAXException e) { + throw new ProcessorException(e); + } + + // restore the serializer properties + this.serializer.setProperties(oldProbs); + + // restore the filter properties + for (int x = 0; x < saxFilterProperties.size(); x++) { + SAXFilterConfig sc = (SAXFilterConfig) saxFilterConfigs.get(x); + this.manager.getSAXFilter(sc.getFilterName()).setProperties( + (Map) saxFilterProperties.get(x)); + } + } + + /** + * @return Returns the serializer. + */ + public SAXSerializer getSAXSerializer() { + return serializer; + } + + /** + * @param serializer + * The serializer to set. + */ + public void setSAXSerializer(SAXSerializer serializer) { + this.serializer = serializer; + } + + /** + * @return Returns the manager. + */ + public ProcessingManager getProcessorManager() { + return manager; + } + + /** + * @param manager + * The manager to set. + */ + public void setProcessorManager(ProcessingManager manager) { + this.manager = manager; + } + + /** + * @return Returns the name. + */ + public String getName() { + return name; + } + + /** + * @param name + * The name to set. + */ + public void setName(String name) { + this.name = name; + } + + public void prepare() { + } + + public List getPostProcessorConfigs() { + return this.postProcessorConfigs; + } + + public void addSAXFilterConfig(SAXFilterConfig config) { + this.saxFilterConfigs.add(config); + } + + public void addPostProcessorConfig(PostProcessorConfig config) { + this.postProcessorConfigs.add(config); + } + + /** + * @return Returns the serializerProperties. + */ + public Map getSerializerProperties() { + return serializerProperties; + } + + /** + * @param serializerProperties + * The serializerProperties to set. + */ + public void setSAXSerializerProperties(Map serializerProperties) { + this.serializerProperties = serializerProperties; + } + + public void setSAXGeneratorProperties(Map generatorProperties) { + this.generatorProperties = generatorProperties; + } + + public Map getSAXGeneratorProperties(Map generatorProperties) { + return this.generatorProperties; + } + + public void setSAXGenerator(SAXGenerator generator) { + this.generator = generator; + } + + public SAXGenerator getSAXGenerator() { + return this.generator; + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } +} diff --git a/dxf/src/main/java/org/kabeja/processing/ProcessingManager.java b/dxf/src/main/java/org/kabeja/processing/ProcessingManager.java new file mode 100644 index 0000000..1d35976 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/processing/ProcessingManager.java @@ -0,0 +1,184 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.processing; + +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.kabeja.dxf.DXFDocument; +import org.kabeja.parser.ParseException; +import org.kabeja.parser.Parser; +import org.kabeja.processing.event.ProcessingListener; +import org.kabeja.xml.SAXFilter; +import org.kabeja.xml.SAXGenerator; +import org.kabeja.xml.SAXSerializer; + + +/** + * @author Simon Mieth + * + */ +public class ProcessingManager { + private Map saxfilters = new HashMap(); + private Map saxserializers = new HashMap(); + private Map postprocessors = new HashMap(); + private Map pipelines = new HashMap(); + private Map saxgenerators = new HashMap(); + private List parsers = new ArrayList(); + + public void addSAXFilter(SAXFilter filter, String name) { + this.saxfilters.put(name, filter); + } + + public SAXFilter getSAXFilter(String name) { + return (SAXFilter) this.saxfilters.get(name); + } + + public Map getSAXFilters() { + return this.saxfilters; + } + + public void addSAXSerializer(SAXSerializer serializer, String name) { + this.saxserializers.put(name, serializer); + } + + public SAXSerializer getSAXSerializer(String name) { + return (SAXSerializer) this.saxserializers.get(name); + } + + public Map getSAXSerializers() { + return this.saxserializers; + } + + public void addPostProcessor(PostProcessor pp, String name) { + this.postprocessors.put(name, pp); + } + + public void addParser(Parser parser) { + this.parsers.add(parser); + } + + public List getParsers() { + return this.parsers; + } + + protected Parser getParser(String extension) { + Iterator i = this.parsers.iterator(); + + while (i.hasNext()) { + Parser parser = (Parser) i.next(); + + if (parser.supportedExtension(extension)) { + return parser; + } + } + + return null; + } + + public PostProcessor getPostProcessor(String name) { + return (PostProcessor) this.postprocessors.get(name); + } + + public Map getPostProcessors() { + return this.postprocessors; + } + + public void addProcessPipeline(ProcessPipeline pp) { + pp.setProcessorManager(this); + this.pipelines.put(pp.getName(), pp); + } + + public ProcessPipeline getProcessPipeline(String name) { + return (ProcessPipeline) this.pipelines.get(name); + } + + public Map getProcessPipelines() { + return this.pipelines; + } + + public void process(InputStream stream, String extension, Map context, + String pipeline, OutputStream out) throws ProcessorException { + Parser parser = this.getParser(extension); + + if (parser != null) { + try { + parser.parse(stream, null); + + DXFDocument doc = parser.getDocument(); + this.process(doc, context, pipeline, out); + } catch (ParseException e) { + throw new ProcessorException(e); + } + } + } + + public void process(DXFDocument doc, Map context, String pipeline, + OutputStream out) throws ProcessorException { + if (this.pipelines.containsKey(pipeline)) { + ProcessPipeline pp = (ProcessPipeline) this.pipelines.get(pipeline); + pp.prepare(); + pp.process(doc, context, out); + } else { + throw new ProcessorException("No pipeline found for name:" + + pipeline); + } + } + + public void process(DXFDocument doc, Map context, String pipeline, + String sourceFile) throws ProcessorException { + if (this.pipelines.containsKey(pipeline)) { + try { + ProcessPipeline pp = (ProcessPipeline) this.pipelines.get(pipeline); + String suffix = pp.getSAXSerializer().getSuffix(); + String file = sourceFile.substring(0, + sourceFile.lastIndexOf('.') + 1) + suffix; + FileOutputStream out = new FileOutputStream(file); + process(doc, context, pipeline, out); + } catch (FileNotFoundException e) { + throw new ProcessorException(e); + } + } else { + throw new ProcessorException("No pipeline found for name:" + + pipeline); + } + } + + public void addSAXGenerator(SAXGenerator saxgenerator, String name) { + this.saxgenerators.put(name, saxgenerator); + } + + public SAXGenerator getSAXGenerator(String name) { + return (SAXGenerator) this.saxgenerators.get(name); + } + + public Map getSAXGenerators() { + return this.saxgenerators; + } + + public void addProcessingListener(ProcessingListener l) { + } + + public void removeProcessingListener(ProcessingListener l) { + } +} diff --git a/dxf/src/main/java/org/kabeja/processing/ProcessorException.java b/dxf/src/main/java/org/kabeja/processing/ProcessorException.java new file mode 100644 index 0000000..2113258 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/processing/ProcessorException.java @@ -0,0 +1,34 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.processing; + + +/** + * @author Simon Mieth + * + */ +public class ProcessorException extends Exception { + public ProcessorException() { + } + + public ProcessorException(Exception e) { + super(e); + } + + public ProcessorException(String msg) { + super(msg); + } +} diff --git a/dxf/src/main/java/org/kabeja/processing/ViewFilter.java b/dxf/src/main/java/org/kabeja/processing/ViewFilter.java new file mode 100644 index 0000000..4065983 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/processing/ViewFilter.java @@ -0,0 +1,108 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.processing; + +import java.util.Iterator; +import java.util.Map; + +import org.kabeja.dxf.Bounds; +import org.kabeja.dxf.DXFDocument; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.dxf.DXFLayer; +import org.kabeja.dxf.DXFView; + + +/** + * @author Simon Mieth + * + */ +public class ViewFilter extends AbstractPostProcessor { + public static final String CONTEXT_OPTION_VIEW_NAME = "view.name"; + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.tools.PostProcessor#process(de.miethxml.kabeja.dxf.DXFDocument) + */ + public void process(DXFDocument doc, Map context) throws ProcessorException { + // get the active viewport + DXFView view = null; + Iterator i = doc.getDXFViewIterator(); + + if (context.containsKey(CONTEXT_OPTION_VIEW_NAME)) { + String name = (String) context.get(CONTEXT_OPTION_VIEW_NAME); + + boolean found = false; + + while (i.hasNext() && !found) { + DXFView v = (DXFView) i.next(); + + if (v.getName().trim().equals(name.trim())) { + view = v; + found = true; + } + } + } else if (i.hasNext()) { + // get the first view + view = (DXFView) i.next(); + } + + if (view != null) { + double w = view.getWidth() / 2; + double h = view.getHeight() / 2; + Bounds b = new Bounds(); + + // the upper right corner + b.addToBounds(view.getCenterPoint().getX() + w, + view.getCenterPoint().getY() + h, view.getCenterPoint().getZ()); + + // the lower left corner + b.addToBounds(view.getCenterPoint().getX() - w, + view.getCenterPoint().getY() - h, view.getCenterPoint().getZ()); + filterEntities(b, doc); + } + } + + protected void filterEntities(Bounds b, DXFDocument doc) { + Iterator i = doc.getDXFLayerIterator(); + + while (i.hasNext()) { + DXFLayer l = (DXFLayer) i.next(); + Iterator ti = l.getDXFEntityTypeIterator(); + + while (ti.hasNext()) { + String type = (String) ti.next(); + Iterator ei = l.getDXFEntities(type).iterator(); + + while (ei.hasNext()) { + DXFEntity entity = (DXFEntity) ei.next(); + Bounds currentBounds = entity.getBounds(); + + if (!b.contains(currentBounds)) { + ei.remove(); + } + } + } + } + } + + /* (non-Javadoc) + * @see org.kabeja.tools.PostProcessor#setProperties(java.util.Map) + */ + public void setProperties(Map properties) { + // TODO Auto-generated method stub + } +} diff --git a/dxf/src/main/java/org/kabeja/processing/ViewportFilter.java b/dxf/src/main/java/org/kabeja/processing/ViewportFilter.java new file mode 100644 index 0000000..419f750 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/processing/ViewportFilter.java @@ -0,0 +1,101 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.processing; + +import java.util.Iterator; +import java.util.Map; + +import org.kabeja.dxf.Bounds; +import org.kabeja.dxf.DXFDocument; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.dxf.DXFLayer; +import org.kabeja.dxf.DXFViewport; + + +/** + * @author Simon Mieth + * + */ +public class ViewportFilter extends AbstractPostProcessor { + /* + * (non-Javadoc) + * + * @see org.kabeja.tools.PostProcessor#process(org.kabeja.dxf.DXFDocument, + * java.util.Map) + */ + public void process(DXFDocument doc, Map context) throws ProcessorException { + DXFViewport viewport = null; + Iterator i = doc.getDXFViewportIterator(); + + boolean found = false; + + while (i.hasNext() && !found) { + DXFViewport v = (DXFViewport) i.next(); + + if (v.isActive()) { + viewport = v; + found = true; + } + } + + if (viewport != null) { + double h = viewport.getHeight() / 2; + double w = (viewport.getHeight() * viewport.getAspectRatio()) / 2; + Bounds b = new Bounds(); + + // the upper right corner + b.addToBounds(viewport.getCenterPoint().getX() + w, + viewport.getCenterPoint().getY() + h, + viewport.getCenterPoint().getZ()); + + // the lower left corner + b.addToBounds(viewport.getCenterPoint().getX() - w, + viewport.getCenterPoint().getY() - h, + viewport.getCenterPoint().getZ()); + filterEntities(b, doc); + } + } + + protected void filterEntities(Bounds b, DXFDocument doc) { + Iterator i = doc.getDXFLayerIterator(); + + while (i.hasNext()) { + DXFLayer l = (DXFLayer) i.next(); + Iterator ti = l.getDXFEntityTypeIterator(); + + while (ti.hasNext()) { + String type = (String) ti.next(); + Iterator ei = l.getDXFEntities(type).iterator(); + + while (ei.hasNext()) { + DXFEntity entity = (DXFEntity) ei.next(); + Bounds currentBounds = entity.getBounds(); + + if (!b.contains(currentBounds)) { + ei.remove(); + } + } + } + } + } + + /* (non-Javadoc) + * @see org.kabeja.tools.PostProcessor#setProperties(java.util.Map) + */ + public void setProperties(Map properties) { + // TODO Auto-generated method stub + } +} diff --git a/dxf/src/main/java/org/kabeja/processing/VisibilityFilter.java b/dxf/src/main/java/org/kabeja/processing/VisibilityFilter.java new file mode 100644 index 0000000..e179256 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/processing/VisibilityFilter.java @@ -0,0 +1,71 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.processing; + +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.kabeja.dxf.DXFDocument; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.dxf.DXFLayer; + + +/** + * This postprocessor remove all invisible entities and layers. + * + * @author Simon Mieth + * + */ +public class VisibilityFilter extends AbstractPostProcessor { + /* (non-Javadoc) + * @see org.kabeja.tools.PostProcessor#process(org.kabeja.dxf.DXFDocument) + */ + public void process(DXFDocument doc, Map context) throws ProcessorException { + Iterator i = doc.getDXFLayerIterator(); + + while (i.hasNext()) { + DXFLayer l = (DXFLayer) i.next(); + + if (l.isVisible()) { + Iterator inner = l.getDXFEntityTypeIterator(); + + while (inner.hasNext()) { + String type = (String) inner.next(); + List entities = l.getDXFEntities(type); + Iterator ei = entities.iterator(); + + while (ei.hasNext()) { + DXFEntity entity = (DXFEntity) ei.next(); + + if (!entity.isVisibile()) { + ei.remove(); + } + } + } + } else { + i.remove(); + } + } + } + + /* (non-Javadoc) + * @see org.kabeja.tools.PostProcessor#setProperties(java.util.Map) + */ + public void setProperties(Map properties) { + // TODO Auto-generated method stub + } +} diff --git a/dxf/src/main/java/org/kabeja/processing/event/ProcessingEvent.java b/dxf/src/main/java/org/kabeja/processing/event/ProcessingEvent.java new file mode 100644 index 0000000..ed7e6a8 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/processing/event/ProcessingEvent.java @@ -0,0 +1,27 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.processing.event; + +import org.kabeja.processing.ProcessPipeline; + + +public class ProcessingEvent { + protected ProcessPipeline pipeline; + + public ProcessPipeline getProcessPipeline() { + return this.pipeline; + } +} diff --git a/dxf/src/main/java/org/kabeja/processing/event/ProcessingListener.java b/dxf/src/main/java/org/kabeja/processing/event/ProcessingListener.java new file mode 100644 index 0000000..b2781f7 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/processing/event/ProcessingListener.java @@ -0,0 +1,27 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.processing.event; + +import org.kabeja.processing.ProcessingManager; + + +public interface ProcessingListener { + public void startProcessig(ProcessingEvent e); + + public void endProcessing(ProcessingEvent e); + + public void configurationChanged(ProcessingManager mangager); +} diff --git a/dxf/src/main/java/org/kabeja/processing/helper/MergeMap.java b/dxf/src/main/java/org/kabeja/processing/helper/MergeMap.java new file mode 100644 index 0000000..be4c21e --- /dev/null +++ b/dxf/src/main/java/org/kabeja/processing/helper/MergeMap.java @@ -0,0 +1,95 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.processing.helper; + +import java.util.Collection; +import java.util.Map; +import java.util.Set; + + +public class MergeMap implements Map { + private Map base; + private Map override; + + public MergeMap(Map base, Map override) { + this.base = base; + this.override = override; + } + + public void clear() { + } + + public boolean containsKey(Object key) { + if (this.override.containsKey(key)) { + return true; + } else { + return this.base.containsKey(key); + } + } + + public boolean containsValue(Object value) { + if (this.override.containsValue(value)) { + return true; + } else { + return this.base.containsValue(value); + } + } + + public Set entrySet() { + return null; + } + + public Object get(Object key) { + Object obj = this.override.get(key); + + if (obj == null) { + obj = this.base.get(key); + } + + return obj; + } + + public boolean isEmpty() { + if (this.override.isEmpty()) { + return true; + } else { + return this.base.isEmpty(); + } + } + + public Set keySet() { + return null; + } + + public Object put(Object arg0, Object arg1) { + return null; + } + + public void putAll(Map arg0) { + } + + public Object remove(Object key) { + return null; + } + + public int size() { + return this.base.size(); + } + + public Collection values() { + return null; + } +} diff --git a/dxf/src/main/java/org/kabeja/processing/helper/PolylineQueue.java b/dxf/src/main/java/org/kabeja/processing/helper/PolylineQueue.java new file mode 100644 index 0000000..4a7f555 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/processing/helper/PolylineQueue.java @@ -0,0 +1,256 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.processing.helper; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.kabeja.dxf.DXFArc; +import org.kabeja.dxf.DXFConstants; +import org.kabeja.dxf.DXFEntity; +import org.kabeja.dxf.DXFLayer; +import org.kabeja.dxf.DXFLine; +import org.kabeja.dxf.DXFPolyline; +import org.kabeja.dxf.DXFVertex; +import org.kabeja.dxf.helpers.DXFUtils; +import org.kabeja.dxf.helpers.Point; + + +public class PolylineQueue { + private List elements = new ArrayList(); + private Point startPoint; + private Point endPoint; + private double radius = DXFConstants.POINT_CONNECTION_RADIUS; + + public PolylineQueue(DXFEntity e, Point start, Point end, double radius) { + this.elements.add(e); + this.startPoint = start; + this.endPoint = end; + this.radius = radius; + } + + public int size() { + return this.elements.size(); + } + + /** + * connect a DXF entity if possible. + * + * @param e + * @param start + * @param end + * @return true if the entity could be connected, otherwise false + */ + public boolean connectDXFEntity(DXFEntity e, Point start, Point end) { + if (DXFUtils.equals(this.startPoint, end, radius)) { + this.startPoint = start; + this.elements.add(0, e); + + return true; + } else if (DXFUtils.equals(this.endPoint, start, radius)) { + this.endPoint = end; + this.elements.add(e); + + return true; + } else if (DXFUtils.equals(this.startPoint, start, radius)) { + // we need to reverse then the entity + this.startPoint = end; + reverse(e); + this.elements.add(0, e); + + return true; + } else if (DXFUtils.equals(this.endPoint, end, radius)) { + // we need to reverse then the entity + this.endPoint = start; + reverse(e); + this.elements.add(e); + + return true; + } + + return false; + } + + public Point getStartPoint() { + return this.startPoint; + } + + public Point getEndPoint() { + return this.endPoint; + } + + public Iterator getElementIterator() { + return this.elements.iterator(); + } + + public boolean connect(PolylineQueue queue) { + if (DXFUtils.equals(queue.getStartPoint(), this.endPoint, radius)) { + // add to the end + add(queue); + + return true; + } else if (DXFUtils.equals(queue.getEndPoint(), this.startPoint, radius)) { + // insert before + insertBefore(queue); + + return true; + } else if (DXFUtils.equals(queue.getStartPoint(), this.startPoint, + radius)) { + queue.reverse(); + insertBefore(queue); + + return true; + } else if (DXFUtils.equals(queue.getEndPoint(), this.endPoint, radius)) { + queue.reverse(); + add(queue); + + return true; + } + + return false; + } + + public void createDXFPolyline(DXFLayer layer) { + // create the polyline and remove the entity + DXFPolyline pline = new DXFPolyline(); + DXFVertex first = new DXFVertex(this.startPoint); + pline.addVertex(first); + + Iterator i = this.elements.iterator(); + + while (i.hasNext()) { + DXFEntity e = (DXFEntity) i.next(); + + if (DXFConstants.ENTITY_TYPE_LINE.equals(e.getType())) { + DXFLine line = (DXFLine) e; + first = new DXFVertex(line.getEndPoint()); + pline.addVertex(first); + } else if (DXFConstants.ENTITY_TYPE_POLYLINE.equals(e.getType()) || + DXFConstants.ENTITY_TYPE_LWPOLYLINE.equals(e.getType())) { + DXFPolyline pl = (DXFPolyline) e; + double bulge = pl.getVertex(0).getBulge(); + + if (bulge != 0.0) { + first.setBulge(bulge); + } + + for (int x = 1; x < pl.getVertexCount(); x++) { + first = pl.getVertex(x); + pline.addVertex(first); + } + } else if (DXFConstants.ENTITY_TYPE_ARC.equals(e.getType())) { + DXFArc arc = (DXFArc) e; + + if (arc.getTotalAngle() > 0.0) { + double h = arc.getRadius() * (1 - + Math.cos(Math.toRadians(arc.getTotalAngle() / 2))); + double chordLength = arc.getChordLength(); + + if (DXFUtils.equals(arc.getStartPoint(), first.getPoint(), + radius)) { + // the last point is our start point, + // which is always set + // we have to calculate the bulge + first.setBulge((2 * h) / chordLength); + first = new DXFVertex(arc.getEndPoint()); + pline.addVertex(first); + } else { + // reverse the arc, we change the start/end points + // and set the bulge to >0 + first.setBulge(-1.0 * ((2 * h) / chordLength)); + + first = new DXFVertex(arc.getStartPoint()); + pline.addVertex(first); + } + } + } + + // remove from layer + layer.removeDXFEntity(e); + } + + // add the new polyline to the layer + pline.setLayerName(layer.getName()); + layer.addDXFEntity(pline); + } + + protected void reverse(DXFEntity entity) { + if (DXFConstants.ENTITY_TYPE_LINE.equals(entity.getType())) { + DXFUtils.reverseDXFLine((DXFLine) entity); + } else if (DXFConstants.ENTITY_TYPE_POLYLINE.equals(entity.getType()) || + DXFConstants.ENTITY_TYPE_LWPOLYLINE.equals(entity.getType())) { + DXFUtils.reverseDXFPolyline((DXFPolyline) entity); + } else if (DXFConstants.ENTITY_TYPE_ARC.equals(entity.getType())) { + // we cannot reverse a DXF ARC + } + } + + protected void reverse() { + Point p = this.endPoint; + this.endPoint = this.startPoint; + this.startPoint = p; + + // reverse the list and all entities + int last = this.elements.size() - 1; + + for (int i = 0; i < (last + 1); i++) { + DXFEntity first = (DXFEntity) this.elements.get(i); + this.reverse(first); + + if (i < last) { + DXFEntity e = (DXFEntity) this.elements.set(last, first); + this.reverse(e); + this.elements.set(i, e); + last--; + } + } + } + + /** + * Insert the PolylineQueue before the first element. + * + * @param queue + */ + public void insertBefore(PolylineQueue queue) { + this.startPoint = queue.getStartPoint(); + + Iterator i = queue.getElementIterator(); + int x = 0; + + while (i.hasNext()) { + DXFEntity e = (DXFEntity) i.next(); + this.elements.add(x, e); + x++; + } + } + + /** + * Adds the queue to the end. + * + * @param queue + */ + public void add(PolylineQueue queue) { + this.endPoint = queue.getEndPoint(); + + Iterator i = queue.getElementIterator(); + + while (i.hasNext()) { + DXFEntity e = (DXFEntity) i.next(); + this.elements.add(e); + } + } +} diff --git a/dxf/src/main/java/org/kabeja/tools/CodePageParser.java b/dxf/src/main/java/org/kabeja/tools/CodePageParser.java new file mode 100644 index 0000000..287ccd4 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/tools/CodePageParser.java @@ -0,0 +1,88 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.tools; + +import java.io.BufferedReader; +import java.io.IOException; + +import org.kabeja.dxf.DXFConstants; + + +/** + * @author Simon Mieth + * + */ +public class CodePageParser { + public static final String CODEPAGE_CODE = "$DWGCODEPAGE"; + public static final String GROUPCODE = "3"; + private static final String[] prefix = { "ansi_", "dos" }; + private static final String javaPrefix = "Cp"; + + public String parseEncoding(BufferedReader reader) { + String encoding = ""; + + try { + String line = null; + String code; + String value; + boolean next = true; + boolean codepage = false; + boolean key = true; + String currentKey = null; + + while (((line = reader.readLine()) != null) && next) { + line = line.trim(); + + if (key) { + currentKey = line; + key = false; + } else { + key = true; + + // we read the first section + if (DXFConstants.SECTION_END.equals(line)) { + return encoding; + } else if (CODEPAGE_CODE.equals(line)) { + codepage = true; + } else if (codepage && currentKey.equals("3")) { + // the encoding + return translateCodePage(line); + } else if (DXFConstants.SECTION_CLASSES.equals(line) || + DXFConstants.SECTION_BLOCKS.equals(line) || + DXFConstants.SECTION_ENTITIES.equals(line)) { + return encoding; + } + } + } + } catch (IOException e) { + e.printStackTrace(); + } + + return encoding; + } + + public String translateCodePage(String cp) { + String c = cp.toLowerCase(); + + for (int i = 0; i < prefix.length; i++) { + if (c.startsWith(prefix[i])) { + return javaPrefix + cp.substring(prefix[i].length()); + } + } + + return cp; + } +} diff --git a/dxf/src/main/java/org/kabeja/tools/ConfigHelper.java b/dxf/src/main/java/org/kabeja/tools/ConfigHelper.java new file mode 100644 index 0000000..b6afece --- /dev/null +++ b/dxf/src/main/java/org/kabeja/tools/ConfigHelper.java @@ -0,0 +1,60 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.tools; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParserFactory; + +import org.xml.sax.SAXException; +import org.xml.sax.XMLReader; +import org.xml.sax.helpers.XMLReaderFactory; + + +/** + * @author Simon Mieth + * + */ +public class ConfigHelper { + public static final String JAVA_14_SAX_DRIVER = "org.apache.crimson.parser.XMLReaderImpl"; + public static final String JAVA_15_SAX_DRIVER = "com.sun.org.apache.xerces.internal.parsers.SAXParser"; + + public static String getSAXSDDriver() { + // check for version 1.4 and above + String ver = System.getProperty("java.version"); + String parser = null; + + try { + parser = SAXParserFactory.newInstance().newSAXParser().getXMLReader() + .getClass().getName(); + + XMLReader r = XMLReaderFactory.createXMLReader(parser); + } catch (SAXException e) { + e.printStackTrace(); + } catch (ParserConfigurationException e) { + e.printStackTrace(); + } + + // if (ver.startsWith("1.2") || ver.startsWith("1.3")) { + // parser = System.getProperty("org.xml.sax.driver"); + // } else if (ver.startsWith("1.4")) { + // // jdk 1.4 uses crimson + // parser = JAVA_14_SAX_DRIVER; + // } else if (ver.startsWith("1.5")) { + // parser = JAVA_15_SAX_DRIVER; + // } + return parser; + } +} diff --git a/dxf/src/main/java/org/kabeja/tools/FontManager.java b/dxf/src/main/java/org/kabeja/tools/FontManager.java new file mode 100644 index 0000000..a2b678c --- /dev/null +++ b/dxf/src/main/java/org/kabeja/tools/FontManager.java @@ -0,0 +1,115 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.tools; + +import java.io.BufferedReader; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Hashtable; + + +/** + * @author Simon Mieth + * + */ +public class FontManager { + private static FontManager instance = new FontManager(); + private String fontDescription = "conf/font.properties"; + private Hashtable fontProperties = new Hashtable(); + + private FontManager() { + loadFontDescription(); + } + + public void setFontDescription(String file) { + this.fontDescription = file; + loadFontDescription(); + } + + private void loadFontDescription() { + fontProperties.clear(); + + try { + InputStream stream = this.getClass() + .getResourceAsStream(this.fontDescription); + + if (stream == null) { + try { + stream = new FileInputStream(this.fontDescription); + } catch (FileNotFoundException e1) { + } + } + + if (stream != null) { + BufferedReader in = new BufferedReader(new InputStreamReader( + stream)); + String line = null; + + while ((line = in.readLine()) != null) { + int index = line.indexOf("="); + + if (index >= 0) { + String font = line.substring(0, index).trim() + .toLowerCase(); + String svgFont = line.substring(index + 1).trim(); + fontProperties.put(font, svgFont); + } + } + } else { + // System.out.println("no font.properties"); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static FontManager getInstance() { + return instance; + } + + /** + * Query if a SVG font description exists for the given shx font. + * + * @param font + * The font.shx or font + * @return + */ + public boolean hasFontDescription(String font) { + font = getFontKey(font); + + if (fontProperties.containsKey(font)) { + return true; + } + + return false; + } + + public String getFontDescription(String font) { + return (String) fontProperties.get(getFontKey(font)); + } + + private String getFontKey(String font) { + font = font.toLowerCase(); + + if (font.endsWith(".shx")) { + font = font.substring(0, font.indexOf(".shx")); + } + + return font; + } +} diff --git a/dxf/src/main/java/org/kabeja/tools/SAXFilterConfig.java b/dxf/src/main/java/org/kabeja/tools/SAXFilterConfig.java new file mode 100644 index 0000000..a2f87cd --- /dev/null +++ b/dxf/src/main/java/org/kabeja/tools/SAXFilterConfig.java @@ -0,0 +1,59 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.tools; + +import java.util.HashMap; +import java.util.Map; + + +/** + * @author Simon Mieth + * + */ +public class SAXFilterConfig { + private Map properties; + private String filterName; + + public SAXFilterConfig(Map properties) { + this.properties = properties; + } + + public SAXFilterConfig() { + this(new HashMap()); + } + + public Map getProperties() { + return this.properties; + } + + public void addProperty(String name, String value) { + this.properties.put(name, value); + } + + /** + * @return Returns the filterName. + */ + public String getFilterName() { + return filterName; + } + + /** + * @param filterName The filterName to set. + */ + public void setFilterName(String filterName) { + this.filterName = filterName; + } +} diff --git a/dxf/src/main/java/org/kabeja/tools/SAXProcessingManagerBuilder.java b/dxf/src/main/java/org/kabeja/tools/SAXProcessingManagerBuilder.java new file mode 100644 index 0000000..7497b0c --- /dev/null +++ b/dxf/src/main/java/org/kabeja/tools/SAXProcessingManagerBuilder.java @@ -0,0 +1,358 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ +package org.kabeja.tools; + +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParserFactory; + +import org.kabeja.parser.Parser; +import org.kabeja.parser.SAXParserBuilder; +import org.kabeja.processing.PostProcessor; +import org.kabeja.processing.PostProcessorConfig; +import org.kabeja.processing.ProcessPipeline; +import org.kabeja.processing.ProcessingManager; +import org.kabeja.xml.AggregatorGenerator; +import org.kabeja.xml.SAXFilter; +import org.kabeja.xml.SAXGenerator; +import org.kabeja.xml.SAXSerializer; +import org.xml.sax.Attributes; +import org.xml.sax.ContentHandler; +import org.xml.sax.InputSource; +import org.xml.sax.Locator; +import org.xml.sax.SAXException; +import org.xml.sax.XMLReader; + +/** + * @author Simon Mieth + * + */ +public class SAXProcessingManagerBuilder implements ContentHandler { + public static String XMLNS_KABEJA_PROCESSING = "http://kabeja.org/processing/1.0"; + public static final String ELEMENT_CONFIGURATION = "configuration"; + public static final String ELEMENT_PARSER = "parser"; + public static final String ELEMENT_PARSERS = "parsers"; + public static final String ELEMENT_SAXSERIALIZER = "serializer"; + public static final String ELEMENT_SAXSERIALIZERS = "serializers"; + public static final String ELEMENT_SAXFILTER = "filter"; + public static final String ELEMENT_FILTER = "filter"; + public static final String ELEMENT_SAXFILTERS = "filters"; + public static final String ELEMENT_PIPELINE = "pipeline"; + public static final String ELEMENT_PIPELINES = "pipelines"; + public static final String ELEMENT_SERIALIZE = "serialize"; + public static final String ELEMENT_PROPERTY = "property"; + public static final String ELEMENT_POSTPROCESSOR = "postprocessor"; + public static final String ELEMENT_POSTPROCESS = "postprocess"; + public static final String ELEMENT_AGGREGATE = "aggregate"; + public static final String ELEMENT_SAXGENERATOR = "generator"; + public static final String ELEMENT_GENERATE = "generate"; + public static final String ATTRIBUTE_NAME = "name"; + public static final String ATTRIBUTE_CLASS = "class"; + public static final String ATTRIBUTE_VALUE = "value"; + public static final String ATTRIBUTE_DESCRIPTION = "description"; + private ProcessingManager manager; + private SAXFilter saxfilter; + private SAXSerializer saxserializer; + private PostProcessor postprocessor; + private SAXGenerator saxgenerator; + private AggregatorGenerator aggregator; + private Map properties; + private StringBuffer buf = new StringBuffer(); + private String name; + private ProcessPipeline pipeline; + private boolean config = false; + private boolean aggregate = false; + protected SAXParserBuilder parserBuilder; + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#characters(char[], int, int) + */ + public void characters(char[] ch, int start, int length) + throws SAXException { + } + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#endDocument() + */ + public void endDocument() throws SAXException { + } + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#endElement(java.lang.String, + * java.lang.String, java.lang.String) + */ + public void endElement(String namespaceURI, String localName, String qName) + throws SAXException { + if (namespaceURI.equals(XMLNS_KABEJA_PROCESSING)) { + if (ELEMENT_SAXFILTER.equals(localName) && this.config) { + this.saxfilter.setProperties(properties); + this.manager.addSAXFilter(this.saxfilter, this.name); + } else if (ELEMENT_SAXSERIALIZER.equals(localName)) { + this.saxserializer.setProperties(this.properties); + this.manager.addSAXSerializer(this.saxserializer, this.name); + } else if (ELEMENT_PIPELINE.equals(localName)) { + this.manager.addProcessPipeline(this.pipeline); + } else if (ELEMENT_SERIALIZE.equals(localName)) { + this.pipeline.setSAXSerializer(this.manager + .getSAXSerializer(this.name)); + + this.pipeline.setSAXSerializerProperties(this.properties); + } else if (ELEMENT_FILTER.equals(localName)) { + SAXFilterConfig config = new SAXFilterConfig(this.properties); + config.setFilterName(this.name); + this.pipeline.addSAXFilterConfig(config); + } else if (ELEMENT_POSTPROCESS.equals(localName)) { + PostProcessorConfig config = new PostProcessorConfig( + this.properties); + config.setPostProcessorName(this.name); + this.pipeline.addPostProcessorConfig(config); + } else if (ELEMENT_POSTPROCESSOR.equals(localName)) { + this.postprocessor.setProperties(this.properties); + this.manager.addPostProcessor(this.postprocessor, this.name); + } else if (ELEMENT_CONFIGURATION.equals(localName)) { + this.config = false; + } else if (ELEMENT_GENERATE.equals(localName)) { + if (this.aggregate) { + this.aggregator.addSAXGenerator(this.manager + .getSAXGenerator(this.name)); + } else { + this.pipeline.setSAXGeneratorProperties(this.properties); + this.pipeline.setSAXGenerator(this.manager + .getSAXGenerator(this.name)); + } + } else if (ELEMENT_SAXGENERATOR.equals(localName)) { + this.saxgenerator.setProperties(this.properties); + this.manager.addSAXGenerator(this.saxgenerator, this.name); + } + } else if (namespaceURI.equals(SAXParserBuilder.XMLNS_KABEJA_PARSER)) { + this.parserBuilder.endElement(namespaceURI, localName, qName); + + if (localName.equals(ELEMENT_PARSER)) { + // finish up the ParserBuilder and + // add the parse to ProcessManager + this.parserBuilder.endDocument(); + + Parser p = this.parserBuilder.getParser(); + this.manager.addParser(p); + } + } + } + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#endPrefixMapping(java.lang.String) + */ + public void endPrefixMapping(String prefix) throws SAXException { + } + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#ignorableWhitespace(char[], int, int) + */ + public void ignorableWhitespace(char[] ch, int start, int length) + throws SAXException { + } + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String, + * java.lang.String) + */ + public void processingInstruction(String target, String data) + throws SAXException { + } + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#setDocumentLocator(org.xml.sax.Locator) + */ + public void setDocumentLocator(Locator locator) { + } + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#skippedEntity(java.lang.String) + */ + public void skippedEntity(String name) throws SAXException { + } + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#startDocument() + */ + public void startDocument() throws SAXException { + manager = new ProcessingManager(); + } + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#startElement(java.lang.String, + * java.lang.String, java.lang.String, org.xml.sax.Attributes) + */ + public void startElement(String namespaceURI, String localName, + String qName, Attributes atts) throws SAXException { + if (namespaceURI.equals(XMLNS_KABEJA_PROCESSING)) { + if (ELEMENT_SAXFILTER.equals(localName) && this.config) { + this.properties = new HashMap(); + name = atts.getValue(ATTRIBUTE_NAME); + saxfilter = (SAXFilter) createInstance(atts + .getValue(ATTRIBUTE_CLASS)); + } else if (ELEMENT_SAXSERIALIZER.equals(localName)) { + this.properties = new HashMap(); + name = atts.getValue(ATTRIBUTE_NAME); + saxserializer = (SAXSerializer) createInstance(atts + .getValue(ATTRIBUTE_CLASS)); + } else if (ELEMENT_POSTPROCESSOR.equals(localName)) { + this.properties = new HashMap(); + this.name = atts.getValue(ATTRIBUTE_NAME); + + String clazz = (atts.getValue(ATTRIBUTE_CLASS)); + postprocessor = (PostProcessor) createInstance(clazz); + } else if (ELEMENT_PIPELINE.equals(localName)) { + this.aggregate = false; + this.pipeline = new ProcessPipeline(); + this.pipeline.setName(atts.getValue(ATTRIBUTE_NAME)); + String des = atts.getValue(ATTRIBUTE_DESCRIPTION); + if (des != null) { + this.pipeline.setDescription(des); + } + } else if (ELEMENT_SERIALIZE.equals(localName)) { + this.properties = new HashMap(); + this.name = atts.getValue(ATTRIBUTE_NAME); + } else if (ELEMENT_FILTER.equals(localName)) { + this.properties = new HashMap(); + name = atts.getValue(ATTRIBUTE_NAME); + } else if (ELEMENT_PROPERTY.equals(localName)) { + this.properties.put(atts.getValue(ATTRIBUTE_NAME), atts + .getValue(ATTRIBUTE_VALUE)); + } else if (ELEMENT_POSTPROCESS.equals(localName)) { + this.properties = new HashMap(); + name = atts.getValue(ATTRIBUTE_NAME); + } else if (ELEMENT_CONFIGURATION.equals(localName)) { + this.config = true; + } else if (ELEMENT_SAXGENERATOR.equals(localName)) { + this.properties = new HashMap(); + this.name = atts.getValue(ATTRIBUTE_NAME); + + String clazz = (atts.getValue(ATTRIBUTE_CLASS)); + this.saxgenerator = (SAXGenerator) createInstance(clazz); + } else if (ELEMENT_GENERATE.equals(localName)) { + this.properties = new HashMap(); + this.name = atts.getValue(ATTRIBUTE_NAME); + } else if (ELEMENT_AGGREGATE.equals(localName)) { + this.aggregate = true; + this.aggregator = new AggregatorGenerator(); + this.pipeline.setSAXGenerator(this.aggregator); + } + } else if (namespaceURI.equals(SAXParserBuilder.XMLNS_KABEJA_PARSER)) { + if (localName.equals(ELEMENT_PARSER)) { + this.parserBuilder = new SAXParserBuilder(); + this.parserBuilder.startDocument(); + } + + this.parserBuilder.startElement(namespaceURI, localName, qName, + atts); + } + } + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#startPrefixMapping(java.lang.String, + * java.lang.String) + */ + public void startPrefixMapping(String prefix, String uri) + throws SAXException { + } + + public ProcessingManager getManager() { + return this.manager; + } + + protected Object createInstance(String clazz) { + try { + Class cl = this.getClass().getClassLoader().loadClass(clazz); + Object obj = cl.newInstance(); + + return obj; + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } catch (InstantiationException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + + return null; + } + + /** + * + * @param in + * the InputStream + * @return The ProcessingManager build from the XML description + */ + public static ProcessingManager buildFromStream(InputStream in) { + SAXProcessingManagerBuilder builder = new SAXProcessingManagerBuilder(); + + try { + SAXParserFactory factory = SAXParserFactory.newInstance(); + factory.setNamespaceAware(true); + + // factory.setXIncludeAware(true); + try { + factory.setFeature("http://apache.org/xml/features/xinclude", + true); + } catch (Exception e) { + // OK older jaxp + System.out + .println("No XInclude support (use JAXP 1.4 or later for XInclude)"); + } + + try { + XMLReader saxparser = factory.newSAXParser().getXMLReader(); + + saxparser.setContentHandler(builder); + saxparser.parse(new InputSource(in)); + } catch (ParserConfigurationException e) { + e.printStackTrace(); + } + } catch (SAXException e) { + e.printStackTrace(); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + + return builder.getManager(); + } +} diff --git a/dxf/src/main/java/org/kabeja/tools/SAXSerializerConfig.java b/dxf/src/main/java/org/kabeja/tools/SAXSerializerConfig.java new file mode 100644 index 0000000..c27b477 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/tools/SAXSerializerConfig.java @@ -0,0 +1,51 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.tools; + +import java.util.HashMap; +import java.util.Map; + + +/** + * @author Simon Mieth + * + */ +public class SAXSerializerConfig { + private Map properties = new HashMap(); + private String saxSerializerName; + + public Map getProperties() { + return this.properties; + } + + public void addProperty(String name, String value) { + this.properties.put(name, value); + } + + /** + * @return Returns the filterName. + */ + public String getSAXSerializerName() { + return saxSerializerName; + } + + /** + * @param filterName The filterName to set. + */ + public void setSAXSerializerName(String filterName) { + this.saxSerializerName = filterName; + } +} diff --git a/dxf/src/main/java/org/kabeja/ui/Application.java b/dxf/src/main/java/org/kabeja/ui/Application.java new file mode 100644 index 0000000..a14e7b3 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/Application.java @@ -0,0 +1,35 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui; +/** + * Main application service for starting and stopping the + * application. + * @author Simon Mieth + * + */ +public interface Application extends Component{ + public final static String SERVICE = Application.class.getName(); + + /** + * Starts the application. + */ + public void start(); + + /** + * Stops the application + */ + public void stop(); +} diff --git a/dxf/src/main/java/org/kabeja/ui/ApplicationMenuBar.java b/dxf/src/main/java/org/kabeja/ui/ApplicationMenuBar.java new file mode 100644 index 0000000..80ea6f7 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/ApplicationMenuBar.java @@ -0,0 +1,42 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui; + +import javax.swing.Action; +import javax.swing.JMenu; +import javax.swing.JMenuItem; +/** + * Appliction menubar service provides access to the applications menubar. + * @author Simon Mieth + * + * + */ + +public interface ApplicationMenuBar { + public static final String SERVICE = ApplicationMenuBar.class.getName(); + public static final String MENU_ID_FILE = "menu.file"; + public static final String MENU_ID_VIEW = "menu.view"; + public static final String MENU_ID_EDIT = "menu.edit"; + public static final String MENU_ID_HELP = "menu.help"; + + public void setMenu(String menuID, JMenu menu); + + public boolean hasMenu(String id); + + public void setAction(String menuID, Action action); + + public void setJMenuItem(String menuID, JMenuItem item); +} diff --git a/dxf/src/main/java/org/kabeja/ui/ApplicationToolBar.java b/dxf/src/main/java/org/kabeja/ui/ApplicationToolBar.java new file mode 100644 index 0000000..7600879 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/ApplicationToolBar.java @@ -0,0 +1,32 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui; + +import javax.swing.Action; +/** + * Application toolbar service provides access to the application toolbar for + * components. + * @author Simon Mieth + * + */ + +public interface ApplicationToolBar { + public static final String SERVICE = ApplicationToolBar.class.getName(); + + public void addAction(Action action); + + public void addAction(java.awt.Component component); +} diff --git a/dxf/src/main/java/org/kabeja/ui/Component.java b/dxf/src/main/java/org/kabeja/ui/Component.java new file mode 100644 index 0000000..32ac22a --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/Component.java @@ -0,0 +1,24 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui; + +/** + * This is the base interface for every component in the application. + * @author Simon Mieth + * + */ +public interface Component { +} diff --git a/dxf/src/main/java/org/kabeja/ui/DXFDocumentViewComponent.java b/dxf/src/main/java/org/kabeja/ui/DXFDocumentViewComponent.java new file mode 100644 index 0000000..5881b1d --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/DXFDocumentViewComponent.java @@ -0,0 +1,48 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui; + +import javax.swing.JComponent; + +import org.kabeja.dxf.DXFDocument; + +/** + * A DXFDocumentViewComponent provides a view of the current DXFDocument. + * @author Simon Mieth + * + */ +public interface DXFDocumentViewComponent extends Component { + public static final String SERVICE = DXFDocumentViewComponent.class.getName(); + + /** + * + * @return the title of the component + */ + abstract String getTitle(); + + /** + * + * @return the view of this component + */ + abstract JComponent getView(); + + /** + * Show the DXFDocument in the view of this component + * @param doc + * @throws UIException + */ + abstract void showDXFDocument(DXFDocument doc) throws UIException; +} diff --git a/dxf/src/main/java/org/kabeja/ui/ProcessingUIComponent.java b/dxf/src/main/java/org/kabeja/ui/ProcessingUIComponent.java new file mode 100644 index 0000000..4a5a862 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/ProcessingUIComponent.java @@ -0,0 +1,33 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui; + +import org.kabeja.processing.ProcessingManager; +/** + * A ProcessingUIComponent gets access to the current Processing Manager of + * the application. + * @author Simon Mieth + * + */ + +public interface ProcessingUIComponent extends Component { + /** + * Set the current @see ProcessingManager of the application. + * Could be called multiple times. + * @param manager + */ + public void setProcessingManager(ProcessingManager manager); +} diff --git a/dxf/src/main/java/org/kabeja/ui/PropertiesEditor.java b/dxf/src/main/java/org/kabeja/ui/PropertiesEditor.java new file mode 100644 index 0000000..be30227 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/PropertiesEditor.java @@ -0,0 +1,48 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui; + +import java.util.Map; +/** + * A Properties Editor edits processing properties. + * + * @author Simon Mieth + * + */ + +public interface PropertiesEditor { + public static final String SERVICE = PropertiesEditor.class.getName(); + + /** + * Set the properties to edit. + * @param properties + */ + public void setProperties(Map properties); + + /** + * Returns the changed properties or properties provided by the properties editor. + * @return + */ + public Map getProperties(); + + /** + * + * @param listener + */ + public void addPropertiesListener(PropertiesListener listener); + + public void removePropertiesListener(PropertiesListener listener); +} diff --git a/dxf/src/main/java/org/kabeja/ui/PropertiesListener.java b/dxf/src/main/java/org/kabeja/ui/PropertiesListener.java new file mode 100644 index 0000000..6fc3737 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/PropertiesListener.java @@ -0,0 +1,31 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui; + +import java.util.Map; + +/** + * + * @author Simon Mieth + * + */ +public interface PropertiesListener { + /** + * Will be called every time the properties have changed + * @param properties changed Properties + */ + public void propertiesChanged(Map properties); +} diff --git a/dxf/src/main/java/org/kabeja/ui/ServiceManager.java b/dxf/src/main/java/org/kabeja/ui/ServiceManager.java new file mode 100644 index 0000000..2dde652 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/ServiceManager.java @@ -0,0 +1,32 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui; +/** + * The Service Manager provides access to services of the application. + * You can query the Service Manager for service. + * + * @author Simon Mieth + * + */ +public interface ServiceManager { + + /** + * + * @param service the searched service + * @return an array of Components which provides the service + */ + public Component[] getServiceComponents(String service); +} diff --git a/dxf/src/main/java/org/kabeja/ui/Serviceable.java b/dxf/src/main/java/org/kabeja/ui/Serviceable.java new file mode 100644 index 0000000..7b75496 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/Serviceable.java @@ -0,0 +1,29 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui; +/** + * A component which implement this interface get access to + * the services which are provided by this application. + * @author Simon Mieth + * + */ +public interface Serviceable { + /** + * Set the @see ServiceManager of the application. + * @param manager + */ + public void setServiceManager(ServiceManager manager); +} diff --git a/dxf/src/main/java/org/kabeja/ui/Startable.java b/dxf/src/main/java/org/kabeja/ui/Startable.java new file mode 100644 index 0000000..9bf5918 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/Startable.java @@ -0,0 +1,28 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui; +/** + * A Startable component will started at Application starts and stopped at the application stop. + * + * + * @author Simon Mieth + * + */ +public interface Startable extends Component { + public void start(); + + public void stop(); +} diff --git a/dxf/src/main/java/org/kabeja/ui/UIException.java b/dxf/src/main/java/org/kabeja/ui/UIException.java new file mode 100644 index 0000000..6f11a67 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/UIException.java @@ -0,0 +1,26 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui; + +public class UIException extends Exception { + public UIException(Exception e) { + super(e); + } + + public UIException(String message) { + super(message); + } +} diff --git a/dxf/src/main/java/org/kabeja/ui/ViewComponent.java b/dxf/src/main/java/org/kabeja/ui/ViewComponent.java new file mode 100644 index 0000000..32dc2b5 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/ViewComponent.java @@ -0,0 +1,39 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui; + +import javax.swing.JComponent; +/** + * A ViewComponent provides a view and title for the Processing. + * @author Simon Mieth + * + */ + +public interface ViewComponent extends ProcessingUIComponent { + public static final String SERVICE = ViewComponent.class.getName(); + + /** + * + * @return the title of the component + */ + abstract String getTitle(); + + /** + * + * @return the view of this component + */ + abstract JComponent getView(); +} diff --git a/dxf/src/main/java/org/kabeja/ui/event/DXFDocumentChangeEventProvider.java b/dxf/src/main/java/org/kabeja/ui/event/DXFDocumentChangeEventProvider.java new file mode 100644 index 0000000..7592a45 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/event/DXFDocumentChangeEventProvider.java @@ -0,0 +1,32 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui.event; + + +/** + * This component will fire a change or exchange of the DXFDocument + * to all listeners. + * @author simon + * + */ +public interface DXFDocumentChangeEventProvider { + public static final String SERVICE = DXFDocumentChangeEventProvider.class.getName(); + + public void addDXFDocumentChangeListener(DXFDocumentChangeListener listener); + + public void removeDXFDocumentChangeListener( + DXFDocumentChangeListener listener); +} diff --git a/dxf/src/main/java/org/kabeja/ui/event/DXFDocumentChangeListener.java b/dxf/src/main/java/org/kabeja/ui/event/DXFDocumentChangeListener.java new file mode 100644 index 0000000..99514ac --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/event/DXFDocumentChangeListener.java @@ -0,0 +1,34 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui.event; + +import org.kabeja.dxf.DXFDocument; + + +/** + * Interface for Listeners which want to receive changes on + * the DXFDocument. + * + * + */ +public interface DXFDocumentChangeListener { + /** + * Called if the DXFDocument is changed or parts are + * changed + * @param doc the changed or exchanged DXFDocument + */ + public void changed(DXFDocument doc); +} diff --git a/dxf/src/main/java/org/kabeja/ui/model/AbstractProcessingTreeNode.java b/dxf/src/main/java/org/kabeja/ui/model/AbstractProcessingTreeNode.java new file mode 100644 index 0000000..293dd93 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/model/AbstractProcessingTreeNode.java @@ -0,0 +1,93 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui.model; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Enumeration; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.swing.tree.TreeNode; + +import org.kabeja.processing.ProcessingManager; + + +public abstract class AbstractProcessingTreeNode implements TreeNode { + protected ProcessingManager manager; + protected TreeNode parent; + protected List children = new ArrayList(); + protected String label; + + public AbstractProcessingTreeNode(TreeNode parent, String label) { + this.parent = parent; + this.label = label; + } + + public void setProcessorManager(ProcessingManager manager) { + this.manager = manager; + this.initializeChildren(); + } + + public TreeNode getParent() { + return parent; + } + + protected void addChild(AbstractProcessingTreeNode child) { + child.setProcessorManager(this.manager); + this.children.add(child); + } + + public int getChildCount() { + return this.children.size(); + } + + public int getIndex(TreeNode node) { + return this.children.indexOf(node); + } + + public TreeNode getChildAt(int childIndex) { + return (TreeNode) this.children.get(childIndex); + } + + public Enumeration children() { + return Collections.enumeration(this.children); + } + + protected abstract void initializeChildren(); + + public String toString() { + return this.getLabel(); + } + + protected void propertiesToChildren(Map properties) { + if (properties == null) { + System.out.println("huuuuuuuuu=" + getClass()); + } + + Iterator i = properties.keySet().iterator(); + + while (i.hasNext()) { + this.addChild(new PropertyTreeNode(this, properties, + (String) i.next())); + } + } + + protected String getLabel() { + return this.label; + } +} diff --git a/dxf/src/main/java/org/kabeja/ui/model/ParserTreeNode.java b/dxf/src/main/java/org/kabeja/ui/model/ParserTreeNode.java new file mode 100644 index 0000000..d9b574e --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/model/ParserTreeNode.java @@ -0,0 +1,47 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui.model; + +import javax.swing.tree.TreeNode; + +import org.kabeja.parser.Parser; + + +public class ParserTreeNode extends AbstractProcessingTreeNode { + protected Parser parser; + + public ParserTreeNode(TreeNode parent, Parser parser) { + super(parent, parser.getName()); + + this.parser = parser; + } + + protected String getLabel() { + // TODO Auto-generated method stub + return parser.getName(); + } + + protected void initializeChildren() { + } + + public boolean getAllowsChildren() { + return false; + } + + public boolean isLeaf() { + return true; + } +} diff --git a/dxf/src/main/java/org/kabeja/ui/model/ParsersTreeNode.java b/dxf/src/main/java/org/kabeja/ui/model/ParsersTreeNode.java new file mode 100644 index 0000000..8ecd26f --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/model/ParsersTreeNode.java @@ -0,0 +1,48 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui.model; + +import java.util.Iterator; + +import javax.swing.tree.TreeNode; + +import org.kabeja.parser.Parser; + + +public class ParsersTreeNode extends AbstractProcessingTreeNode { + public static String LABEL = "Parsers"; + + public ParsersTreeNode(TreeNode parent) { + super(parent, LABEL); + } + + public boolean getAllowsChildren() { + return true; + } + + public boolean isLeaf() { + return false; + } + + protected void initializeChildren() { + Iterator i = this.manager.getParsers().iterator(); + + while (i.hasNext()) { + ParserTreeNode ptn = new ParserTreeNode(this, (Parser) i.next()); + this.addChild(ptn); + } + } +} diff --git a/dxf/src/main/java/org/kabeja/ui/model/PipelineTreeNode.java b/dxf/src/main/java/org/kabeja/ui/model/PipelineTreeNode.java new file mode 100644 index 0000000..ae5527f --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/model/PipelineTreeNode.java @@ -0,0 +1,42 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui.model; + +import javax.swing.tree.TreeNode; + +import org.kabeja.processing.ProcessPipeline; + + +public class PipelineTreeNode extends AbstractProcessingTreeNode { + protected ProcessPipeline pipeline; + + public PipelineTreeNode(TreeNode parent, ProcessPipeline pipeline, + String label) { + super(parent, label); + this.pipeline = pipeline; + } + + protected void initializeChildren() { + } + + public boolean getAllowsChildren() { + return false; + } + + public boolean isLeaf() { + return false; + } +} diff --git a/dxf/src/main/java/org/kabeja/ui/model/PipelinesTreeNode.java b/dxf/src/main/java/org/kabeja/ui/model/PipelinesTreeNode.java new file mode 100644 index 0000000..d2668ba --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/model/PipelinesTreeNode.java @@ -0,0 +1,48 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui.model; + +import java.util.Iterator; + +import javax.swing.tree.TreeNode; + + +public class PipelinesTreeNode extends AbstractProcessingTreeNode { + public final static String LABEL = "Pipelines"; + + public PipelinesTreeNode(TreeNode parent) { + super(parent, LABEL); + } + + protected void initializeChildren() { + Iterator i = this.manager.getProcessPipelines().keySet().iterator(); + + while (i.hasNext()) { + String key = (String) i.next(); + PipelineTreeNode node = new PipelineTreeNode(this, + this.manager.getProcessPipeline(key), key); + this.addChild(node); + } + } + + public boolean getAllowsChildren() { + return false; + } + + public boolean isLeaf() { + return false; + } +} diff --git a/dxf/src/main/java/org/kabeja/ui/model/PostProcessorTreeNode.java b/dxf/src/main/java/org/kabeja/ui/model/PostProcessorTreeNode.java new file mode 100644 index 0000000..745cc43 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/model/PostProcessorTreeNode.java @@ -0,0 +1,42 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui.model; + +import javax.swing.tree.TreeNode; + +import org.kabeja.processing.PostProcessor; + + +public class PostProcessorTreeNode extends AbstractProcessingTreeNode { + protected PostProcessor pp; + + public PostProcessorTreeNode(TreeNode parent, PostProcessor pp, String label) { + super(parent, label); + this.pp = pp; + } + + protected void initializeChildren() { + this.propertiesToChildren(this.pp.getProperties()); + } + + public boolean getAllowsChildren() { + return true; + } + + public boolean isLeaf() { + return this.pp.getProperties().size() > 0; + } +} diff --git a/dxf/src/main/java/org/kabeja/ui/model/PostProcessorsTreeNode.java b/dxf/src/main/java/org/kabeja/ui/model/PostProcessorsTreeNode.java new file mode 100644 index 0000000..1070ae1 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/model/PostProcessorsTreeNode.java @@ -0,0 +1,48 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui.model; + +import java.util.Iterator; + +import javax.swing.tree.TreeNode; + + +public class PostProcessorsTreeNode extends AbstractProcessingTreeNode { + public final static String LABEL = "PostProcessors"; + + public PostProcessorsTreeNode(TreeNode parent) { + super(parent, LABEL); + } + + protected void initializeChildren() { + Iterator i = this.manager.getPostProcessors().keySet().iterator(); + + while (i.hasNext()) { + String key = (String) i.next(); + PostProcessorTreeNode node = new PostProcessorTreeNode(this, + this.manager.getPostProcessor(key), key); + this.addChild(node); + } + } + + public boolean getAllowsChildren() { + return true; + } + + public boolean isLeaf() { + return false; + } +} diff --git a/dxf/src/main/java/org/kabeja/ui/model/ProcessingTreeModelPresenter.java b/dxf/src/main/java/org/kabeja/ui/model/ProcessingTreeModelPresenter.java new file mode 100644 index 0000000..92c02cc --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/model/ProcessingTreeModelPresenter.java @@ -0,0 +1,104 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui.model; + +import java.util.ArrayList; +import java.util.List; + +import javax.swing.event.TreeModelListener; +import javax.swing.tree.TreeModel; +import javax.swing.tree.TreePath; + +import org.kabeja.processing.ProcessingManager; + + +public class ProcessingTreeModelPresenter extends AbstractProcessingTreeNode + implements TreeModel { + protected List listeners = new ArrayList(); + + public ProcessingTreeModelPresenter(ProcessingManager manager) { + super(null, "ProcessManager"); + this.setProcessorManager(manager); + } + + public boolean isLeaf() { + return false; + } + + protected void initializeChildren() { + AbstractProcessingTreeNode node = new ParsersTreeNode(this); + addChild(node); + + node = new SAXGeneratorsTreeNode(this); + addChild(node); + + node = new PostProcessorsTreeNode(this); + addChild(node); + + node = new SAXFiltersTreeNode(this); + addChild(node); + + node = new SAXSerializersTreeNode(this); + addChild(node); + node = new PipelinesTreeNode(this); + addChild(node); + } + + public boolean getAllowsChildren() { + return false; + } + + public void addTreeModelListener(TreeModelListener l) { + this.listeners.add(l); + } + + public Object getChild(Object parent, int index) { + //delegate to nodes + AbstractProcessingTreeNode node = (AbstractProcessingTreeNode) parent; + + return node.getChildAt(index); + } + + public int getChildCount(Object parent) { + AbstractProcessingTreeNode node = (AbstractProcessingTreeNode) parent; + + return node.getChildCount(); + } + + public int getIndexOfChild(Object parent, Object child) { + AbstractProcessingTreeNode node = (AbstractProcessingTreeNode) parent; + + return node.getIndex((AbstractProcessingTreeNode) child); + } + + public Object getRoot() { + return this; + } + + public boolean isLeaf(Object obj) { + AbstractProcessingTreeNode node = (AbstractProcessingTreeNode) obj; + + return node.isLeaf(); + } + + public void removeTreeModelListener(TreeModelListener l) { + this.listeners.remove(l); + } + + public void valueForPathChanged(TreePath path, Object newValue) { + System.out.println("Changed path=" + path); + } +} diff --git a/dxf/src/main/java/org/kabeja/ui/model/PropertiesTreeNode.java b/dxf/src/main/java/org/kabeja/ui/model/PropertiesTreeNode.java new file mode 100644 index 0000000..eeaf15d --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/model/PropertiesTreeNode.java @@ -0,0 +1,49 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui.model; + +import java.util.Iterator; +import java.util.Map; + +import javax.swing.tree.TreeNode; + + +public class PropertiesTreeNode extends AbstractProcessingTreeNode { + protected final static String LABEL = "Properties"; + protected Map properties; + + public PropertiesTreeNode(TreeNode parent, Map properties) { + super(parent, LABEL); + this.properties = properties; + } + + protected void initializeChildren() { + Iterator i = this.properties.keySet().iterator(); + + while (i.hasNext()) { + this.addChild(new PropertyTreeNode(this, properties, + (String) i.next())); + } + } + + public boolean getAllowsChildren() { + return false; + } + + public boolean isLeaf() { + return false; + } +} diff --git a/dxf/src/main/java/org/kabeja/ui/model/PropertyTreeNode.java b/dxf/src/main/java/org/kabeja/ui/model/PropertyTreeNode.java new file mode 100644 index 0000000..e91dbed --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/model/PropertyTreeNode.java @@ -0,0 +1,48 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui.model; + +import java.util.Map; + +import javax.swing.tree.TreeNode; + + +public class PropertyTreeNode extends AbstractProcessingTreeNode { + protected Map properties; + protected String propertyKey; + + public PropertyTreeNode(TreeNode parent, Map properties, String propertyKey) { + super(parent, propertyKey + "=" + properties.get(propertyKey)); + + this.properties = properties; + this.propertyKey = propertyKey; + } + + protected String getLabel() { + return this.propertyKey + "=" + this.properties.get(this.propertyKey); + } + + protected void initializeChildren() { + } + + public boolean getAllowsChildren() { + return false; + } + + public boolean isLeaf() { + return true; + } +} diff --git a/dxf/src/main/java/org/kabeja/ui/model/SAXFilterTreeNode.java b/dxf/src/main/java/org/kabeja/ui/model/SAXFilterTreeNode.java new file mode 100644 index 0000000..2d106fe --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/model/SAXFilterTreeNode.java @@ -0,0 +1,44 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui.model; + +import javax.swing.tree.TreeNode; + +import org.kabeja.xml.SAXFilter; + + +public class SAXFilterTreeNode extends AbstractProcessingTreeNode { + protected SAXFilter filter; + protected String label; + + public SAXFilterTreeNode(TreeNode parent, SAXFilter filter, String label) { + super(parent, label); + + this.filter = filter; + } + + protected void initializeChildren() { + this.propertiesToChildren(filter.getProperties()); + } + + public boolean getAllowsChildren() { + return false; + } + + public boolean isLeaf() { + return false; + } +} diff --git a/dxf/src/main/java/org/kabeja/ui/model/SAXFiltersTreeNode.java b/dxf/src/main/java/org/kabeja/ui/model/SAXFiltersTreeNode.java new file mode 100644 index 0000000..701c8ce --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/model/SAXFiltersTreeNode.java @@ -0,0 +1,47 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui.model; + +import java.util.Iterator; + +import javax.swing.tree.TreeNode; + + +public class SAXFiltersTreeNode extends AbstractProcessingTreeNode { + protected final static String LABEL = "SAXFilters"; + + public SAXFiltersTreeNode(TreeNode parent) { + super(parent, LABEL); + } + + protected void initializeChildren() { + Iterator i = this.manager.getSAXFilters().keySet().iterator(); + + while (i.hasNext()) { + String key = (String) i.next(); + this.addChild(new SAXFilterTreeNode(this, + this.manager.getSAXFilter(key), key)); + } + } + + public boolean getAllowsChildren() { + return true; + } + + public boolean isLeaf() { + return false; + } +} diff --git a/dxf/src/main/java/org/kabeja/ui/model/SAXGeneratorTreeNode.java b/dxf/src/main/java/org/kabeja/ui/model/SAXGeneratorTreeNode.java new file mode 100644 index 0000000..e8f2c9e --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/model/SAXGeneratorTreeNode.java @@ -0,0 +1,62 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui.model; + +import java.util.Iterator; + +import javax.swing.tree.TreeNode; + +import org.kabeja.xml.SAXGenerator; + + +public class SAXGeneratorTreeNode extends AbstractProcessingTreeNode { + protected SAXGenerator generator; + protected String label; + + public SAXGeneratorTreeNode(TreeNode parent, SAXGenerator generator, + String label) { + super(parent, label); + this.generator = generator; + } + + protected void initializeChildren() { + this.propertiesToChildren(this.generator.getProperties()); + } + + protected String findLabel() { + Iterator i = manager.getSAXGenerators().keySet().iterator(); + + while (i.hasNext()) { + String key = (String) i.next(); + + if (this.manager.getSAXGenerator(key) == this.generator) { + return key; + } + } + + return null; + } + + public boolean getAllowsChildren() { + // TODO Auto-generated method stub + return false; + } + + public boolean isLeaf() { + // TODO Auto-generated method stub + return false; + } +} diff --git a/dxf/src/main/java/org/kabeja/ui/model/SAXGeneratorsTreeNode.java b/dxf/src/main/java/org/kabeja/ui/model/SAXGeneratorsTreeNode.java new file mode 100644 index 0000000..e63f57b --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/model/SAXGeneratorsTreeNode.java @@ -0,0 +1,48 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui.model; + +import java.util.Iterator; + +import javax.swing.tree.TreeNode; + + +public class SAXGeneratorsTreeNode extends AbstractProcessingTreeNode { + protected final static String LABEL = "SAXSerializers"; + + public SAXGeneratorsTreeNode(TreeNode parent) { + super(parent, LABEL); + } + + protected void initializeChildren() { + Iterator i = this.manager.getSAXGenerators().keySet().iterator(); + + while (i.hasNext()) { + String key = (String) i.next(); + SAXGeneratorTreeNode node = new SAXGeneratorTreeNode(this, + this.manager.getSAXGenerator(key), key); + this.addChild(node); + } + } + + public boolean getAllowsChildren() { + return true; + } + + public boolean isLeaf() { + return false; + } +} diff --git a/dxf/src/main/java/org/kabeja/ui/model/SAXSerializerTreeNode.java b/dxf/src/main/java/org/kabeja/ui/model/SAXSerializerTreeNode.java new file mode 100644 index 0000000..b9220e9 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/model/SAXSerializerTreeNode.java @@ -0,0 +1,42 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui.model; + +import javax.swing.tree.TreeNode; + +import org.kabeja.xml.SAXSerializer; + + +public class SAXSerializerTreeNode extends AbstractProcessingTreeNode { + protected SAXSerializer serializer; + + public SAXSerializerTreeNode(TreeNode parent, SAXSerializer serializer, + String label) { + super(parent, label); + this.serializer = serializer; + } + + protected void initializeChildren() { + } + + public boolean getAllowsChildren() { + return true; + } + + public boolean isLeaf() { + return false; + } +} diff --git a/dxf/src/main/java/org/kabeja/ui/model/SAXSerializersTreeNode.java b/dxf/src/main/java/org/kabeja/ui/model/SAXSerializersTreeNode.java new file mode 100644 index 0000000..88e070b --- /dev/null +++ b/dxf/src/main/java/org/kabeja/ui/model/SAXSerializersTreeNode.java @@ -0,0 +1,50 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.ui.model; + +import java.util.Iterator; + +import javax.swing.tree.TreeNode; + + +public class SAXSerializersTreeNode extends AbstractProcessingTreeNode { + public final static String LABEL = "SAXSerializers"; + + public SAXSerializersTreeNode(TreeNode parent) { + super(parent, LABEL); + } + + protected void initializeChildren() { + Iterator i = this.manager.getSAXSerializers().keySet().iterator(); + + while (i.hasNext()) { + String key = (String) i.next(); + SAXSerializerTreeNode node = new SAXSerializerTreeNode(this, + this.manager.getSAXSerializer(key), key); + this.addChild(node); + } + } + + public boolean getAllowsChildren() { + // TODO Auto-generated method stub + return false; + } + + public boolean isLeaf() { + // TODO Auto-generated method stub + return false; + } +} diff --git a/dxf/src/main/java/org/kabeja/xml/AbstractSAXFilter.java b/dxf/src/main/java/org/kabeja/xml/AbstractSAXFilter.java new file mode 100644 index 0000000..0789c6d --- /dev/null +++ b/dxf/src/main/java/org/kabeja/xml/AbstractSAXFilter.java @@ -0,0 +1,42 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.xml; + +import java.util.HashMap; +import java.util.Map; + +import org.xml.sax.helpers.XMLFilterImpl; + + +/** + * @author Simon Mieth + * + */ +public abstract class AbstractSAXFilter extends XMLFilterImpl + implements SAXFilter { + protected Map properties = new HashMap(); + + /* (non-Javadoc) + * @see org.kabeja.xml.SAXFilter#setProperties(java.util.Map) + */ + public void setProperties(Map properties) { + this.properties = properties; + } + + public Map getProperties() { + return this.properties; + } +} diff --git a/dxf/src/main/java/org/kabeja/xml/AbstractSAXGenerator.java b/dxf/src/main/java/org/kabeja/xml/AbstractSAXGenerator.java new file mode 100644 index 0000000..a0299f6 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/xml/AbstractSAXGenerator.java @@ -0,0 +1,47 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.xml; + +import java.util.Map; + +import org.kabeja.dxf.DXFDocument; +import org.kabeja.processing.AbstractConfigurable; +import org.xml.sax.ContentHandler; +import org.xml.sax.SAXException; + + +public abstract class AbstractSAXGenerator extends AbstractConfigurable + implements SAXGenerator { + protected DXFDocument doc; + protected ContentHandler handler; + protected Map context; + + public void generate(DXFDocument doc, ContentHandler handler, Map context) + throws SAXException { + this.doc = doc; + this.handler = handler; + this.context = context; + this.generate(); + } + + /** + * This method has to be overwritten by any subclass. At this point the + * XMLGenerator is setup (properties, ContentHandler and DXFDocument) and + * should emit the XML content to the ContentHandler. + * + */ + protected abstract void generate() throws SAXException; +} diff --git a/dxf/src/main/java/org/kabeja/xml/AbstractSAXSerializer.java b/dxf/src/main/java/org/kabeja/xml/AbstractSAXSerializer.java new file mode 100644 index 0000000..8efed98 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/xml/AbstractSAXSerializer.java @@ -0,0 +1,22 @@ +/* + Copyright 2008 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.xml; + +import org.kabeja.processing.AbstractConfigurable; + + +public abstract class AbstractSAXSerializer extends AbstractConfigurable { +} diff --git a/dxf/src/main/java/org/kabeja/xml/AggregatorGenerator.java b/dxf/src/main/java/org/kabeja/xml/AggregatorGenerator.java new file mode 100644 index 0000000..8c0e2d0 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/xml/AggregatorGenerator.java @@ -0,0 +1,79 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.xml; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.kabeja.dxf.DXFDocument; +import org.xml.sax.ContentHandler; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + + +public class AggregatorGenerator extends AbstractSAXFilter + implements SAXGenerator { + public final static String ROOT_ELEMENT = "aggregate"; + public final static String NAMESPACE = "http://kabeja.org/aggregate"; + protected List generators = new ArrayList(); + protected DXFDocument doc; + + public void generate(DXFDocument doc, ContentHandler handler, Map context) + throws SAXException { + this.setContentHandler(handler); + this.doc = doc; + + try { + handler.startDocument(); + + String raw = NAMESPACE + ":" + ROOT_ELEMENT; + handler.startElement(NAMESPACE, raw, ROOT_ELEMENT, + new AttributesImpl()); + doGenerate(); + handler.endElement(NAMESPACE, raw, ROOT_ELEMENT); + handler.endDocument(); + } catch (SAXException e) { + e.printStackTrace(); + } + } + + protected void doGenerate() throws SAXException { + Iterator i = this.generators.iterator(); + + while (i.hasNext()) { + SAXGenerator generator = (SAXGenerator) i.next(); + generator.generate(this.doc, this, null); + } + } + + public void endDocument() throws SAXException { + // ignore + } + + public void startDocument() throws SAXException { + // ignore + } + + public void addSAXGenerator(SAXGenerator generator) { + this.generators.add(generator); + } + + public Map getProperties() { + return this.properties; + } +} diff --git a/dxf/src/main/java/org/kabeja/xml/ConsoleSerializer.java b/dxf/src/main/java/org/kabeja/xml/ConsoleSerializer.java new file mode 100644 index 0000000..b5e7ed5 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/xml/ConsoleSerializer.java @@ -0,0 +1,22 @@ +/* + * Created on 28.11.2005 + * + */ +package org.kabeja.xml; + +import java.io.OutputStream; + + +/** + * @author simon + * + */ +public class ConsoleSerializer extends SAXPrettyOutputter { + /* (non-Javadoc) + * @see org.kabeja.xml.SAXSerializer#setOutput(java.io.OutputStream) + */ + public void setOutput(OutputStream out) { + //switch output to console + super.setOutput(System.out); + } +} diff --git a/dxf/src/main/java/org/kabeja/xml/SAXFilter.java b/dxf/src/main/java/org/kabeja/xml/SAXFilter.java new file mode 100644 index 0000000..e0aa1e6 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/xml/SAXFilter.java @@ -0,0 +1,31 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.xml; + +import org.kabeja.processing.Configurable; +import org.xml.sax.ContentHandler; + + +/** + * A SAXFilter consumes SAX events and passes SAX event to the next + * org.xml.sax.ContentHandler. + * + * @author Simon Mieth + * + */ +public interface SAXFilter extends ContentHandler, Configurable { + public void setContentHandler(ContentHandler handler); +} diff --git a/dxf/src/main/java/org/kabeja/xml/SAXGenerator.java b/dxf/src/main/java/org/kabeja/xml/SAXGenerator.java new file mode 100644 index 0000000..c8ab350 --- /dev/null +++ b/dxf/src/main/java/org/kabeja/xml/SAXGenerator.java @@ -0,0 +1,42 @@ +/* + Copyright 2006 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.xml; + +import java.util.Map; + +import org.kabeja.dxf.DXFDocument; +import org.kabeja.processing.Configurable; +import org.xml.sax.ContentHandler; +import org.xml.sax.SAXException; + + +/** + * This interface describes a generator component, which emit convert the + * DXFDocument to SAX-Event. + *

      Lifecycle

      + * + *
        + *
      1. setProperties
      2. + *
      3. generate(DXFDocument doc,ConentHandler handler)
      4. + *
      + * + * @author simon.mieth + * + */ +public interface SAXGenerator extends Configurable { + public void generate(DXFDocument doc, ContentHandler handler, Map context) + throws SAXException; +} diff --git a/dxf/src/main/java/org/kabeja/xml/SAXPrettyOutputter.java b/dxf/src/main/java/org/kabeja/xml/SAXPrettyOutputter.java new file mode 100644 index 0000000..51b98cf --- /dev/null +++ b/dxf/src/main/java/org/kabeja/xml/SAXPrettyOutputter.java @@ -0,0 +1,340 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.xml; + +import java.io.BufferedOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.zip.GZIPOutputStream; + +import org.xml.sax.Attributes; +import org.xml.sax.Locator; +import org.xml.sax.SAXException; + + +/** + *

      + * This outputs a SAXStream to an OutputStream with the given encoding or + * otherwise with the default encoding (utf-8). + *

      + *

      + * Note: Not all features are implemented, so if you use this with other + * SAXStreams others then the Kabeja-SAXStream you will get broken + * XML-Documents. + *

      + * + * @author Simon Mieth + * + */ +public class SAXPrettyOutputter extends AbstractSAXSerializer + implements SAXSerializer { + public static final String DEFAULT_ENCODING = "UTF-8"; + public static final String SUFFIX = "svg"; + public static final String SUFFIX_GZIP = "svgz"; + public static final String MIMETYPE = "text/svg"; + public static final String PROPERTY_ENCODING = "encoding"; + public static final String PROPERTY_GZIP = "gzip"; + private OutputStreamWriter out; + private String encoding; + private String dtd; + private int indent = 0; + private boolean parent = false; + private ArrayList textContentList = new ArrayList(); + protected HashMap rootxmlns = new HashMap(); + protected boolean gzip = false; + + public SAXPrettyOutputter(OutputStream output, String encoding) { + this.encoding = encoding; + this.setOutput(output); + } + + /** + * + */ + public SAXPrettyOutputter(OutputStream out) { + this(out, DEFAULT_ENCODING); + } + + public SAXPrettyOutputter() { + this.encoding = DEFAULT_ENCODING; + } + + public void characters(char[] ch, int start, int length) + throws SAXException { + try { + if (length > 0) { + if (parent) { + this.out.write(">"); + parent = false; + } + + char[] enc = encodeXML(new String(ch, 0, length)).toCharArray(); + this.out.write(enc, start, enc.length); + + // textNode in this context + textContentList.set(textContentList.size() - 1, + new Boolean(true)); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void endDocument() throws SAXException { + try { + this.out.flush(); + this.out.close(); + + textContentList.clear(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void endElement(String namespaceURI, String localName, String qName) + throws SAXException { + try { + if (parent) { + this.out.write("/>"); + } else { + // check for textNodes in this context + Boolean b = (Boolean) textContentList.remove(textContentList.size() - + 1); + + if (b.booleanValue()) { + this.out.write(""); + } else { + // there was no textNode we can create a new line + this.out.write('\n'); + indentOutput(indent); + this.out.write(""); + } + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + indent--; + parent = false; + } + + public void endPrefixMapping(String prefix) throws SAXException { + } + + public void ignorableWhitespace(char[] ch, int start, int length) + throws SAXException { + } + + public void processingInstruction(String target, String data) + throws SAXException { + } + + public void setDocumentLocator(Locator locator) { + } + + public void skippedEntity(String name) throws SAXException { + } + + public void startDocument() throws SAXException { + indent = 0; + + try { + this.out.write(""); + + if (this.dtd != null) { + this.out.write("\n"); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void startElement(String namespaceURI, String localName, + String qName, Attributes atts) throws SAXException { + this.indent++; + + try { + if (this.parent) { + // we are nested + this.out.write(">"); + } else { + this.parent = true; + } + + // first create a new line + this.out.write('\n'); + + // indent the line + this.indentOutput(indent); + + // the element + this.out.write("<" + qName); + + int attrCount = atts.getLength(); + + for (int i = 0; i < attrCount; i++) { + //we need a white space between the + //attributes + this.indentOutput(1); + + String uri = atts.getURI(i); + String qname = atts.getQName(i); + + // if (uri.length() > 0) { + // String prefix = qname.substring(0, qname.indexOf(':')); + // out + // .write(" xmlns:" + prefix + "=\"" + uri + // + "\" "); + // } + String value = atts.getValue(i); + if(value == null){ + value=""; + } + this.out.write(qname + "=\"" + encodeXML(atts.getValue(i)) + + "\""); + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + // no text in this context now + this.textContentList.add(Boolean.valueOf(false)); + } + + public void startPrefixMapping(String prefix, String uri) + throws SAXException { + } + + /** + * Indent the output + * + * @param indentSize + */ + private void indentOutput(int indentSize) { + try { + for (int i = 0; i < indentSize; i++) { + this.out.write(' '); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static String encodeXML(String text) { + int length = text.length(); + StringBuffer work = new StringBuffer(length); + + for (int i = 0; i < length; i++) { + char c = text.charAt(i); + + if (c == '&') { + work.append("&"); + } else if (c == '<') { + work.append("<"); + } else if (c == '>') { + work.append(">"); + } else if (!Character.isIdentifierIgnorable(c)) { + work.append(c); + } + } + + return work.toString(); + } + + public void setDTD(String dtd) { + this.dtd = dtd; + } + + protected void queryXMLNS(Attributes atts) { + for (int i = 0; i < atts.getLength(); i++) { + String qname = atts.getQName(i); + + if (qname.startsWith("xmlns:")) { + String prefix = atts.getLocalName(i); + String uri = atts.getValue(i); + rootxmlns.put(uri, prefix); + } + } + } + + /* + * (non-Javadoc) + * + * @see org.kabeja.xml.SAXSerializer#getMimeType() + */ + public String getMimeType() { + return MIMETYPE; + } + + /* + * (non-Javadoc) + * + * @see org.kabeja.xml.SAXSerializer#getSuffix() + */ + public String getSuffix() { + if (gzip) { + return SUFFIX_GZIP; + } else { + return SUFFIX; + } + } + + /* + * (non-Javadoc) + * + * @see org.kabeja.xml.SAXSerializer#setOutput(java.io.OutputStream) + */ + public void setOutput(OutputStream out) { + OutputStream bout = null; + + try { + if (gzip) { + bout = new BufferedOutputStream(new GZIPOutputStream(out)); + } else { + bout = new BufferedOutputStream(out); + } + + this.out = new OutputStreamWriter(bout, this.encoding); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /* + * (non-Javadoc) + * + * @see org.kabeja.xml.SAXSerializer#setProperties(java.util.Map) + */ + public void setProperties(Map properties) { + this.properties = properties; + + if (properties.containsKey(PROPERTY_ENCODING)) { + this.encoding = (String) properties.get(PROPERTY_ENCODING); + } + + if (properties.containsKey(PROPERTY_GZIP)) { + this.gzip = Boolean.getBoolean((String) properties.get( + PROPERTY_GZIP)); + } + } +} diff --git a/dxf/src/main/java/org/kabeja/xml/SAXSerializer.java b/dxf/src/main/java/org/kabeja/xml/SAXSerializer.java new file mode 100644 index 0000000..d301f0e --- /dev/null +++ b/dxf/src/main/java/org/kabeja/xml/SAXSerializer.java @@ -0,0 +1,46 @@ +/* + Copyright 2005 Simon Mieth + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package org.kabeja.xml; + +import java.io.OutputStream; + +import org.kabeja.processing.Configurable; +import org.xml.sax.ContentHandler; + + +/** + *This interface describes a Serializer, which will serialize the SAX-Events + *to the given stream. + *

      Lifecycle

      + * + *
        + *
      1. setProperties
      2. + *
      3. getSuffix()
      4. + *
      5. getMimeType()
      6. + *
      7. setOutput()
      8. + *
      9. startDocument and all other methods from org.xml.sax.ContentHandler
      10. + *
      + * + * @author Simon Mieth + * + */ +public interface SAXSerializer extends ContentHandler, Configurable { + public String getSuffix(); + + public String getMimeType(); + + public void setOutput(OutputStream out); +} diff --git a/gpx/.gitignore b/gpx/.gitignore new file mode 100644 index 0000000..b0be712 --- /dev/null +++ b/gpx/.gitignore @@ -0,0 +1,4 @@ +target +.settings +.classpath +.project \ No newline at end of file diff --git a/gpx/pom.xml b/gpx/pom.xml new file mode 100644 index 0000000..9505216 --- /dev/null +++ b/gpx/pom.xml @@ -0,0 +1,94 @@ + + 4.0.0 + + com.atolcd.gis + gpx + 1.0 + jar + + AtolCD gpx + AtolCD gpx + + + UTF-8 + UTF-8 + + + + package + + + org.apache.maven.plugins + maven-compiler-plugin + 3.2 + + 1.8 + 1.8 + UTF-8 + + + + + + + + + local-maven-repo + Local Maven Repo + file://${project.basedir}/../local-maven-repo + + + 52north.org-releases + 52north.org-releases + http://52north.org/maven/repo/releases/ + + + datanucleus + datanucleus + http://www.datanucleus.org/downloads/maven2/ + + + jboss.org + jboss.org + https://repository.jboss.org + + + pentaho-releases + https://nexus.pentaho.org/content/groups/omni/ + + + lds-main + Main Approved LDS Repo + http://code.lds.org/nexus/content/groups/main-repo + + + maven-us.nuxeo.org + maven-us.nuxeo.org + http://maven-us.nuxeo.org/nexus/content/groups/public/ + + + axiomalaska + axiomalaska + http://nexus.axiomalaska.com/nexus/content/groups/public/ + + + + + + com.vividsolutions + jts-core + 1.14.0 + + + org.jdom + jdom2 + 2.0.6 + + + + + Atol CD + http://www.atolcd.com + + diff --git a/gpx/src/main/java/com/atolcd/gis/gpx/AbstractReaderWriter.java b/gpx/src/main/java/com/atolcd/gis/gpx/AbstractReaderWriter.java new file mode 100644 index 0000000..8bfc3f0 --- /dev/null +++ b/gpx/src/main/java/com/atolcd/gis/gpx/AbstractReaderWriter.java @@ -0,0 +1,45 @@ +package com.atolcd.gis.gpx; + +import org.jdom2.Namespace; + +public abstract class AbstractReaderWriter { + + protected static Namespace GPX_NS_1_1 = Namespace.getNamespace("http://www.topografix.com/GPX/1/1"); + protected static Namespace GPX_NS_1_0 = Namespace.getNamespace("http://www.topografix.com/GPX/1/0"); + + protected static String GPX_TAG = "gpx"; + protected static String GPX_TAG_ATT_VERSION = "version"; + protected static String GPX_TAG_ATT_CREATOR = "creator"; + + protected static String GPX_TAG_METADATA = "metadata"; + protected static String GPX_TAG_NAME = "name"; + protected static String GPX_TAG_CMT = "cmt"; + protected static String GPX_TAG_DESC = "desc"; + protected static String GPX_TAG_SRC = "src"; + protected static String GPX_TAG_TIME = "time"; + protected static String GPX_TAG_KEYWORDS = "keywords"; + protected static String GPX_TAG_ELE = "ele"; + protected static String GPX_TAG_SYM = "sym"; + protected static String GPX_TAG_TYPE = "type"; + protected static String GPX_TAG_NUMBER = "number"; + + protected static String GPX_TAG_AUTHOR = "author"; + protected static String GPX_TAG_EMAIL = "email"; + protected static String GPX_TAG_EMAIL_ATT_ID = "id"; + protected static String GPX_TAG_EMAIL_ATT_DOMAIN = "domain"; + protected static String GPX_TAG_BOUNDS = "bounds"; + protected static String GPX_TAG_BOUNDS_ATT_MINLON = "minlon"; + protected static String GPX_TAG_BOUNDS_ATT_MAXLON = "maxlon"; + protected static String GPX_TAG_BOUNDS_ATT_MINLAT = "minlat"; + protected static String GPX_TAG_BOUNDS_ATT_MAXLAT = "maxlat"; + + public static String GPX_TAG_TRK = "trk"; + protected static String GPX_TAG_TRKSEG = "trkseg"; + public static String GPX_TAG_RTE = "rte"; + public static String GPX_TAG_WPT = "wpt"; + protected static String GPX_TAG_RTEPT = "rtept"; + protected static String GPX_TAG_TRKPT = "trkpt"; + protected static String GPX_TAG_PT_ATT_LON = "lon"; + protected static String GPX_TAG_PT_ATT_LAT = "lat"; + +} diff --git a/gpx/src/main/java/com/atolcd/gis/gpx/GpxReader.java b/gpx/src/main/java/com/atolcd/gis/gpx/GpxReader.java new file mode 100644 index 0000000..5899289 --- /dev/null +++ b/gpx/src/main/java/com/atolcd/gis/gpx/GpxReader.java @@ -0,0 +1,228 @@ +package com.atolcd.gis.gpx; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.GregorianCalendar; +import java.util.List; + +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; + +import org.jdom2.Element; +import org.jdom2.JDOMException; +import org.jdom2.Namespace; +import org.jdom2.input.SAXBuilder; + +import com.atolcd.gis.gpx.type.Author; +import com.atolcd.gis.gpx.type.Author.AuthorException; +import com.atolcd.gis.gpx.type.Document; +import com.atolcd.gis.gpx.type.Route; +import com.atolcd.gis.gpx.type.Route.RouteException; +import com.atolcd.gis.gpx.type.Track; +import com.atolcd.gis.gpx.type.Track.TrackException; +import com.atolcd.gis.gpx.type.TrackSegment; +import com.atolcd.gis.gpx.type.WayPoint; +import com.atolcd.gis.gpx.type.Document.GpxException; +import com.atolcd.gis.gpx.type.Metadata; +import com.atolcd.gis.gpx.type.WayPoint.WayPointException; +import com.vividsolutions.jts.geom.Coordinate; +import com.vividsolutions.jts.geom.Envelope; + +public class GpxReader extends AbstractReaderWriter{ + + public Document read(String filename, String charsetName) throws JDOMException, IOException, GpxException, WayPointException, RouteException, TrackException, AuthorException{ + + Document gpxDocument = new Document(); + + SAXBuilder sxb = new SAXBuilder(); + org.jdom2.Document document = sxb.build(new InputStreamReader(new FileInputStream(filename), charsetName)); + + Element gpxElt = document.getRootElement(); + Namespace gpxNameSpace = null; + + //version & creator + gpxDocument.setVersion(gpxElt.getAttributeValue(GPX_TAG_ATT_VERSION)); + gpxDocument.setCreator(gpxElt.getAttributeValue(GPX_TAG_ATT_CREATOR)); + + //metadata + Element parentMetadataElt = null; + if(gpxDocument.getVersion().equals(Document.GPX_VERSION_1_0)){ + gpxNameSpace = GPX_NS_1_0; + }else{ + gpxNameSpace = GPX_NS_1_1; + parentMetadataElt = gpxElt.getChild(GPX_TAG_METADATA,gpxNameSpace); + } + + if(parentMetadataElt != null){ + + Metadata metadata = new Metadata(); + metadata.setName((String) getChildValue(parentMetadataElt, GPX_TAG_NAME,gpxNameSpace)); + metadata.setDescription((String) getChildValue(parentMetadataElt, GPX_TAG_DESC,gpxNameSpace)); + metadata.setTime((GregorianCalendar) getChildValue(parentMetadataElt, GPX_TAG_TIME,gpxNameSpace)); + + Element authorElt = parentMetadataElt.getChild(GPX_TAG_AUTHOR,gpxNameSpace); + String authorName = null; + String authorEmail = null; + if(authorElt != null){ + + if(gpxDocument.getVersion().equals(Document.GPX_VERSION_1_0)){ + + authorName = (String) getChildValue(parentMetadataElt,GPX_TAG_AUTHOR,gpxNameSpace); + + }else{ + + authorName = (String) getChildValue(authorElt, GPX_TAG_NAME,gpxNameSpace); + Element authorEmailElt = authorElt.getChild(GPX_TAG_EMAIL,gpxNameSpace); + if(authorEmailElt != null){ + authorEmail = authorEmailElt.getAttributeValue(GPX_TAG_EMAIL_ATT_ID) + + "@" + + authorEmailElt.getAttributeValue(GPX_TAG_EMAIL_ATT_DOMAIN); + } + + } + } + + if(gpxDocument.getVersion().equals(Document.GPX_VERSION_1_0)){ + authorEmail = (String) getChildValue(parentMetadataElt,GPX_TAG_EMAIL,gpxNameSpace); + } + + if(authorName != null || authorEmail != null){ + metadata.setAuthor(new Author(authorName, authorEmail)); + } + + metadata.setKeywords((String) getChildValue(parentMetadataElt, GPX_TAG_KEYWORDS,gpxNameSpace)); + Element boundsElt = parentMetadataElt.getChild(GPX_TAG_BOUNDS,gpxNameSpace); + if(boundsElt != null){ + + Envelope bounds = new Envelope(); + bounds.init( + Double.parseDouble(boundsElt.getAttributeValue(GPX_TAG_BOUNDS_ATT_MINLON)), + Double.parseDouble(boundsElt.getAttributeValue(GPX_TAG_BOUNDS_ATT_MAXLON)), + Double.parseDouble(boundsElt.getAttributeValue(GPX_TAG_BOUNDS_ATT_MINLAT)), + Double.parseDouble(boundsElt.getAttributeValue(GPX_TAG_BOUNDS_ATT_MAXLAT)) + ); + + metadata.setBounds(bounds); + + } + + gpxDocument.setMetadata(metadata); + } + + //waypoints + List wptElts = gpxElt.getChildren(GPX_TAG_WPT,gpxNameSpace); + for(Element wptElt : wptElts){ + gpxDocument.getWayPoints().add(toWayPoint(wptElt, gpxNameSpace)); + } + + //routes + List rteElts = gpxElt.getChildren(GPX_TAG_RTE,gpxNameSpace); + for(Element rteElt : rteElts){ + + Route route = new Route(); + route.setComment((String) getChildValue(rteElt,GPX_TAG_CMT,gpxNameSpace)); + route.setDescription((String) getChildValue(rteElt,GPX_TAG_DESC,gpxNameSpace)); + route.setName((String) getChildValue(rteElt,GPX_TAG_NAME,gpxNameSpace)); + route.setNumber((Integer) getChildValue(rteElt,GPX_TAG_NUMBER,gpxNameSpace)); + route.setSource((String) getChildValue(rteElt,GPX_TAG_SRC,gpxNameSpace)); + route.setType((String) getChildValue(rteElt,GPX_TAG_TYPE,gpxNameSpace)); + + List rteptElts = rteElt.getChildren(GPX_TAG_RTEPT,gpxNameSpace); + for(Element rteptElt : rteptElts){ + route.getPoints().add(toWayPoint(rteptElt, gpxNameSpace)); + } + + gpxDocument.getRoutes().add(route); + } + + //tracks + List trkElts = gpxElt.getChildren(GPX_TAG_TRK,gpxNameSpace); + for(Element trkElt : trkElts){ + + Track track = new Track(); + track.setComment((String) getChildValue(trkElt,GPX_TAG_CMT,gpxNameSpace)); + track.setDescription((String) getChildValue(trkElt,GPX_TAG_DESC,gpxNameSpace)); + track.setName((String) getChildValue(trkElt,GPX_TAG_NAME,gpxNameSpace)); + track.setNumber((Integer) getChildValue(trkElt,GPX_TAG_NUMBER,gpxNameSpace)); + track.setSource((String) getChildValue(trkElt,GPX_TAG_SRC,gpxNameSpace)); + track.setType((String) getChildValue(trkElt,GPX_TAG_TYPE,gpxNameSpace)); + + List trksegElts = trkElt.getChildren(GPX_TAG_TRKSEG,gpxNameSpace); + for(Element trksegElt : trksegElts){ + + TrackSegment trackSegment = new TrackSegment(); + List trkptElts = trksegElt.getChildren(GPX_TAG_TRKPT,gpxNameSpace); + for(Element trkptElt : trkptElts){ + trackSegment.getPoints().add(toWayPoint(trkptElt, gpxNameSpace)); + } + + track.getSegments().add(trackSegment); + } + + gpxDocument.getTracks().add(track); + } + + + return gpxDocument; + } + + private WayPoint toWayPoint(Element ptElt, Namespace namespace) throws WayPointException{ + + Coordinate coordinate = new Coordinate( + Double.parseDouble(ptElt.getAttributeValue(GPX_TAG_PT_ATT_LON).replace(",", ".")), + Double.parseDouble(ptElt.getAttributeValue(GPX_TAG_PT_ATT_LAT).replace(",", ".")) + ); + + Object elevation = getChildValue(ptElt, GPX_TAG_ELE,namespace); + if(elevation != null){ + coordinate.z = Double.parseDouble(elevation.toString()); + } + + WayPoint waypoint = new WayPoint(coordinate); + waypoint.setTime((GregorianCalendar) getChildValue(ptElt, GPX_TAG_TIME,namespace)); + waypoint.setName((String) getChildValue(ptElt, GPX_TAG_NAME,namespace)); + waypoint.setComment((String) getChildValue(ptElt, GPX_TAG_CMT,namespace)); + waypoint.setDescription((String) getChildValue(ptElt, GPX_TAG_DESC,namespace)); + waypoint.setSource((String) getChildValue(ptElt, GPX_TAG_SRC,namespace)); + waypoint.setSymbol((String) getChildValue(ptElt, GPX_TAG_SYM,namespace)); + waypoint.setType((String) getChildValue(ptElt, GPX_TAG_TYPE,namespace)); + + return waypoint; + } + + private Object getChildValue(Element parent, String childName,Namespace namespace){ + + Element childElt = parent.getChild(childName,namespace); + if(childElt != null && childElt.getText() != null){ + + String chiltText = childElt.getText(); + + try{ + + XMLGregorianCalendar xmlCalendar= DatatypeFactory.newInstance().newXMLGregorianCalendar(chiltText); + return xmlCalendar.toGregorianCalendar(); + + }catch(Exception e){} + + try{ + + return Integer.parseInt(chiltText); + + }catch(Exception e){} + + try{ + + return Double.parseDouble(chiltText.replace(",", ".")); + + }catch(Exception e){} + + return childElt.getText(); + } + + return null; + + } + +} + diff --git a/gpx/src/main/java/com/atolcd/gis/gpx/GpxWriter.java b/gpx/src/main/java/com/atolcd/gis/gpx/GpxWriter.java new file mode 100644 index 0000000..6992f4c --- /dev/null +++ b/gpx/src/main/java/com/atolcd/gis/gpx/GpxWriter.java @@ -0,0 +1,277 @@ +package com.atolcd.gis.gpx; + +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.Writer; +import java.util.GregorianCalendar; + +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; + +import org.jdom2.Element; +import org.jdom2.Namespace; +import org.jdom2.output.Format; +import org.jdom2.output.XMLOutputter; + +import com.atolcd.gis.gpx.type.Document; +import com.atolcd.gis.gpx.type.Metadata; +import com.atolcd.gis.gpx.type.Route; +import com.atolcd.gis.gpx.type.Track; +import com.atolcd.gis.gpx.type.TrackSegment; +import com.atolcd.gis.gpx.type.WayPoint; +import com.vividsolutions.jts.geom.Envelope; + +public class GpxWriter extends AbstractReaderWriter{ + + public void write(Document gpxDocument, Writer writer, String charsetName) throws IOException, DatatypeConfigurationException{ + + org.jdom2.Document document = getGpxDocument(gpxDocument); + Format format = Format.getPrettyFormat(); + format.setEncoding(charsetName); + XMLOutputter xmlOutputter = new XMLOutputter(format); + xmlOutputter.output(document, writer); + writer.close(); + + } + + public void write(Document gpxDocument, String filename, String charsetName) throws FileNotFoundException, IOException, DatatypeConfigurationException{ + + org.jdom2.Document document = getGpxDocument(gpxDocument); + Format format = Format.getPrettyFormat(); + format.setEncoding(charsetName); + XMLOutputter xmlOutputter = new XMLOutputter(format); + FileOutputStream fileOutputStream = new FileOutputStream(filename); + xmlOutputter.output(document, fileOutputStream); + fileOutputStream.close(); + + } + + + private org.jdom2.Document getGpxDocument(Document gpxDocument) throws FileNotFoundException, IOException, DatatypeConfigurationException{ + + //Namespace + Namespace gpxNameSpace = null; + if(gpxDocument.getVersion().equals(Document.GPX_VERSION_1_0)){ + gpxNameSpace = GPX_NS_1_0; + }else{ + gpxNameSpace = GPX_NS_1_1; + } + + //gpx + Element gpxElt = new Element(GPX_TAG,gpxNameSpace); + gpxElt.setAttribute(GPX_TAG_ATT_VERSION, gpxDocument.getVersion()); + gpxElt.setAttribute(GPX_TAG_ATT_CREATOR, gpxDocument.getCreator()); + + //metadata + Metadata metadata = gpxDocument.getMetadata(); + if(metadata != null){ + + Element parentMetadataElt = null; + + Element authorElt = null; + Element emailElt = null; + + if(gpxDocument.getVersion().equals(Document.GPX_VERSION_1_0)){ + parentMetadataElt = gpxElt; + + //Author + if(metadata.getAuthor()!=null && metadata.getAuthor().getName()!=null){ + authorElt = new Element(GPX_TAG_AUTHOR,gpxNameSpace); + authorElt.setText(metadata.getAuthor().getName()); + } + + if(metadata.getAuthor()!=null && metadata.getAuthor().getEmail()!=null){ + emailElt = new Element(GPX_TAG_EMAIL,gpxNameSpace); + emailElt.setText(metadata.getAuthor().getEmail()); + } + + }else{ + + parentMetadataElt = new Element(GPX_TAG_METADATA,gpxNameSpace); + + //Author + if(metadata.getAuthor()!=null){ + + authorElt = new Element(GPX_TAG_AUTHOR,gpxNameSpace); + authorElt = addToElt(authorElt, GPX_TAG_NAME, metadata.getAuthor().getName(),gpxNameSpace); + if(metadata.getAuthor().getEmail()!=null){ + + Element authorEmailElt = new Element(GPX_TAG_EMAIL,gpxNameSpace); + authorEmailElt.setAttribute(GPX_TAG_EMAIL_ATT_ID,metadata.getAuthor().getEmailId()); + authorEmailElt.setAttribute(GPX_TAG_EMAIL_ATT_DOMAIN,metadata.getAuthor().getEmailDomain()); + authorElt.addContent(authorEmailElt); + } + } + } + + parentMetadataElt = addToElt(parentMetadataElt, GPX_TAG_NAME, metadata.getName(),gpxNameSpace); + parentMetadataElt = addToElt(parentMetadataElt, GPX_TAG_DESC, metadata.getDescription(),gpxNameSpace); + if(authorElt !=null){ + parentMetadataElt.addContent(authorElt); + } + + //uniquement 1.0 + if(emailElt !=null){ + parentMetadataElt.addContent(emailElt); + } + + parentMetadataElt = addToElt(parentMetadataElt, GPX_TAG_TIME, metadata.getTime(),gpxNameSpace); + parentMetadataElt = addToElt(parentMetadataElt, GPX_TAG_KEYWORDS, metadata.getKeywords(),gpxNameSpace); + + Envelope bounds = metadata.getBounds(); + if(metadata.getBounds() == null){ + bounds = gpxDocument.getExtent(); + } + + if(bounds !=null && !bounds.isNull()){ + + Element boundsElt = new Element(GPX_TAG_BOUNDS,gpxNameSpace); + boundsElt.setAttribute(GPX_TAG_BOUNDS_ATT_MINLON,String.valueOf(bounds.getMinX())); + boundsElt.setAttribute(GPX_TAG_BOUNDS_ATT_MAXLON,String.valueOf(bounds.getMaxX())); + boundsElt.setAttribute(GPX_TAG_BOUNDS_ATT_MINLAT,String.valueOf(bounds.getMinY())); + boundsElt.setAttribute(GPX_TAG_BOUNDS_ATT_MAXLAT,String.valueOf(bounds.getMaxY())); + parentMetadataElt.addContent(boundsElt); + } + + if(gpxDocument.getVersion().equals(Document.GPX_VERSION_1_0)){ + gpxElt = parentMetadataElt; + }else{ + gpxElt.addContent(parentMetadataElt); + } + + } + + //waypoints + if(gpxDocument.getWayPoints() != null + && gpxDocument.getWayPoints().size() > 0){ + + for(WayPoint wayPoint : gpxDocument.getWayPoints()){ + gpxElt.addContent(toPtElt(wayPoint,GPX_TAG_WPT,gpxNameSpace)); + } + } + + //routes + if(gpxDocument.getRoutes() != null + && gpxDocument.getRoutes().size() > 0){ + + for(Route route : gpxDocument.getRoutes()){ + + Element rteElt = new Element(GPX_TAG_RTE,gpxNameSpace); + rteElt = addToElt(rteElt, GPX_TAG_NAME, route.getName(),gpxNameSpace); + rteElt = addToElt(rteElt, GPX_TAG_CMT, route.getComment(),gpxNameSpace); + rteElt = addToElt(rteElt, GPX_TAG_DESC, route.getDescription(),gpxNameSpace); + rteElt = addToElt(rteElt, GPX_TAG_SRC, route.getSource(),gpxNameSpace); + rteElt = addToElt(rteElt, GPX_TAG_NUMBER, route.getNumber(),gpxNameSpace); + + if(gpxDocument.getVersion().equals(Document.GPX_VERSION_1_1)){ + rteElt = addToElt(rteElt, GPX_TAG_TYPE, route.getType(),gpxNameSpace); + } + + if(route.getPoints() != null + && route.getPoints().size() > 0){ + + for(WayPoint wayPoint : route.getPoints()){ + rteElt.addContent(toPtElt(wayPoint,GPX_TAG_RTEPT,gpxNameSpace)); + } + } + + gpxElt.addContent(rteElt); + } + + } + + //tracks + if(gpxDocument.getTracks() != null + && gpxDocument.getTracks().size() > 0){ + + for(Track track : gpxDocument.getTracks()){ + + Element trkElt = new Element(GPX_TAG_TRK,gpxNameSpace); + trkElt = addToElt(trkElt, GPX_TAG_NAME, track.getName(),gpxNameSpace); + trkElt = addToElt(trkElt, GPX_TAG_CMT, track.getComment(),gpxNameSpace); + trkElt = addToElt(trkElt, GPX_TAG_DESC, track.getDescription(),gpxNameSpace); + trkElt = addToElt(trkElt, GPX_TAG_SRC, track.getSource(),gpxNameSpace); + trkElt = addToElt(trkElt, GPX_TAG_NUMBER, track.getNumber(),gpxNameSpace); + + if(gpxDocument.getVersion().equals(Document.GPX_VERSION_1_1)){ + trkElt = addToElt(trkElt, GPX_TAG_TYPE, track.getType(),gpxNameSpace); + } + + if(track.getSegments() != null + && track.getSegments().size() > 0){ + + for(TrackSegment trackSegment : track.getSegments()){ + + Element trksegElt = new Element(GPX_TAG_TRKSEG,gpxNameSpace); + + if(trackSegment.getPoints() != null + && trackSegment.getPoints().size() > 0){ + + for(WayPoint wayPoint : trackSegment.getPoints()){ + trksegElt.addContent(toPtElt(wayPoint,GPX_TAG_TRKPT,gpxNameSpace)); + } + } + + trkElt.addContent(trksegElt); + + } + + } + + gpxElt.addContent(trkElt); + + } + + } + + return new org.jdom2.Document(gpxElt); + } + + private Element addToElt(Element parent, String childName, Object childValue, Namespace namespace) throws DatatypeConfigurationException{ + + if(childValue != null){ + + String stringValue = null; + + if(childValue instanceof GregorianCalendar){ + + stringValue = DatatypeFactory.newInstance().newXMLGregorianCalendar((GregorianCalendar)childValue).toString(); + + }else{ + stringValue = String.valueOf(childValue); + } + + Element childElt = new Element(childName,namespace); + childElt.setText(stringValue); + parent.addContent(childElt); + + } + + return parent; + + } + + private Element toPtElt(WayPoint waypoint, String ptEltName, Namespace namespace) throws DatatypeConfigurationException{ + + Element ptElt = new Element(ptEltName,namespace); + ptElt.setAttribute(GPX_TAG_PT_ATT_LON, String.valueOf(waypoint.getLongitude())); + ptElt.setAttribute(GPX_TAG_PT_ATT_LAT, String.valueOf(waypoint.getLatitude())); + + if(waypoint.getElevation() != null && !waypoint.getElevation().isNaN()){ + ptElt = addToElt(ptElt,GPX_TAG_ELE,waypoint.getElevation(),namespace); + } + + ptElt = addToElt(ptElt, GPX_TAG_TIME, waypoint.getTime(),namespace); + ptElt = addToElt(ptElt, GPX_TAG_NAME, waypoint.getName(),namespace); + ptElt = addToElt(ptElt, GPX_TAG_CMT, waypoint.getComment(),namespace); + ptElt = addToElt(ptElt, GPX_TAG_DESC, waypoint.getDescription(),namespace); + ptElt = addToElt(ptElt, GPX_TAG_SRC, waypoint.getSource(),namespace); + ptElt = addToElt(ptElt, GPX_TAG_SYM, waypoint.getSymbol(),namespace); + ptElt = addToElt(ptElt, GPX_TAG_TYPE, waypoint.getType(),namespace); + + return ptElt; + + } + +} diff --git a/gpx/src/main/java/com/atolcd/gis/gpx/IElement.java b/gpx/src/main/java/com/atolcd/gis/gpx/IElement.java new file mode 100644 index 0000000..344eba6 --- /dev/null +++ b/gpx/src/main/java/com/atolcd/gis/gpx/IElement.java @@ -0,0 +1,11 @@ +package com.atolcd.gis.gpx; + +public interface IElement { + + public void setName(String name); + public void setDescription(String description); + + public String getName(); + public String getDescription(); + +} diff --git a/gpx/src/main/java/com/atolcd/gis/gpx/ISpatialElement.java b/gpx/src/main/java/com/atolcd/gis/gpx/ISpatialElement.java new file mode 100644 index 0000000..13afd81 --- /dev/null +++ b/gpx/src/main/java/com/atolcd/gis/gpx/ISpatialElement.java @@ -0,0 +1,18 @@ +package com.atolcd.gis.gpx; + +import com.vividsolutions.jts.geom.Geometry; + +public interface ISpatialElement extends IElement{ + + public void setComment(String comment); + public void setSource(String source); + public void setType(String type); + + public String getComment(); + public String getSource(); + public String getType(); + + public Geometry getGeometry(); + + +} diff --git a/gpx/src/main/java/com/atolcd/gis/gpx/type/AbstractElement.java b/gpx/src/main/java/com/atolcd/gis/gpx/type/AbstractElement.java new file mode 100644 index 0000000..24893f9 --- /dev/null +++ b/gpx/src/main/java/com/atolcd/gis/gpx/type/AbstractElement.java @@ -0,0 +1,29 @@ +package com.atolcd.gis.gpx.type; + +public abstract class AbstractElement { + + private String name; + private String description; + + public AbstractElement(){ + this.name = null; + this.description = null; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + +} diff --git a/gpx/src/main/java/com/atolcd/gis/gpx/type/AbstractSpatialElement.java b/gpx/src/main/java/com/atolcd/gis/gpx/type/AbstractSpatialElement.java new file mode 100644 index 0000000..2c0c96a --- /dev/null +++ b/gpx/src/main/java/com/atolcd/gis/gpx/type/AbstractSpatialElement.java @@ -0,0 +1,48 @@ +package com.atolcd.gis.gpx.type; + +import com.vividsolutions.jts.geom.GeometryFactory; + +public abstract class AbstractSpatialElement extends AbstractElement{ + + private static GeometryFactory geometryFactory = new GeometryFactory(); + + private String comment; + private String source; + private String type; + + public AbstractSpatialElement(){ + super(); + this.comment = null; + this.source = null; + this.type = null; + } + + public String getComment() { + return comment; + } + + public void setComment(String comment) { + this.comment = comment; + } + + public String getSource() { + return source; + } + + public void setSource(String source) { + this.source = source; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public static GeometryFactory getGeometryFactory() { + return geometryFactory; + } + +} diff --git a/gpx/src/main/java/com/atolcd/gis/gpx/type/Author.java b/gpx/src/main/java/com/atolcd/gis/gpx/type/Author.java new file mode 100644 index 0000000..9c63b72 --- /dev/null +++ b/gpx/src/main/java/com/atolcd/gis/gpx/type/Author.java @@ -0,0 +1,72 @@ +package com.atolcd.gis.gpx.type; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class Author { + + private String name; + private String email; + + public Author(String name, String email) throws AuthorException{ + this.name = name; + this.email = checkEmail(email); + } + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getEmail() { + return email; + } + + public void setEmail(String email) throws AuthorException { + this.email = checkEmail(email); + } + + public String getEmailId(){ + + if(this.email !=null){ + return this.email.split("@")[0]; + }else{ + return null; + } + } + + public String getEmailDomain(){ + + if(this.email !=null){ + return this.email.split("@")[1]; + }else{ + return null; + } + } + + private String checkEmail(String email) throws AuthorException { + + if(email != null){ + + Pattern pattern = Pattern.compile("^.+@.+\\..+$"); + Matcher matcher = pattern.matcher(email); + if (!matcher.matches()){ + throw new AuthorException("Wrong author mail address"); + } + + } + + return email; + } + + @SuppressWarnings("serial") + public class AuthorException extends Exception { + + public AuthorException(String message) { + super(message); + } + + } + +} diff --git a/gpx/src/main/java/com/atolcd/gis/gpx/type/Document.java b/gpx/src/main/java/com/atolcd/gis/gpx/type/Document.java new file mode 100644 index 0000000..4c94e82 --- /dev/null +++ b/gpx/src/main/java/com/atolcd/gis/gpx/type/Document.java @@ -0,0 +1,130 @@ +package com.atolcd.gis.gpx.type; + +import java.util.ArrayList; +import java.util.List; + +import com.vividsolutions.jts.geom.Envelope; +import com.vividsolutions.jts.geom.Geometry; +import com.vividsolutions.jts.geom.GeometryFactory; + +public class Document { + + public static String GPX_CREATOR_DEFAULT = "Atol Conseils et Developpements GPX Library"; + public static String GPX_VERSION_1_0 = "1.0"; + public static String GPX_VERSION_1_1 = "1.1"; + + private String version; + private String creator; + private Metadata metadata; + private List wayPoints; + private List tracks; + private List routes; + + public Document(){ + this.version= GPX_VERSION_1_1; + this.creator = GPX_CREATOR_DEFAULT; + this.metadata = null; + this.wayPoints = new ArrayList(); + this.tracks = new ArrayList(); + this.routes = new ArrayList(); + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) throws GpxException{ + this.version = checkVersion(version); + } + + public String getCreator() { + return creator; + } + + public void setCreator(String creator) throws GpxException{ + this.creator = checkCreator(creator); + } + + public Metadata getMetadata() { + return metadata; + } + + public void setMetadata(Metadata metadata) { + this.metadata = metadata; + } + + public List getWayPoints() { + return wayPoints; + } + + public List getTracks() { + return tracks; + } + + public List getRoutes() { + return routes; + } + + private String checkVersion(String version) throws GpxException{ + + if(!version.equals(GPX_VERSION_1_0) && !version.equals(GPX_VERSION_1_1)){ + + throw new GpxException("Only 1.0 and 1.1 versions are allowed"); + + } + + return version; + } + + private String checkCreator(String creator) throws GpxException{ + + if(creator == null){ + throw new GpxException("Creator should not be null"); + } + + return creator; + } + + + @SuppressWarnings("serial") + public class GpxException extends Exception { + + public GpxException(String message) { + super(message); + } + + } + + public Envelope getExtent(){ + + List geometries = new ArrayList(); + for(WayPoint wayPoint: wayPoints){ + Geometry geometry = wayPoint.getGeometry(); + if(geometry != null && !geometry.isEmpty()){ + geometries.add(wayPoint.getGeometry()); + } + } + + for(Route route: routes){ + Geometry geometry = route.getGeometry(); + if(geometry != null && !geometry.isEmpty()){ + geometries.add(route.getGeometry()); + } + } + + for(Track track: tracks){ + Geometry geometry = track.getGeometry(); + if(geometry != null && !geometry.isEmpty()){ + geometries.add(track.getGeometry()); + } + } + + if(geometries.size() > 0){ + return new GeometryFactory().buildGeometry(geometries).getEnvelopeInternal(); + }else{ + return null; + } + + } + +} diff --git a/gpx/src/main/java/com/atolcd/gis/gpx/type/Metadata.java b/gpx/src/main/java/com/atolcd/gis/gpx/type/Metadata.java new file mode 100644 index 0000000..5cee079 --- /dev/null +++ b/gpx/src/main/java/com/atolcd/gis/gpx/type/Metadata.java @@ -0,0 +1,48 @@ +package com.atolcd.gis.gpx.type; + +import java.util.GregorianCalendar; + +import com.atolcd.gis.gpx.IElement; +import com.vividsolutions.jts.geom.Envelope; + + +public class Metadata extends AbstractElement implements IElement{ + + private Author author; + private GregorianCalendar time; + private String keywords; + private Envelope bounds; + + public Author getAuthor() { + return author; + } + + public void setAuthor(Author author) { + this.author = author; + } + + public GregorianCalendar getTime() { + return time; + } + + public void setTime(GregorianCalendar time) { + this.time = time; + } + + public String getKeywords() { + return keywords; + } + + public void setKeywords(String keywords) { + this.keywords = keywords; + } + + public Envelope getBounds() { + return bounds; + } + + public void setBounds(Envelope bounds) { + this.bounds = bounds; + } + +} diff --git a/gpx/src/main/java/com/atolcd/gis/gpx/type/Route.java b/gpx/src/main/java/com/atolcd/gis/gpx/type/Route.java new file mode 100644 index 0000000..e958ffb --- /dev/null +++ b/gpx/src/main/java/com/atolcd/gis/gpx/type/Route.java @@ -0,0 +1,95 @@ +package com.atolcd.gis.gpx.type; + +import java.util.ArrayList; +import java.util.List; + +import com.atolcd.gis.gpx.ISpatialElement; +import com.atolcd.gis.gpx.type.WayPoint.WayPointException; +import com.vividsolutions.jts.geom.Coordinate; +import com.vividsolutions.jts.geom.CoordinateList; +import com.vividsolutions.jts.geom.Geometry; +import com.vividsolutions.jts.geom.LineString; + +public class Route extends AbstractSpatialElement implements ISpatialElement{ + + private Integer number; + private List points; + + public Route(){ + this.number = null; + this.points = new ArrayList(); + } + + public Route(LineString geometry) throws WayPointException{ + + this.number = null; + this.points = new ArrayList(); + if(geometry != null && !geometry.isEmpty()){ + + for(Coordinate coordinate : geometry.getCoordinates()){ + this.points.add(new WayPoint(coordinate)); + } + + } + + } + + public Route(List points){ + + this.number = null; + if(points == null){ + this.points = new ArrayList(); + }else{ + this.points = points; + } + } + + public Integer getNumber() { + return number; + } + + public void setNumber(Integer number) throws RouteException { + this.number = checkNumber(number); + } + + @SuppressWarnings("unchecked") + public Geometry getGeometry() { + + CoordinateList coordinates = new CoordinateList(); + for(WayPoint wayPoint : this.points){ + coordinates.add(wayPoint.getCoordinate()); + } + + if(coordinates.size() > 1){ + Geometry geometry = getGeometryFactory().createLineString(coordinates.toCoordinateArray()); + geometry.setSRID(4326); + return geometry; + }else{ + return null; + } + } + + public List getPoints() { + return points; + } + + private Integer checkNumber(Integer number) throws RouteException{ + + if(number != null && number < 0){ + throw new RouteException("Route number should be positive"); + } + + return number; + } + + @SuppressWarnings("serial") + public class RouteException extends Exception { + + public RouteException(String message) { + super(message); + } + + } + + +} diff --git a/gpx/src/main/java/com/atolcd/gis/gpx/type/Track.java b/gpx/src/main/java/com/atolcd/gis/gpx/type/Track.java new file mode 100644 index 0000000..99003d5 --- /dev/null +++ b/gpx/src/main/java/com/atolcd/gis/gpx/type/Track.java @@ -0,0 +1,107 @@ +package com.atolcd.gis.gpx.type; + +import java.util.ArrayList; +import java.util.List; + +import com.atolcd.gis.gpx.ISpatialElement; +import com.atolcd.gis.gpx.type.WayPoint.WayPointException; +import com.vividsolutions.jts.geom.CoordinateList; +import com.vividsolutions.jts.geom.Geometry; +import com.vividsolutions.jts.geom.LineString; +import com.vividsolutions.jts.geom.MultiLineString; + +public class Track extends AbstractSpatialElement implements ISpatialElement{ + + private Integer number; + private List segments; + + public Track(){ + this.number = null; + this.segments = new ArrayList(); + } + + public Track(MultiLineString geometry) throws WayPointException{ + + this.number = null; + this.segments = new ArrayList(); + if(geometry != null && !geometry.isEmpty()){ + + for(int iGeom = 0; iGeom < geometry.getNumGeometries(); iGeom++){ + this.segments.add(new TrackSegment((LineString) geometry.getGeometryN(iGeom))); + } + } + } + + public Track(List segments){ + + this.number = null; + if(segments == null){ + this.segments = new ArrayList(); + }else{ + this.segments = segments; + } + + this.number = null; + } + + public List getSegments() { + return segments; + } + + public Integer getNumber() { + return number; + } + + public void setNumber(Integer number) throws TrackException { + this.number = checkNumber(number); + } + + @SuppressWarnings("unchecked") + public Geometry getGeometry() { + + List lineStrings = new ArrayList(); + for(TrackSegment trackSegment : this.segments){ + + CoordinateList coordinates = new CoordinateList(); + for(WayPoint wayPoint : trackSegment.getPoints()){ + coordinates.add(wayPoint.getCoordinate()); + } + + if(coordinates.size() > 1){ + lineStrings.add(getGeometryFactory().createLineString(coordinates.toCoordinateArray())); + } + + } + + if(lineStrings.size() > 0){ + + Geometry geometry = getGeometryFactory().createMultiLineString(lineStrings.toArray(new LineString[lineStrings.size()])); + geometry.setSRID(4326); + return geometry; + + }else{ + return null; + } + + } + + private Integer checkNumber(Integer number) throws TrackException{ + + if(number != null && number < 0){ + throw new TrackException("Track number should be positive"); + } + + return number; + } + + + @SuppressWarnings("serial") + public class TrackException extends Exception { + + public TrackException(String message) { + super(message); + } + + } + +} diff --git a/gpx/src/main/java/com/atolcd/gis/gpx/type/TrackSegment.java b/gpx/src/main/java/com/atolcd/gis/gpx/type/TrackSegment.java new file mode 100644 index 0000000..502b702 --- /dev/null +++ b/gpx/src/main/java/com/atolcd/gis/gpx/type/TrackSegment.java @@ -0,0 +1,44 @@ +package com.atolcd.gis.gpx.type; + +import java.util.ArrayList; +import java.util.List; + +import com.atolcd.gis.gpx.type.WayPoint.WayPointException; +import com.vividsolutions.jts.geom.Coordinate; +import com.vividsolutions.jts.geom.LineString; + +public class TrackSegment{ + + private List points; + + public TrackSegment(){ + this.points = new ArrayList(); + } + + public TrackSegment(LineString geometry) throws WayPointException{ + + this.points = new ArrayList(); + if(geometry != null && !geometry.isEmpty()){ + + for(Coordinate coordinate : geometry.getCoordinates()){ + this.points.add(new WayPoint(coordinate)); + } + + } + + } + + public TrackSegment(List points){ + + if(points == null){ + this.points = new ArrayList(); + }else{ + this.points = points; + } + } + + public List getPoints() { + return points; + } + +} diff --git a/gpx/src/main/java/com/atolcd/gis/gpx/type/WayPoint.java b/gpx/src/main/java/com/atolcd/gis/gpx/type/WayPoint.java new file mode 100644 index 0000000..9654919 --- /dev/null +++ b/gpx/src/main/java/com/atolcd/gis/gpx/type/WayPoint.java @@ -0,0 +1,83 @@ +package com.atolcd.gis.gpx.type; + +import java.util.GregorianCalendar; + +import com.atolcd.gis.gpx.ISpatialElement; +import com.vividsolutions.jts.geom.Coordinate; +import com.vividsolutions.jts.geom.Geometry; + +public class WayPoint extends AbstractSpatialElement implements ISpatialElement{ + + private Coordinate coordinate; + private GregorianCalendar time; + private String symbol; + + public WayPoint(Coordinate coordinate) throws WayPointException{ + this.coordinate = checkCoordinate(coordinate); + this.time = null; + this.symbol = null; + } + + public Geometry getGeometry() { + + Geometry geometry = getGeometryFactory().createPoint(this.coordinate); + geometry.setSRID(4326); + return geometry; + + } + + public Double getLongitude(){ + return coordinate.x; + } + + public Double getLatitude(){ + return coordinate.y; + } + + public Double getElevation(){ + return coordinate.z; + } + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public GregorianCalendar getTime() { + return time; + } + + public void setTime(GregorianCalendar time) { + this.time = time; + } + + protected Coordinate getCoordinate(){ + return this.coordinate; + } + + private Coordinate checkCoordinate(Coordinate coordinate) throws WayPointException{ + + if(coordinate == null){ + throw new WayPointException("Coordinates can not be null"); + } + + if(coordinate.x > 180 || coordinate.x < -180 ||coordinate.y > 90 ||coordinate.y < -90){ + throw new WayPointException("Wrong coordinates (" + coordinate.x + "|" + coordinate.y + ") for WGS84 system"); + } + + return coordinate; + } + + @SuppressWarnings("serial") + public class WayPointException extends Exception { + + public WayPointException(String message) { + super(message); + } + + } + +} diff --git a/pentaho-gis-plugins/pom.xml b/pentaho-gis-plugins/pom.xml index 1958e72..5bb7ed2 100644 --- a/pentaho-gis-plugins/pom.xml +++ b/pentaho-gis-plugins/pom.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xs com.atolcd.pentaho.di pentaho-gis-plugins - 1.3.0 + 1.4.0 jar Pentaho's Data Integrator GIS Plugins @@ -12,9 +12,21 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xs - pentaho-8 + pentaho-9 true + + pentaho + 9 + + + + 9.0.0.0-423 + + + + pentaho-8 + pentaho 8 @@ -63,7 +75,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xs - 8 + 9 UTF-8 UTF-8 @@ -252,6 +264,56 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xs JavaAPIforKml 2.2.1 + + org.jdom + jdom2 + 2.0.6 + + + mil.nga.geopackage + geopackage + 4.0.0 + + + mil.nga.geopackage + geopackage-core + 4.0.0 + + + mil.nga + sf + 2.0.3 + + + mil.nga.sf + sf-proj + 3.0.3 + + + mil.nga.sf + sf-wkb + 2.0.3 + + + com.j256.ormlite + ormlite-core + 5.1 + + + com.j256.ormlite + ormlite-jdbc + 5.1 + + + org.locationtech.proj4j + proj4j + 1.1.1 + + + org.geolatte + geolatte-geom + 1.6.0 + com.atolcd.gis @@ -290,6 +352,16 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xs spatialite 1.1 + + com.atolcd.gis + gpx + 1.0 + + + com.atolcd.gis + svg + 1.0 + diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/core/row/value/ValueMetaGeometry.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/core/row/value/ValueMetaGeometry.java index 4aace6d..007200c 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/core/row/value/ValueMetaGeometry.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/core/row/value/ValueMetaGeometry.java @@ -36,13 +36,23 @@ import java.sql.Types; import java.util.Date; -import oracle.spatial.geometry.JGeometry; -import oracle.spatial.util.WKT; -import oracle.sql.STRUCT; +import com.atolcd.pentaho.di.gis.utils.GeometryUtils; +import com.vividsolutions.jts.geom.Geometry; +import com.vividsolutions.jts.geom.GeometryFactory; +import com.vividsolutions.jts.io.ByteOrderValues; +import com.vividsolutions.jts.io.InputStreamInStream; +import com.vividsolutions.jts.io.OutputStreamOutStream; +import com.vividsolutions.jts.io.ParseException; +import com.vividsolutions.jts.io.WKBReader; +import com.vividsolutions.jts.io.WKBWriter; +import com.vividsolutions.jts.io.WKTReader; +import com.vividsolutions.jts.io.WKTWriter; +import org.geolatte.geom.jts.JTS; import org.pentaho.di.core.Const; import org.pentaho.di.core.database.DatabaseInterface; import org.pentaho.di.core.database.DatabaseMeta; +import org.pentaho.di.core.database.MSSQLServerDatabaseMeta; import org.pentaho.di.core.database.MySQLDatabaseMeta; import org.pentaho.di.core.database.OracleDatabaseMeta; import org.pentaho.di.core.database.PostgreSQLDatabaseMeta; @@ -59,20 +69,12 @@ import org.postgis.binary.BinaryParser; import org.postgis.binary.BinaryWriter; -import com.atolcd.pentaho.di.gis.utils.GeometryUtils; -import com.vividsolutions.jts.geom.Geometry; -import com.vividsolutions.jts.geom.GeometryFactory; -import com.vividsolutions.jts.io.ByteOrderValues; -import com.vividsolutions.jts.io.InputStreamInStream; -import com.vividsolutions.jts.io.OutputStreamOutStream; -import com.vividsolutions.jts.io.ParseException; -import com.vividsolutions.jts.io.WKBReader; -import com.vividsolutions.jts.io.WKBWriter; -import com.vividsolutions.jts.io.WKTReader; -import com.vividsolutions.jts.io.WKTWriter; +import oracle.spatial.geometry.JGeometry; +import oracle.spatial.util.WKT; +import oracle.sql.STRUCT; @ValueMetaPlugin(id = ""+ValueMetaGeometry.TYPE_GEOMETRY, name = "Geometry", description = "A geometry GIS object") -public class ValueMetaGeometry extends ValueMetaBase implements GeometryInterface, Cloneable { +public class ValueMetaGeometry extends ValueMetaBase implements GeometryInterface { // Postgis public static BinaryParser pgGeometryParser = new BinaryParser(); @@ -330,7 +332,6 @@ public Object getNativeDataType(Object object) throws KettleValueException { return getGeometry(object); } - @Override public Geometry getGeometry(Object object) throws KettleValueException { try { @@ -485,15 +486,19 @@ public ValueMetaInterface getValueFromSQLType(DatabaseMeta databaseMeta, String isDatabaseGeometryColumn = true; - // Oracle Spatial/Locator + // Oracle Spatial/Locator } else if (databaseMeta.getDatabaseInterface() instanceof OracleDatabaseMeta && type == java.sql.Types.STRUCT && columnTypeName.equalsIgnoreCase("MDSYS.SDO_GEOMETRY")) { isDatabaseGeometryColumn = true; - // MySQL + // MySQL } else if (databaseMeta.getDatabaseInterface() instanceof MySQLDatabaseMeta && type == java.sql.Types.BINARY && columnTypeName.equalsIgnoreCase("GEOMETRY")) { isDatabaseGeometryColumn = true; + // MSSQL + } else if (databaseMeta.getDatabaseInterface() instanceof MSSQLServerDatabaseMeta && type == java.sql.Types.VARBINARY && columnTypeName.equalsIgnoreCase("GEOMETRY")) { + + isDatabaseGeometryColumn = true; } else { @@ -526,7 +531,7 @@ public ValueMetaInterface getValueFromSQLType(DatabaseMeta databaseMeta, String * @return * @throws KettleDatabaseException */ - + @SuppressWarnings("unchecked") @Override public Object getValueFromResultSet(DatabaseInterface databaseInterface, ResultSet resultSet, int index) throws KettleDatabaseException { @@ -547,7 +552,7 @@ public Object getValueFromResultSet(DatabaseInterface databaseInterface, ResultS geometry = new WKTReader().read(type + coords); } - // Oracle Spatial/Locator + // Oracle Spatial/Locator } else if (databaseInterface instanceof OracleDatabaseMeta) { if (resultSet.getObject(index + 1) != null) { @@ -572,7 +577,7 @@ public Object getValueFromResultSet(DatabaseInterface databaseInterface, ResultS geometry = new WKTReader().read(wkt); } - // MySQL + // MySQL } else if (databaseInterface instanceof MySQLDatabaseMeta) { int byteOrder = ByteOrderValues.LITTLE_ENDIAN; @@ -591,6 +596,20 @@ public Object getValueFromResultSet(DatabaseInterface databaseInterface, ResultS geometry = new WKBReader().read(new InputStreamInStream(inputStream)); } + // MSSQL + } else if (databaseInterface instanceof MSSQLServerDatabaseMeta) { + + + byte[] bytes = resultSet.getBytes(index + 1); + if (bytes != null) { + + org.locationtech.jts.geom.Geometry ms_geometry = JTS.to(org.geolatte.geom.codec.db.sqlserver.Decoders.decode(bytes)); + srid = ms_geometry.getSRID(); + String type = ms_geometry.getGeometryType().trim(); + String coords = ms_geometry.toText().trim(); + geometry = new WKTReader().read(type + coords); + } + } if (srid != null) { @@ -622,7 +641,9 @@ public String getDatabaseColumnTypeDefinition(DatabaseInterface databaseInterfac String retval = null; // Postgis or Oracle Spatial/Locator or Mysql - if (databaseInterface instanceof PostgreSQLDatabaseMeta || databaseInterface instanceof OracleDatabaseMeta || databaseInterface instanceof MySQLDatabaseMeta) { + if (databaseInterface instanceof PostgreSQLDatabaseMeta + || databaseInterface instanceof OracleDatabaseMeta + || databaseInterface instanceof MySQLDatabaseMeta) { if (add_fieldname) { retval = getName() + " "; @@ -641,6 +662,10 @@ public String getDatabaseColumnTypeDefinition(DatabaseInterface databaseInterfac // Mysql } else if (databaseInterface instanceof MySQLDatabaseMeta) { retval += "GEOMETRY"; + + // MSSQL + } else if (databaseInterface instanceof MSSQLServerDatabaseMeta) { + retval += "GEOMETRY"; } if (add_cr) { @@ -693,7 +718,7 @@ public void setPreparedStatementValue(DatabaseMeta databaseMeta, PreparedStateme } - // Oracle Spatial/Locator + // Oracle Spatial/Locator } else if (databaseMeta.getDatabaseInterface() instanceof OracleDatabaseMeta) { Geometry geometry = getGeometry(data); @@ -727,7 +752,7 @@ public void setPreparedStatementValue(DatabaseMeta databaseMeta, PreparedStateme } - // Mysql + // Mysql } else if (databaseMeta.getDatabaseInterface() instanceof MySQLDatabaseMeta) { Geometry geometry = getGeometry(data); @@ -750,6 +775,35 @@ public void setPreparedStatementValue(DatabaseMeta databaseMeta, PreparedStateme } + // MSSQL + } else if (databaseMeta.getDatabaseInterface() instanceof MSSQLServerDatabaseMeta) { + + Geometry geometry = getGeometry(data); + + if (geometry != null) { + + String wkt = null; + + if (GeometryUtils.getCoordinateDimension(geometry) == 3) { + wkt = new WKTWriter(3).write(geometry); + } else { + wkt = new WKTWriter(2).write(geometry); + } + + if (geometry.getSRID() > 0) { + wkt = "SRID=" + geometry.getSRID() + ";" + wkt; + } + + org.locationtech.jts.io.WKTReader reader = new org.locationtech.jts.io.WKTReader(); + org.locationtech.jts.geom.Geometry msGeom = reader.read(wkt); + preparedStatement.setBytes(index, org.geolatte.geom.codec.db.sqlserver.Encoders.encode(JTS.from(msGeom))); + + } else { + + preparedStatement.setObject(index, null, Types.VARBINARY); + + } + } } catch (Exception e) { diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/AbstractFileReader.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/AbstractFileReader.java index 8d4e257..c5dc6b2 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/AbstractFileReader.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/AbstractFileReader.java @@ -60,6 +60,19 @@ public AbstractFileReader(String layerName, String geometryFieldName, String cha } + public Field getField(String name){ + + for(Field field : this.fields){ + + if(field.getName().equalsIgnoreCase(name)){ + return field; + } + } + + return null; + + } + public List getFields() { return fields; } diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/DXFReader.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/DXFReader.java index a1fef3c..27ddd9f 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/DXFReader.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/DXFReader.java @@ -28,6 +28,7 @@ import org.pentaho.di.core.exception.KettleException; import com.atolcd.gis.dxf.Entity; +import com.atolcd.gis.dxf.ExtendedData; import com.atolcd.gis.dxf.Layer; import com.atolcd.pentaho.di.gis.io.features.Feature; import com.atolcd.pentaho.di.gis.io.features.Field; @@ -41,8 +42,9 @@ public class DXFReader extends AbstractFileReader { private boolean circleAsPolygon; private boolean ellipseAsPolygon; private boolean lineAsPolygon; + private boolean readXData; - public DXFReader(String fileName, String geometryFieldName, String charsetName, boolean circleAsPolygon, boolean ellipseAsPolygon, boolean lineAsPolygon) + public DXFReader(String fileName, String geometryFieldName, String charsetName, boolean circleAsPolygon, boolean ellipseAsPolygon, boolean lineAsPolygon, boolean readXData) throws KettleException { super(null, geometryFieldName, charsetName); @@ -54,10 +56,14 @@ public DXFReader(String fileName, String geometryFieldName, String charsetName, } else { this.dxfFileName = checkFilename(fileName).getFile(); } + this.readXData = readXData; this.fields.add(new Field(geometryFieldName, FieldType.GEOMETRY, null, null)); this.fields.add(new Field("Layer", FieldType.STRING, null, null)); this.fields.add(new Field("Text", FieldType.STRING, null, null)); + if(this.readXData){ + this.fields.add(new Field("XData", FieldType.STRING, null, null)); + } this.circleAsPolygon = circleAsPolygon; this.ellipseAsPolygon = ellipseAsPolygon; @@ -103,6 +109,24 @@ public List getFeatures() throws KettleException { feature.addValue(this.fields.get(1), layer.getName()); feature.addValue(this.fields.get(2), entity.getText()); + if(this.readXData){ + + List xDatas = entity.getExtendedData(); + String xmlXData = ""; + + if(xDatas.isEmpty()){ + xmlXData = ""; + }else{ + + xmlXData = ""; + for(ExtendedData xData : xDatas){ + xmlXData+="" + String.valueOf(xData.getValue()) + ""; + } + xmlXData+=""; + feature.addValue(this.fields.get(3), xmlXData); + } + } + features.add(feature); entityNumber += 1; } else { diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/DXFWriter.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/DXFWriter.java index 3a06b29..41e9b50 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/DXFWriter.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/DXFWriter.java @@ -1,55 +1,34 @@ -package com.atolcd.pentaho.di.gis.io; - -/* - * #%L - * Pentaho Data Integrator GIS Plugin - * %% - * Copyright (C) 2015 Atol CD - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * . - * #L% - */ - - -import java.io.FileWriter; +package com.atolcd.pentaho.di.gis.io; + import java.io.IOException; import java.text.Normalizer; -import java.util.ArrayList; -import java.util.HashSet; +import java.util.Date; import java.util.List; -import java.util.Set; import java.util.regex.Pattern; -import org.pentaho.di.core.exception.KettleException; - +import com.atolcd.gis.dxf.Entity; +import com.atolcd.gis.dxf.Layer; import com.atolcd.pentaho.di.gis.io.features.Feature; +import com.atolcd.pentaho.di.gis.io.features.Field.FieldType; +import com.atolcd.pentaho.di.gis.io.features.Value; import com.atolcd.pentaho.di.gis.utils.GeometryUtils; import com.vividsolutions.jts.geom.Geometry; +import org.pentaho.di.core.exception.KettleException; + import fr.michaelm.jump.drivers.dxf.DxfFile; public class DXFWriter extends AbstractFileWriter { - private DxfFile dxfFile; private String dxfFileName; private String layerName; private String layerNameFieldName; private boolean forceTo2DGeometry; private int precision; + private boolean exportWithAttributs; - public DXFWriter(String fileName, String layerName, String geometryFieldName, String charsetName) throws KettleException { + public DXFWriter(String fileName, String layerName, String geometryFieldName, String charsetName) + throws KettleException { super(geometryFieldName, charsetName); this.dxfFileName = checkFilename(fileName).getFile(); @@ -59,10 +38,10 @@ public DXFWriter(String fileName, String layerName, String geometryFieldName, St this.layerName = checkLayerName(layerName); } this.layerNameFieldName = null; - this.dxfFile = new DxfFile(); + new DxfFile(); this.forceTo2DGeometry = false; this.precision = 0; - + this.exportWithAttributs = true; } public int getPrecision() { @@ -85,53 +64,46 @@ public void setLayerNameFieldName(String layerNameFieldName) { this.layerNameFieldName = layerNameFieldName; } + public void setExportWithAttributs(boolean exportWithAttributs) { + this.exportWithAttributs = exportWithAttributs; + } + public void writeFeatures(List features) throws KettleException { try { - Set layerNames = new HashSet(); - List geometries = new ArrayList(); - - for (Feature feature : features) { - - Geometry geometry = (Geometry) feature.getValue(feature.getField(this.geometryFieldName)); - - if (!GeometryUtils.isNullOrEmptyGeometry(geometry)) { - - if (this.forceTo2DGeometry) { - geometry = GeometryUtils.get2DGeometry(geometry); - } - - if (this.layerNameFieldName != null) { - - String featureLayerName = (String) feature.getValue(feature.getField(this.layerNameFieldName)); - if (featureLayerName != null && !featureLayerName.isEmpty()) { - - featureLayerName = checkLayerName(featureLayerName); - layerNames.add(featureLayerName); - geometry.setUserData(featureLayerName); - - } else { - geometry.setUserData(this.layerName); - layerNames.add(this.layerName); - } - - } else { - - geometry.setUserData(this.layerName); - layerNames.add(this.layerName); - - } - - geometries.add(geometry); - - } + com.atolcd.gis.dxf.DXFWriter dxfWriter= new com.atolcd.gis.dxf.DXFWriter(this.dxfFileName); + + //Plusieurs layers potentiels + if (this.layerNameFieldName != null) { + + + }else{ + + //Un seul Layer + Layer layer = new Layer(this.layerName); + + long fid = 0; + for (Feature feature : features) { + + Geometry geometry = (Geometry) feature.getValue(feature.getField(this.geometryFieldName)); + if (!GeometryUtils.isNullOrEmptyGeometry(geometry)) { + layer.getEntities().add(toEntity(feature,String.valueOf(fid),null)); + fid++; + } + + } + + dxfWriter.addLayer(layer); + } - - this.dxfFile.write(geometries, layerNames.toArray(new String[layerNames.size()]), new FileWriter(this.dxfFileName), this.precision); + + dxfWriter.write(this.precision, this.exportWithAttributs); } catch (IOException e) { throw new KettleException("Error writing features to " + this.dxfFileName, e); + } catch (Exception e) { + throw new KettleException("Error converting to Entity " + this.dxfFileName, e); } } @@ -143,4 +115,61 @@ private String checkLayerName(String layerName) { } + private Entity toEntity(Feature feature, String id, String text) throws Exception { + + Geometry geometry = (Geometry) feature.getValue(feature.getField(this.geometryFieldName)); + + if(this.forceTo2DGeometry){ + geometry = GeometryUtils.get2DGeometry(geometry); + } + + Entity entity = new Entity( + id, + geometry, + "", + text); + + if(this.exportWithAttributs){ + + for(Value value : feature.getValues()){ + + if(!value.getField().getType().equals(FieldType.GEOMETRY) + && !value.getField().getType().equals(FieldType.BINARY)){ + + Class classz = null; + + if (value.getField().getType().equals(FieldType.STRING)) { + classz = String.class; + + } else if (value.getField().getType().equals(FieldType.LONG)) { + classz = Long.class; + + } else if (value.getField().getType().equals(FieldType.DOUBLE)) { + classz = Double.class; + + } else if (value.getField().getType().equals(FieldType.BOOLEAN)) { + classz = Boolean.class; + + } else if (value.getField().getType().equals(FieldType.DATE)) { + classz = Date.class; + } + + if(classz !=null){ + + entity.AddExtendedData( + value.getField().getName(), + String.class, + String.valueOf(value.getValue()) + ); + + } + } + + } + + } + + return entity; + } + } diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/GPXReader.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/GPXReader.java new file mode 100644 index 0000000..6f238cc --- /dev/null +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/GPXReader.java @@ -0,0 +1,157 @@ +package com.atolcd.pentaho.di.gis.io; + +/* + * #%L + * Pentaho Data Integrator GIS Plugin + * %% + * Copyright (C) 2015 Atol CD + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * . + * #L% + */ +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.pentaho.di.core.exception.KettleException; + +import com.atolcd.gis.gpx.AbstractReaderWriter; +import com.atolcd.gis.gpx.type.Route; +import com.atolcd.gis.gpx.type.Track; +import com.atolcd.gis.gpx.type.WayPoint; +import com.atolcd.pentaho.di.gis.io.features.Feature; +import com.atolcd.pentaho.di.gis.io.features.Field; +import com.atolcd.pentaho.di.gis.io.features.Field.FieldType; +import com.atolcd.pentaho.di.gis.utils.GeometryUtils; +import com.vividsolutions.jts.geom.Geometry; + +public class GPXReader extends AbstractFileReader { + + private String gpxFileName; + private boolean gpxFileExist; + + public GPXReader(String fileName, String geometryFieldName, String charsetName) + throws KettleException { + super(null, geometryFieldName, charsetName); + + try { + this.gpxFileExist = new File(checkFilename(fileName).getFile()).exists(); + + if (!this.gpxFileExist) { + throw new KettleException("Missing " + fileName + " file"); + } else { + this.gpxFileName = checkFilename(fileName).getFile(); + } + + this.fields.add(new Field(geometryFieldName, FieldType.GEOMETRY, null, null)); + this.fields.add(new Field("type", FieldType.STRING, null, null)); + this.fields.add(new Field("name", FieldType.STRING, null, null)); + this.fields.add(new Field("description", FieldType.STRING, null, null)); + + } catch (Exception e) { + throw new KettleException("Error initialize reader", e); + } + } + + public List getFeatures() throws KettleException { + List features = new ArrayList(); + + try { + + com.atolcd.gis.gpx.type.Document gpxDocument = new com.atolcd.gis.gpx.GpxReader().read(gpxFileName, this.charset.displayName()); + + List wayPoints = gpxDocument.getWayPoints(); + List routes = gpxDocument.getRoutes(); + List tracks = gpxDocument.getTracks(); + + int entitiesTotalNumber = wayPoints.size() + routes.size() + tracks.size(); + + if (this.limit == 0 || this.limit > entitiesTotalNumber || this.limit < 0) { + this.limit = entitiesTotalNumber; + } + + int entityNumber = 0; + + //WPT + for (WayPoint wayPoint : wayPoints) { + if (entityNumber < this.limit) { + + Feature feature = new Feature(); + if (this.forceTo2DGeometry) { + feature.addValue(this.fields.get(0),GeometryUtils.get2DGeometry(wayPoint.getGeometry())); + }else{ + feature.addValue(this.fields.get(0), wayPoint.getGeometry()); + } + feature.addValue(this.fields.get(1), AbstractReaderWriter.GPX_TAG_WPT); + feature.addValue(this.fields.get(2), wayPoint.getName()); + feature.addValue(this.fields.get(3), wayPoint.getDescription()); + + features.add(feature); + entityNumber ++; + } else { + break; + } + } + + //RTE + for (Route route : routes) { + if (entityNumber < this.limit) { + + Feature feature = new Feature(); + if (this.forceTo2DGeometry) { + feature.addValue(this.fields.get(0),GeometryUtils.get2DGeometry(route.getGeometry())); + }else{ + feature.addValue(this.fields.get(0), route.getGeometry()); + } + feature.addValue(this.fields.get(1), AbstractReaderWriter.GPX_TAG_RTE); + feature.addValue(this.fields.get(2), route.getName()); + feature.addValue(this.fields.get(3), route.getDescription()); + + features.add(feature); + entityNumber++; + } else { + break; + } + } + + //TRK + for (Track track : tracks) { + if (entityNumber < this.limit) { + + Feature feature = new Feature(); + Geometry geometry = GeometryUtils.getNonEmptyGeometry(4326,GeometryUtils.getMultiGeometry(track.getGeometry())); + if (this.forceTo2DGeometry) { + feature.addValue(this.fields.get(0),GeometryUtils.get2DGeometry(geometry)); + }else{ + feature.addValue(this.fields.get(0),geometry); + } + + feature.addValue(this.fields.get(1), AbstractReaderWriter.GPX_TAG_TRK); + feature.addValue(this.fields.get(2), track.getName()); + feature.addValue(this.fields.get(3), track.getDescription()); + + features.add(feature); + entityNumber++; + } else { + break; + } + } + + } catch (Exception e) { + throw new KettleException("Error reading features" + this.gpxFileName, e); + } + return features; + } +} diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/GPXWriter.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/GPXWriter.java new file mode 100644 index 0000000..e484033 --- /dev/null +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/GPXWriter.java @@ -0,0 +1,321 @@ +package com.atolcd.pentaho.di.gis.io; + +/* + * #%L + * Pentaho Data Integrator GIS Plugin + * %% + * Copyright (C) 2015 Atol CD + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * . + * #L% + */ + + +import java.io.Writer; +import java.util.GregorianCalendar; +import java.util.Iterator; +import java.util.List; + +import org.pentaho.di.core.exception.KettleException; + +import com.atolcd.gis.gpx.GpxWriter; +import com.atolcd.gis.gpx.type.AbstractSpatialElement; +import com.atolcd.gis.gpx.type.Author; +import com.atolcd.gis.gpx.type.Document; +import com.atolcd.gis.gpx.type.Metadata; +import com.atolcd.gis.gpx.type.Route; +import com.atolcd.gis.gpx.type.Track; +import com.atolcd.gis.gpx.type.WayPoint; +import com.atolcd.pentaho.di.gis.io.features.Feature; +import com.atolcd.pentaho.di.gis.io.features.Field; +import com.vividsolutions.jts.geom.Envelope; +import com.vividsolutions.jts.geom.Geometry; +import com.vividsolutions.jts.geom.Point; +import com.vividsolutions.jts.geom.LineString; +import com.vividsolutions.jts.geom.MultiLineString; + +public class GPXWriter extends AbstractFileWriter { + + private static String GPX_CREATOR = "Pentaho Data Integration - GIS plugins"; + + private String gpxFileName; + private String version; + private String documentName; + private String documentDescription; + private String authorName; + private String authorEmail; + private String keywords; + private GregorianCalendar datetime; + + + private String featureNameField; + private String featureDescriptionField; + + private Writer writer; + private boolean isServletOutput; + + public GPXWriter(String fileName, String geometryFieldName, String charsetName) throws KettleException { + + super(geometryFieldName, charsetName); + + this.gpxFileName = checkFilename(fileName).getFile(); + this.writer = null; + this.isServletOutput = false; + + this.version = Document.GPX_VERSION_1_1; + this.documentName = null; + this.documentDescription = null; + this.authorName = null; + this.authorEmail = null; + this.keywords = null; + this.datetime = null; + + this.featureNameField = null; + this.featureDescriptionField = null; + + } + + public GPXWriter(Writer writer, String geometryFieldName, String charsetName) throws KettleException { + + super(geometryFieldName, charsetName); + + this.gpxFileName = null; + this.writer = writer; + this.isServletOutput = true; + + this.version = Document.GPX_VERSION_1_1; + this.documentName = null; + this.documentDescription = null; + this.authorName = null; + this.authorEmail = null; + this.keywords = null; + this.datetime = null; + + this.featureNameField = null; + this.featureDescriptionField = null; + + + } + + public String getDocumentName() { + return documentName; + } + + public void setDocumentName(String documentName) { + this.documentName = documentName; + } + + public String getDocumentDescription() { + return documentDescription; + } + + public void setDocumentDescription(String documentDescription) { + this.documentDescription = documentDescription; + } + + public String getFeatureNameField() { + return featureNameField; + } + + public void setFeatureNameField(String featureNameField) { + this.featureNameField = featureNameField; + } + + public String getFeatureDescriptionField() { + return featureDescriptionField; + } + + public void setFeatureDescriptionField(String featureDescriptionField) { + this.featureDescriptionField = featureDescriptionField; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getAuthorName() { + return authorName; + } + + public void setAuthorName(String authorName) { + this.authorName = authorName; + } + + public String getAuthorEmail() { + return authorEmail; + } + + public void setAuthorEmail(String authorEmail) { + this.authorEmail = authorEmail; + } + + public String getKeywords() { + return keywords; + } + + public void setKeywords(String keywords) { + this.keywords = keywords; + } + + public GregorianCalendar getDatetime() { + return datetime; + } + + public void setDatetime(GregorianCalendar datetime) { + this.datetime = datetime; + } + + public void writeFeatures(List features) throws KettleException { + + try{ + + Document gpxDocument = new Document(); + gpxDocument.setCreator(GPX_CREATOR); + gpxDocument.setVersion(this.version); + + Metadata metadata = new Metadata(); + if (this.documentName != null && !this.documentName.isEmpty()) { + metadata.setName(this.documentName); + } + + if (this.documentDescription != null && !this.documentDescription.isEmpty()) { + metadata.setDescription(this.documentDescription); + } + + if (this.authorName != null && !this.authorName.isEmpty()) { + + metadata.setAuthor(new Author(this.authorName,this.authorEmail)); + } + + if (this.keywords != null && !this.keywords.isEmpty()) { + + metadata.setKeywords(this.keywords); + } + + if (this.datetime != null) { + + metadata.setTime(this.datetime); + } + + + gpxDocument.setMetadata(metadata); + + // Récupération des champs utilisés + Field geometryField = null; + Field nameField = null; + Field descriptionField = null; + + Iterator featureIt = features.iterator(); + boolean first = true; + while (featureIt.hasNext()) { + + Feature feature = featureIt.next(); + if (first) { + + geometryField = feature.getField(this.geometryFieldName); + + if (featureNameField != null) { + nameField = feature.getField(this.featureNameField); + } + + if (featureDescriptionField != null) { + descriptionField = feature.getField(this.featureDescriptionField); + } + + first = false; + } + + //Récupération de la géométrie + Geometry geometry = (Geometry) feature.getValue(geometryField); + + // Vérification de l'emprise : doit être en WGS 84 + Envelope envelope = geometry.getEnvelopeInternal(); + if (envelope.getMaxX() > 180 || envelope.getMinX() < -180 || envelope.getMaxY() > 90 || envelope.getMinY() < -90) { + + throw new KettleException("Bad coordinates for WGS84 system"); + + } + + //Alimention du GPX + AbstractSpatialElement spatialElement; + + + //Conversion de geometrie + //Conversion JTS en GPX + //- Point -> Gpx Wpt , + //- LineString -> Gpx Route , + //- MultilineString -> Gpx Track + if(geometry instanceof Point){ + spatialElement = new WayPoint(geometry.getCoordinate()); + gpxDocument.getWayPoints().add((WayPoint) spatialElement); + + }else if(geometry instanceof LineString){ + spatialElement = new Route((LineString) geometry); + gpxDocument.getRoutes().add((Route) spatialElement); + + }else if(geometry instanceof MultiLineString){ + spatialElement = new Track((MultiLineString) geometry); + gpxDocument.getTracks().add((Track) spatialElement); + + }else{ + throw new KettleException("Only Point , LineString and MultilineString are allowed."); + + } + + // Nom de feature + if (featureNameField != null) { + String name = (String) feature.getValue(nameField); + if (name != null && !name.isEmpty()) { + spatialElement.setName(name); + } + + } + + // Description de feature + if (featureDescriptionField != null) { + String description = (String) feature.getValue(descriptionField); + if (description != null && !description.isEmpty()) { + spatialElement.setDescription(description); + } + } + + + //Ecriture du fichier ou du flux + GpxWriter gpxWriter = new GpxWriter(); + if (isServletOutput) { + + if (features.size() > 0) { + gpxWriter.write(gpxDocument, writer, this.charset.name()); + } + + } else { + + gpxWriter.write(gpxDocument, this.gpxFileName, this.charset.name()); + + } + } + + + + }catch(Exception e){ + throw new KettleException(e.getMessage()); + } + } + +} diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/GeoPackageReader.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/GeoPackageReader.java new file mode 100644 index 0000000..d358f5a --- /dev/null +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/GeoPackageReader.java @@ -0,0 +1,592 @@ +package com.atolcd.pentaho.di.gis.io; + +/* + * #%L + * Pentaho Data Integrator GIS Plugin + * %% + * Copyright (C) 2015 Atol CD + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * . + * #L% + */ + + +import java.io.File; +import java.sql.SQLException; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import mil.nga.geopackage.GeoPackage; +import mil.nga.geopackage.contents.Contents; +import mil.nga.geopackage.contents.ContentsDao; +import mil.nga.geopackage.db.GeoPackageDataType; +import mil.nga.geopackage.features.user.FeatureRow; +import mil.nga.geopackage.features.user.FeatureTable; +import mil.nga.geopackage.geom.GeoPackageGeometryData; +import mil.nga.geopackage.GeoPackageManager; +import mil.nga.geopackage.user.UserColumn; +import mil.nga.geopackage.user.UserCoreResult; +import mil.nga.geopackage.user.UserCoreRow; +import mil.nga.geopackage.user.UserDao; +import mil.nga.geopackage.user.UserTable; + +import org.pentaho.di.core.exception.KettleException; + +import com.atolcd.pentaho.di.gis.io.features.Feature; +import com.atolcd.pentaho.di.gis.io.features.Field; +import com.atolcd.pentaho.di.gis.io.features.Field.FieldType; +import com.atolcd.pentaho.di.gis.utils.GeometryUtils; +import com.vividsolutions.jts.geom.Envelope; +import com.vividsolutions.jts.geom.Geometry; +import com.vividsolutions.jts.geom.GeometryFactory; + + +public class GeoPackageReader extends AbstractFileReader { + + private static String GPKG_CONTENTS_TABLE_NAME = "gpkg_contents"; + private static GeometryFactory geometryFactory = new GeometryFactory(); + private static SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-DD"); + private static SimpleDateFormat dateTimeFormat = new SimpleDateFormat(" YYYY-MM-DD HH:MM:SS.SSSZ"); + + private String gpkgFileName; + private boolean gpkgFileExist; + @SuppressWarnings("rawtypes") + private HashMap gpkgTables; + private boolean gpkgContents; + + @SuppressWarnings("rawtypes") + public GeoPackageReader(String fileName, String tableName, String geometryFieldName, String charsetName) throws KettleException { + + super(tableName, null, charsetName); + + this.gpkgFileExist = new File(checkFilename(fileName).getFile()).exists(); + + if (!this.gpkgFileExist) { + throw new KettleException("Missing " + fileName + " file"); + } else { + this.gpkgFileName = checkFilename(fileName).getFile(); + } + + if(tableName.equalsIgnoreCase("*")){ + this.layerName = GeoPackageReader.GPKG_CONTENTS_TABLE_NAME; + }else{ + this.layerName = tableName; + } + this.gpkgTables = new HashMap(); + this.gpkgContents = false; + this.geometryFieldName = geometryFieldName; + + GeoPackage geoPackage = GeoPackageManager.open(new File(this.gpkgFileName)); + + //Si table gpk_contents + if(this.layerName.equalsIgnoreCase(GeoPackageReader.GPKG_CONTENTS_TABLE_NAME)){ + + //Liste les tables de type + //- features + //- attributes + //- tiles + //- autres si extensions + + this.fields.add(new Field("table_name",FieldType.STRING,null,null)); + this.fields.add(new Field("data_type",FieldType.STRING,null,null)); + this.fields.add(new Field("identifier",FieldType.STRING,null,null)); + this.fields.add(new Field("description",FieldType.STRING,null,null)); + this.fields.add(new Field("last_change",FieldType.DATE,null,null)); + this.fields.add(new Field("min_x",FieldType.DOUBLE,null,null)); + this.fields.add(new Field("min_y",FieldType.DOUBLE,null,null)); + this.fields.add(new Field("max_x",FieldType.DOUBLE,null,null)); + this.fields.add(new Field("max_y",FieldType.DOUBLE,null,null)); + this.fields.add(new Field("srs_id",FieldType.LONG,null,null)); + this.gpkgContents = true; + + //Sinon, table "features" ou "attributes" + }else{ + + //Collection de toutes les tables "features" ou "attributes" + //avec nom en majuscule + + //Liste des tables "attributes" + for(String table : geoPackage.getAttributesTables()){ + this.gpkgTables.put(table.toUpperCase(), geoPackage.getAttributesDao(table).getTable()); + } + + //Liste des tables "features" + for(String table : geoPackage.getFeatureTables()){ + this.gpkgTables.put(table.toUpperCase(), geoPackage.getFeatureDao(table).getTable()); + } + + //Si table non trouvée + if(!this.gpkgTables.containsKey(this.layerName.toUpperCase())){ + throw new KettleException("Error initialize reader : Table " + this.layerName + " not found"); + } + + //Récupère la table + UserTable table = this.gpkgTables.get(this.layerName.toUpperCase()); + + //Boucle sur les champs + for(int i = 0; i < table.columnCount(); i++){ + + UserColumn column = table.getColumn(i); + Field field = null; + + //Si type null teste si table de features + //et colonne de "geometry" + if (column.getDataType() == null) { + + if(table instanceof FeatureTable && column.getIndex() == ((FeatureTable)table).getGeometryColumnIndex()){ + + field = new Field(this.geometryFieldName, FieldType.GEOMETRY, null, null); + + }else{ + throw new KettleException("Error initialize reader : Unknow data type for column " + column.getName()); + } + } else if (column.getDataType().equals(GeoPackageDataType.BLOB)) { + + if(table instanceof FeatureTable && column.getIndex() == ((FeatureTable)table).getGeometryColumnIndex()){ + + field = new Field(this.geometryFieldName, FieldType.GEOMETRY, null, null); + } + + } else if (column.getDataType().equals(GeoPackageDataType.BLOB)) { + field = new Field(column.getName(), FieldType.BINARY, null, null); + + } else if (column.getDataType().equals(GeoPackageDataType.BOOLEAN)) { + field = new Field(column.getName(), FieldType.BOOLEAN, null, null); + + } else if (column.getDataType().equals(GeoPackageDataType.DATE)) { + field = new Field(column.getName(), FieldType.DATE, null, null); + + } else if (column.getDataType().equals(GeoPackageDataType.DATETIME)) { + field = new Field(column.getName(), FieldType.DATE, null, null); + + } else if (column.getDataType().equals(GeoPackageDataType.DOUBLE)) { + field = new Field(column.getName(), FieldType.DOUBLE, null, null); + + } else if (column.getDataType().equals(GeoPackageDataType.FLOAT)) { + field = new Field(column.getName(), FieldType.DOUBLE, null, null); + + } else if (column.getDataType().equals(GeoPackageDataType.INT)) { + field = new Field(column.getName(), FieldType.LONG, null, null); + + } else if (column.getDataType().equals(GeoPackageDataType.INTEGER)) { + field = new Field(column.getName(), FieldType.LONG, null, null); + + } else if (column.getDataType().equals(GeoPackageDataType.MEDIUMINT)) { + field = new Field(column.getName(), FieldType.LONG, null, null); + + } else if (column.getDataType().equals(GeoPackageDataType.REAL)) { + field = new Field(column.getName(), FieldType.DOUBLE, null, null); + + } else if (column.getDataType().equals(GeoPackageDataType.SMALLINT)) { + field = new Field(column.getName(), FieldType.LONG, null, null); + + } else if (column.getDataType().equals(GeoPackageDataType.TEXT)) { + field = new Field(column.getName(), FieldType.STRING, null, null); + + } else if (column.getDataType().equals(GeoPackageDataType.TINYINT)) { + field = new Field(column.getName(), FieldType.LONG, null, null); + + }else{ + throw new KettleException("Error initialize reader : Type of column " + column.getType() + " not allowed for attribut table " + this.layerName); + + } + + this.fields.add(field); + + } + + } + + geoPackage.close(); + + } + + @SuppressWarnings("rawtypes") + public List getFeatures() throws KettleException { + + List features = new ArrayList(); + long entityNumber = 0; + + + GeoPackage geoPackage = GeoPackageManager.open(new File(this.gpkgFileName)); + + //Si table gpk_contents + if(this.gpkgContents){ + + //Récupère le contenu + ContentsDao contentsDao = geoPackage.getContentsDao(); + long entitiesTotalNumber = 0; + try { + entitiesTotalNumber = contentsDao.countOf(); + } catch (SQLException e) { + throw new KettleException("Error reading features :" + e.getMessage()); + } + if (this.limit == 0 || this.limit > entitiesTotalNumber || this.limit < 0) { + this.limit = entitiesTotalNumber; + } + + //Boucle sur chaque content tant que limite non atteinte + for(Contents contents : contentsDao){ + + if (entityNumber < this.limit) { + Feature feature = new Feature(); + feature.addValue(this.getField("table_name"), contents.getTableName()); + feature.addValue(this.getField("data_type"), contents.getDataType().getName()); + feature.addValue(this.getField("identifier"), contents.getIdentifier()); + feature.addValue(this.getField("description"), contents.getDescription()); + feature.addValue(this.getField("last_change"), contents.getLastChange()); + feature.addValue(this.getField("min_x"), contents.getMinX()); + feature.addValue(this.getField("min_y"), contents.getMinY()); + feature.addValue(this.getField("max_x"), contents.getMaxX()); + feature.addValue(this.getField("max_y"), contents.getMaxY()); + feature.addValue(this.getField("srs_id"), contents.getSrsId()); + + features.add(feature); + entityNumber++; + + } else { + break; + } + } + + //Sinon, table de feature ou d'attributs + }else{ + + //Récupère la table + UserTable table = this.gpkgTables.get(this.layerName.toUpperCase()); + UserDao userDao = null; + + if(table instanceof FeatureTable){ + userDao = geoPackage.getFeatureDao(table.getTableName()); + }else{ + userDao = geoPackage.getAttributesDao(table.getTableName()); + } + + //Requête avec limite + UserCoreResult userCoreResult = null; + if (this.limit <= 0) { + userCoreResult = userDao.queryForAll(); + }else{ + userCoreResult = userDao.query(null, null,null,null,null, null, String.valueOf(this.limit)); + } + + //Bouche sur chaque ligne du résultat + while(userCoreResult.moveToNext()){ + + UserCoreRow userCoreRow = userCoreResult.getRow(); + Feature feature = new Feature(); + + for(Field field : this.fields){ + + Object inValue = null; + Object outValue = null; + + if(field.getType().equals(FieldType.GEOMETRY)){ + inValue = ((FeatureRow)userCoreRow).getGeometry(); + }else{ + inValue = userCoreRow.getValue(field.getName()); + } + + if(inValue != null){ + + //byte[] + if(field.getType().equals(FieldType.BINARY)){ + + outValue = (byte[]) inValue; + + //boolean + }else if(field.getType().equals(FieldType.BOOLEAN)){ + + outValue = (Boolean) inValue; + + //date + }else if(field.getType().equals(FieldType.DATE)){ + + try { + if(table.getColumn(field.getName()).getDataType().equals(GeoPackageDataType.DATE)){ + outValue = dateFormat.parse(inValue.toString()); + + }else{ + outValue = dateTimeFormat.parse(inValue.toString()); + } + + } catch (ParseException e) { + throw new KettleException("Error reading features :" + e.getMessage()); + } + + //double + }else if(field.getType().equals(FieldType.DOUBLE)){ + + outValue = Double.parseDouble(inValue.toString()); + + //geometry + }else if(field.getType().equals(FieldType.GEOMETRY)){ + + GeoPackageGeometryData geometryData = (GeoPackageGeometryData) inValue; + Geometry jtsGeometry = toJtsGeometry(geometryData.getGeometry()); + jtsGeometry.setSRID(geometryData.getSrsId()); + + if (this.forceTo2DGeometry) { + jtsGeometry = GeometryUtils.get2DGeometry(jtsGeometry); + } + + if (this.forceToMultiGeometry) { + jtsGeometry = GeometryUtils.getMultiGeometry(jtsGeometry); + } + + outValue = jtsGeometry; + + //long + }else if(field.getType().equals(FieldType.LONG)){ + + outValue = Long.parseLong(inValue.toString()); + + //String + }else if(field.getType().equals(FieldType.STRING)){ + outValue = inValue.toString(); + + } + + } + + feature.addValue(field, outValue); + + } + + features.add(feature); + + } + + } + + geoPackage.close(); + + return features; + + } + + /** + * JTS Envelope to Gpkg bounding box + * @param boundingBox + * @return + */ + public static Envelope toJtsBounds(mil.nga.geopackage.BoundingBox bounds){ + + Envelope jtsBounds = new Envelope(); + jtsBounds.init( + bounds.getMinLongitude(), + bounds.getMaxLongitude(), + bounds.getMinLatitude(), + bounds.getMaxLatitude() + ); + return jtsBounds; + + } + + /** + * Gpkg Geometry to JTS Geometry + * @param geometry + * @return + * @throws KettleException + * @throws GpkgGeometryConverterException + */ + public static com.vividsolutions.jts.geom.Geometry toJtsGeometry(mil.nga.sf.Geometry geometry) throws KettleException{ + + com.vividsolutions.jts.geom.Geometry jtsGeometry = null; + + if(geometry != null){ + + //Point + if (geometry.getGeometryType().equals(mil.nga.sf.GeometryType.POINT)){ + return toJtsPoint((mil.nga.sf.Point) geometry); + + //MultiPoint + }else if (geometry.getGeometryType().equals(mil.nga.sf.GeometryType.MULTIPOINT)){ + return toJtsMultiPoint((mil.nga.sf.MultiPoint) geometry); + + //LineString + }else if (geometry.getGeometryType().equals(mil.nga.sf.GeometryType.LINESTRING)){ + return toJtsLineString((mil.nga.sf.LineString) geometry); + + //MultiLineString + }else if (geometry.getGeometryType().equals(mil.nga.sf.GeometryType.MULTILINESTRING)){ + return toJtsMultiLineString((mil.nga.sf.MultiLineString) geometry); + + //Polygon + }else if (geometry.getGeometryType().equals(mil.nga.sf.GeometryType.POLYGON)){ + return toJtsPolygon((mil.nga.sf.Polygon) geometry); + + //MultiPolygon + }else if(geometry.getGeometryType().equals(mil.nga.sf.GeometryType.MULTIPOLYGON)){ + return toJtsMultiPolygon((mil.nga.sf.MultiPolygon) geometry); + + //GeometryCollection + }else if(geometry.getGeometryType().equals(mil.nga.sf.GeometryType.GEOMETRYCOLLECTION)){ + + List jtsGeometries = new ArrayList(); + for(mil.nga.sf.Geometry gpkgSubgeometry : ((mil.nga.sf.GeometryCollection) geometry).getGeometries()){ + jtsGeometries.add(toJtsGeometry(gpkgSubgeometry)); + } + + return geometryFactory.createGeometryCollection(jtsGeometries.toArray(new com.vividsolutions.jts.geom.Geometry[jtsGeometries.size()])); + + }else{ + + throw new KettleException(geometry.getGeometryType().getName() + " is not supported."); + + } + + } + + return jtsGeometry; + } + + /** + * Gpkg Point to JTS Coordinate + * @param point + * @return + */ + private static com.vividsolutions.jts.geom.Coordinate toJtsCoordinate(mil.nga.sf.Point point) { + + com.vividsolutions.jts.geom.Coordinate coordinate = new com.vividsolutions.jts.geom.Coordinate(point.getX(), point.getY()); + if(point.getZ() != null){ + coordinate.z = point.getZ(); + } + + return coordinate; + + } + + /** + * Gpkg Points to JTS Coordinates + * @param linestring + * @return + */ + @SuppressWarnings("unchecked") + private static com.vividsolutions.jts.geom.Coordinate[] toJtsCoordinates(List points) { + + com.vividsolutions.jts.geom.CoordinateList coordinateList = new com.vividsolutions.jts.geom.CoordinateList(); + for(mil.nga.sf.Point point : points){ + coordinateList.add(toJtsCoordinate(point)); + } + + return coordinateList.toCoordinateArray(); + + } + + /** + * Gpkg Point to JTS Point + * @param point + * @return + */ + private static com.vividsolutions.jts.geom.Point toJtsPoint(mil.nga.sf.Point point) { + + return geometryFactory.createPoint(toJtsCoordinate((mil.nga.sf.Point) point)); + + } + + /** + * Gpkg MultiPoint to JTS MultiPoint + * @param multiPoint + * @return + */ + private static com.vividsolutions.jts.geom.MultiPoint toJtsMultiPoint(mil.nga.sf.MultiPoint multiPoint) { + + return geometryFactory.createMultiPoint(toJtsCoordinates(multiPoint.getPoints())); + + } + + /** + * Gpkg LineString to JTS LineString + * @param lineString + * @return + */ + private static com.vividsolutions.jts.geom.LineString toJtsLineString(mil.nga.sf.LineString lineString) { + + return geometryFactory.createLineString(toJtsCoordinates(lineString.getPoints())); + + } + + /** + * Gpkg MultiLineString to JTS MultiLineString + * @param multiLineString + * @return + */ + private static com.vividsolutions.jts.geom.MultiLineString toJtsMultiLineString(mil.nga.sf.MultiLineString multiLineString) { + + List lineStrings = new ArrayList() ; + for(mil.nga.sf.LineString linestring : ((mil.nga.sf.MultiLineString) multiLineString).getLineStrings()){ + lineStrings.add(toJtsLineString(linestring)); + } + + return geometryFactory.createMultiLineString(lineStrings.toArray(new com.vividsolutions.jts.geom.LineString[lineStrings.size()])); + + } + + /** + * Gpkg Polygon to JTS Polygon + * @param polygon + * @return + */ + private static com.vividsolutions.jts.geom.Polygon toJtsPolygon(mil.nga.sf.Polygon polygon) { + + mil.nga.sf.GeometryEnvelope envelope = mil.nga.sf.util.GeometryEnvelopeBuilder.buildEnvelope(polygon); + + com.vividsolutions.jts.geom.LinearRing exteriorRing = null; + List interiorRings = new ArrayList() ; + + for(mil.nga.sf.LineString ring : ((mil.nga.sf.Polygon) polygon).getRings()){ + + com.vividsolutions.jts.geom.LinearRing linearRing = geometryFactory.createLinearRing(toJtsCoordinates(ring.getPoints())); + com.vividsolutions.jts.geom.Envelope jtsEnvelope = linearRing.getEnvelopeInternal(); + + if(jtsEnvelope.getMinX() == envelope.getMinX() + && jtsEnvelope.getMinY() == envelope.getMinY() + && jtsEnvelope.getMaxX() == envelope.getMaxX() + && jtsEnvelope.getMaxY() == envelope.getMaxY() + ){ + exteriorRing = linearRing; + + }else{ + interiorRings.add(linearRing); + } + + } + + return geometryFactory.createPolygon(exteriorRing, interiorRings.toArray(new com.vividsolutions.jts.geom.LinearRing[interiorRings.size()])); + + } + + + /** + * Gpkg MultiPolygon to JTS MultiPolygon + * @param multiPolygon + * @return + */ + private static com.vividsolutions.jts.geom.MultiPolygon toJtsMultiPolygon(mil.nga.sf.MultiPolygon multiPolygon) { + + List polygons = new ArrayList(); + for(mil.nga.sf.Polygon polygon : ((mil.nga.sf.MultiPolygon) multiPolygon).getPolygons()){ + polygons.add(toJtsPolygon(polygon)); + }; + + return geometryFactory.createMultiPolygon(polygons.toArray(new com.vividsolutions.jts.geom.Polygon[polygons.size()])); + + } + +} diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/GeoPackageWriter.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/GeoPackageWriter.java new file mode 100644 index 0000000..2ea2a72 --- /dev/null +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/GeoPackageWriter.java @@ -0,0 +1,974 @@ +package com.atolcd.pentaho.di.gis.io; + +import java.io.File; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.TreeSet; + +import com.atolcd.pentaho.di.gis.io.features.Feature; +import com.atolcd.pentaho.di.gis.io.features.Field; +import com.atolcd.pentaho.di.gis.io.features.Field.FieldType; +import com.atolcd.pentaho.di.gis.utils.GeometryUtils; +import com.vividsolutions.jts.geom.Coordinate; +import com.vividsolutions.jts.geom.Envelope; +import com.vividsolutions.jts.geom.Geometry; +import com.vividsolutions.jts.geom.LineString; +import com.vividsolutions.jts.geom.MultiLineString; +import com.vividsolutions.jts.geom.MultiPoint; +import com.vividsolutions.jts.geom.MultiPolygon; +import com.vividsolutions.jts.geom.Point; +import com.vividsolutions.jts.geom.Polygon; + +import org.cts.CRSFactory; +import org.cts.crs.CRSException; +import org.cts.crs.CoordinateReferenceSystem; +import org.cts.registry.EPSGRegistry; +import org.cts.registry.RegistryManager; +import org.pentaho.di.core.exception.KettleException; + +import mil.nga.geopackage.BoundingBox; +import mil.nga.geopackage.GeoPackage; +import mil.nga.geopackage.GeoPackageManager; +import mil.nga.geopackage.attributes.AttributesColumn; +import mil.nga.geopackage.attributes.AttributesDao; +import mil.nga.geopackage.attributes.AttributesRow; +import mil.nga.geopackage.attributes.AttributesTable; +import mil.nga.geopackage.contents.Contents; +import mil.nga.geopackage.contents.ContentsDataType; +import mil.nga.geopackage.db.GeoPackageDataType; +import mil.nga.geopackage.extension.rtree.RTreeIndexExtension; +import mil.nga.geopackage.features.columns.GeometryColumns; +import mil.nga.geopackage.features.user.FeatureColumn; +import mil.nga.geopackage.features.user.FeatureDao; +import mil.nga.geopackage.features.user.FeatureRow; +import mil.nga.geopackage.features.user.FeatureTableMetadata; +import mil.nga.geopackage.geom.GeoPackageGeometryData; +import mil.nga.geopackage.user.ContentValues; + +/* + * #%L + * Pentaho Data Integrator GIS Plugin + * %% + * Copyright (C) 2015 Atol CD + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * . + * #L% + */ + + +public class GeoPackageWriter extends AbstractFileWriter { + + private String gpkgFileName; + private String tableName; + private String pkFieldName; + private String contentsIdentifier; + private String contentsDescription; + private boolean forceTo2DGeometry; + private boolean replaceFile; + private boolean replaceTable; + private Long assignedSrid; + private GpkgGeometryType assignedGeometryType; + private long commitLimit; + + public enum GpkgGeometryType{ + GEOMETRY(mil.nga.sf.GeometryType.GEOMETRY), + POINT(mil.nga.sf.GeometryType.POINT), + LINESTRING(mil.nga.sf.GeometryType.LINESTRING), + POLYGON(mil.nga.sf.GeometryType.POLYGON), + MULTIPOINT(mil.nga.sf.GeometryType.MULTIPOINT), + MULTILINESTRING(mil.nga.sf.GeometryType.MULTILINESTRING), + MULTIPOLYGON(mil.nga.sf.GeometryType.MULTIPOLYGON), + GEOMETRYCOLLECTION(mil.nga.sf.GeometryType.GEOMETRYCOLLECTION); + + private mil.nga.sf.GeometryType geometryType; + + GpkgGeometryType(mil.nga.sf.GeometryType geometryType){ + this.geometryType = geometryType; + + if(!geometryType.equals(mil.nga.sf.GeometryType.POINT) + || !geometryType.equals(mil.nga.sf.GeometryType.LINESTRING) + || !geometryType.equals(mil.nga.sf.GeometryType.POLYGON) + || !geometryType.equals(mil.nga.sf.GeometryType.MULTIPOINT) + || !geometryType.equals(mil.nga.sf.GeometryType.MULTILINESTRING) + || !geometryType.equals(mil.nga.sf.GeometryType.MULTIPOLYGON) + || !geometryType.equals(mil.nga.sf.GeometryType.GEOMETRYCOLLECTION)){ + + this.geometryType = geometryType; + + }else{ + this.geometryType = mil.nga.sf.GeometryType.GEOMETRY; + } + + } + + public mil.nga.sf.GeometryType toGpkgValue(){ + return geometryType; + } + + } + + public enum GpkgGeometryWithZType{ + PROHIBITED((byte)0), + MANDATORY((byte)1), + OPTIONAL((byte)2); + + private byte code; + + GpkgGeometryWithZType(byte code){ + this.code = code; + } + + public byte toGpkgValue(){ + return code; + } + + } + + public enum GpkgGeometryWithMType{ + PROHIBITED((byte)0); + + private byte code; + + GpkgGeometryWithMType(byte code){ + this.code = code; + } + + public byte toGpkgValue(){ + return code; + } + + } + + public GeoPackageWriter(String fileName, String tableName, String pkFieldName, String charsetName) throws KettleException { + this(fileName, tableName, pkFieldName, null, charsetName); + } + + + public GeoPackageWriter(String fileName, String tableName, String pkFieldName, String geometryFieldName, String charsetName) throws KettleException { + + super(geometryFieldName, charsetName); + if(geometryFieldName == null || geometryFieldName.isEmpty()){ + this.geometryFieldName = ""; + } + this.gpkgFileName = fileName; + this.tableName = tableName; + this.pkFieldName = pkFieldName; + this.contentsIdentifier = null; + this.contentsDescription = null; + this.forceTo2DGeometry = false; + this.replaceFile = false; + this.replaceTable = false; + this.assignedSrid = null; + this.assignedGeometryType = GpkgGeometryType.GEOMETRY; + this.commitLimit = 1; + } + + public void setReplaceFile(boolean replaceFile) { + this.replaceFile = replaceFile; + } + + public void setReplaceTable(boolean replaceTable) { + this.replaceTable = replaceTable; + } + + public void setContentsIdentifier(String contentsIdentifier) { + this.contentsIdentifier = contentsIdentifier; + } + + public void setContentsDescription(String contentsDescription) { + this.contentsDescription = contentsDescription; + } + + public void setForceTo2DGeometry(boolean forceTo2DGeometry) { + this.forceTo2DGeometry = forceTo2DGeometry; + } + + public void setAssignedSrid(long assignedSrid) { + this.assignedSrid = assignedSrid; + } + + public void setCommitLimit(long commitLimit) { + this.commitLimit = commitLimit; + } + + + public void setAssignedGeometryType(String geometryType) { + + if(geometryType.equalsIgnoreCase("POINT")){ + this.assignedGeometryType = GpkgGeometryType.POINT; + + }else if(geometryType.equalsIgnoreCase("LINESTRING")){ + this.assignedGeometryType = GpkgGeometryType.LINESTRING ; + + }else if(geometryType.equalsIgnoreCase("POLYGON")){ + this.assignedGeometryType = GpkgGeometryType.POLYGON ; + + }else if(geometryType.equalsIgnoreCase("MULTIPOINT")){ + this.assignedGeometryType = GpkgGeometryType.MULTIPOINT ; + + }else if(geometryType.equalsIgnoreCase("MULTILINESTRING")){ + this.assignedGeometryType = GpkgGeometryType.MULTILINESTRING ; + + }else if(geometryType.equalsIgnoreCase("MULTIPOLYGON")){ + this.assignedGeometryType = GpkgGeometryType.MULTIPOLYGON ; + + }else if(geometryType.equalsIgnoreCase("GEOMETRYCOLLECTION")){ + this.assignedGeometryType = GpkgGeometryType.GEOMETRYCOLLECTION ; + + }else{ + this.assignedGeometryType = GpkgGeometryType.GEOMETRY ; + } + + } + + public void writeFeatures(List features) throws KettleException { + + boolean createTable = true; + + //Fichier existe et demande remplacement + if(new File(checkFilename(this.gpkgFileName).getFile()).exists() && this.replaceFile){ + if(!new File(checkFilename(this.gpkgFileName).getFile()).delete()){ + throw new KettleException("File " + this.gpkgFileName + " can not be deleted."); + } + } + + //Fichier n'existe pas -> tentative de création + if(!new File(checkFilename(this.gpkgFileName).getFile()).exists()){ + + try{ + GeoPackageManager.create(new File(checkFilename(this.gpkgFileName).getFile())); + } + catch (Exception e){ + throw new KettleException("File " + this.gpkgFileName + " can not be created."); + } + } + + //Ouverture du fichier + GeoPackage geoPackage = GeoPackageManager.open(new File(checkFilename(this.gpkgFileName).getFile())); + if((geoPackage.getFeatureTables().contains(this.tableName) + || geoPackage.getAttributesTables().contains(this.tableName))){ + + if(this.replaceTable){ + geoPackage.deleteTableQuietly(this.tableName); + geoPackage.getContentsDao().deleteTable(this.tableName); + + }else{ + createTable = false; + } + + } + + //Récupération des colonnes de PK et de géométrie (si existe) + Field pkField = null; + Field geometryField = null; + List otherFields = new ArrayList(); + + //Toutes les colonnes sauf pk et geometry + for(Field field : this.fields){ + + //Autres colonnes + if(!field.getName().equalsIgnoreCase(this.pkFieldName) && !field.getType().equals(FieldType.GEOMETRY)){ + otherFields.add(field); + + }else{ + + //La colonne de PK + if(field.getName().equalsIgnoreCase(this.pkFieldName)){ + + if(!field.getType().equals(FieldType.LONG)){ + throw new KettleException("Field " + this.pkFieldName + " is not of Integer type. The PK field must be of type Integer"); + }else{ + pkField = field; + } + } + + //La colonne de geometry + if(field.getName().equalsIgnoreCase(this.geometryFieldName)){ + + if(!field.getType().equals(FieldType.GEOMETRY)){ + throw new KettleException("Field " + this.geometryFieldName + " is not of Geometry type."); + }else{ + geometryField = field; + } + } + + } + } + + //Contents + Contents contents = null; + + //Si création de table + if(createTable){ + contents = new Contents(); + contents.setDescription(this.contentsDescription); + contents.setIdentifier(this.contentsIdentifier); + contents.setTableName(this.tableName); + + //Feature Table + if(geometryField != null){ + + //SRS + mil.nga.geopackage.srs.SpatialReferenceSystem srs = null; + if(this.assignedSrid !=null){ + + //Inconnu geography/geometry + if(this.assignedSrid == 0 || this.assignedSrid == -1){ + try { + srs = geoPackage.getSpatialReferenceSystemDao().getOrCreateFromEpsg(this.assignedSrid); + } catch (SQLException e) { + throw new KettleException("Error writing features to " + this.gpkgFileName, e); + } + + //Code EPSG à priori connu + }else{ + + try { + srs = toGpkgSrs(this.assignedSrid); + geoPackage.getSpatialReferenceSystemDao().createIfNotExists(srs); + } catch (SQLException e) { + throw new KettleException("Error writing features to " + this.gpkgFileName, e); + } + + } + + //On fixe à -1 défaut + }else{ + + try { + srs = geoPackage.getSpatialReferenceSystemDao().getOrCreateFromEpsg(-1); + } catch (SQLException e) { + throw new KettleException("Error writing features to " + this.gpkgFileName, e); + } + } + + //Contents + contents.setDataType(ContentsDataType.FEATURES); + contents.setSrs(srs); + + //geometryColumns + GeometryColumns geometryColumns = new GeometryColumns(); + geometryColumns.setGeometryType(this.assignedGeometryType.toGpkgValue()); + geometryColumns.setColumnName(geometryField.getName()); + geometryColumns.setSrs(srs); + + //3D autorisé ? + if(this.forceTo2DGeometry){ + geometryColumns.setZ(GpkgGeometryWithZType.PROHIBITED.toGpkgValue()); + }else{ + geometryColumns.setZ(GpkgGeometryWithZType.OPTIONAL.toGpkgValue()); + } + //M jamais géré + geometryColumns.setM(GpkgGeometryWithMType.PROHIBITED.toGpkgValue()); + + //Création des métadonnées pour la FeatureTable + geometryColumns.setContents(contents); + geoPackage.createFeatureTable(new FeatureTableMetadata( + geometryColumns, + this.pkFieldName, + toGpkgFeatureColumns(otherFields), + new BoundingBox() + ) + ); + + //Création d'index + RTreeIndexExtension extension = new RTreeIndexExtension(geoPackage); + extension.create(this.tableName,this.geometryFieldName, this.pkFieldName); + + + //Attribute Table + }else{ + + //Création des métadonnées pour la AttributeTable + contents.setDataType(ContentsDataType.ATTRIBUTES); + geoPackage.createAttributesTable( + new AttributesTable( + this.tableName, + toGpkgAttributesColumns(otherFields) + ) + ); + } + + //Sinon, récupère les métadonnées pour la table sans créer + }else{ + + ContentsDataType contentsDataType = null; + if(geometryField != null){ + contentsDataType= ContentsDataType.FEATURES; + }else { + contentsDataType = ContentsDataType.ATTRIBUTES; + } + + try { + + for(Contents currentContents : geoPackage.getContentsDao().getContents(contentsDataType)){ + + if(currentContents.getTableName().equalsIgnoreCase(this.tableName)){ + contents = currentContents; + break; + } + } + + } catch (SQLException e) { + + throw new KettleException("Error writing features to " + this.gpkgFileName, e); + } + + } + + //Alimentation des tables + if(features != null){ + + //Feature Table + if(geometryField != null){ + + //On stocke les srids des features pour mettre + //éventuellement le contenu des tables de métadonnées à jour si srid non forcé + TreeSet srids = new TreeSet(); + + //Pour stockage de l'extent + Envelope extent = null; + + FeatureDao featureDao = geoPackage.getFeatureDao(this.tableName); + int featIndex = 0; + + try { + + if (this.commitLimit <= 0) { + this.commitLimit = (long) 1; + } + + featureDao.getConnection().setAutoCommit(false); + + } catch (SQLException e) { + throw new KettleException("Error writing features to " + this.gpkgFileName, e); + } + + for(Feature feature : features){ + + //Nouvelle ligne de données + FeatureRow featureRow = featureDao.newRow(); + + //Récupération de la géométrie + Geometry geometry = (Geometry) feature.getValue(geometryField); + + + //Si forcer en 2d + if(this.forceTo2DGeometry){ + geometry = GeometryUtils.get2DGeometry(geometry); + } + + //On essaye d'hamoniser le type ou on retounr une erreur + geometry = checkGeometryType(geometry, (Long) feature.getValue(pkField), this.tableName); + + //On recupère le srid stocké dans la géométrie JTS uniquement si non forcé + Long currentSrid = GeometryUtils.getSrid(geometry).longValue(); + if(currentSrid != null && this.assignedSrid == null){ + srids.add(currentSrid); + this.assignedSrid = currentSrid; + } + + //Geométrie Geopackage + GeoPackageGeometryData geometryData = new GeoPackageGeometryData(this.assignedSrid); + geometryData.setGeometry(toGpkgGeometry(geometry)); + featureRow.setGeometry(geometryData); + + //Intialisation ou modification de l'étendue + if(extent == null){ + extent = geometry.getEnvelopeInternal(); + }else{ + extent.expandToInclude(geometry.getEnvelopeInternal()); + } + + //Autres colonnes + for(Field field : otherFields){ + featureRow.setValue(field.getName(), feature.getValue(field)); + } + + ContentValues contentValues = featureRow.toContentValues(); + Object pkFieldValue = feature.getValue(pkField); + if(pkFieldValue !=null){ + contentValues.put(this.pkFieldName, pkFieldValue); + } + featureDao.insert(contentValues); + featIndex++; + + if (featIndex == commitLimit) { + try { + featureDao.getConnection().commit(); + } catch (SQLException e) { + throw new KettleException("Error writing features to " + this.gpkgFileName, e); + } + featIndex = 0; + } + + + } + + try { + featureDao.getConnection().commit(); + } catch (SQLException e) { + throw new KettleException("Error writing features to " + this.gpkgFileName, e); + } + + //Maj etendue + if (extent !=null){ + + BoundingBox boundingBox = contents.getBoundingBox(); + if(boundingBox != null){ + + Envelope currentExtent = GeoPackageReader.toJtsBounds(boundingBox); + currentExtent.expandToInclude(extent); + contents.setBoundingBox(toGpkgBounds(currentExtent)); + + }else{ + contents.setBoundingBox(toGpkgBounds(extent)); + } + + } + + //Maj du srid car non forcé et détecté depuis les géométries + if(srids.size() == 1){ + + mil.nga.geopackage.srs.SpatialReferenceSystem srs = toGpkgSrs(srids.first()); + if (srs != null){ + try { + srs = toGpkgSrs(this.assignedSrid); + geoPackage.getSpatialReferenceSystemDao().createIfNotExists(srs); + + } catch (SQLException e) { + throw new KettleException("Error writing features to " + this.gpkgFileName, e); + } + + try { + + GeometryColumns currentGeometryColumns = geoPackage.getGeometryColumnsDao().queryForTableName(this.tableName); + currentGeometryColumns.setSrs(srs); + geoPackage.getGeometryColumnsDao().update(currentGeometryColumns); + contents.setSrs(srs); + + } catch (SQLException e) { + throw new KettleException("Error writing features to " + this.gpkgFileName, e); + } + + + } + + } + + //Attributes Table + }else{ + + AttributesDao attributesDao = geoPackage.getAttributesDao(this.tableName); + int featIndex = 0; + try { + + if (this.commitLimit <= 0) { + this.commitLimit = (long) 1; + } + + attributesDao.getConnection().setAutoCommit(false); + + } catch (SQLException e) { + throw new KettleException("Error writing features to " + this.gpkgFileName, e); + } + + for(Feature feature : features){ + + AttributesRow attributesRow = attributesDao.newRow(); + + for(Field field : otherFields){ + attributesRow.setValue(field.getName(), feature.getValue(field)); + } + + ContentValues contentValues = attributesRow.toContentValues(); + Object pkFieldValue = feature.getValue(pkField); + if(pkFieldValue !=null){ + contentValues.put(this.pkFieldName, pkFieldValue); + } + attributesDao.insert(contentValues); + + if (featIndex == this.commitLimit) { + try { + attributesDao.getConnection().commit(); + } catch (SQLException e) { + throw new KettleException("Error writing features to " + this.gpkgFileName, e); + } + featIndex = 0; + } + + } + try { + attributesDao.getConnection().commit(); + } catch (SQLException e) { + throw new KettleException("Error writing features to " + this.gpkgFileName, e); + } + + } + + contents.setLastChange(new Date()); + try { + geoPackage.getContentsDao().update(contents); + } catch (SQLException e) { + throw new KettleException("Error writing features to " + this.gpkgFileName, e); + } + geoPackage.close(); + + } + + geoPackage.close(); + + + } + + private List toGpkgFeatureColumns(List fields){ + + List featureColumns = new ArrayList(); + int i = 2; + + for(Field field : fields){ + featureColumns.add(FeatureColumn.createColumn(i, field.getName(), toGpkgDataType(field), false, null)); + i++; + } + + return featureColumns; + + } + + private List toGpkgAttributesColumns(List fields){ + + List attributesColumns = new ArrayList(); + int i = 1; + + for(Field field : fields){ + attributesColumns.add(AttributesColumn.createColumn(i, field.getName(), toGpkgDataType(field), false, null)); + i++; + } + + return attributesColumns; + + } + + private Geometry checkGeometryType(Geometry geometry, Long fid, String tableName) throws KettleException{ + + //Pas de test : type générique + if(this.assignedGeometryType.equals(GpkgGeometryType.GEOMETRY)){ + return geometry; + } + + //Si géométrie simple et forcé à type simple : test adéquation + if((this.assignedGeometryType.equals(GpkgGeometryType.POINT) && !(geometry instanceof Point)) + || (this.assignedGeometryType.equals(GpkgGeometryType.LINESTRING) && !(geometry instanceof LineString)) + || (this.assignedGeometryType.equals(GpkgGeometryType.POLYGON) && !(geometry instanceof Polygon)) + ){ + throw new KettleException("Error writing features to " + this.tableName + " in file " + this.gpkgFileName + ". The geometry of feature " + fid.toString() + " is not of type " + this.assignedGeometryType.toString()); + } + + //Si forcé à multi, test sur la géométrie forcé en multi-géométrie + if((this.assignedGeometryType.equals(GpkgGeometryType.MULTIPOINT) && !(GeometryUtils.getMultiGeometry(geometry) instanceof MultiPoint)) + || (this.assignedGeometryType.equals(GpkgGeometryType.MULTILINESTRING) && !(GeometryUtils.getMultiGeometry(geometry) instanceof MultiLineString)) + || (this.assignedGeometryType.equals(GpkgGeometryType.MULTIPOLYGON) && !(GeometryUtils.getMultiGeometry(geometry) instanceof MultiPolygon)) + ){ + throw new KettleException("Error writing features to " + this.tableName + " in file " + this.gpkgFileName + ". The geometry of feature " + fid.toString() + " is not of type " + this.assignedGeometryType.toString()); + + }else{ + + //retourne la géométrie en multi + if(this.assignedGeometryType.equals(GpkgGeometryType.MULTIPOINT) + || this.assignedGeometryType.equals(GpkgGeometryType.MULTILINESTRING) + || this.assignedGeometryType.equals(GpkgGeometryType.MULTIPOLYGON)){ + + return GeometryUtils.getMultiGeometry(geometry); + + } + + } + + //Si collection + if(this.assignedGeometryType.equals(GpkgGeometryType.GEOMETRYCOLLECTION)){ + + return GeometryUtils.getGeometryCollection(geometry); + + } + + return null; + + } + + + private GeoPackageDataType toGpkgDataType(Field field){ + + GeoPackageDataType dataType = null; + + if(field.getType().equals(FieldType.BINARY)){ + dataType = GeoPackageDataType.BLOB; + + }else if (field.getType().equals(FieldType.BOOLEAN)){ + dataType = GeoPackageDataType.BOOLEAN; + + }else if (field.getType().equals(FieldType.DATE)){ + dataType = GeoPackageDataType.DATETIME; + + }else if (field.getType().equals(FieldType.DOUBLE)){ + dataType = GeoPackageDataType.DOUBLE; + + }else if (field.getType().equals(FieldType.LONG)){ + dataType = GeoPackageDataType.INTEGER; + + }else if (field.getType().equals(FieldType.STRING)){ + dataType = GeoPackageDataType.TEXT; + } + + return dataType; + } + + private static boolean hasZ(com.vividsolutions.jts.geom.Geometry geometry){ + + if(geometry != null && !geometry.isEmpty()){ + return !Double.isNaN(geometry.getCoordinates()[0].z); + }else{ + return false; + } + } + + + /** + * srid number to GPKG Srs + * @param srid + * @return + * @throws KettleException + * @throws CRSException + */ + private mil.nga.geopackage.srs.SpatialReferenceSystem toGpkgSrs(long srid) throws KettleException{ + + try { + + CRSFactory cRSFactory = new CRSFactory(); + RegistryManager registryManager = cRSFactory.getRegistryManager(); + registryManager.addRegistry(new EPSGRegistry()); + + CoordinateReferenceSystem crs = cRSFactory.getCRS("EPSG:" + srid); + + if (crs == null) { + throw new KettleException("Coordinate system EPSG:" + srid + " not found"); + } + + mil.nga.geopackage.srs.SpatialReferenceSystem srs = new mil.nga.geopackage.srs.SpatialReferenceSystem(); + srs.setSrsName(crs.getName()); + srs.setId(Long.parseLong(crs.getAuthorityKey())); + srs.setOrganization(crs.getAuthorityName()); + srs.setOrganizationCoordsysId(Long.parseLong(crs.getAuthorityKey())); + srs.setDefinition(crs.toWKT()); + return srs; + + } catch (CRSException e) { + throw new KettleException("Coordinate system EPSG:" + srid + " error"); + } + + } + + + + + /** + * JTS Geometry to GPKG Bounds + * @param Envelope + * @return + */ + public static mil.nga.geopackage.BoundingBox toGpkgBounds(Envelope bounds){ + + mil.nga.geopackage.BoundingBox gpkgBounds = new mil.nga.geopackage.BoundingBox(); + gpkgBounds.setMinLongitude(bounds.getMinX()); + gpkgBounds.setMinLatitude(bounds.getMinY()); + gpkgBounds.setMaxLongitude(bounds.getMaxX()); + gpkgBounds.setMaxLatitude(bounds.getMaxY()); + return gpkgBounds; + + } + + + /** + * JTS Geometry to GPKG Geometry + * @param jtsGeometry + * @return + */ + private static mil.nga.sf.Geometry toGpkgGeometry(com.vividsolutions.jts.geom.Geometry geometry){ + + mil.nga.sf.Geometry gpkgGeometry = null; + + if(geometry != null && !geometry.isEmpty()){ + + //Point + if (geometry.getGeometryType().equals(com.vividsolutions.jts.geom.Point.class.getSimpleName())){ + return toGpkgPoint((com.vividsolutions.jts.geom.Point) geometry); + + //MultiPoint + }else if (geometry.getGeometryType().equals(com.vividsolutions.jts.geom.MultiPoint.class.getSimpleName())){ + return toGpkgMultiPoint((com.vividsolutions.jts.geom.MultiPoint) geometry); + + //LineString + }else if (geometry.getGeometryType().equals(com.vividsolutions.jts.geom.LineString.class.getSimpleName())){ + return toGpkgLineString((com.vividsolutions.jts.geom.LineString) geometry); + + //MultiLineString + }else if (geometry.getGeometryType().equals(com.vividsolutions.jts.geom.MultiLineString.class.getSimpleName())){ + return toGpkgMultiLineString((com.vividsolutions.jts.geom.MultiLineString) geometry); + + //Polygon + }else if (geometry.getGeometryType().equals(com.vividsolutions.jts.geom.Polygon.class.getSimpleName())){ + return toGpkgPolygon((com.vividsolutions.jts.geom.Polygon) geometry); + + //MultiPolygon + }else if(geometry.getGeometryType().equals(com.vividsolutions.jts.geom.MultiPolygon.class.getSimpleName())){ + return toGpkgMultiPolygon((com.vividsolutions.jts.geom.MultiPolygon) geometry); + + //GeometryCollection + }else if(geometry.getGeometryType().equals(com.vividsolutions.jts.geom.GeometryCollection.class.getSimpleName())){ + + mil.nga.sf.GeometryCollection gpkgGeometryCollection = new mil.nga.sf.GeometryCollection(hasZ(geometry),false); + for(int i = 0; i < geometry.getNumGeometries(); i++){ + gpkgGeometryCollection.addGeometry(toGpkgGeometry(geometry.getGeometryN(i))); + } + + return gpkgGeometryCollection; + + } + + } + + return gpkgGeometry; + } + + /** + * JTS Coordinate to Gpkg Point + * @param coordinate + * @return + */ + private static mil.nga.sf.Point toGpkgPoint(com.vividsolutions.jts.geom.Coordinate coordinate){ + + mil.nga.sf.Point gpkgPoint = new mil.nga.sf.Point(coordinate.x, coordinate.y); + if(!Double.isNaN(coordinate.z)){ + gpkgPoint.setZ(coordinate.z); + } + + return gpkgPoint; + + } + + /** + * JTS Coordinates to Gpkg Points + * @param coordinates + * @return + */ + private static List toGpkgPoints(com.vividsolutions.jts.geom.Coordinate[] coordinates){ + + List points = new ArrayList(); + for(Coordinate coordinate : coordinates){ + points.add(toGpkgPoint(coordinate)); + } + + return points; + + } + + /** + * JTS Point to Gpkg Point + * @param point + * @return + */ + private static mil.nga.sf.Point toGpkgPoint(com.vividsolutions.jts.geom.Point point){ + + return toGpkgPoint(point.getCoordinate()); + + } + + /** + * JTS MultiPoint to Gpkg MultiPoint + * @param multiPoint + * @return + */ + private static mil.nga.sf.MultiPoint toGpkgMultiPoint(com.vividsolutions.jts.geom.MultiPoint multiPoint){ + + mil.nga.sf.MultiPoint gpkgMultiPoint = new mil.nga.sf.MultiPoint(hasZ(multiPoint),false); + gpkgMultiPoint.setPoints(toGpkgPoints(multiPoint.getCoordinates())); + return gpkgMultiPoint; + + } + + /** + * JTS LineString to Gpkg LineString + * @param lineString + * @return + */ + private static mil.nga.sf.LineString toGpkgLineString(com.vividsolutions.jts.geom.LineString lineString){ + + mil.nga.sf.LineString gpkgLineString = new mil.nga.sf.LineString(hasZ(lineString),false); + gpkgLineString.setPoints(toGpkgPoints(lineString.getCoordinates())); + return gpkgLineString; + + } + + /** + * JTS MultiLineString to Gpkg MultiLineString + * @param multiLineString + * @return + */ + private static mil.nga.sf.MultiLineString toGpkgMultiLineString(com.vividsolutions.jts.geom.MultiLineString multiLineString){ + + mil.nga.sf.MultiLineString gpkgMultiLineString = new mil.nga.sf.MultiLineString(hasZ(multiLineString),false); + for(int i = 0; i < multiLineString.getNumGeometries(); i++){ + gpkgMultiLineString.addLineString(toGpkgLineString((LineString) multiLineString.getGeometryN(i))); + } + + return gpkgMultiLineString; + + } + + /** + * JTS Polygon to Gpkg Polygon + * @param polygon + * @return + */ + private static mil.nga.sf.Polygon toGpkgPolygon(com.vividsolutions.jts.geom.Polygon polygon){ + + mil.nga.sf.Polygon gpkgPolygon = new mil.nga.sf.Polygon(hasZ(polygon),false); + gpkgPolygon.addRing(toGpkgLineString(polygon.getExteriorRing())); + for(int i = 0; i < polygon.getNumInteriorRing(); i++){ + gpkgPolygon.addRing(toGpkgLineString(polygon.getInteriorRingN(i))); + } + + return gpkgPolygon; + + } + + /** + * JTS MultiPolygon to Gpkg MultiPolygon + * @param multiPolygon + * @return + */ + private static mil.nga.sf.MultiPolygon toGpkgMultiPolygon(com.vividsolutions.jts.geom.MultiPolygon multiPolygon){ + + mil.nga.sf.MultiPolygon gpkgMultiPolygon = new mil.nga.sf.MultiPolygon(hasZ(multiPolygon),false); + for(int i = 0; i < multiPolygon.getNumGeometries(); i++){ + gpkgMultiPolygon.addPolygon(toGpkgPolygon((Polygon) multiPolygon.getGeometryN(i))); + } + + return gpkgMultiPolygon; + + } + +} diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/SVGWriter.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/SVGWriter.java new file mode 100644 index 0000000..3363947 --- /dev/null +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/SVGWriter.java @@ -0,0 +1,704 @@ +package com.atolcd.pentaho.di.gis.io; + +/* + * #%L + * Pentaho Data Integrator GIS Plugin + * %% + * Copyright (C) 2015 Atol CD + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * . + * #L% + */ + + +import java.io.UnsupportedEncodingException; +import java.io.Writer; +import java.net.URL; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.TreeMap; + +import org.pentaho.di.core.exception.KettleException; + +import com.atolcd.gis.svg.SvgUtil; +import com.atolcd.gis.svg.SvgWriter; +import com.atolcd.gis.svg.type.AbstractElement; +import com.atolcd.gis.svg.type.AbstractStyle; +import com.atolcd.gis.svg.type.Document; +import com.atolcd.gis.svg.type.container.Defs; +import com.atolcd.gis.svg.type.container.Group; +import com.atolcd.gis.svg.type.graphic.Circle; +import com.atolcd.gis.svg.type.graphic.Image; +import com.atolcd.gis.svg.type.graphic.Text; +import com.atolcd.gis.svg.type.graphic.Use; +import com.atolcd.gis.svg.type.style.EmbeddedStyle; +import com.atolcd.gis.svg.type.style.ExternalStyle; +import com.atolcd.pentaho.di.gis.io.features.Feature; +import com.atolcd.pentaho.di.gis.io.features.Field; +import com.atolcd.pentaho.di.gis.utils.GeometryUtils; +import com.vividsolutions.jts.geom.Envelope; +import com.vividsolutions.jts.geom.Geometry; +import com.vividsolutions.jts.geom.Lineal; +import com.vividsolutions.jts.geom.Point; +import com.vividsolutions.jts.geom.Polygonal; +import com.vividsolutions.jts.geom.Puntal; +import com.vividsolutions.jts.geom.util.AffineTransformation; + +public class SVGWriter extends AbstractFileWriter{ + + + public static String RESSOURCE_EXTERNAL = "RESSOURCE_EXTERNAL"; + public static String RESSOURCE_EMBEDDED = "RESSOURCE_EMBEDDED"; + public static int SYMBOL_DEFAULT_SIZE = 4; + public static String SYMBOL_DEFAULT_ID = "symbolDefault"; + public static String GROUP_PREFIX = "layer_"; + + private String svgFileName; + private Writer writer; + private boolean isServletOutput; + + private double height; + private double width; + private String documentTitle; + private String documentDescription; + private String styleSheet; + private String styleSheetMode; + private int precision; + private String symbolMode; + + private String featureIdField; + private String featureTitleField; + private String featureDescriptionField; + private String featureSvgStyleField; + private String featureCssClassField; + private String featureSymbolField; + private String featureLabelField; + private String featureGroupField; + + public SVGWriter(String fileName, String geometryFieldName, String charsetName) throws KettleException { + + super(geometryFieldName, charsetName); + + this.svgFileName = checkFilename(fileName).getFile(); + this.isServletOutput = false; + this.writer = null; + + this.height = 0; + this.width = 0; + this.documentTitle = null; + this.documentDescription = null; + this.styleSheet = null; + this.styleSheetMode = null; + this.precision = 0; + this.symbolMode = null; + + this.featureIdField = null; + this.featureTitleField = null; + this.featureDescriptionField = null; + this.featureSvgStyleField = null; + this.featureCssClassField = null; + this.featureSymbolField = null; + this.featureLabelField = null; + this.featureGroupField = null; + this.symbolMode = null; + + } + + public SVGWriter(Writer writer, String geometryFieldName, String charsetName) throws KettleException { + + super(geometryFieldName, charsetName); + + this.svgFileName = null; + this.isServletOutput = true; + this.writer = writer; + + this.height = 0; + this.width = 0; + this.documentTitle = null; + this.documentDescription = null; + this.styleSheet = null; + this.styleSheetMode = null; + + this.featureIdField = null; + this.featureTitleField = null; + this.featureDescriptionField = null; + this.featureSvgStyleField = null; + this.featureCssClassField = null; + this.featureSymbolField = null; + this.featureLabelField = null; + this.featureGroupField = null; + + } + + public String getFeatureLabelField() { + return featureLabelField; + } + + public void setFeatureLabelField(String featureLabelField) { + this.featureLabelField = featureLabelField; + } + + public int getPrecision() { + return precision; + } + + public void setPrecision(int precision) { + this.precision = precision; + } + + public Writer getWriter() { + return writer; + } + + public void setWriter(Writer writer) { + this.writer = writer; + } + + public double getHeight() { + return height; + } + + public void setHeight(double height) { + this.height = height; + } + + public double getWidth() { + return width; + } + + public void setWidth(double width) { + this.width = width; + } + + public String getFeatureIdField() { + return featureIdField; + } + + public void setFeatureIdField(String featureIdField) { + this.featureIdField = featureIdField; + } + + public String getFeatureTitleField() { + return featureTitleField; + } + + public void setFeatureTitleField(String featureTitleField) { + this.featureTitleField = featureTitleField; + } + + public String getFeatureDescriptionField() { + return featureDescriptionField; + } + + public void setFeatureDescriptionField(String featureDescriptionField) { + this.featureDescriptionField = featureDescriptionField; + } + + public String getDocumentTitle() { + return documentTitle; + } + + public void setDocumentTitle(String documentTitle) { + this.documentTitle = documentTitle; + } + + public String getDocumentDescription() { + return documentDescription; + } + + public void setDocumentDescription(String documentDescription) { + this.documentDescription = documentDescription; + } + + public String getStyleSheet() { + return styleSheet; + } + + public void setStyleSheet(String styleSheet) { + this.styleSheet = styleSheet; + } + + public String getStyleSheetMode() { + return styleSheetMode; + } + + public void setStyleSheetMode(String styleSheetMode) { + this.styleSheetMode = styleSheetMode; + } + + public String getFeatureSvgStyleField() { + return featureSvgStyleField; + } + + public void setFeatureSvgStyleField(String featureSvgStyleField) { + this.featureSvgStyleField = featureSvgStyleField; + } + + public String getFeatureCssClassField() { + return featureCssClassField; + } + + public void setFeatureCssClassField(String featureCssClassField) { + this.featureCssClassField = featureCssClassField; + } + + public String getFeatureSymbolField() { + return featureSymbolField; + } + + public void setFeatureSymbolField(String featureSymbolField) { + this.featureSymbolField = featureSymbolField; + } + + public String getFeatureGroupField() { + return featureGroupField; + } + + public void setFeatureGroupField(String featureGroupField) { + this.featureGroupField = featureGroupField; + } + + public String getSymbolMode() { + return symbolMode; + } + + public void setSymbolMode(String symbolMode) { + this.symbolMode = symbolMode; + } + + private String getMD5(String chaine) throws UnsupportedEncodingException, NoSuchAlgorithmException{ + + byte[] chaineBytes = chaine.getBytes("UTF-8"); + MessageDigest messageDigest = MessageDigest.getInstance("MD5"); + byte[] hash = messageDigest.digest(chaineBytes); + + StringBuilder hexString = new StringBuilder(); + for (int i = 0; i < hash.length; i++) { + String hex = Integer.toHexString(0xFF & hash[i]); + if (hex.length() == 1) { + hexString.append('0'); + } + hexString.append(hex); + } + return hexString.toString(); + + } + + public void writeFeatures(List features) throws KettleException { + + + //Nouveau SVG + Document svgDocument = new Document(); + svgDocument.setHeight(this.height); + svgDocument.setWidth(this.width); + svgDocument.setUnits(Document.SVG_UNIT_PX); + + //Si présence d'un titre et d'une description + if (this.documentTitle != null && !this.documentTitle.isEmpty()) { + svgDocument.setTitle(this.documentTitle); + } + + if (this.documentDescription != null && !this.documentDescription.isEmpty()) { + svgDocument.setDescription(this.documentDescription); + } + + //Si présence d'une feuille de style + if(this.styleSheet != null){ + + AbstractStyle style = null; + + try{ + + //Charge le contenu CSS ou établi un lien + if(this.styleSheetMode != null && this.styleSheetMode.equalsIgnoreCase(SVGWriter.RESSOURCE_EMBEDDED)){ + style = new EmbeddedStyle(SvgUtil.toURL(this.styleSheet)); + + }else{ + style = new ExternalStyle(this.styleSheet); + } + + svgDocument.setStyle(style); + + }catch(Exception e){ + throw new KettleException(e.getMessage()); + } + + } + + //Première passe : + // - Récupération des champs de paramètres dynamiques + // - Récupération de l'extent + // - Création de groupe de features + // - Référencement des images comme defs svg + + Field geometryField = null; + Field idField = null; + Field titleField = null; + Field descriptionField = null; + Field svgStyleField = null; + Field cssClassField = null; + Field symbolField = null; + Field labelField = null; + Field groupField = null; + + Envelope geoExtent = new Envelope(); + geoExtent.setToNull(); + + HashMap symbols = new HashMap(); + boolean hasPuntal = false; + + TreeMap> groups= new TreeMap>(); + groups.put(Long.MAX_VALUE, new ArrayList()); + + List labels = new ArrayList(); + + boolean first = true; + for(Feature feature : features){ + + if (first) { + + geometryField = feature.getField(this.geometryFieldName); + + //id de feature + if (this.featureIdField != null) { + idField = feature.getField(this.featureIdField); + } + + if (this.featureTitleField != null) { + titleField = feature.getField(this.featureTitleField); + } + + if (this.featureDescriptionField != null) { + descriptionField = feature.getField(this.featureDescriptionField); + } + + if (this.featureSvgStyleField != null) { + svgStyleField = feature.getField(this.featureSvgStyleField); + } + + if (this.featureCssClassField != null) { + cssClassField = feature.getField(this.featureCssClassField); + } + + if (this.featureSymbolField != null) { + symbolField = feature.getField(this.featureSymbolField); + } + + if (this.featureLabelField != null) { + labelField = feature.getField(this.featureLabelField); + } + + if (this.featureGroupField != null) { + groupField = feature.getField(this.featureGroupField); + } + + first = false; + + } + + Geometry geometry = (Geometry) feature.getValue(geometryField); + if(geometry instanceof Puntal && !hasPuntal){ + hasPuntal = true; + } + + //Extent + if(geoExtent.isNull()){ + geoExtent = geometry.getEnvelopeInternal(); + }else{ + geoExtent.expandToInclude(geometry.getEnvelopeInternal()); + } + + //Si présence d'un champs de symbole + if(symbolField != null + && feature.getValue(symbolField) != null + && geometry instanceof Puntal){ + + try{ + + URL imageURL = new URL((String)feature.getValue(symbolField)); + String symbolId = getMD5(imageURL.toExternalForm()); + + if(!symbols.containsKey(symbolId)){ + + boolean encodeImage = false; + + //Conversion en base 64 + if(this.symbolMode != null && this.symbolMode.equalsIgnoreCase(SVGWriter.RESSOURCE_EMBEDDED)){ + encodeImage = true; + } + + Image image = SvgUtil.toSvgImage(imageURL, encodeImage); + image.setId(symbolId); + symbols.put(symbolId, image); + } + + + }catch(Exception e){ + throw new KettleException(e.getMessage() + feature.getValue(symbolField)); + } + + } + + //Groupe + if(groupField != null && feature.getValue(groupField) != null){ + + long key = (Long)feature.getValue(groupField); + + //Création du group s'il n'existe pas + if(!groups.containsKey(key)){ + groups.put(key, new ArrayList()); + } + + //Ajout au groupe + groups.get(key).add(feature); + + //Absence de groupe + }else{ + groups.get(Long.MAX_VALUE).add(feature); + } + + + } + + if(hasPuntal){ + Defs defs = new Defs(); + + //Symbole par défaut + Circle circle = new Circle(0,0,SYMBOL_DEFAULT_SIZE/2); + circle.setId(SYMBOL_DEFAULT_ID); + defs.getElements().add(circle); + + //Si symboles dynamiques + if(!symbols.isEmpty()){ + defs.getElements().addAll(symbols.values()); + } + + svgDocument.getElements().add(defs); + + } + + Envelope svgExtent = new Envelope(0,this.width,0,this.height); + AffineTransformation svgTransformation = SvgUtil.getGeometryToSvgTransformation(geoExtent, svgExtent); + + //Bouclage sur les groupe de feature + for (long key : groups.keySet()) { + + Group groupElement = new Group(); + groupElement.setId(GROUP_PREFIX + String.valueOf(key)); + + for(Feature feature : groups.get(key)){ + + //Récupération de la géométrie + Geometry geometry = (Geometry) feature.getValue(geometryField); + geometry = svgTransformation.transform(geometry); + + //Alimention du SVG + AbstractElement element = null; + + if(geometry instanceof Puntal){ + + String symbolId = SYMBOL_DEFAULT_ID; + if(symbolField != null && feature.getValue(symbolField) != null){ + + try{ + + URL imageURL = new URL((String)feature.getValue(symbolField)); + String md5 = getMD5(imageURL.toExternalForm()); + + if(symbols.containsKey(md5)){ + symbolId = md5; + } + + + }catch(Exception e){ + throw new KettleException(e.getMessage() + feature.getValue(symbolField)); + } + + } + + double dX = 0; + double dY = 0; + + + if(!symbolId.equalsIgnoreCase(SYMBOL_DEFAULT_ID)){ + Image image = symbols.get(symbolId); + dX = image.getWidth()/2; + dY = image.getHeight()/2; + } + + Puntal puntal = (Puntal) GeometryUtils.getLessPrecisionGeometry(geometry, this.precision);; + + //Simple point + if(geometry instanceof Point){ + + try{ + + element = new Use(((Point)puntal).getX() - dX, ((Point)puntal).getY() - dY, symbolId); + + }catch(Exception e){ + throw new KettleException(e.getMessage() + feature.getValue(symbolField)); + } + + + //Multipoint + }else{ + + try{ + + element = new Group(); + for(int i = 0; i < geometry.getNumGeometries(); i++){ + + Point point = (Point) geometry.getGeometryN(i); + ((Group)element).getElements().add(new Use(point.getX() - dX, point.getY() - dY, symbolId)); + } + + }catch(Exception e){ + throw new KettleException(e.getMessage() + feature.getValue(symbolField)); + } + + } + + }else if(geometry instanceof Lineal || geometry instanceof Polygonal){ + + element = SvgUtil.toSvgPath(geometry,this.precision); + + }else{ + + throw new KettleException("Geometry " + GeometryUtils.getGeometryType(geometry) + " is not allowed"); + + } + + // Id de feature + if (idField != null) { + String id = (String) feature.getValue(idField); + if (id != null && !id.isEmpty()) { + element.setId(id); + } + + } + + // Titre de feature + if (titleField != null) { + String title = (String) feature.getValue(titleField); + if (title != null && !title.isEmpty()) { + element.setTitle(title); + } + } + + // Description de feature + if (descriptionField != null) { + String description = (String) feature.getValue(descriptionField); + if (description != null && !description.isEmpty()) { + element.setDescription(description); + } + } + + // Style SVG de feature + if (svgStyleField != null) { + String style = (String) feature.getValue(svgStyleField); + if (style != null && !style.isEmpty()) { + element.setSvgStyle(style); + } + } + + // Css class de feature + if (cssClassField != null) { + String cssClass = (String) feature.getValue(cssClassField); + if (cssClass != null && !cssClass.isEmpty()) { + element.setCssClass(cssClass); + } + } + + groupElement.getElements().add(element); + + //On ajoute le label à la liste globale : etiquettes doivent être dessinées en dernier + if (labelField != null) { + + try{ + + String textValue = (String) feature.getValue(labelField); + + if(textValue != null && !textValue.isEmpty()){ + + Text labelElement = SvgUtil.toSvgText(geometry,textValue); + + if (featureCssClassField != null) { + String cssClass = (String) feature.getValue(cssClassField); + if (cssClass != null && !cssClass.isEmpty()) { + + //class = nom classe associée à la feature suffixée de "_label" + labelElement.setCssClass(cssClass + "_label"); + } + } + + labels.add(labelElement); + } + + }catch(Exception e){ + throw new KettleException(e.getMessage()); + } + + } + + } + + //Si groupe max -> pas un groupe réel + //ajout de la feature directement dans la racine svg + if(key == Long.MAX_VALUE){ + + svgDocument.getElements().addAll(groupElement.getElements()); + + //Sinon, ajoute le groupe au svg + }else{ + svgDocument.getElements().add(groupElement); + } + + + } + + //Ajout des labels + if(!labels.isEmpty()){ + Group groupElement = new Group(); + groupElement.setId(GROUP_PREFIX + String.valueOf("Labels")); + groupElement.getElements().addAll(labels); + svgDocument.getElements().add(groupElement); + } + + try{ + + //Ecriture du fichier ou du flux + SvgWriter svgWriter = new SvgWriter(); + if (isServletOutput) { + + if (features.size() > 0) { + svgWriter.write(svgDocument, writer, this.charset.name()); + } + + } else { + + svgWriter.write(svgDocument, this.svgFileName, this.charset.name()); + + } + + }catch(Exception e){ + throw new KettleException(e.getMessage()); + } + + } + +} diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/SpatialiteReader.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/SpatialiteReader.java index 7eebc83..3b9b165 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/SpatialiteReader.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/SpatialiteReader.java @@ -1,27 +1,26 @@ -package com.atolcd.pentaho.di.gis.io; - -/* - * #%L - * Pentaho Data Integrator GIS Plugin - * %% - * Copyright (C) 2015 Atol CD - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * . - * #L% - */ - +package com.atolcd.pentaho.di.gis.io; + +/* + * #%L + * Pentaho Data Integrator GIS Plugin + * %% + * Copyright (C) 2015 Atol CD + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * . + * #L% + */ import java.io.File; import java.sql.SQLException; @@ -36,12 +35,15 @@ import com.atolcd.pentaho.di.gis.io.features.Feature; import com.atolcd.pentaho.di.gis.io.features.Field; import com.atolcd.pentaho.di.gis.io.features.Field.FieldType; +import com.atolcd.pentaho.di.gis.utils.GeometryUtils; +import com.vividsolutions.jts.geom.Geometry; public class SpatialiteReader extends AbstractFileReader { private String spatialiteFileName; private boolean spatialiteFileExist; private Database database; + private boolean listContent; public SpatialiteReader(String fileName, String tableName, String charsetName) throws KettleException { @@ -55,39 +57,59 @@ public SpatialiteReader(String fileName, String tableName, String charsetName) t this.spatialiteFileName = checkFilename(fileName).getFile(); } + if(tableName.equalsIgnoreCase("*")){ + this.listContent = true; + }else{ + this.listContent = false; + } + this.database = new Database(); try { database.open(this.spatialiteFileName); - Table dbTable = database.getTable(this.layerName); - for (com.atolcd.gis.spatialite.Field dbField : dbTable.getFields()) { + //Si liste de contenu + if(this.listContent){ - Field field = null; + this.fields.add(new Field("table_name",FieldType.STRING,null,null)); + this.fields.add(new Field("is_spatial",FieldType.BOOLEAN,null,null)); + + }else{ + Table dbTable = database.getTable(this.layerName); - if (dbField.getTypeAffinity().equalsIgnoreCase(com.atolcd.gis.spatialite.Field.TYPE_GEOMETRY)) { - field = new Field(dbField.getName(), FieldType.GEOMETRY, null, null); + //Si table non trouvée + if(dbTable == null){ + throw new KettleException("Error initialize reader : Table " + this.layerName + " not found"); + } - } else if (dbField.getTypeAffinity().equalsIgnoreCase(com.atolcd.gis.spatialite.Field.TYPE_INTEGER)) { - field = new Field(dbField.getName(), FieldType.LONG, null, null); + for (com.atolcd.gis.spatialite.Field dbField : dbTable.getFields()) { - } else if (dbField.getTypeAffinity().equalsIgnoreCase(com.atolcd.gis.spatialite.Field.TYPE_NONE)) { - field = new Field(dbField.getName(), FieldType.BINARY, null, null); + Field field = null; - } else if (dbField.getTypeAffinity().equalsIgnoreCase(com.atolcd.gis.spatialite.Field.TYPE_NUMERIC)) { - field = new Field(dbField.getName(), FieldType.DOUBLE, null, null); + if (dbField.getTypeAffinity().equalsIgnoreCase(com.atolcd.gis.spatialite.Field.TYPE_GEOMETRY)) { + field = new Field(dbField.getName(), FieldType.GEOMETRY, null, null); - } else if (dbField.getTypeAffinity().equalsIgnoreCase(com.atolcd.gis.spatialite.Field.TYPE_REAL)) { + } else if (dbField.getTypeAffinity().equalsIgnoreCase(com.atolcd.gis.spatialite.Field.TYPE_INTEGER)) { + field = new Field(dbField.getName(), FieldType.LONG, null, null); - field = new Field(dbField.getName(), FieldType.DOUBLE, null, null); + } else if (dbField.getTypeAffinity().equalsIgnoreCase(com.atolcd.gis.spatialite.Field.TYPE_NONE)) { + field = new Field(dbField.getName(), FieldType.BINARY, null, null); - } else if (dbField.getTypeAffinity().equalsIgnoreCase(com.atolcd.gis.spatialite.Field.TYPE_TEXT)) { + } else if (dbField.getTypeAffinity().equalsIgnoreCase(com.atolcd.gis.spatialite.Field.TYPE_NUMERIC)) { + field = new Field(dbField.getName(), FieldType.DOUBLE, null, null); - field = new Field(dbField.getName(), FieldType.STRING, null, null); - } + } else if (dbField.getTypeAffinity().equalsIgnoreCase(com.atolcd.gis.spatialite.Field.TYPE_REAL)) { + + field = new Field(dbField.getName(), FieldType.DOUBLE, null, null); + + } else if (dbField.getTypeAffinity().equalsIgnoreCase(com.atolcd.gis.spatialite.Field.TYPE_TEXT)) { - this.fields.add(field); + field = new Field(dbField.getName(), FieldType.STRING, null, null); + } + + this.fields.add(field); + } } database.close(); @@ -107,17 +129,43 @@ public List getFeatures() throws KettleException { try { database.open(this.spatialiteFileName); - Table dbTable = database.getTable(this.layerName); - for (Row row : this.database.getRows(dbTable, limit)) { + //Si liste de contenu + if(this.listContent){ + + for(Table dbTable : database.getTables()){ + + Feature feature = new Feature(); + feature.addValue(this.getField("table_name"), dbTable.getName()); + feature.addValue(this.getField("is_spatial"), dbTable.isSpatial()); + features.add(feature); + } + + + }else{ + Table dbTable = database.getTable(this.layerName); + + for (Row row : this.database.getRows(dbTable, limit)) { + + Feature feature = new Feature(); + for (Field field : this.fields) { + Object value = row.getValue(field.getName()); + + if(field.getType().equals(FieldType.GEOMETRY)){ + if (this.forceTo2DGeometry) { + value = GeometryUtils.get2DGeometry((Geometry) value); + } + + if (this.forceToMultiGeometry) { + value = GeometryUtils.getMultiGeometry((Geometry) value); + } + } + + feature.addValue(field, row.getValue(field.getName())); + } + features.add(feature); - Feature feature = new Feature(); - for (Field field : this.fields) { - - feature.addValue(field, row.getValue(field.getName())); } - features.add(feature); - } database.close(); diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/features/FeatureConverter.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/features/FeatureConverter.java index c2075e6..891b466 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/features/FeatureConverter.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/io/features/FeatureConverter.java @@ -30,8 +30,12 @@ import org.pentaho.di.core.exception.KettleValueException; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.RowMetaInterface; -import org.pentaho.di.core.row.ValueMeta; import org.pentaho.di.core.row.ValueMetaInterface; +import org.pentaho.di.core.row.value.ValueMetaBoolean; +import org.pentaho.di.core.row.value.ValueMetaDate; +import org.pentaho.di.core.row.value.ValueMetaInteger; +import org.pentaho.di.core.row.value.ValueMetaNumber; +import org.pentaho.di.core.row.value.ValueMetaString; import com.atolcd.pentaho.di.core.row.value.ValueMetaGeometry; import com.atolcd.pentaho.di.gis.io.features.Field.FieldType; @@ -60,27 +64,27 @@ public static List getFields(RowMetaInterface rowMeta) { switch (valueMetaInterface.getType()) { - case ValueMeta.TYPE_BOOLEAN: + case ValueMetaInterface.TYPE_BOOLEAN: field = new Field(fieldName, FieldType.BOOLEAN, length, precision); break; - case ValueMeta.TYPE_INTEGER: + case ValueMetaInterface.TYPE_INTEGER: field = new Field(fieldName, FieldType.LONG, length, precision); break; - case ValueMeta.TYPE_NUMBER: + case ValueMetaInterface.TYPE_NUMBER: field = new Field(fieldName, FieldType.DOUBLE, length, precision); break; - case ValueMeta.TYPE_BIGNUMBER: + case ValueMetaInterface.TYPE_BIGNUMBER: field = new Field(fieldName, FieldType.DOUBLE, length, precision); break; - case ValueMeta.TYPE_STRING: + case ValueMetaInterface.TYPE_STRING: field = new Field(fieldName, FieldType.STRING, length, precision); break; - case ValueMeta.TYPE_DATE: + case ValueMetaInterface.TYPE_DATE: field = new Field(fieldName, FieldType.DATE, length, precision); break; @@ -152,23 +156,23 @@ public static RowMetaInterface getRowMeta(List fields, String origin) { } else if (field.getType().equals(FieldType.BOOLEAN)) { - valueMeta = new ValueMeta(field.getName(), ValueMetaInterface.TYPE_BOOLEAN); + valueMeta = new ValueMetaBoolean(field.getName()); } else if (field.getType().equals(FieldType.DATE)) { - valueMeta = new ValueMeta(field.getName(), ValueMetaInterface.TYPE_DATE); + valueMeta = new ValueMetaDate(field.getName()); } else if (field.getType().equals(FieldType.DOUBLE)) { - valueMeta = new ValueMeta(field.getName(), ValueMetaInterface.TYPE_NUMBER); + valueMeta = new ValueMetaNumber(field.getName()); } else if (field.getType().equals(FieldType.LONG)) { - valueMeta = new ValueMeta(field.getName(), ValueMetaInterface.TYPE_INTEGER); + valueMeta = new ValueMetaInteger(field.getName()); } else { - valueMeta = new ValueMeta(field.getName(), ValueMetaInterface.TYPE_STRING); + valueMeta = new ValueMetaString(field.getName()); } diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/utils/GeometryUtils.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/utils/GeometryUtils.java index fc30a79..dc1eea1 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/utils/GeometryUtils.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/gis/utils/GeometryUtils.java @@ -22,7 +22,6 @@ * #L% */ - import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -39,11 +38,13 @@ import com.vividsolutions.jts.geom.MultiPolygon; import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.geom.Polygon; +import com.vividsolutions.jts.geom.PrecisionModel; import com.vividsolutions.jts.geom.util.GeometryExtracter; import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.WKTReader; import com.vividsolutions.jts.io.WKTWriter; import com.vividsolutions.jts.operation.linemerge.LineMerger; +import com.vividsolutions.jts.precision.GeometryPrecisionReducer; public final class GeometryUtils { @@ -434,6 +435,26 @@ private static Coordinate[] get2DCoordinates(Coordinate coordinates[]) { } + /** + * Returns geometry with less precision + * @param geometry + * @param decCount + * @return + */ + public static Geometry getLessPrecisionGeometry(Geometry geometry, int decCount) { + + Geometry outputGeometry = null; + if (!isNullOrEmptyGeometry(geometry)) { + + decCount = Math.abs(decCount); + double scale = Math.pow(10, decCount); + outputGeometry = GeometryPrecisionReducer.reduce(geometry, new PrecisionModel(scale)); + } + + return getNonEmptyGeometry(geometry.getSRID(), outputGeometry); + + } + /** * Returns 2D geometry from input geometry * @@ -579,6 +600,25 @@ public static Geometry getMultiGeometry(Geometry geometry) { } + /** + * Returns Geometry Collection from input geometry + * + * @param geometry + * @return + */ + public static Geometry getGeometryCollection(Geometry geometry) { + + GeometryFactory geometryFactory = new GeometryFactory(); + Geometry outputGeometry = null; + + if (!isNullOrEmptyGeometry(geometry)) { + outputGeometry = geometryFactory.createGeometryCollection(new Geometry[]{geometry}); + } + + return getNonEmptyGeometry(geometry.getSRID(), outputGeometry); + + } + /** * Returns metadatas from a GeometryCollection geometry * @@ -646,57 +686,4 @@ public static Geometry getMergedGeometry(Geometry geometry) { return getNonEmptyGeometry(geometry.getSRID(), outputGeometry); } - - /* - * public static Geometry asCurve(Geometry geometry){ - * - * GeometryFactory geometryFactory = new GeometryFactory(); - * - * if(!isNullOrEmptyGeometry(geometry)){ if(geometry.getDimension() >= 1){ - * - * LineMerger lineMerger = new LineMerger(); lineMerger.add(geometry); - * LineString[] lineStrings = - * GeometryFactory.toLineStringArray(lineMerger.getMergedLineStrings()); - * Geometry outputGeometry = - * geometryFactory.createMultiLineString(lineStrings); - * outputGeometry.setSRID(geometry.getSRID()); - * - * if(!isNullOrEmptyGeometry(outputGeometry) && - * outputGeometry.getNumGeometries()==1){ outputGeometry = - * outputGeometry.getGeometryN(0); - * outputGeometry.setSRID(geometry.getSRID()); } - * - * return getNonEmptyGeometry(outputGeometry); - * - * }else{ return null; } }else{ return null; } } - * - * public static Geometry asSurface(Geometry geometry){ - * - * GeometryFactory geometryFactory = new GeometryFactory(); - * - * if(!isNullOrEmptyGeometry(geometry)){ - * - * if(geometry.getDimension() == 2){ - * - * return getNonEmptyGeometry(geometry); - * - * }else if(geometry.getDimension() == 1){ - * - * LineMerger lineMerger = new LineMerger(); lineMerger.add(geometry); - * Polygonizer polygonizer = new Polygonizer(); - * polygonizer.add(lineMerger.getMergedLineStrings()); Polygon[] polygons = - * GeometryFactory.toPolygonArray(polygonizer.getPolygons()); Geometry - * outputGeometry = geometryFactory.createMultiPolygon(polygons); - * outputGeometry.setSRID(geometry.getSRID()); - * - * if(!isNullOrEmptyGeometry(outputGeometry) && - * outputGeometry.getNumGeometries()==1){ outputGeometry = - * outputGeometry.getGeometryN(0); - * outputGeometry.setSRID(outputGeometry.getSRID()); } - * - * return getNonEmptyGeometry(outputGeometry); - * - * }else{ return null; } }else{ return null; } } - */ - } diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/giscoordinatetransformation/GisCoordinateTransformation.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/giscoordinatetransformation/GisCoordinateTransformation.java index 48361db..ae40ff0 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/giscoordinatetransformation/GisCoordinateTransformation.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/giscoordinatetransformation/GisCoordinateTransformation.java @@ -24,6 +24,11 @@ import java.util.List; +import com.atolcd.pentaho.di.core.row.value.GeometryInterface; +import com.atolcd.pentaho.di.gis.utils.CoordinateTransformer; +import com.atolcd.pentaho.di.gis.utils.GeometryUtils; +import com.vividsolutions.jts.geom.Geometry; + import org.cts.CRSFactory; import org.cts.crs.CRSException; import org.cts.crs.CoordinateReferenceSystem; @@ -39,20 +44,14 @@ import org.pentaho.di.core.row.RowDataUtil; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMetaInterface; -import com.atolcd.pentaho.di.core.row.value.GeometryInterface; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; -import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; -import com.atolcd.pentaho.di.gis.utils.CoordinateTransformer; -import com.atolcd.pentaho.di.gis.utils.GeometryUtils; -import com.vividsolutions.jts.geom.Geometry; - -public class GisCoordinateTransformation extends BaseStep implements StepInterface { +public class GisCoordinateTransformation extends BaseStep { private GisCoordinateTransformationData data; private GisCoordinateTransformationMeta meta; diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/giscoordinatetransformation/GisCoordinateTransformationData.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/giscoordinatetransformation/GisCoordinateTransformationData.java index a20daaf..e2642eb 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/giscoordinatetransformation/GisCoordinateTransformationData.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/giscoordinatetransformation/GisCoordinateTransformationData.java @@ -24,9 +24,8 @@ import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.trans.step.BaseStepData; -import org.pentaho.di.trans.step.StepDataInterface; -public class GisCoordinateTransformationData extends BaseStepData implements StepDataInterface { +public class GisCoordinateTransformationData extends BaseStepData { public RowMetaInterface outputRowMeta; diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisfileinput/GisFileInput.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisfileinput/GisFileInput.java index 985988d..fbe824b 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisfileinput/GisFileInput.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisfileinput/GisFileInput.java @@ -24,6 +24,17 @@ import java.util.Iterator; +import com.atolcd.pentaho.di.gis.io.AbstractFileReader; +import com.atolcd.pentaho.di.gis.io.DXFReader; +import com.atolcd.pentaho.di.gis.io.GPXReader; +import com.atolcd.pentaho.di.gis.io.GeoJSONReader; +import com.atolcd.pentaho.di.gis.io.GeoPackageReader; +import com.atolcd.pentaho.di.gis.io.MapInfoReader; +import com.atolcd.pentaho.di.gis.io.ShapefileReader; +import com.atolcd.pentaho.di.gis.io.SpatialiteReader; +import com.atolcd.pentaho.di.gis.io.features.Feature; +import com.atolcd.pentaho.di.gis.io.features.FeatureConverter; + import org.pentaho.di.core.Const; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.row.RowMeta; @@ -31,20 +42,10 @@ import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; -import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; -import com.atolcd.pentaho.di.gis.io.AbstractFileReader; -import com.atolcd.pentaho.di.gis.io.DXFReader; -import com.atolcd.pentaho.di.gis.io.GeoJSONReader; -import com.atolcd.pentaho.di.gis.io.MapInfoReader; -import com.atolcd.pentaho.di.gis.io.ShapefileReader; -import com.atolcd.pentaho.di.gis.io.SpatialiteReader; -import com.atolcd.pentaho.di.gis.io.features.Feature; -import com.atolcd.pentaho.di.gis.io.features.FeatureConverter; - -public class GisFileInput extends BaseStep implements StepInterface { +public class GisFileInput extends BaseStep { private GisFileInputData data; private GisFileInputMeta meta; @@ -76,12 +77,34 @@ public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws K fileReader = new SpatialiteReader(environmentSubstitute(meta.getInputFileName()), tableName, meta.getEncoding()); } else if (meta.getInputFormat().equalsIgnoreCase("DXF")) { + String readXData = environmentSubstitute((String) meta.getInputParameterValue("READ_XDATA")); String circleAsPolygon = environmentSubstitute((String) meta.getInputParameterValue("CIRCLE_AS_POLYGON")); String ellipseAsPolygon = environmentSubstitute((String) meta.getInputParameterValue("ELLIPSE_AS_POLYGON")); String lineAsPolygon = environmentSubstitute((String) meta.getInputParameterValue("LINE_AS_POLYGON")); - fileReader = new DXFReader(environmentSubstitute(meta.getInputFileName()), environmentSubstitute(meta.getGeometryFieldName()), meta.getEncoding(), - Boolean.parseBoolean(circleAsPolygon), Boolean.parseBoolean(ellipseAsPolygon), Boolean.parseBoolean(lineAsPolygon)); + fileReader = new DXFReader( + environmentSubstitute(meta.getInputFileName()), + environmentSubstitute(meta.getGeometryFieldName()), + meta.getEncoding(), + Boolean.parseBoolean(circleAsPolygon), + Boolean.parseBoolean(ellipseAsPolygon), + Boolean.parseBoolean(lineAsPolygon), + Boolean.parseBoolean(readXData) + ); + } else if (meta.getInputFormat().equalsIgnoreCase("GPX")) { + fileReader = new GPXReader(environmentSubstitute(meta.getInputFileName()), + environmentSubstitute(meta.getGeometryFieldName()), + meta.getEncoding() + ); + + } else if (meta.getInputFormat().equalsIgnoreCase("GEOPACKAGE")) { + + fileReader = new GeoPackageReader( + environmentSubstitute(meta.getInputFileName()), + environmentSubstitute((String) meta.getInputParameterValue("DB_TABLE_NAME")), + environmentSubstitute(meta.getGeometryFieldName()), + meta.getEncoding() + ); } String forceToMultigeometry = environmentSubstitute((String) meta.getInputParameterValue("FORCE_TO_MULTIGEOMETRY")); diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisfileinput/GisFileInputData.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisfileinput/GisFileInputData.java index 1d1c2d9..1328ed2 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisfileinput/GisFileInputData.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisfileinput/GisFileInputData.java @@ -24,9 +24,8 @@ import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.trans.step.BaseStepData; -import org.pentaho.di.trans.step.StepDataInterface; -public class GisFileInputData extends BaseStepData implements StepDataInterface { +public class GisFileInputData extends BaseStepData { public RowMetaInterface outputRowMeta; diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisfileinput/GisFileInputMeta.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisfileinput/GisFileInputMeta.java index 71e6d2c..4bd96b4 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisfileinput/GisFileInputMeta.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisfileinput/GisFileInputMeta.java @@ -40,7 +40,7 @@ import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.row.RowMetaInterface; -import org.pentaho.di.core.row.ValueMeta; +import org.pentaho.di.core.row.value.ValueMetaBase; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.repository.ObjectId; @@ -57,7 +57,9 @@ import com.atolcd.pentaho.di.gis.io.AbstractFileReader; import com.atolcd.pentaho.di.gis.io.DXFReader; +import com.atolcd.pentaho.di.gis.io.GPXReader; import com.atolcd.pentaho.di.gis.io.GeoJSONReader; +import com.atolcd.pentaho.di.gis.io.GeoPackageReader; import com.atolcd.pentaho.di.gis.io.MapInfoReader; import com.atolcd.pentaho.di.gis.io.ShapefileReader; import com.atolcd.pentaho.di.gis.io.SpatialiteReader; @@ -84,32 +86,45 @@ public GisFileInputMeta() { // ESRI Shapefile GisInputFormatDef shpDef = new GisInputFormatDef("ESRI_SHP", new String[] { "*.shp;*.SHP" }, new String[] { "*.shp" }); - shpDef.addParameterDef("FORCE_TO_2D", ValueMeta.TYPE_BOOLEAN, true, Arrays.asList(new String[] { "TRUE", "FALSE" }), "TRUE"); - shpDef.addParameterDef("FORCE_TO_MULTIGEOMETRY", ValueMeta.TYPE_BOOLEAN, true, Arrays.asList(new String[] { "TRUE", "FALSE" }), "FALSE"); + shpDef.addParameterDef("FORCE_TO_2D", ValueMetaBase.TYPE_BOOLEAN, true, Arrays.asList(new String[] { "TRUE", "FALSE" }), "TRUE"); + shpDef.addParameterDef("FORCE_TO_MULTIGEOMETRY", ValueMetaBase.TYPE_BOOLEAN, true, Arrays.asList(new String[] { "TRUE", "FALSE" }), "FALSE"); this.inputFormatDefs.put("ESRI_SHP", shpDef); // GeoJSON GisInputFormatDef geojsonDef = new GisInputFormatDef("GEOJSON", new String[] { "*.geojson;*.GEOJSON", "*.json;*.JSON" }, new String[] { "*.geojson", "*.json" }); - geojsonDef.addParameterDef("FORCE_TO_MULTIGEOMETRY", ValueMeta.TYPE_BOOLEAN, true, Arrays.asList(new String[] { "TRUE", "FALSE" }), "FALSE"); + geojsonDef.addParameterDef("FORCE_TO_MULTIGEOMETRY", ValueMetaBase.TYPE_BOOLEAN, true, Arrays.asList(new String[] { "TRUE", "FALSE" }), "FALSE"); this.inputFormatDefs.put("GEOJSON", geojsonDef); // Mapinfo MIF/MID GisInputFormatDef mapinfoDef = new GisInputFormatDef("MAPINFO_MIF", new String[] { "*.mif;*.MIF" }, new String[] { "*.mif" }); - mapinfoDef.addParameterDef("FORCE_TO_MULTIGEOMETRY", ValueMeta.TYPE_BOOLEAN, true, Arrays.asList(new String[] { "TRUE", "FALSE" }), "FALSE"); + mapinfoDef.addParameterDef("FORCE_TO_MULTIGEOMETRY", ValueMetaBase.TYPE_BOOLEAN, true, Arrays.asList(new String[] { "TRUE", "FALSE" }), "FALSE"); this.inputFormatDefs.put("MAPINFO_MIF", mapinfoDef); // SpatialLite GisInputFormatDef sqlLiteDef = new GisInputFormatDef("SPATIALITE", new String[] { "*.db;*.DB", "*.sqlite;*.SQLITE" }, new String[] { "*.db", "*.sqlite" }); - sqlLiteDef.addParameterDef("DB_TABLE_NAME", ValueMeta.TYPE_STRING, true); + sqlLiteDef.addParameterDef("DB_TABLE_NAME", ValueMetaBase.TYPE_STRING, true); this.inputFormatDefs.put("SPATIALITE", sqlLiteDef); // DXF GisInputFormatDef dxfDef = new GisInputFormatDef("DXF", new String[] { "*.dxf;*.DXF" }, new String[] { "*.dxf" }); - dxfDef.addParameterDef("FORCE_TO_MULTIGEOMETRY", ValueMeta.TYPE_BOOLEAN, true, Arrays.asList(new String[] { "TRUE", "FALSE" }), "FALSE"); - dxfDef.addParameterDef("CIRCLE_AS_POLYGON", ValueMeta.TYPE_BOOLEAN, true, Arrays.asList(new String[] { "TRUE", "FALSE" }), "FALSE"); - dxfDef.addParameterDef("ELLIPSE_AS_POLYGON", ValueMeta.TYPE_BOOLEAN, true, Arrays.asList(new String[] { "TRUE", "FALSE" }), "FALSE"); - dxfDef.addParameterDef("LINE_AS_POLYGON", ValueMeta.TYPE_BOOLEAN, true, Arrays.asList(new String[] { "TRUE", "FALSE" }), "FALSE"); + dxfDef.addParameterDef("FORCE_TO_MULTIGEOMETRY", ValueMetaBase.TYPE_BOOLEAN, true, Arrays.asList(new String[] { "TRUE", "FALSE" }), "FALSE"); + dxfDef.addParameterDef("READ_XDATA", ValueMetaBase.TYPE_BOOLEAN, true, Arrays.asList(new String[] { "TRUE", "FALSE" }), "FALSE"); + dxfDef.addParameterDef("CIRCLE_AS_POLYGON", ValueMetaBase.TYPE_BOOLEAN, true, Arrays.asList(new String[] { "TRUE", "FALSE" }), "FALSE"); + dxfDef.addParameterDef("ELLIPSE_AS_POLYGON", ValueMetaBase.TYPE_BOOLEAN, true, Arrays.asList(new String[] { "TRUE", "FALSE" }), "FALSE"); + dxfDef.addParameterDef("LINE_AS_POLYGON", ValueMetaBase.TYPE_BOOLEAN, true, Arrays.asList(new String[] { "TRUE", "FALSE" }), "FALSE"); this.inputFormatDefs.put("DXF", dxfDef); + + // GPX + GisInputFormatDef gpxDef = new GisInputFormatDef("GPX", new String[] { "*.gpx;*.GPX" }, new String[] { "*.gpx"}); + gpxDef.addParameterDef("FORCE_TO_2D", ValueMetaBase.TYPE_BOOLEAN, true, Arrays.asList(new String[] {"TRUE", "FALSE"}), "TRUE"); + this.inputFormatDefs.put("GPX", gpxDef); + + // GeoPackage + GisInputFormatDef gpkgDef = new GisInputFormatDef("GEOPACKAGE", new String[] { "*.gpkg;*.GPKG"}, new String[] {"*.gpkg"}); + gpkgDef.addParameterDef("DB_TABLE_NAME", ValueMetaBase.TYPE_STRING, true); + gpkgDef.addParameterDef("FORCE_TO_2D", ValueMetaBase.TYPE_BOOLEAN, true, Arrays.asList(new String[] {"TRUE", "FALSE"}), "TRUE"); + gpkgDef.addParameterDef("FORCE_TO_MULTIGEOMETRY", ValueMetaBase.TYPE_BOOLEAN, true, Arrays.asList(new String[] {"TRUE", "FALSE"}), "FALSE"); + this.inputFormatDefs.put("GEOPACKAGE", gpkgDef); } public List getInputFormatParameters() { @@ -217,8 +232,25 @@ public void getFields(RowMetaInterface r, String origin, RowMetaInterface[] info String tableName = space.environmentSubstitute((String) getInputParameterValue("DB_TABLE_NAME")); fileReader = new SpatialiteReader(space.environmentSubstitute(inputFileName), tableName, charset.displayName()); } else if (inputFormat.equalsIgnoreCase("DXF")) { - fileReader = new DXFReader(space.environmentSubstitute(inputFileName), space.environmentSubstitute(geometryFieldName), charset.displayName(), false, false, false); - } + fileReader = new DXFReader( + space.environmentSubstitute(inputFileName), + space.environmentSubstitute(geometryFieldName), + charset.displayName(), + false, + false, + false, + Boolean.valueOf(space.environmentSubstitute((String) getInputParameterValue("READ_XDATA")))); + }else if (inputFormat.equalsIgnoreCase("GPX")) { + fileReader = new GPXReader(space.environmentSubstitute(inputFileName), space.environmentSubstitute(geometryFieldName), charset.displayName()); + } else if (inputFormat.equalsIgnoreCase("GEOPACKAGE")) { + + fileReader = new GeoPackageReader( + space.environmentSubstitute(inputFileName), + space.environmentSubstitute((String) getInputParameterValue("DB_TABLE_NAME")), + space.environmentSubstitute(geometryFieldName), + charset.displayName() + ); + } r.addRowMeta(FeatureConverter.getRowMeta(fileReader.getFields(), origin)); } catch (KettleException e) { e.printStackTrace(); diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisfileoutput/GisFileOutput.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisfileoutput/GisFileOutput.java index e34d89d..dbe9c76 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisfileoutput/GisFileOutput.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisfileoutput/GisFileOutput.java @@ -23,7 +23,10 @@ */ import java.io.Writer; +import java.time.OffsetDateTime; import java.util.ArrayList; +import java.util.Date; +import java.util.GregorianCalendar; import java.util.List; import org.pentaho.di.core.Const; @@ -33,19 +36,21 @@ import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; -import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; import com.atolcd.pentaho.di.gis.io.AbstractFileWriter; import com.atolcd.pentaho.di.gis.io.DXFWriter; +import com.atolcd.pentaho.di.gis.io.GPXWriter; import com.atolcd.pentaho.di.gis.io.GeoJSONWriter; +import com.atolcd.pentaho.di.gis.io.GeoPackageWriter; import com.atolcd.pentaho.di.gis.io.KMLWriter; +import com.atolcd.pentaho.di.gis.io.SVGWriter; import com.atolcd.pentaho.di.gis.io.ShapefileWriter; import com.atolcd.pentaho.di.gis.io.features.Feature; import com.atolcd.pentaho.di.gis.io.features.FeatureConverter; -public class GisFileOutput extends BaseStep implements StepInterface { +public class GisFileOutput extends BaseStep { private GisFileOutputData data; private GisFileOutputMeta meta; @@ -170,8 +175,255 @@ public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws K ((DXFWriter) fileWriter).setForceTo2DGeometry(Boolean.parseBoolean(forceTo2D)); } + // Write xData + String exportXdataD = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIXED, "DXF_WRITE_XDATA")); + if (exportXdataD != null) { + ((DXFWriter) fileWriter).setExportWithAttributs(Boolean.parseBoolean(exportXdataD)); + } + //GPX + } else if (meta.getOutputFormat().equalsIgnoreCase("GPX")) { + + if (meta.isDataToServlet()) { + Writer writer = getTrans().getServletPrintWriter(); + fileWriter = new GPXWriter(writer, meta.getGeometryFieldName(), meta.getEncoding()); + + } else { + fileWriter = new GPXWriter(environmentSubstitute(meta.getOutputFileName()), meta.getGeometryFieldName(), meta.getEncoding()); + } + + //Version + String version = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIXED, "GPX_VERSION")); + if (version != null) { + ((GPXWriter) fileWriter).setVersion(version); + } + + // Exporter nom + String metaName = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIXED, "GPX_META_NAME")); + if (metaName != null) { + ((GPXWriter) fileWriter).setDocumentName(metaName); + } + + // Exporter description + String metaDescription = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIXED, "GPX_META_DESCRIPTION")); + if (metaDescription != null) { + ((GPXWriter) fileWriter).setDocumentDescription(metaDescription); + } + + //Nom Auteur + String metaAuthorName = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIXED, "GPX_META_AUTHOR_NAME")); + if (metaAuthorName != null) { + ((GPXWriter) fileWriter).setAuthorName(metaAuthorName); + } + + //Email Auteur + String metaAuthorEmail = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIXED, "GPX_META_AUTHOR_EMAIL")); + if (metaAuthorEmail != null) { + ((GPXWriter) fileWriter).setAuthorEmail(metaAuthorEmail); + } + + //Mots clefs + String metaKeyWords = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIXED, "GPX_META_KEYWORDS")); + if (metaKeyWords != null) { + ((GPXWriter) fileWriter).setKeywords(metaKeyWords); + } + + //Date et heure + String dateTime = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIXED, "GPX_META_DATETIME")); + if (dateTime != null) { + + try { + ((GPXWriter) fileWriter).setDatetime(toCalendar(dateTime)); + } catch (Exception e) { + + throw new KettleException(e.getMessage()); + } + + } + + // Exporter nom , ou + String featureNameField = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIELD, "GPX_FEATURE_NAME")); + if (featureNameField != null && !featureNameField.isEmpty()) { + ((GPXWriter) fileWriter).setFeatureNameField(featureNameField); + } + + // Exporter description , ou + String featureDescriptionField = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIELD, "GPX_FEATURE_DESCRIPTION")); + if (featureDescriptionField != null && !featureDescriptionField.isEmpty()) { + ((GPXWriter) fileWriter).setFeatureDescriptionField(featureDescriptionField); + } + + //GEOPACKAGE + } else if (meta.getOutputFormat().equalsIgnoreCase("GEOPACKAGE")) { + + + fileWriter = new GeoPackageWriter( + environmentSubstitute(meta.getOutputFileName()), + environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIXED, "DB_TABLE_NAME")), + environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIELD, "DB_TABLE_PK_FIELD")), + environmentSubstitute(meta.getGeometryFieldName()), + meta.getEncoding() + ); + + //Commit limit + String commitLimit = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIXED, "DB_TABLE_COMMIT_LIMIT")); + if (commitLimit != null) { + ((GeoPackageWriter) fileWriter).setCommitLimit(Long.parseLong(commitLimit)); + } + + // Remplacer fichier + String replaceFile = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIXED, "REPLACE_FILE")); + if (replaceFile != null) { + ((GeoPackageWriter) fileWriter).setReplaceFile(Boolean.parseBoolean(replaceFile)); + } + + // Remplacer table + String replaceTable = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIXED, "REPLACE_TABLE")); + if (replaceTable != null) { + ((GeoPackageWriter) fileWriter).setReplaceTable(Boolean.parseBoolean(replaceTable)); + } + + // Forcer en 2D + String forceTo2D = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIXED, "FORCE_TO_2D")); + if (forceTo2D != null) { + ((GeoPackageWriter) fileWriter).setForceTo2DGeometry(Boolean.parseBoolean(forceTo2D)); + } + + //SRID + String geometrySrid = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIXED, "GPKG_GEOMETRY_SRID")); + if (geometrySrid != null) { + if(geometrySrid.isEmpty()){ + ((GeoPackageWriter) fileWriter).setAssignedSrid(-1); + }else{ + ((GeoPackageWriter) fileWriter).setAssignedSrid(Long.parseLong(geometrySrid)); + } + } + + //Type de géométrie + String geometryType = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIXED, "GPKG_GEOMETRY_GEOMETRYTYPE")); + if (geometryType != null) { + ((GeoPackageWriter) fileWriter).setAssignedGeometryType(geometryType); + } + + //Identifier + String contentsIdentifier = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIXED, "GPKG_CONTENTS_IDENTIFIER")); + if (contentsIdentifier != null) { + ((GeoPackageWriter) fileWriter).setContentsIdentifier(contentsIdentifier); + }else{ + environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIXED, "DB_TABLE_NAME")); + } + + //Description + String contentsDescription = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIXED, "GPKG_CONTENTS_DESCRIPTION")); + if (contentsDescription != null) { + ((GeoPackageWriter) fileWriter).setContentsDescription(contentsDescription); + } + + //SVG + } else if (meta.getOutputFormat().equalsIgnoreCase("SVG")) { + + if (meta.isDataToServlet()) { + Writer writer = getTrans().getServletPrintWriter(); + fileWriter = new SVGWriter(writer, meta.getGeometryFieldName(), meta.getEncoding()); + + } else { + fileWriter = new SVGWriter(environmentSubstitute(meta.getOutputFileName()), meta.getGeometryFieldName(), meta.getEncoding()); + } + + // Largeur + int svgWidth = Integer.parseInt(environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIXED, "SVG_DOC_WIDTH"))); + ((SVGWriter) fileWriter).setWidth(svgWidth); + + // Hauteur + int svgHeight = Integer.parseInt(environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIXED, "SVG_DOC_HEIGHT"))); + ((SVGWriter) fileWriter).setHeight(svgHeight); + + //Precision + String precision = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIXED, "SVG_DOC_COORD_PRECISION")); + if (precision != null) { + ((SVGWriter) fileWriter).setPrecision(Integer.parseInt(precision)); + } + + // Exporter title du doc + String title = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIXED, "SVG_DOC_TITLE")); + if (title != null) { + ((SVGWriter) fileWriter).setDocumentTitle(title); } + // Exporter description du doc + String description = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIXED, "SVG_DOC_DESCRIPTION")); + if (description != null) { + ((SVGWriter) fileWriter).setDocumentDescription(description); + } + + // Feuille de style + String styleSheet = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIXED, "SVG_DOC_STYLESHEET")); + if (styleSheet != null) { + ((SVGWriter) fileWriter).setStyleSheet(styleSheet); + } + + // Usage de la feuille de style + String styleSheetMode = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIXED, "SVG_DOC_STYLESHEET_MODE")); + if (styleSheetMode != null) { + ((SVGWriter) fileWriter).setStyleSheetMode(styleSheetMode); + } + + // Usage des symboles + String symbolMode = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIXED, "SVG_DOC_SYMBOL_MODE")); + if (symbolMode != null) { + ((SVGWriter) fileWriter).setSymbolMode(symbolMode); + } + + // Exporter id + String featureIdField = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIELD, "SVG_FEATURE_ID")); + if (featureIdField != null && !featureIdField.isEmpty()) { + ((SVGWriter) fileWriter).setFeatureIdField(featureIdField); + } + + // Exporter title + String featureTitleField = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIELD, "SVG_FEATURE_TITLE")); + if (featureTitleField != null && !featureTitleField.isEmpty()) { + ((SVGWriter) fileWriter).setFeatureTitleField(featureTitleField); + } + + + // Exporter description + String featureDescriptionField = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIELD, "SVG_FEATURE_DESCRIPTION")); + if (featureDescriptionField != null && !featureDescriptionField.isEmpty()) { + ((SVGWriter) fileWriter).setFeatureDescriptionField(featureDescriptionField); + } + + //Style svg + String featureStyleField = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIELD, "SVG_FEATURE_STYLE")); + if (featureStyleField != null && !featureStyleField.isEmpty()) { + ((SVGWriter) fileWriter).setFeatureSvgStyleField(featureStyleField); + } + + //Class CSS + String featureCssClassField = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIELD, "SVG_FEATURE_CLASS")); + if (featureCssClassField != null && !featureCssClassField.isEmpty()) { + ((SVGWriter) fileWriter).setFeatureCssClassField(featureCssClassField); + } + + //Symbole + String featureSymbolField = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIELD, "SVG_FEATURE_SYMBOL")); + if (featureSymbolField != null && !featureSymbolField.isEmpty()) { + ((SVGWriter) fileWriter).setFeatureSymbolField(featureSymbolField); + } + + //Symbole + String featureLabelField = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIELD, "SVG_FEATURE_LABEL")); + if (featureLabelField != null && !featureLabelField.isEmpty()) { + ((SVGWriter) fileWriter).setFeatureLabelField(featureLabelField); + } + + //Groupe + String featureGroupField = environmentSubstitute((String) meta.getInputParameterValue(GisOutputFormatParameterDef.TYPE_FIELD, "SVG_FEATURE_GROUP")); + if (featureGroupField != null && !featureGroupField.isEmpty()) { + ((SVGWriter) fileWriter).setFeatureGroupField(featureGroupField); + } + + } + fileWriter.setFields(FeatureConverter.getFields(getTransMeta().getPrevStepFields(getStepMeta()))); // Création contextuelle du fichier @@ -236,5 +488,20 @@ public void run() { markStop(); } } + + private static GregorianCalendar toCalendar(String iso8601string) throws Exception{ + + try{ + + java.util.Date date = Date.from(OffsetDateTime.parse(iso8601string).toInstant()); + GregorianCalendar calendar = new GregorianCalendar(); + calendar.setTime(date); + return calendar; + + }catch(Exception e){ + throw new Exception(e.getMessage()); + } + + } } diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisfileoutput/GisFileOutputData.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisfileoutput/GisFileOutputData.java index 403991d..40302a7 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisfileoutput/GisFileOutputData.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisfileoutput/GisFileOutputData.java @@ -24,9 +24,8 @@ import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.trans.step.BaseStepData; -import org.pentaho.di.trans.step.StepDataInterface; -public class GisFileOutputData extends BaseStepData implements StepDataInterface { +public class GisFileOutputData extends BaseStepData { public RowMetaInterface outputRowMeta; diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisfileoutput/GisFileOutputMeta.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisfileoutput/GisFileOutputMeta.java index 66317d9..20f048c 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisfileoutput/GisFileOutputMeta.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisfileoutput/GisFileOutputMeta.java @@ -39,7 +39,7 @@ import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.row.RowMetaInterface; -import org.pentaho.di.core.row.ValueMeta; +import org.pentaho.di.core.row.value.ValueMetaBase; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.repository.ObjectId; @@ -78,33 +78,79 @@ public GisFileOutputMeta() { // ESRI Shapefile GisOutputFormatDef shpDef = new GisOutputFormatDef("ESRI_SHP", new String[] { "*.shp;*.SHP" }, new String[] { "*.shp" }); - shpDef.addParameterFixedDef("FORCE_TO_2D", ValueMeta.TYPE_BOOLEAN, true, Arrays.asList(new String[] { "TRUE", "FALSE" }), "TRUE"); - shpDef.addParameterFixedDef("ESRI_SHP_CREATE_PRJ", ValueMeta.TYPE_BOOLEAN, true, Arrays.asList(new String[] { "TRUE", "FALSE" }), "TRUE"); + shpDef.addParameterFixedDef("FORCE_TO_2D", ValueMetaBase.TYPE_BOOLEAN, true, Arrays.asList(new String[] { "TRUE", "FALSE" }), "TRUE"); + shpDef.addParameterFixedDef("ESRI_SHP_CREATE_PRJ", ValueMetaBase.TYPE_BOOLEAN, true, Arrays.asList(new String[] { "TRUE", "FALSE" }), "TRUE"); this.outputFormatDefs.put("ESRI_SHP", shpDef); // GeoJSON GisOutputFormatDef geojsonDef = new GisOutputFormatDef("GEOJSON", new String[] { "*.geojson;*.GEOJSON", "*.json;*.JSON" }, new String[] { "*.geojson", "*.json" }); - geojsonDef.addParameterFieldDef("GEOJSON_FEATURE_ID", ValueMeta.TYPE_STRING, false); + geojsonDef.addParameterFieldDef("GEOJSON_FEATURE_ID", ValueMetaBase.TYPE_STRING, false); this.outputFormatDefs.put("GEOJSON", geojsonDef); // Keyhole Markup LanguageKML GisOutputFormatDef kmlDef = new GisOutputFormatDef("KML", new String[] { "*.kml;*.KML" }, new String[] { "*.kml" }); - kmlDef.addParameterFixedDef("FORCE_TO_2D", ValueMeta.TYPE_BOOLEAN, true, Arrays.asList(new String[] { "TRUE", "FALSE" }), "TRUE"); - kmlDef.addParameterFixedDef("KML_DOC_NAME", ValueMeta.TYPE_STRING, false); - kmlDef.addParameterFixedDef("KML_DOC_DESCRIPTION", ValueMeta.TYPE_STRING, false); - kmlDef.addParameterFixedDef("KML_EXPORT_ATTRIBUTS", ValueMeta.TYPE_BOOLEAN, true, Arrays.asList(new String[] { "TRUE", "FALSE" }), "FALSE"); - kmlDef.addParameterFieldDef("KML_PLACEMARK_NAME", ValueMeta.TYPE_STRING, false); - kmlDef.addParameterFieldDef("KML_PLACEMARK_DESCRIPTION", ValueMeta.TYPE_STRING, false); + kmlDef.addParameterFixedDef("FORCE_TO_2D", ValueMetaBase.TYPE_BOOLEAN, true, Arrays.asList(new String[] { "TRUE", "FALSE" }), "TRUE"); + kmlDef.addParameterFixedDef("KML_DOC_NAME", ValueMetaBase.TYPE_STRING, false); + kmlDef.addParameterFixedDef("KML_DOC_DESCRIPTION", ValueMetaBase.TYPE_STRING, false); + kmlDef.addParameterFixedDef("KML_EXPORT_ATTRIBUTS", ValueMetaBase.TYPE_BOOLEAN, true, Arrays.asList(new String[] { "TRUE", "FALSE" }), "FALSE"); + kmlDef.addParameterFieldDef("KML_PLACEMARK_NAME", ValueMetaBase.TYPE_STRING, false); + kmlDef.addParameterFieldDef("KML_PLACEMARK_DESCRIPTION", ValueMetaBase.TYPE_STRING, false); this.outputFormatDefs.put("KML", kmlDef); // DXF GisOutputFormatDef dxfDef = new GisOutputFormatDef("DXF", new String[] { "*.dxf;*.DXF" }, new String[] { "*.dxf" }); - dxfDef.addParameterFixedDef("FORCE_TO_2D", ValueMeta.TYPE_BOOLEAN, true, Arrays.asList(new String[] { "TRUE", "FALSE" }), "TRUE"); - dxfDef.addParameterFixedDef("DXF_LAYER_NAME", ValueMeta.TYPE_STRING, true, null, "0"); - dxfDef.addParameterFixedDef("DXF_COORD_PRECISION", ValueMeta.TYPE_INTEGER, true, null, "5"); - dxfDef.addParameterFieldDef("DXF_FEATURE_LAYER_NAME", ValueMeta.TYPE_STRING, false); + dxfDef.addParameterFixedDef("FORCE_TO_2D", ValueMetaBase.TYPE_BOOLEAN, true, Arrays.asList(new String[] { "TRUE", "FALSE" }), "TRUE"); + dxfDef.addParameterFixedDef("DXF_LAYER_NAME", ValueMetaBase.TYPE_STRING, true, null, "0"); + dxfDef.addParameterFixedDef("DXF_COORD_PRECISION", ValueMetaBase.TYPE_INTEGER, true, null, "5"); + dxfDef.addParameterFieldDef("DXF_FEATURE_LAYER_NAME", ValueMetaBase.TYPE_STRING, false); this.outputFormatDefs.put("DXF", dxfDef); + // Gps exchange Format GPX + GisOutputFormatDef gpxDef = new GisOutputFormatDef("GPX", new String[] { "*.gpx;*.GPX" }, new String[] { "*.gpx" }); + gpxDef.addParameterFixedDef("GPX_VERSION", ValueMetaBase.TYPE_STRING, true, Arrays.asList(new String[] { "1.0", "1.1" }), "1.1"); + gpxDef.addParameterFixedDef("GPX_META_NAME", ValueMetaBase.TYPE_STRING, false); + gpxDef.addParameterFixedDef("GPX_META_DESCRIPTION", ValueMetaBase.TYPE_STRING, false); + gpxDef.addParameterFixedDef("GPX_META_AUTHOR_NAME", ValueMetaBase.TYPE_STRING, false); + gpxDef.addParameterFixedDef("GPX_META_AUTHOR_EMAIL", ValueMetaBase.TYPE_STRING, false); + gpxDef.addParameterFixedDef("GPX_META_KEYWORDS", ValueMetaBase.TYPE_STRING, false); + gpxDef.addParameterFixedDef("GPX_META_DATETIME", ValueMetaBase.TYPE_DATE, false); + gpxDef.addParameterFieldDef("GPX_FEATURE_NAME", ValueMetaBase.TYPE_STRING, false); + gpxDef.addParameterFieldDef("GPX_FEATURE_DESCRIPTION", ValueMetaBase.TYPE_STRING, false); + this.outputFormatDefs.put("GPX", gpxDef); + + // GeoPackage + GisOutputFormatDef gpkgDef = new GisOutputFormatDef("GEOPACKAGE", new String[] { "*.gpkg;*.GPKG"}, new String[] {"*.gpkg"}); + gpkgDef.addParameterFixedDef("REPLACE_FILE", ValueMetaBase.TYPE_BOOLEAN, true, Arrays.asList(new String[] {"TRUE", "FALSE"}), "TRUE"); + gpkgDef.addParameterFixedDef("DB_TABLE_NAME", ValueMetaBase.TYPE_STRING, true); + gpkgDef.addParameterFixedDef("DB_TABLE_COMMIT_LIMIT", ValueMetaBase.TYPE_INTEGER, true,null,"1000"); + gpkgDef.addParameterFixedDef("REPLACE_TABLE", ValueMetaBase.TYPE_BOOLEAN, true, Arrays.asList(new String[] {"TRUE", "FALSE"}), "FALSE"); + gpkgDef.addParameterFixedDef("GPKG_CONTENTS_IDENTIFIER", ValueMetaBase.TYPE_STRING, false); + gpkgDef.addParameterFixedDef("GPKG_CONTENTS_DESCRIPTION", ValueMetaBase.TYPE_STRING, false); + gpkgDef.addParameterFixedDef("GPKG_GEOMETRY_SRID", ValueMetaBase.TYPE_INTEGER, false); + gpkgDef.addParameterFixedDef("GPKG_GEOMETRY_GEOMETRYTYPE", ValueMetaBase.TYPE_STRING, false, Arrays.asList(new String[] {"POINT", "LINESTRING", "POLYGON","MULTIPOINT", "MULTILINESTRING", "MULTIPOLYGON","GEOMETRY"}), "GEOMETRY"); + gpkgDef.addParameterFixedDef("FORCE_TO_2D", ValueMetaBase.TYPE_BOOLEAN, true, Arrays.asList(new String[] {"TRUE", "FALSE"}), "TRUE"); + gpkgDef.addParameterFieldDef("DB_TABLE_PK_FIELD", ValueMetaBase.TYPE_INTEGER, true); + this.outputFormatDefs.put("GEOPACKAGE", gpkgDef); + + // Scalable Vector Graphics SVG + GisOutputFormatDef svgDef = new GisOutputFormatDef("SVG", new String[] { "*.svg;*.SVG" }, new String[] { "*.svg" }); + svgDef.addParameterFixedDef("SVG_DOC_WIDTH", ValueMetaBase.TYPE_INTEGER, true, null, "1000"); + svgDef.addParameterFixedDef("SVG_DOC_HEIGHT", ValueMetaBase.TYPE_INTEGER, true,null, "1000"); + svgDef.addParameterFixedDef("SVG_DOC_COORD_PRECISION", ValueMetaBase.TYPE_INTEGER, true, null, "5"); + svgDef.addParameterFixedDef("SVG_DOC_TITLE", ValueMetaBase.TYPE_STRING, false); + svgDef.addParameterFixedDef("SVG_DOC_DESCRIPTION", ValueMetaBase.TYPE_STRING, false); + svgDef.addParameterFixedDef("SVG_DOC_STYLESHEET", ValueMetaBase.TYPE_STRING, false); + svgDef.addParameterFixedDef("SVG_DOC_STYLESHEET_MODE", ValueMetaBase.TYPE_STRING, false, Arrays.asList(new String[] {"RESSOURCE_EXTERNAL", "RESSOURCE_EMBEDDED"}), "RESSOURCE_EXTERNAL"); + svgDef.addParameterFixedDef("SVG_DOC_SYMBOL_MODE", ValueMetaBase.TYPE_STRING, false, Arrays.asList(new String[] {"RESSOURCE_EXTERNAL", "RESSOURCE_EMBEDDED"}), "RESSOURCE_EXTERNAL"); + svgDef.addParameterFieldDef("SVG_FEATURE_ID", ValueMetaBase.TYPE_STRING, false); + svgDef.addParameterFieldDef("SVG_FEATURE_TITLE", ValueMetaBase.TYPE_STRING, false); + svgDef.addParameterFieldDef("SVG_FEATURE_DESCRIPTION", ValueMetaBase.TYPE_STRING, false); + svgDef.addParameterFieldDef("SVG_FEATURE_STYLE", ValueMetaBase.TYPE_STRING, false); + svgDef.addParameterFieldDef("SVG_FEATURE_CLASS", ValueMetaBase.TYPE_STRING, false); + svgDef.addParameterFieldDef("SVG_FEATURE_SYMBOL", ValueMetaBase.TYPE_STRING, false); + svgDef.addParameterFieldDef("SVG_FEATURE_LABEL", ValueMetaBase.TYPE_STRING, false); + svgDef.addParameterFieldDef("SVG_FEATURE_GROUP", ValueMetaBase.TYPE_INTEGER, false); + this.outputFormatDefs.put("SVG", svgDef); } public HashMap getOutputFormatDefs() { @@ -265,7 +311,7 @@ public boolean isParameterValueRequired(String formatKey, String parameterType, public int getParameterValueMetaType(String formatKey, String parameterType, String parameterKey) { - int valueMetaType = ValueMeta.TYPE_NONE; + int valueMetaType = ValueMetaBase.TYPE_NONE; if (parameterType.equalsIgnoreCase(GisOutputFormatParameterDef.TYPE_FIELD)) { diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgeometryinfo/GisGeometryInfo.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgeometryinfo/GisGeometryInfo.java index f931d0b..ae98bb6 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgeometryinfo/GisGeometryInfo.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgeometryinfo/GisGeometryInfo.java @@ -25,6 +25,10 @@ import java.util.LinkedHashMap; import java.util.Map.Entry; +import com.atolcd.pentaho.di.core.row.value.ValueMetaGeometry; +import com.atolcd.pentaho.di.gis.utils.GeometryUtils; +import com.vividsolutions.jts.geom.Geometry; + import org.pentaho.di.core.Const; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.row.RowDataUtil; @@ -33,15 +37,10 @@ import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; -import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; -import com.atolcd.pentaho.di.core.row.value.ValueMetaGeometry; -import com.atolcd.pentaho.di.gis.utils.GeometryUtils; -import com.vividsolutions.jts.geom.Geometry; - -public class GisGeometryInfo extends BaseStep implements StepInterface { +public class GisGeometryInfo extends BaseStep { private GisGeometryInfoData data; private GisGeometryInfoMeta meta; diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgeometryinfo/GisGeometryInfoData.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgeometryinfo/GisGeometryInfoData.java index b1338bb..2fa4309 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgeometryinfo/GisGeometryInfoData.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgeometryinfo/GisGeometryInfoData.java @@ -24,9 +24,8 @@ import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.trans.step.BaseStepData; -import org.pentaho.di.trans.step.StepDataInterface; -public class GisGeometryInfoData extends BaseStepData implements StepDataInterface { +public class GisGeometryInfoData extends BaseStepData { public RowMetaInterface outputRowMeta; diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgeometryinfo/GisGeometryInfoMeta.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgeometryinfo/GisGeometryInfoMeta.java index 5cd9221..55c4a4c 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgeometryinfo/GisGeometryInfoMeta.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgeometryinfo/GisGeometryInfoMeta.java @@ -38,7 +38,7 @@ import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.row.RowMetaInterface; -import org.pentaho.di.core.row.ValueMeta; +import org.pentaho.di.core.row.value.ValueMetaBase; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.core.xml.XMLHandler; @@ -70,20 +70,20 @@ public GisGeometryInfoMeta() { this.infosTypes = new HashMap(); this.outputFields = new LinkedHashMap(); - this.infosTypes.put("NULL_OR_EMPTY", ValueMeta.TYPE_BOOLEAN); - this.infosTypes.put("AREA", ValueMeta.TYPE_NUMBER); - this.infosTypes.put("LENGTH", ValueMeta.TYPE_NUMBER); - this.infosTypes.put("DIMENSION", ValueMeta.TYPE_INTEGER); - this.infosTypes.put("SRID", ValueMeta.TYPE_INTEGER); - this.infosTypes.put("GEOMETRY_TYPE", ValueMeta.TYPE_STRING); - this.infosTypes.put("GEOMETRY_COUNT", ValueMeta.TYPE_INTEGER); - this.infosTypes.put("GEOMETRY_VERTEX_COUNT", ValueMeta.TYPE_INTEGER); - this.infosTypes.put("X_MIN", ValueMeta.TYPE_NUMBER); - this.infosTypes.put("Y_MIN", ValueMeta.TYPE_NUMBER); - this.infosTypes.put("Z_MIN", ValueMeta.TYPE_NUMBER); - this.infosTypes.put("X_MAX", ValueMeta.TYPE_NUMBER); - this.infosTypes.put("Y_MAX", ValueMeta.TYPE_NUMBER); - this.infosTypes.put("Z_MAX", ValueMeta.TYPE_NUMBER); + this.infosTypes.put("NULL_OR_EMPTY", ValueMetaBase.TYPE_BOOLEAN); + this.infosTypes.put("AREA", ValueMetaBase.TYPE_NUMBER); + this.infosTypes.put("LENGTH", ValueMetaBase.TYPE_NUMBER); + this.infosTypes.put("DIMENSION", ValueMetaBase.TYPE_INTEGER); + this.infosTypes.put("SRID", ValueMetaBase.TYPE_INTEGER); + this.infosTypes.put("GEOMETRY_TYPE", ValueMetaBase.TYPE_STRING); + this.infosTypes.put("GEOMETRY_COUNT", ValueMetaBase.TYPE_INTEGER); + this.infosTypes.put("GEOMETRY_VERTEX_COUNT", ValueMetaBase.TYPE_INTEGER); + this.infosTypes.put("X_MIN", ValueMetaBase.TYPE_NUMBER); + this.infosTypes.put("Y_MIN", ValueMetaBase.TYPE_NUMBER); + this.infosTypes.put("Z_MIN", ValueMetaBase.TYPE_NUMBER); + this.infosTypes.put("X_MAX", ValueMetaBase.TYPE_NUMBER); + this.infosTypes.put("Y_MAX", ValueMetaBase.TYPE_NUMBER); + this.infosTypes.put("Z_MAX", ValueMetaBase.TYPE_NUMBER); } @@ -148,7 +148,7 @@ public void getFields(RowMetaInterface r, String origin, RowMetaInterface[] info if (valueMetaType == ValueMetaGeometry.TYPE_GEOMETRY) { valueMeta = new ValueMetaGeometry(fieldName); } else { - valueMeta = new ValueMeta(fieldName, valueMetaType); + valueMeta = new ValueMetaBase(fieldName, valueMetaType); } valueMeta.setOrigin(origin); diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgeoprocessing/GisGeoprocessing.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgeoprocessing/GisGeoprocessing.java index a6a5391..c3dc87a 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgeoprocessing/GisGeoprocessing.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgeoprocessing/GisGeoprocessing.java @@ -23,25 +23,13 @@ */ import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.TreeSet; -import org.apache.commons.lang.ArrayUtils; -import org.opensphere.geometry.algorithm.ConcaveHull; -import org.pentaho.di.core.Const; -import org.pentaho.di.core.exception.KettleException; -import org.pentaho.di.core.row.RowDataUtil; -import org.pentaho.di.core.row.RowMetaInterface; -import org.pentaho.di.trans.Trans; -import org.pentaho.di.trans.TransMeta; -import org.pentaho.di.trans.step.BaseStep; -import org.pentaho.di.trans.step.StepDataInterface; -import org.pentaho.di.trans.step.StepInterface; -import org.pentaho.di.trans.step.StepMeta; -import org.pentaho.di.trans.step.StepMetaInterface; - import com.atolcd.pentaho.di.core.row.value.ValueMetaGeometry; import com.atolcd.pentaho.di.gis.utils.GeometryUtils; +import com.vividsolutions.jts.algorithm.MinimumBoundingCircle; import com.vividsolutions.jts.densify.Densifier; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.CoordinateArrays; @@ -66,9 +54,24 @@ import com.vividsolutions.jts.operation.linemerge.LineMerger; import com.vividsolutions.jts.operation.overlay.snap.GeometrySnapper; import com.vividsolutions.jts.operation.polygonize.Polygonizer; +import com.vividsolutions.jts.operation.union.UnaryUnionOp; import com.vividsolutions.jts.simplify.DouglasPeuckerSimplifier; +import com.vividsolutions.jts.simplify.VWSimplifier; -public class GisGeoprocessing extends BaseStep implements StepInterface { +import org.apache.commons.lang.ArrayUtils; +import org.opensphere.geometry.algorithm.ConcaveHull; +import org.pentaho.di.core.Const; +import org.pentaho.di.core.exception.KettleException; +import org.pentaho.di.core.row.RowDataUtil; +import org.pentaho.di.core.row.RowMetaInterface; +import org.pentaho.di.trans.Trans; +import org.pentaho.di.trans.TransMeta; +import org.pentaho.di.trans.step.BaseStep; +import org.pentaho.di.trans.step.StepDataInterface; +import org.pentaho.di.trans.step.StepMeta; +import org.pentaho.di.trans.step.StepMetaInterface; + +public class GisGeoprocessing extends BaseStep { private GisGeoprocessingData data; private GisGeoprocessingMeta meta; @@ -109,7 +112,7 @@ private Geometry getGeoprocessingResult(Object[] row) throws KettleException { distance = getInputRowMeta().getNumber(row, distanceFieldIndex); if (distance == null) { - throw new KettleException("Distance can not be null"); + throw new KettleException("Distance, area, threshold or decimal count can not be null"); } } else { @@ -246,7 +249,7 @@ public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws K try { distanceValue = Double.parseDouble(environmentSubstitute(meta.getDistanceValue())); } catch (Exception e) { - throw new KettleException("Distance is not valid"); + throw new KettleException("Distance, area, threshold or decimal count is not valid"); } } @@ -462,6 +465,166 @@ private Geometry getOneGeometryGeoprocessing(String operator, Geometry inGeometr throw new KettleException("Distance can not be null"); } + } else if (operator.equalsIgnoreCase("SIMPLIFY_VW")) { + + if (distance != null) { + + distance = Math.abs(distance); + VWSimplifier simplifier = new VWSimplifier(inGeometry); + simplifier.setDistanceTolerance(distance); + outGeometry = simplifier.getResultGeometry(); + + } else { + throw new KettleException("Distance can not be null"); + } + + } else if (operator.equalsIgnoreCase("LESS_PRECISION")) { + + if (distance != null) { + outGeometry = GeometryUtils.getLessPrecisionGeometry(inGeometry, distance.intValue()); + + } else { + throw new KettleException("Decimal count can not be null"); + } + } else if (operator.equalsIgnoreCase("POLYGONIZE")) { + + Polygonizer polygonizer = new Polygonizer(); + polygonizer.add(inGeometry); + outGeometry = geometryFactory.buildGeometry(polygonizer.getPolygons()); + + } else if (operator.equalsIgnoreCase("LINEMERGE")) { + + outGeometry = GeometryUtils.getMergedGeometry(inGeometry); + + + } else if (operator.equalsIgnoreCase("REMOVE_HOLES")) { + + if (distance != null) { + + if(inGeometry instanceof Polygon){ + + Polygon polygon = (Polygon) inGeometry; + List rings = new ArrayList(); + for(int i = 0; i < polygon.getNumInteriorRing(); i++){ + LinearRing currentRing = (LinearRing) polygon.getInteriorRingN(i); + + if(geometryFactory.createPolygon(currentRing).getArea() > distance){ + rings.add(currentRing); + } + } + + outGeometry = geometryFactory.createPolygon( + (LinearRing) polygon.getExteriorRing(), + rings.toArray(new LinearRing[rings.size()]) + ); + + } else if (inGeometry instanceof MultiPolygon){ + + Polygon[] polygons = new Polygon[inGeometry.getNumGeometries()]; + for(int i = 0; i < polygons.length; i++){ + polygons[i] = (Polygon) getOneGeometryGeoprocessing("REMOVE_HOLES", inGeometry.getGeometryN(i), distance); + } + outGeometry = geometryFactory.createMultiPolygon(polygons); + + } + + } else { + throw new KettleException("Area can not be null"); + } + + } else if (operator.equalsIgnoreCase("LARGEST_POLYGON")) { + + if(inGeometry instanceof Polygon){ + outGeometry = (Geometry) inGeometry.clone(); + + } else if (inGeometry instanceof MultiPolygon){ + Polygon largestPolygon = (Polygon) inGeometry.getGeometryN(0); + for(int i = 0; i < inGeometry.getNumGeometries(); i++){ + + Polygon currentPolygon = (Polygon)inGeometry.getGeometryN(i); + if(currentPolygon.getArea() > largestPolygon.getArea()){ + largestPolygon = currentPolygon; + } + + } + outGeometry = largestPolygon; + + } + + } else if (operator.equalsIgnoreCase("SMALLEST_POLYGON")) { + + if(inGeometry instanceof Polygon){ + outGeometry = (Geometry) inGeometry.clone(); + + } else if (inGeometry instanceof MultiPolygon){ + Polygon smallestPolygon = (Polygon) inGeometry.getGeometryN(0); + for(int i = 0; i < inGeometry.getNumGeometries(); i++){ + + Polygon currentPolygon = (Polygon)inGeometry.getGeometryN(i); + if(currentPolygon.getArea() < smallestPolygon.getArea()){ + smallestPolygon = currentPolygon; + } + + } + outGeometry = smallestPolygon; + + } + + } else if (operator.equalsIgnoreCase("LONGEST_LINESTRING")) { + + if(inGeometry instanceof LineString){ + outGeometry = (Geometry) inGeometry.clone(); + + } else if (inGeometry instanceof MultiLineString){ + LineString longestLineString = (LineString) inGeometry.getGeometryN(0); + for(int i = 0; i < inGeometry.getNumGeometries(); i++){ + + LineString currentLineString = (LineString)inGeometry.getGeometryN(i); + if(currentLineString.getLength() > longestLineString.getLength()){ + longestLineString = currentLineString; + } + + } + outGeometry = longestLineString; + + } + } else if (operator.equalsIgnoreCase("SHORTEST_LINESTRING")) { + + if(inGeometry instanceof LineString){ + outGeometry = (Geometry) inGeometry.clone(); + + } else if (inGeometry instanceof MultiLineString){ + LineString shortestLineString = (LineString) inGeometry.getGeometryN(0); + for(int i = 0; i < inGeometry.getNumGeometries(); i++){ + + LineString currentLineString = (LineString)inGeometry.getGeometryN(i); + if(currentLineString.getLength() < shortestLineString.getLength()){ + shortestLineString = currentLineString; + } + + } + outGeometry = shortestLineString; + + } + + } else if (operator.equalsIgnoreCase("LINEAR_REFERENCING")) { + + if(inGeometry instanceof LineString){ + + if (distance != null) { + + outGeometry = geometryFactory.createPoint( + new LengthIndexedLine((LineString) inGeometry) + .extractPoint(distance) + ); + + }else{ + + throw new KettleException("Distance can not be null"); + } + + } + } else if (operator.equalsIgnoreCase("TO_2D_GEOMETRY")) { outGeometry = GeometryUtils.get2DGeometry(inGeometry); @@ -474,16 +637,26 @@ private Geometry getOneGeometryGeoprocessing(String operator, Geometry inGeometr outGeometry = geometryFactory.createMultiPoint(inGeometry.getCoordinates()); + } else if (operator.equalsIgnoreCase("EXTRACT_FIRST_COORDINATE")) { + + outGeometry = geometryFactory.createPoint(inGeometry.getCoordinates()[0]); + + } else if (operator.equalsIgnoreCase("EXTRACT_LAST_COORDINATE")) { + + outGeometry = geometryFactory.createPoint(inGeometry.getCoordinates()[inGeometry.getCoordinates().length -1]); + } else if (operator.equalsIgnoreCase("MBR")) { outGeometry = inGeometry.getEnvelope(); + } else if (operator.equalsIgnoreCase("MBC")) { + + outGeometry = new MinimumBoundingCircle(inGeometry).getCircle(); + } else if (operator.equalsIgnoreCase("CENTROID")) { outGeometry = inGeometry.getCentroid(); - } - } return GeometryUtils.getNonEmptyGeometry(inGeometry.getSRID(), outGeometry); @@ -527,8 +700,8 @@ private Geometry getTwoGeometriesGeoprocessing(String operator, Geometry inGeome throw new KettleException("The first geometry is not a POLYGON or a MULTIPOLYGON"); } - if (!(inGeometryA instanceof Polygonal)) { - throw new KettleException("The first geometry is not a POLYGON or a MULTIPOLYGON"); + if (!(inGeometryB instanceof Polygonal)) { + throw new KettleException("The second geometry is not a POLYGON or a MULTIPOLYGON"); } if (distance != null) { @@ -540,6 +713,79 @@ private Geometry getTwoGeometriesGeoprocessing(String operator, Geometry inGeome throw new KettleException("Distance can not be null"); } + } else if (operator.equalsIgnoreCase("SPLIT")) { + + //Géométrie à découper ne doit pas être nulle + if(!GeometryUtils.isNullOrEmptyGeometry(inGeometryA)){ + + //Geometrie de découpe ne doit pas être nulle + if(GeometryUtils.isNullOrEmptyGeometry(inGeometryB)){ + + outGeometry = (Geometry) inGeometryA.clone(); + + }else{ + + //Découpe de surface par un linéaire + if (inGeometryA instanceof Polygonal + && inGeometryB instanceof Lineal){ + + Polygonizer polygonizer = new Polygonizer(); + List boundaries = new ArrayList(); + boundaries.add(inGeometryA.getBoundary()); + boundaries.add(inGeometryB); + UnaryUnionOp uOp = new UnaryUnionOp(geometryFactory.buildGeometry(boundaries)); + polygonizer.add(GeometryUtils.getMergedGeometry(uOp.union())); + + List realPolygons = new ArrayList(); + for (Polygon polygon : GeometryFactory.toPolygonArray(polygonizer.getPolygons())) { + + if (inGeometryA.contains(polygon.getInteriorPoint())) { + realPolygons.add(polygon); + } + + } + + outGeometry = geometryFactory.buildGeometry(realPolygons); + + //Découpe de linéaire par un linéaire + }else if (inGeometryA instanceof Lineal + && inGeometryB instanceof Lineal + && !GeometryUtils.isNullOrEmptyGeometry(inGeometryA) + && !GeometryUtils.isNullOrEmptyGeometry(inGeometryB)){ + + outGeometry = inGeometryA.difference(inGeometryB); + + //Découpe de linéaire par un ponctuel + }else if (inGeometryA instanceof Lineal + && inGeometryB instanceof Puntal){ + + List linestrings = new ArrayList(); + if(inGeometryA instanceof LineString){ + + linestrings.addAll(Arrays.asList(splitLineStringAtCoordinates(inGeometryB.getCoordinates(), (LineString) inGeometryA, 10E-6))); + + }else{ + + for(int i = 0; i < inGeometryA.getNumGeometries(); i++){ + linestrings.addAll(Arrays.asList(splitLineStringAtCoordinates( + inGeometryB.getCoordinates(), + (LineString) inGeometryA.getGeometryN(i), + 10E-6) + )); + } + } + + outGeometry = geometryFactory.buildGeometry(linestrings); + + //Autres cas de découpe non pris en charge + }else{ + throw new KettleException("Split (MULTI)POLYGON by a (MULTI)LINESTRING, (MULTI)LINESTRING by (MULTI)LINESTRING or (MULTI)LINESTRING by (MULTI)POINT"); + } + + } + + } + } else { throw new IllegalArgumentException("Function \"" + operator + "\" is not allowed"); } @@ -775,9 +1021,7 @@ private static LineString[] splitLineStringAtCoordinates(Coordinate[] splitCoord for (Coordinate splitCoordinate : splitCoordinates) { if (geometryFactory.createPoint(splitCoordinate).distance(inputLineString) <= distance) { - indexesTree.add(lengthIndexedLine.project(splitCoordinate)); - } } diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgeoprocessing/GisGeoprocessingData.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgeoprocessing/GisGeoprocessingData.java index 611120b..ab76197 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgeoprocessing/GisGeoprocessingData.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgeoprocessing/GisGeoprocessingData.java @@ -24,9 +24,8 @@ import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.trans.step.BaseStepData; -import org.pentaho.di.trans.step.StepDataInterface; -public class GisGeoprocessingData extends BaseStepData implements StepDataInterface { +public class GisGeoprocessingData extends BaseStepData { public RowMetaInterface outputRowMeta; diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgeoprocessing/GisGeoprocessingMeta.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgeoprocessing/GisGeoprocessingMeta.java index a7a9c17..36824af 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgeoprocessing/GisGeoprocessingMeta.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgeoprocessing/GisGeoprocessingMeta.java @@ -59,11 +59,13 @@ public class GisGeoprocessingMeta extends BaseStepMeta implements StepMetaInterf // Pour opérateurs avec une seule géométrie private static String[] oneGeometryOperators = new String[] { "BOUNDARY", "INTERIOR_POINT", "CONVEX_HULL", "CONCAVE_HULL", "BUFFER", "EXTENDED_BUFFER", "EXPLODE", "REVERSE", - "DENSIFY", "SIMPLIFY", "TO_2D_GEOMETRY", "TO_MULTI_GEOMETRY", "EXTRACT_COORDINATES", "MBR", "CENTROID" }; + "DENSIFY", "SIMPLIFY", "SIMPLIFY_VW", "TO_2D_GEOMETRY", "TO_MULTI_GEOMETRY", "EXTRACT_COORDINATES","EXTRACT_FIRST_COORDINATE","EXTRACT_LAST_COORDINATE", "MBR", "MBC", "CENTROID", "LESS_PRECISION", "POLYGONIZE", + "LINEMERGE", "REMOVE_HOLES", "LARGEST_POLYGON", "SMALLEST_POLYGON","LONGEST_LINESTRING", "SHORTEST_LINESTRING", "LINEAR_REFERENCING" }; private String firstGeometryFieldName; // Pour opérateurs avec deux géométries - private static String[] twoGeometriesOperators = new String[] { "UNION", "DIFFERENCE", "INTERSECTION", "SYM_DIFFERENCE", "SNAP_TO_GEOMETRY", "SIMPLIFY_POLYGON" }; + private static String[] twoGeometriesOperators = new String[] { "UNION", "DIFFERENCE", "INTERSECTION", "SYM_DIFFERENCE", "SNAP_TO_GEOMETRY", + "SIMPLIFY_POLYGON", "SPLIT" }; private String secondGeometryFieldName; // Pour opérateurs avec possibilités de filtrage de géométries hétérogènes @@ -76,8 +78,8 @@ public class GisGeoprocessingMeta extends BaseStepMeta implements StepMetaInterf private String returnType; // Pour opérateurs avec besoin de distance - private static String[] withDistanceOperators = new String[] { "CONCAVE_HULL", "BUFFER", "EXTENDED_BUFFER", "DENSIFY", "SIMPLIFY", ",CONCAVE_HULL", "SNAP_TO_GEOMETRY", - "SIMPLIFY_POLYGON" }; + private static String[] withDistanceOperators = new String[] { "CONCAVE_HULL", "BUFFER", "EXTENDED_BUFFER", + "DENSIFY", "SIMPLIFY", "SIMPLIFY_VW", "CONCAVE_HULL", "SNAP_TO_GEOMETRY", "SIMPLIFY_POLYGON", "LESS_PRECISION","REMOVE_HOLES", "LINEAR_REFERENCING" }; private boolean dynamicDistance; private String distanceFieldName; private String distanceValue; diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgroupby/GisGroupBy.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgroupby/GisGroupBy.java index 1d3ab49..ae049ce 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgroupby/GisGroupBy.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgroupby/GisGroupBy.java @@ -34,8 +34,15 @@ import java.util.Set; import java.util.TreeSet; +import com.atolcd.pentaho.di.core.row.value.GeometryInterface; +import com.atolcd.pentaho.di.gis.utils.GeometryUtils; +import com.vividsolutions.jts.dissolve.LineDissolver; +import com.vividsolutions.jts.geom.Geometry; +import com.vividsolutions.jts.geom.GeometryFactory; +import com.vividsolutions.jts.geom.util.GeometryCombiner; +import com.vividsolutions.jts.operation.union.UnaryUnionOp; + import org.apache.commons.math.stat.descriptive.rank.Percentile; -import org.pentaho.di.core.Const; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleFileException; import org.pentaho.di.core.exception.KettleValueException; @@ -43,9 +50,8 @@ import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueDataUtil; -import org.pentaho.di.core.row.ValueMeta; import org.pentaho.di.core.row.ValueMetaInterface; -import com.atolcd.pentaho.di.core.row.value.GeometryInterface; +import org.pentaho.di.core.row.value.ValueMetaBase; import org.pentaho.di.core.row.value.ValueMetaInteger; import org.pentaho.di.core.row.value.ValueMetaNumber; import org.pentaho.di.i18n.BaseMessages; @@ -53,23 +59,16 @@ import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; -import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; -import com.atolcd.pentaho.di.gis.utils.GeometryUtils; -import com.vividsolutions.jts.geom.Geometry; -import com.vividsolutions.jts.geom.GeometryFactory; -import com.vividsolutions.jts.geom.util.GeometryCombiner; -import com.vividsolutions.jts.operation.union.UnaryUnionOp; - /** * Groups informations based on aggregation rules. (sum, count, ...) * * @author Matt * @since 2-jun-2003 */ -public class GisGroupBy extends BaseStep implements StepInterface { +public class GisGroupBy extends BaseStep { private static Class PKG = GisGroupByMeta.class; // for i18n purposes, // needed by // Translator2!! @@ -259,7 +258,7 @@ public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws K lineNr++; - if (meta.isAddingLineNrInGroup() && !Const.isEmpty(meta.getLineNrInGroupField())) { + if (meta.isAddingLineNrInGroup() && !meta.getLineNrInGroupField().isEmpty()) { Object lineNrValue = new Long(lineNr); // ValueMetaInterface lineNrValueMeta = new // ValueMeta(meta.getLineNrInGroupField(), @@ -316,7 +315,7 @@ private void handleLastOfGroup() throws KettleException { size += data.groupResult.length; lineNr++; - if (meta.isAddingLineNrInGroup() && !Const.isEmpty(meta.getLineNrInGroupField())) { + if (meta.isAddingLineNrInGroup() && !meta.getLineNrInGroupField().isEmpty()) { Object lineNrValue = new Long(lineNr); // ValueMetaInterface lineNrValueMeta = new // ValueMeta(meta.getLineNrInGroupField(), @@ -576,7 +575,7 @@ void calcAggregate(Object[] r) throws KettleValueException { case GisGroupByMeta.TYPE_GROUP_CONCAT_STRING: if (!(subj == null)) { String separator = ""; - if (!Const.isEmpty(meta.getValueField()[i])) { + if (!meta.getValueField()[i].isEmpty()) { separator = environmentSubstitute(meta.getValueField()[i]); } @@ -618,6 +617,15 @@ void calcAggregate(Object[] r) throws KettleValueException { } break; + // GIS : Dissolution des géométries + case GisGroupByMeta.TYPE_GROUP_GEOMETRY_DISSOLVE: + if (subj != null) { + Geometry geometryForDissolve = GeometryCombiner.combine(((GeometryInterface) valueMeta).getGeometry(value), ((GeometryInterface) subjMeta).getGeometry(subj)); + geometrySRID = ((GeometryInterface) subjMeta).getGeometry(subj).getSRID(); + data.agg[i] = geometryForDissolve; + } + break; + default: break; } @@ -650,20 +658,20 @@ void newAggregate(Object[] r) { case GisGroupByMeta.TYPE_GROUP_AVERAGE: case GisGroupByMeta.TYPE_GROUP_CUMULATIVE_SUM: case GisGroupByMeta.TYPE_GROUP_CUMULATIVE_AVERAGE: - vMeta = new ValueMeta(meta.getAggregateField()[i], subjMeta.isNumeric() ? subjMeta.getType() : ValueMetaInterface.TYPE_NUMBER); + vMeta = new ValueMetaBase(meta.getAggregateField()[i], subjMeta.isNumeric() ? subjMeta.getType() : ValueMetaInterface.TYPE_NUMBER); break; case GisGroupByMeta.TYPE_GROUP_MEDIAN: case GisGroupByMeta.TYPE_GROUP_PERCENTILE: - vMeta = new ValueMeta(meta.getAggregateField()[i], ValueMetaInterface.TYPE_NUMBER); + vMeta = new ValueMetaBase(meta.getAggregateField()[i], ValueMetaInterface.TYPE_NUMBER); v = new ArrayList(); break; case GisGroupByMeta.TYPE_GROUP_STANDARD_DEVIATION: - vMeta = new ValueMeta(meta.getAggregateField()[i], ValueMetaInterface.TYPE_NUMBER); + vMeta = new ValueMetaBase(meta.getAggregateField()[i], ValueMetaInterface.TYPE_NUMBER); break; case GisGroupByMeta.TYPE_GROUP_COUNT_DISTINCT: case GisGroupByMeta.TYPE_GROUP_COUNT_ANY: case GisGroupByMeta.TYPE_GROUP_COUNT_ALL: - vMeta = new ValueMeta(meta.getAggregateField()[i], ValueMetaInterface.TYPE_INTEGER); + vMeta = new ValueMetaBase(meta.getAggregateField()[i], ValueMetaInterface.TYPE_INTEGER); break; case GisGroupByMeta.TYPE_GROUP_FIRST: case GisGroupByMeta.TYPE_GROUP_LAST: @@ -676,11 +684,11 @@ void newAggregate(Object[] r) { v = r == null ? null : r[data.subjectnrs[i]]; break; case GisGroupByMeta.TYPE_GROUP_CONCAT_COMMA: - vMeta = new ValueMeta(meta.getAggregateField()[i], ValueMetaInterface.TYPE_STRING); + vMeta = new ValueMetaBase(meta.getAggregateField()[i], ValueMetaInterface.TYPE_STRING); v = new StringBuilder(); break; case GisGroupByMeta.TYPE_GROUP_CONCAT_STRING: - vMeta = new ValueMeta(meta.getAggregateField()[i], ValueMetaInterface.TYPE_STRING); + vMeta = new ValueMetaBase(meta.getAggregateField()[i], ValueMetaInterface.TYPE_STRING); v = new StringBuilder(); break; @@ -688,6 +696,7 @@ void newAggregate(Object[] r) { case GisGroupByMeta.TYPE_GROUP_GEOMETRY_UNION: case GisGroupByMeta.TYPE_GROUP_GEOMETRY_EXTENT: case GisGroupByMeta.TYPE_GROUP_GEOMETRY_AGG: + case GisGroupByMeta.TYPE_GROUP_GEOMETRY_DISSOLVE: vMeta = subjMeta.clone(); vMeta.setName(meta.getAggregateField()[i]); v = new GeometryFactory().createGeometryCollection(null); @@ -758,7 +767,7 @@ Object[] getAggregateResult() throws KettleValueException { case GisGroupByMeta.TYPE_GROUP_SUM: break; case GisGroupByMeta.TYPE_GROUP_AVERAGE: - ag = ValueDataUtil.divide(data.aggMeta.getValueMeta(i), ag, new ValueMeta("c", ValueMetaInterface.TYPE_INTEGER), new Long(data.counts[i])); + ag = ValueDataUtil.divide(data.aggMeta.getValueMeta(i), ag, new ValueMetaBase("c", ValueMetaInterface.TYPE_INTEGER), new Long(data.counts[i])); break; case GisGroupByMeta.TYPE_GROUP_MEDIAN: case GisGroupByMeta.TYPE_GROUP_PERCENTILE: @@ -822,6 +831,15 @@ Object[] getAggregateResult() throws KettleValueException { ag = geomtryAgg; break; + // GIS : Dissolution des géométries + case GisGroupByMeta.TYPE_GROUP_GEOMETRY_DISSOLVE: + + Geometry geomDissolveGroup = ((GeometryInterface) data.aggMeta.getValueMeta(i)).getGeometry(ag); + Geometry geometryDissolve = LineDissolver.dissolve(geomDissolveGroup); + geometryDissolve.setSRID(geometrySRID); + ag = geometryDissolve; + break; + default: break; } diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgroupby/GisGroupByData.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgroupby/GisGroupByData.java index fa4665a..6c98f9c 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgroupby/GisGroupByData.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgroupby/GisGroupByData.java @@ -34,14 +34,13 @@ import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.trans.step.BaseStepData; -import org.pentaho.di.trans.step.StepDataInterface; /** * @author Matt * @since 24-jan-2005 * */ -public class GisGroupByData extends BaseStepData implements StepDataInterface { +public class GisGroupByData extends BaseStepData { public Object[] previous; /** diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgroupby/GisGroupByMeta.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgroupby/GisGroupByMeta.java index bb37c45..d29adee 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgroupby/GisGroupByMeta.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisgroupby/GisGroupByMeta.java @@ -33,7 +33,7 @@ import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.RowMetaInterface; -import org.pentaho.di.core.row.ValueMeta; +import org.pentaho.di.core.row.value.ValueMetaBase; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.core.xml.XMLHandler; @@ -99,6 +99,7 @@ public class GisGroupByMeta extends BaseStepMeta implements StepMetaInterface { public static final int TYPE_GROUP_GEOMETRY_UNION = 19; public static final int TYPE_GROUP_GEOMETRY_EXTENT = 20; public static final int TYPE_GROUP_GEOMETRY_AGG = 21; + public static final int TYPE_GROUP_GEOMETRY_DISSOLVE = 22; // GIS : Ajout d'opérateurs d'aggrégation public static final String[] typeGroupCode = /* @@ -107,7 +108,7 @@ public class GisGroupByMeta extends BaseStepMeta implements StepMetaInterface { * TRANSLATE! */ { "-", "SUM", "AVERAGE", "MEDIAN", "PERCENTILE", "MIN", "MAX", "COUNT_ALL", "CONCAT_COMMA", "FIRST", "LAST", "FIRST_INCL_NULL", "LAST_INCL_NULL", "CUM_SUM", "CUM_AVG", - "STD_DEV", "CONCAT_STRING", "COUNT_DISTINCT", "COUNT_ANY", "GEOMETRY_UNION", "GEOMETRY_EXTENT", "GEOMETRY_AGG" }; + "STD_DEV", "CONCAT_STRING", "COUNT_DISTINCT", "COUNT_ANY", "GEOMETRY_UNION", "GEOMETRY_EXTENT", "GEOMETRY_AGG", "GEOMETRY_DISSOLVE" }; public static final String[] typeGroupLongDesc = { "-", BaseMessages.getString(PKG, "GroupByMeta.TypeGroupLongDesc.SUM"), BaseMessages.getString(PKG, "GroupByMeta.TypeGroupLongDesc.AVERAGE"), BaseMessages.getString(PKG, "GroupByMeta.TypeGroupLongDesc.MEDIAN"), @@ -121,7 +122,7 @@ public class GisGroupByMeta extends BaseStepMeta implements StepMetaInterface { BaseMessages.getString(PKG, "GroupByMeta.TypeGroupLongDesc.COUNT_ANY"), // GIS : Ajout d'opérateurs d'aggrégation BaseMessages.getString(PKG, "GroupByMeta.TypeGroupLongDesc.GEOMETRY_UNION"), BaseMessages.getString(PKG, "GroupByMeta.TypeGroupLongDesc.GEOMETRY_EXTENT"), - BaseMessages.getString(PKG, "GroupByMeta.TypeGroupLongDesc.GEOMETRY_AGG"), }; + BaseMessages.getString(PKG, "GroupByMeta.TypeGroupLongDesc.GEOMETRY_AGG"), BaseMessages.getString(PKG, "GroupByMeta.TypeGroupLongDesc.GEOMETRY_DISSOLVE")}; /** * All rows need to pass, adding an extra row at the end of each @@ -355,7 +356,7 @@ private void readData(Node stepnode) throws KettleXMLException { } String giveBackRow = XMLHandler.getTagValue(stepnode, "give_back_row"); - if (Const.isEmpty(giveBackRow)) { + if (giveBackRow.isEmpty()) { alwaysGivingBackOneRow = hasNumberOfValues; } else { alwaysGivingBackOneRow = "Y".equalsIgnoreCase(giveBackRow); @@ -470,6 +471,7 @@ public void getFields(RowMetaInterface r, String origin, RowMetaInterface[] info case TYPE_GROUP_GEOMETRY_UNION: case TYPE_GROUP_GEOMETRY_EXTENT: case TYPE_GROUP_GEOMETRY_AGG: + case TYPE_GROUP_GEOMETRY_DISSOLVE: value_type = ValueMetaGeometry.TYPE_GEOMETRY; break; @@ -497,7 +499,7 @@ public void getFields(RowMetaInterface r, String origin, RowMetaInterface[] info } if (value_type != ValueMetaInterface.TYPE_NONE) { - ValueMetaInterface v = new ValueMeta(value_name, value_type); + ValueMetaInterface v = new ValueMetaBase(value_name, value_type); v.setOrigin(origin); v.setLength(length, precision); fields.addValueMeta(v); @@ -507,8 +509,8 @@ public void getFields(RowMetaInterface r, String origin, RowMetaInterface[] info if (passAllRows) { // If we pass all rows, we can add a line nr in the group... - if (addingLineNrInGroup && !Const.isEmpty(lineNrInGroupField)) { - ValueMetaInterface lineNr = new ValueMeta(lineNrInGroupField, ValueMetaInterface.TYPE_INTEGER); + if (addingLineNrInGroup && !lineNrInGroupField.isEmpty()) { + ValueMetaInterface lineNr = new ValueMetaBase(lineNrInGroupField, ValueMetaInterface.TYPE_INTEGER); lineNr.setLength(ValueMetaInterface.DEFAULT_INTEGER_LENGTH, 0); lineNr.setOrigin(origin); fields.addValueMeta(lineNr); diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisrelate/GisRelate.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisrelate/GisRelate.java index f0fe251..f340d44 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisrelate/GisRelate.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisrelate/GisRelate.java @@ -1,5 +1,11 @@ package com.atolcd.pentaho.di.trans.steps.gisrelate; +import com.atolcd.pentaho.di.core.row.value.GeometryInterface; +import com.atolcd.pentaho.di.gis.utils.GeometryUtils; +import com.vividsolutions.jts.geom.Coordinate; +import com.vividsolutions.jts.geom.Geometry; +import com.vividsolutions.jts.geom.GeometryFactory; + /* * #%L * Pentaho Data Integrator GIS Plugin @@ -27,21 +33,14 @@ import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.row.RowDataUtil; import org.pentaho.di.core.row.RowMetaInterface; -import com.atolcd.pentaho.di.core.row.value.GeometryInterface; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; -import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; -import com.atolcd.pentaho.di.gis.utils.GeometryUtils; -import com.vividsolutions.jts.geom.Coordinate; -import com.vividsolutions.jts.geom.Geometry; -import com.vividsolutions.jts.geom.GeometryFactory; - -public class GisRelate extends BaseStep implements StepInterface { +public class GisRelate extends BaseStep { private static GeometryFactory geometryFactory = new GeometryFactory(); diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisrelate/GisRelateData.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisrelate/GisRelateData.java index e0baedb..5e0da50 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisrelate/GisRelateData.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisrelate/GisRelateData.java @@ -24,9 +24,8 @@ import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.trans.step.BaseStepData; -import org.pentaho.di.trans.step.StepDataInterface; -public class GisRelateData extends BaseStepData implements StepDataInterface { +public class GisRelateData extends BaseStepData { public RowMetaInterface outputRowMeta; diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisrelate/GisRelateMeta.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisrelate/GisRelateMeta.java index 7e47cc9..ef6547b 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisrelate/GisRelateMeta.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/trans/steps/gisrelate/GisRelateMeta.java @@ -35,7 +35,7 @@ import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.row.RowMetaInterface; -import org.pentaho.di.core.row.ValueMeta; +import org.pentaho.di.core.row.value.ValueMetaBase; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.core.xml.XMLHandler; @@ -179,7 +179,7 @@ public String getXML() { public void getFields(RowMetaInterface r, String origin, RowMetaInterface[] info, StepMeta nextStep, VariableSpace space) { if (ArrayUtils.contains(numericResultOperators, operator)) { - ValueMetaInterface valueMeta = new ValueMeta(outputFieldName, ValueMeta.TYPE_NUMBER); + ValueMetaInterface valueMeta = new ValueMetaBase(outputFieldName, ValueMetaBase.TYPE_NUMBER); valueMeta.setOrigin(origin); r.addValueMeta(valueMeta); } @@ -187,7 +187,7 @@ public void getFields(RowMetaInterface r, String origin, RowMetaInterface[] info if (ArrayUtils.contains(boolResultOperators, operator)) { if (returnType.equalsIgnoreCase("ALL")) { - ValueMetaInterface valueMeta = new ValueMeta(outputFieldName, ValueMeta.TYPE_BOOLEAN); + ValueMetaInterface valueMeta = new ValueMetaBase(outputFieldName, ValueMetaBase.TYPE_BOOLEAN); valueMeta.setOrigin(origin); r.addValueMeta(valueMeta); } diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/ui/trans/steps/gisfileinput/GisFileInputDialog.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/ui/trans/steps/gisfileinput/GisFileInputDialog.java index 34a0c04..52bb7dc 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/ui/trans/steps/gisfileinput/GisFileInputDialog.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/ui/trans/steps/gisfileinput/GisFileInputDialog.java @@ -51,7 +51,7 @@ import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.pentaho.di.core.Const; -import org.pentaho.di.core.row.ValueMeta; +import org.pentaho.di.core.row.value.ValueMetaBase; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStepMeta; @@ -191,20 +191,32 @@ public void modifyText(ModifyEvent arg0) { // Pas de nom de colonne géométrie pour spatialite : plusieurs // géométries autorisées if (wInputFormat.getText() != null && !wInputFormat.getText().isEmpty() - && (getFormatKey(wInputFormat.getText()).equalsIgnoreCase("SPATIALITE") - || getFormatKey(wInputFormat.getText()).equalsIgnoreCase("DXF") - )) { - + && ( + getFormatKey(wInputFormat.getText()).equalsIgnoreCase("SPATIALITE") + || getFormatKey(wInputFormat.getText()).equalsIgnoreCase("DXF") + || getFormatKey(wInputFormat.getText()).equalsIgnoreCase("GPX") + || getFormatKey(wInputFormat.getText()).equalsIgnoreCase("GEOPACKAGE") + ) + ) { + //Si spatialite : Pas de nom de colonne géométrie car plusieurs géométries autorisées if(getFormatKey(wInputFormat.getText()).equalsIgnoreCase("SPATIALITE")){ wGeometryField.setEnabled(false); wGeometryField.setText(""); - wlGeometryField.setEnabled(false); - } + } else { + wGeometryField.setEnabled(true); + wGeometryField.setText(BaseMessages.getString(PKG, "GisFileInput.GeometryFieldName.Default")); + wlGeometryField.setEnabled(true); + } wEncoding.setEnabled(false); wlEncoding.setEnabled(false); - if(getFormatKey(wInputFormat.getText()).equalsIgnoreCase("SPATIALITE")){ + //SPATIALITE / GEOPACKAGE / GPX + if(getFormatKey(wInputFormat.getText()).equalsIgnoreCase("SPATIALITE") + || getFormatKey(wInputFormat.getText()).equalsIgnoreCase("GEOPACKAGE") + || getFormatKey(wInputFormat.getText()).equalsIgnoreCase("GPX") + ){ + wEncoding.setText("UTF-8"); }else{ //DXF @@ -216,10 +228,9 @@ public void modifyText(ModifyEvent arg0) { wGeometryField.setEnabled(true); wGeometryField.setText(BaseMessages.getString(PKG, "GisFileInput.GeometryFieldName.Default")); wlGeometryField.setEnabled(true); - wEncoding.setEnabled(true); wlEncoding.setEnabled(true); - + wEncoding.setText(""); } } }); @@ -701,7 +712,7 @@ public void widgetSelected(SelectionEvent e) { // Paramétrage de la boîte de dialogue (commun) String dialogTitle = BaseMessages.getString(PKG, "GisFileInput.Params.Dialog.PARAM_VALUE.Title"); - String dialogParamComment = BaseMessages.getString(PKG, "GisFileInput.Params." + paramKey + ".Description") + " (" + ValueMeta.getTypeDesc(paramValueMetaType) + String dialogParamComment = BaseMessages.getString(PKG, "GisFileInput.Params." + paramKey + ".Description") + " (" + ValueMetaBase.getTypeDesc(paramValueMetaType) + ")"; if (values.isEmpty()) { diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/ui/trans/steps/gisfileoutput/GisFileOutputDialog.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/ui/trans/steps/gisfileoutput/GisFileOutputDialog.java index 273eba4..bfbf8ec 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/ui/trans/steps/gisfileoutput/GisFileOutputDialog.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/ui/trans/steps/gisfileoutput/GisFileOutputDialog.java @@ -54,7 +54,7 @@ import org.pentaho.di.core.Const; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.row.RowMetaInterface; -import org.pentaho.di.core.row.ValueMeta; +import org.pentaho.di.core.row.value.ValueMetaBase; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStepMeta; @@ -205,9 +205,10 @@ public void modifyText(ModifyEvent arg0) { if (wOutputFormat.getText() != null && !wOutputFormat.getText().isEmpty()) { - // Si ESRI_SHP ou SPATIALITE ou SQLITE ou DXF pas de servlet - if (getFormatKey(wOutputFormat.getText()).equalsIgnoreCase("ESRI_SHP") || getFormatKey(wOutputFormat.getText()).equalsIgnoreCase("SPATIALITE") - || getFormatKey(wOutputFormat.getText()).equalsIgnoreCase("SQLITE") || getFormatKey(wOutputFormat.getText()).equalsIgnoreCase("DXF")) { + // Si ESRI_SHP, DXF, GEOPACKAGE pas de servlet + if (getFormatKey(wOutputFormat.getText()).equalsIgnoreCase("ESRI_SHP") + || getFormatKey(wOutputFormat.getText()).equalsIgnoreCase("GEOPACKAGE") + || getFormatKey(wOutputFormat.getText()).equalsIgnoreCase("DXF")) { wlDataToServlet.setEnabled(false); wDataToServlet.setEnabled(false); @@ -221,14 +222,17 @@ public void modifyText(ModifyEvent arg0) { } // Si KML ou Spatalite ou sqlite UTF8 forcé - if (getFormatKey(wOutputFormat.getText()).equalsIgnoreCase("KML") || getFormatKey(wOutputFormat.getText()).equalsIgnoreCase("SPATIALITE") - || getFormatKey(wOutputFormat.getText()).equalsIgnoreCase("SQLITE") || getFormatKey(wOutputFormat.getText()).equalsIgnoreCase("DXF")) { + if (getFormatKey(wOutputFormat.getText()).equalsIgnoreCase("KML") + || getFormatKey(wOutputFormat.getText()).equalsIgnoreCase("GPX") + || getFormatKey(wOutputFormat.getText()).equalsIgnoreCase("GEOPACKAGE") + || getFormatKey(wOutputFormat.getText()).equalsIgnoreCase("DXF")) { wEncoding.setEnabled(false); wlEncoding.setEnabled(false); - if (getFormatKey(wOutputFormat.getText()).equalsIgnoreCase("KML") || getFormatKey(wOutputFormat.getText()).equalsIgnoreCase("SPATIALITE") - || getFormatKey(wOutputFormat.getText()).equalsIgnoreCase("SQLITE")){ + if (getFormatKey(wOutputFormat.getText()).equalsIgnoreCase("KML") + || getFormatKey(wOutputFormat.getText()).equalsIgnoreCase("GPX") + || getFormatKey(wOutputFormat.getText()).equalsIgnoreCase("GEOPACKAGE")){ wEncoding.setText("UTF-8"); @@ -236,26 +240,11 @@ public void modifyText(ModifyEvent arg0) { //DXF wEncoding.setText("windows-1252"); } - } else { - wEncoding.setEnabled(true); wlEncoding.setEnabled(true); - + wEncoding.setText(""); } - - // Si sqlite : pas besoin de géométrie - if (getFormatKey(wOutputFormat.getText()).equalsIgnoreCase("SQLITE")) { - - wlGeometryField.setEnabled(false); - wGeometryField.setEnabled(false); - wGeometryField.setText(""); - - } else { - wlGeometryField.setEnabled(true); - wGeometryField.setEnabled(true); - } - } clearTables(); @@ -437,7 +426,7 @@ public void widgetSelected(SelectionEvent e) { fdFixedParams.left = new FormAttachment(0, 0); fdFixedParams.top = new FormAttachment(wlFixedParams, margin); fdFixedParams.right = new FormAttachment(100, 0); - fdFixedParams.height = 150; + fdFixedParams.height = 200; wFixedParams.setLayoutData(fdFixedParams); // Boutons Ok et Annuler @@ -492,7 +481,7 @@ public void shellClosed(ShellEvent e) { }); loadEncodings(); - wGeometryField.setItems(getFieldsFromType(ValueMeta.getTypeDesc(ValueMetaGeometry.TYPE_GEOMETRY), false)); + wGeometryField.setItems(getFieldsFromType(ValueMetaBase.getTypeDesc(ValueMetaGeometry.TYPE_GEOMETRY), false)); loadData(); setDataToServletFlags(); input.setChanged(changed); @@ -962,7 +951,7 @@ public void widgetSelected(SelectionEvent e) { // Paramétrage de la boîte de dialogue (commun) String dialogTitle = BaseMessages.getString(PKG, "GisFileOutput.Params.Dialog.PARAM_VALUE.Title"); - String dialogParamComment = BaseMessages.getString(PKG, "GisFileOutput.Params." + paramKey + ".Description") + " (" + ValueMeta.getTypeDesc(paramValueMetaType) + String dialogParamComment = BaseMessages.getString(PKG, "GisFileOutput.Params." + paramKey + ".Description") + " (" + ValueMetaBase.getTypeDesc(paramValueMetaType) + ")"; if (values.isEmpty()) { @@ -1044,7 +1033,7 @@ public void widgetSelected(SelectionEvent e) { // Paramètrage de la boîte de dialogue String dialogTitle = BaseMessages.getString(PKG, "GisFileOutput.Params.Dialog.PARAM_FIELD.Title"); - String dialogParamComment = BaseMessages.getString(PKG, "GisFileOutput.Params." + paramKey + ".Description") + " (" + ValueMeta.getTypeDesc(paramValueMetaType) + String dialogParamComment = BaseMessages.getString(PKG, "GisFileOutput.Params." + paramKey + ".Description") + " (" + ValueMetaBase.getTypeDesc(paramValueMetaType) + ")"; if (!values.isEmpty()) { dialogParamComment = dialogParamComment + "\n\n" + BaseMessages.getString(PKG, "GisFileOutput.Params.Dialog.PARAM_ALLOWED_VALUES.Description") + " :\n" @@ -1052,7 +1041,7 @@ public void widgetSelected(SelectionEvent e) { } // Valeur vide dans la liste si champ non obligatoire - String[] fields = getFieldsFromType(ValueMeta.getTypeDesc(paramValueMetaType), + String[] fields = getFieldsFromType(ValueMetaBase.getTypeDesc(paramValueMetaType), !input.isParameterValueRequired(formatKey, GisOutputFormatParameterDef.TYPE_FIELD, paramKey)); // Choix dans une liste diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/ui/trans/steps/gisgeometryinfo/GisGeometryInfoDialog.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/ui/trans/steps/gisgeometryinfo/GisGeometryInfoDialog.java index cb72fed..44a0433 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/ui/trans/steps/gisgeometryinfo/GisGeometryInfoDialog.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/ui/trans/steps/gisgeometryinfo/GisGeometryInfoDialog.java @@ -52,7 +52,7 @@ import org.pentaho.di.core.Const; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.row.RowMetaInterface; -import org.pentaho.di.core.row.ValueMeta; +import org.pentaho.di.core.row.value.ValueMetaBase; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStepMeta; @@ -208,7 +208,7 @@ public void shellClosed(ShellEvent e) { } }); - wGeometryField.setItems(getFieldsFromType(ValueMeta.getTypeDesc(ValueMetaGeometry.TYPE_GEOMETRY))); + wGeometryField.setItems(getFieldsFromType(ValueMetaBase.getTypeDesc(ValueMetaGeometry.TYPE_GEOMETRY))); loadData(); input.setChanged(changed); setSize(); diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/ui/trans/steps/gisgeoprocessing/GisGeoprocessingDialog.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/ui/trans/steps/gisgeoprocessing/GisGeoprocessingDialog.java index 2344a90..57f5087 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/ui/trans/steps/gisgeoprocessing/GisGeoprocessingDialog.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/ui/trans/steps/gisgeoprocessing/GisGeoprocessingDialog.java @@ -50,7 +50,7 @@ import org.pentaho.di.core.Const; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.row.RowMetaInterface; -import org.pentaho.di.core.row.ValueMeta; +import org.pentaho.di.core.row.value.ValueMetaBase; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStepMeta; @@ -537,9 +537,9 @@ public void shellClosed(ShellEvent e) { } }); - wFirstGeometryField.setItems(getFieldsFromType(ValueMeta.getTypeDesc(ValueMetaGeometry.TYPE_GEOMETRY))); - wSecondGeometryField.setItems(getFieldsFromType(ValueMeta.getTypeDesc(ValueMetaGeometry.TYPE_GEOMETRY))); - wDistanceField.setItems(getFieldsFromType(ValueMeta.getTypeDesc(ValueMeta.TYPE_NUMBER))); + wFirstGeometryField.setItems(getFieldsFromType(ValueMetaBase.getTypeDesc(ValueMetaGeometry.TYPE_GEOMETRY))); + wSecondGeometryField.setItems(getFieldsFromType(ValueMetaBase.getTypeDesc(ValueMetaGeometry.TYPE_GEOMETRY))); + wDistanceField.setItems(getFieldsFromType(ValueMetaBase.getTypeDesc(ValueMetaBase.TYPE_NUMBER))); loadData(); input.setChanged(changed); setSize(); diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/ui/trans/steps/gisgroupby/GisGroupByDialog.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/ui/trans/steps/gisgroupby/GisGroupByDialog.java index d8d7f5e..870a874 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/ui/trans/steps/gisgroupby/GisGroupByDialog.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/ui/trans/steps/gisgroupby/GisGroupByDialog.java @@ -585,7 +585,7 @@ private void cancel() { } private void ok() { - if (Const.isEmpty(wStepname.getText())) { + if (wStepname.getText().isEmpty()) { return; } diff --git a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/ui/trans/steps/gisrelate/GisRelateDialog.java b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/ui/trans/steps/gisrelate/GisRelateDialog.java index 642037e..376a3fa 100644 --- a/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/ui/trans/steps/gisrelate/GisRelateDialog.java +++ b/pentaho-gis-plugins/src/main/java/com/atolcd/pentaho/di/ui/trans/steps/gisrelate/GisRelateDialog.java @@ -50,7 +50,7 @@ import org.pentaho.di.core.Const; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.row.RowMetaInterface; -import org.pentaho.di.core.row.ValueMeta; +import org.pentaho.di.core.row.value.ValueMetaBase; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStepMeta; @@ -415,9 +415,9 @@ public void shellClosed(ShellEvent e) { } }); - wFirstGeometryField.setItems(getFieldsFromType(ValueMeta.getTypeDesc(ValueMetaGeometry.TYPE_GEOMETRY))); - wSecondGeometryField.setItems(getFieldsFromType(ValueMeta.getTypeDesc(ValueMetaGeometry.TYPE_GEOMETRY))); - wDistanceField.setItems(getFieldsFromType(ValueMeta.getTypeDesc(ValueMeta.TYPE_NUMBER))); + wFirstGeometryField.setItems(getFieldsFromType(ValueMetaBase.getTypeDesc(ValueMetaGeometry.TYPE_GEOMETRY))); + wSecondGeometryField.setItems(getFieldsFromType(ValueMetaBase.getTypeDesc(ValueMetaGeometry.TYPE_GEOMETRY))); + wDistanceField.setItems(getFieldsFromType(ValueMetaBase.getTypeDesc(ValueMetaBase.TYPE_NUMBER))); loadData(); // setReturnTypeFlags(); // setOperatorFlags diff --git a/pentaho-gis-plugins/src/main/resources/com/atolcd/pentaho/di/trans/steps/giscoordinatetransformation/messages/messages_fr_FR.properties b/pentaho-gis-plugins/src/main/resources/com/atolcd/pentaho/di/trans/steps/giscoordinatetransformation/messages/messages_fr_FR.properties index 1e7380e..71fd783 100644 --- a/pentaho-gis-plugins/src/main/resources/com/atolcd/pentaho/di/trans/steps/giscoordinatetransformation/messages/messages_fr_FR.properties +++ b/pentaho-gis-plugins/src/main/resources/com/atolcd/pentaho/di/trans/steps/giscoordinatetransformation/messages/messages_fr_FR.properties @@ -60,6 +60,6 @@ GisCoordinateTransformation.Button.Check.ASSIGN.ToolTip = V\u00e9rifier la pr\ GisCoordinateTransformation.Button.Check.REPROJECT.ToolTip = V\u00e9rifier la la possibilit\u00e9 de transformation GisCoordinateTransformation.MessageBox.CRSCode.OK = Le syst\u00e8me de coordonn\u00e9es %1$s est reconnu. -GisCoordinateTransformation.MessageBox.CRSCode.ERROR = Le syst\u00e8me de coordonn\u00e9es %1$s n'est pas reconnu. +GisCoordinateTransformation.MessageBox.CRSCode.ERROR = Le syst\u00e8me de coordonn\u00e9es %1$s n''est pas reconnu. GisCoordinateTransformation.MessageBox.CRSTransformation.OK = La reprojection du syst\u00e8me %1$s vers le syst\u00e8me %2$s est r\u00e9alisable. GisCoordinateTransformation.MessageBox.CRSTransformation.ERROR = La reprojection du syst\u00e8me %1$s vers le syst\u00e8me %2$s n''est pas r\u00e9alisable. \ No newline at end of file diff --git a/pentaho-gis-plugins/src/main/resources/com/atolcd/pentaho/di/trans/steps/gisfileinput/messages/messages_en_US.properties b/pentaho-gis-plugins/src/main/resources/com/atolcd/pentaho/di/trans/steps/gisfileinput/messages/messages_en_US.properties index f99c59b..78c979f 100644 --- a/pentaho-gis-plugins/src/main/resources/com/atolcd/pentaho/di/trans/steps/gisfileinput/messages/messages_en_US.properties +++ b/pentaho-gis-plugins/src/main/resources/com/atolcd/pentaho/di/trans/steps/gisfileinput/messages/messages_en_US.properties @@ -55,19 +55,23 @@ GisFileInput.Format.GEOJSON.Label = GeoJSON GisFileInput.Format.MAPINFO_MIF.Label = MapInfo Interchange Format GisFileInput.Format.SPATIALITE.Label = SpatiaLite SQLite GisFileInput.Format.DXF.Label = Drawing eXchange Format +GisFileInput.Format.GPX.Label = GPS eXchange Format +GisFileInput.Format.GEOPACKAGE.Label = GeoPackage GisFileInput.Params.FORCE_TO_2D.Label = Force to 2D GisFileInput.Params.FORCE_TO_2D.Description = Force to 2D geometries\nif 3D geometries GisFileInput.Params.FORCE_TO_MULTIGEOMETRY.Label = Force to multi geometries GisFileInput.Params.FORCE_TO_MULTIGEOMETRY.Description = Force to MultiLinestring\nand MultiPolygon GisFileInput.Params.DB_TABLE_NAME.Label = Table -GisFileInput.Params.DB_TABLE_NAME.Description = Table name +GisFileInput.Params.DB_TABLE_NAME.Description = Table name or * to list contents GisFileInput.Params.CIRCLE_AS_POLYGON.Label = Circles as polygons GisFileInput.Params.CIRCLE_AS_POLYGON.Description = Circles are converted to polygons GisFileInput.Params.ELLIPSE_AS_POLYGON.Label = Ellipses as polygons GisFileInput.Params.ELLIPSE_AS_POLYGON.Description = Ellipses are converted to polygons GisFileInput.Params.LINE_AS_POLYGON.Label = Closed polylines as polygons GisFileInput.Params.LINE_AS_POLYGON.Description = Closed polylines are converted to polygons +GisFileInput.Params.READ_XDATA.Label = Extract attributes +GisFileInput.Params.READ_XDATA.Description = Extract attributes (XData) GisFileInput.Params.Predefined.TRUE.Label = Yes GisFileInput.Params.Predefined.FALSE.Label = No \ No newline at end of file diff --git a/pentaho-gis-plugins/src/main/resources/com/atolcd/pentaho/di/trans/steps/gisfileinput/messages/messages_fr_FR.properties b/pentaho-gis-plugins/src/main/resources/com/atolcd/pentaho/di/trans/steps/gisfileinput/messages/messages_fr_FR.properties index 6c37959..3f573a2 100644 --- a/pentaho-gis-plugins/src/main/resources/com/atolcd/pentaho/di/trans/steps/gisfileinput/messages/messages_fr_FR.properties +++ b/pentaho-gis-plugins/src/main/resources/com/atolcd/pentaho/di/trans/steps/gisfileinput/messages/messages_fr_FR.properties @@ -54,19 +54,23 @@ GisFileInput.Format.GEOJSON.Label = GeoJSON GisFileInput.Format.MAPINFO_MIF.Label = MapInfo Interchange Format GisFileInput.Format.SPATIALITE.Label = SpatiaLite / SQLite GisFileInput.Format.DXF.Label = Drawing eXchange Format +GisFileInput.Format.GPX.Label = GPS eXchange Format +GisFileInput.Format.GEOPACKAGE.Label = GeoPackage GisFileInput.Params.FORCE_TO_2D.Label = Forcer en 2D GisFileInput.Params.FORCE_TO_2D.Description = Ne pas r\u00e9cup\u00e9rer la 3\u00e8me dimension\nm\u00eame si cette derni\u00e8re est pr\u00e9sente GisFileInput.Params.FORCE_TO_MULTIGEOMETRY.Label = Forcer en multi-g\u00e9om\u00e9tries GisFileInput.Params.FORCE_TO_MULTIGEOMETRY.Description = Forcer la cr\u00e9ation de multi-g\u00e9om\u00e9tries\npour les g\u00e9om\u00e9tries lin\u00e9aires et surfaciques GisFileInput.Params.DB_TABLE_NAME.Label = Table -GisFileInput.Params.DB_TABLE_NAME.Description = Nom de la table \u00e0 extraire +GisFileInput.Params.DB_TABLE_NAME.Description = Nom de la table \u00e0 extraire ou * pour lister le contenu GisFileInput.Params.CIRCLE_AS_POLYGON.Label = Cercles en polygones GisFileInput.Params.CIRCLE_AS_POLYGON.Description = Les cercles sont transform\u00e9s en \u00e9l\u00e9ments surfaciques GisFileInput.Params.ELLIPSE_AS_POLYGON.Label = Ellipses en polygones GisFileInput.Params.ELLIPSE_AS_POLYGON.Description = Les ellipses sont transform\u00e9es en \u00e9l\u00e9ments surfaciques GisFileInput.Params.LINE_AS_POLYGON.Label = Polylignes ferm\u00e9es en polygones GisFileInput.Params.LINE_AS_POLYGON.Description = Les polylignes ferm\u00e9es sont transform\u00e9es en \u00e9l\u00e9ments surfaciques +GisFileInput.Params.READ_XDATA.Label = Extraire les attributs +GisFileInput.Params.READ_XDATA.Description = Extraire les informations contenues dans les XData GisFileInput.Params.Predefined.TRUE.Label = Oui GisFileInput.Params.Predefined.FALSE.Label = Non \ No newline at end of file diff --git a/pentaho-gis-plugins/src/main/resources/com/atolcd/pentaho/di/trans/steps/gisfileoutput/messages/messages_en_US.properties b/pentaho-gis-plugins/src/main/resources/com/atolcd/pentaho/di/trans/steps/gisfileoutput/messages/messages_en_US.properties index 114f70a..7c0c7ed 100644 --- a/pentaho-gis-plugins/src/main/resources/com/atolcd/pentaho/di/trans/steps/gisfileoutput/messages/messages_en_US.properties +++ b/pentaho-gis-plugins/src/main/resources/com/atolcd/pentaho/di/trans/steps/gisfileoutput/messages/messages_en_US.properties @@ -63,14 +63,9 @@ GisFileOutput.Format.KML.Label = Keyhole Markup Language GisFileOutput.Format.SPATIALITE.Label = SpatiaLite GisFileOutput.Format.SQLITE.Label = SQLite GisFileOutput.Format.DXF.Label = Drawing eXchange Format - -GisFileInput.Params.FORCE_TO_2D.Label = Force to 2D -GisFileInput.Params.FORCE_TO_2D.Description = Force to 2D geometries\nif 3D geometries -GisFileInput.Params.FORCE_TO_MULTIGEOMETRY.Label = Force to multi geometries -GisFileInput.Params.FORCE_TO_MULTIGEOMETRY.Description = Force to MultiLinestring\nand MultiPolygon -GisFileInput.Params.DB_TABLE_NAME.Label = Table -GisFileInput.Params.DB_TABLE_NAME.Description = Table name - +GisFileOutput.Format.GPX.Label = GPS eXchange Format +GisFileOutput.Format.GEOPACKAGE.Label = GeoPackage +GisFileOutput.Format.SVG.Label = Scalable Vector Graphics GisFileOutput.Params.FORCE_TO_2D.Label = Force to 2D GisFileOutput.Params.FORCE_TO_2D.Description = Force to 2D geometries\nif 3D geometries @@ -105,5 +100,113 @@ GisFileOutput.Params.DXF_FEATURE_LAYER_NAME.Description = Layer name GisFileOutput.Params.DXF_COORD_PRECISION.Label = Accuracy GisFileOutput.Params.DXF_COORD_PRECISION.Description = Accuracy (decimal number) +GisFileOutput.Params.DXF_WRITE_XDATA.Label = Write attributes +GisFileOutput.Params.DXF_WRITE_XDATA.Description = Write attributes (XData) + +GisFileOutput.Params.GPX_VERSION.Label = Version +GisFileOutput.Params.GPX_VERSION.Description = GPX schema + +GisFileOutput.Params.GPX_DOC_NAME.Label = Document name +GisFileOutput.Params.GPX_DOC_NAME.Description = Value of tag for + +GisFileOutput.Params.GPX_META_DESCRIPTION.Label = Document description +GisFileOutput.Params.GPX_META_DESCRIPTION.Description = Value of tag for + +GisFileOutput.Params.GPX_META_AUTHOR_NAME.Label = Author name +GisFileOutput.Params.GPX_META_AUTHOR_NAME.Description = Value of tag for + +GisFileOutput.Params.GPX_META_AUTHOR_EMAIL.Label = Author email +GisFileOutput.Params.GPX_META_AUTHOR_EMAIL.Description = Value of tag for + +GisFileOutput.Params.GPX_META_KEYWORDS.Label = Keywords +GisFileOutput.Params.GPX_META_KEYWORDS.Description = Value of tag for + +GisFileOutput.Params.GPX_META_DATETIME.Label = Date +GisFileOutput.Params.GPX_META_DATETIME.Description = Value of