Download OSM file from the official server

@param file
@param geometryEnvelope
@throws IOException
495883
public static void downloadOSMFile(File file, Envelope geometryEnvelope) throws IOException {
        HttpURLConnection urlCon = (HttpURLConnection) createOsmUrl(geometryEnvelope).openConnection();
        urlCon.setRequestMethod("GET");
        urlCon.connect();
        switch (urlCon.getResponseCode()) {
            case 400:
                throw new IOException("Error : Cannot query the OSM API with the following bounding box");
            case 509:
                throw new IOException("Error: You have downloaded too much data. Please try again later");
            default:
                InputStream in = urlCon.getInputStream();
                OutputStream out = new FileOutputStream(file);
                try {
                    byte[] data = new byte[4096];
                    while (true) {
                        int numBytes = in.read(data);
                        if (numBytes == -1) {
                            break;
                        }
                        out.write(data, 0, numBytes);
                    }
                } finally {
                    out.close();
                    in.close();
                }       break;
        }
    }
769312
public static void validateGeoPackageExtension(File file) {
		if (!hasGeoPackageExtension(file)) {
			throw new GeoPackageException("GeoPackage database file '" + file
					+ "' does not have a valid extension of '"
					+ GeoPackageConstants.GEOPACKAGE_EXTENSION + "' or '"
					+ GeoPackageConstants.GEOPACKAGE_EXTENDED_EXTENSION + "'");
		}
	}
958008
static public void encodeGeographyPoint(final FastSerializer fs, GeographyPointValue value)
    throws IOException {
        final int length = GeographyPointValue.getLengthInBytes();
        ByteBuffer bb = ByteBuffer.allocate(length);
        bb.order(ByteOrder.nativeOrder());
        value.flattenToBuffer(bb);
        byte[] array = bb.array();

        assert(array.length == length);

        fs.write(array);
    }
277115
public static <T> T readObjectFromFile(File file) throws IOException,
  ClassNotFoundException {
    ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(
        new GZIPInputStream(new FileInputStream(file))));
    Object o = ois.readObject();
    ois.close();
    return ErasureUtils.<T> uncheckedCast(o);
  }
773832
public void downloadFileUsingRequesterPays(
      String projectId, String bucketName, String srcFilename, Path destFilePath)
      throws IOException {
    // [START storage_download_file_requester_pays]
    // The project ID to bill
    // String projectId = "my-billable-project-id";

    // The name of the bucket to access
    // String bucketName = "my-bucket";

    // The name of the remote file to download
    // String srcFilename = "file.txt";

    // The path to which the file should be downloaded
    // Path destFilePath = Paths.get("/local/path/to/file.txt");

    // Instantiate a Google Cloud Storage client
    Storage storage = StorageOptions.getDefaultInstance().getService();

    // Get specific file from specified bucket
    Blob blob = storage.get(BlobId.of(bucketName, srcFilename));

    // Download file to specified path
    blob.downloadTo(destFilePath, Blob.BlobSourceOption.userProject(projectId));
    // [END storage_download_file_requester_pays]
  }
1198833
protected void downloadFromMavenRepo(PluginCoordinates coordinates, URI mavenRepoUrl, IAsyncResultHandler<File> handler) {
        String artifactSubPath = PluginUtils.getMavenPath(coordinates);
        try {
            File tempArtifactFile = File.createTempFile("_plugin", "dwn"); //$NON-NLS-1$ //$NON-NLS-2$
            URL artifactUrl = new URL(mavenRepoUrl.toURL(), artifactSubPath);
            downloadArtifactTo(artifactUrl, tempArtifactFile, handler);
        } catch (Exception e) {
            handler.handle(AsyncResultImpl.<File>create(e));
        }
    }
1073998
public static GeoPackage open(String name, File file) {

		// Validate or add the file extension
		if (GeoPackageIOUtils.hasFileExtension(file)) {
			GeoPackageValidate.validateGeoPackageExtension(file);
		} else {
			file = GeoPackageIOUtils.addFileExtension(file,
					GeoPackageConstants.GEOPACKAGE_EXTENSION);
		}

		// Create the GeoPackage Connection and table creator
		GeoPackageConnection connection = connect(file);
		GeoPackageTableCreator tableCreator = new GeoPackageTableCreator(
				connection);

		// Create a GeoPackage
		GeoPackage geoPackage = new GeoPackageImpl(name, file, connection,
				tableCreator);

		// Validate the GeoPackage has the minimum required tables
		try {
			GeoPackageValidate.validateMinimumTables(geoPackage);
		} catch (RuntimeException e) {
			geoPackage.close();
			throw e;
		}

		return geoPackage;
	}
851569
public File downloadFile(File file, String ouputFilePath) {
    try (CloseableHttpClient httpClient = pkgmgr.getHttpClient()) {
      log.info("Download " + file.getName() + " from " + props.getPackageManagerUrl());

      // 1st: try upload to get path of package - or otherwise make sure package def exists (no install!)
      HttpPost post = new HttpPost(props.getPackageManagerUrl() + "/.json?cmd=upload");
      MultipartEntityBuilder entity = MultipartEntityBuilder.create()
          .addBinaryBody("package", file)
          .addTextBody("force", "true");
      post.setEntity(entity.build());
      JSONObject jsonResponse = pkgmgr.executePackageManagerMethodJson(httpClient, post);
      boolean success = jsonResponse.optBoolean("success", false);
      String msg = jsonResponse.optString("msg", null);
      String path = jsonResponse.optString("path", null);

      // package already exists - get path from error message and continue
      if (!success && StringUtils.startsWith(msg, CRX_PACKAGE_EXISTS_ERROR_MESSAGE_PREFIX) && StringUtils.isEmpty(path)) {
        path = StringUtils.substringAfter(msg, CRX_PACKAGE_EXISTS_ERROR_MESSAGE_PREFIX);
        success = true;
      }
      if (!success) {
        throw new PackageManagerException("Package path detection failed: " + msg);
      }

      log.info("Package path is: " + path + " - now rebuilding package...");

      // 2nd: build package
      HttpPost buildMethod = new HttpPost(props.getPackageManagerUrl() + "/console.html" + path + "?cmd=build");
      pkgmgr.executePackageManagerMethodHtmlOutputResponse(httpClient, buildMethod);

      // 3rd: download package
      String baseUrl = VendorInstallerFactory.getBaseUrl(props.getPackageManagerUrl(), log);
      HttpGet downloadMethod = new HttpGet(baseUrl + path);

      // execute download
      CloseableHttpResponse response = httpClient.execute(downloadMethod);
      try {
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

          // get response stream
          InputStream responseStream = response.getEntity().getContent();

          // delete existing file
          File outputFileObject = new File(ouputFilePath);
          if (outputFileObject.exists()) {
            outputFileObject.delete();
          }

          // write response file
          FileOutputStream fos = new FileOutputStream(outputFileObject);
          IOUtils.copy(responseStream, fos);
          fos.flush();
          responseStream.close();
          fos.close();

          log.info("Package downloaded to " + outputFileObject.getAbsolutePath());

          return outputFileObject;
        }
        else {
          throw new PackageManagerException("Package download failed:\n"
              + EntityUtils.toString(response.getEntity()));
        }
      }
      finally {
        if (response != null) {
          EntityUtils.consumeQuietly(response.getEntity());
          try {
            response.close();
          }
          catch (IOException ex) {
            // ignore
          }
        }
      }
    }
    catch (FileNotFoundException ex) {
      throw new PackageManagerException("File not found: " + file.getAbsolutePath(), ex);
    }
    catch (IOException ex) {
      throw new PackageManagerException("Download operation failed.", ex);
    }
  }
607051
@WebOperationMethod
    public Map<String,Object> downloadAsFile(Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String database = Objects.get(params, "database");
        String collection = Objects.get(params, "collection", COLLECTION);
        String id = Objects.get(params, "id");
        String name = Objects.get(params, "name");

        FileStorage.FileReadBean b = null;
        try{
            b = FileStorage.read(new Id(database,collection,id));
            response.setContentType(b.getMeta().getContentType());
            if (Objects.isNullOrEmpty(name)) {
                name = b.getMeta().getName();
                if (name.length() > 100)
                    name = name.substring(0, 100);
                if (!Objects.isNullOrEmpty(b.getMeta().getExt()))
                    name += "." + b.getMeta().getExt();
            }
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name, "UTF-8"));
            try {
                IOUtils.copy(b.getInputStream(), response.getOutputStream());
            } catch (IOException e) {
                throw S1SystemError.wrap(e);
            }
        }catch (NotFoundException e) {
            response.setStatus(404);
        }finally {
            FileStorage.closeAfterRead(b);
        }
        return null;
    }
864242
public static Geometry toGeometry(String gmlFile, int srid) throws SAXException, IOException, ParserConfigurationException {
        if (gmlFile == null) {
            return null;
        }
        if (gf == null) {
            gf = new GeometryFactory(new PrecisionModel(), srid);
        }
        GMLReader gMLReader = new GMLReader();
        return gMLReader.read(gmlFile, gf);
    }
11785
public Table file(File file) throws IOException {
	String extension = Files.getFileExtension(file.getCanonicalPath());
	DataReader<?> reader = registry.getReaderForExtension(extension);
	return reader.read(new Source(file));
    }
249700
public static void writeGeoJson(Connection connection, String fileName, String tableReference, String encoding) throws IOException, SQLException {
            JsonDriverFunction jsonDriver = new JsonDriverFunction();
            jsonDriver.exportTable(connection,tableReference, URIUtilities.fileFromString(fileName), new EmptyProgressVisitor(),encoding);
    }
553223
public BytesWritable evaluate(BytesWritable geomref) {
		if (geomref == null || geomref.getLength() == 0){
			LogUtils.Log_ArgumentsNull(LOG);
			return null;
		}

		OGCGeometry ogcGeometry = GeometryUtils.geometryFromEsriShape(geomref);
		if (ogcGeometry == null){
			LogUtils.Log_ArgumentsNull(LOG);
			return null;
		}

		if (GeometryUtils.getType(geomref) == GeometryUtils.OGCType.ST_LINESTRING) {
			MultiPath lines = (MultiPath)(ogcGeometry.getEsriGeometry());
			int wkid = GeometryUtils.getWKID(geomref);
			SpatialReference spatialReference = null;
			if (wkid != GeometryUtils.WKID_UNKNOWN) {
				spatialReference = SpatialReference.create(wkid);
			}
			return GeometryUtils.geometryToEsriShapeBytesWritable(OGCGeometry.createFromEsriGeometry(lines.getPoint(lines.getPointCount()-1),
																									 spatialReference));
		} else {
			LogUtils.Log_InvalidType(LOG, GeometryUtils.OGCType.ST_LINESTRING, GeometryUtils.getType(geomref));
			return null;
		}
	}
16359
public void loadFile(File file)
   {
      InputStream is = null;

      try
      {
         is = new FileInputStream(file);
         POIFSFileSystem fs = new POIFSFileSystem(is);
         m_model.setFile(fs);
      }

      catch (IOException ex)
      {
         throw new RuntimeException(ex);
      }

      finally
      {
         StreamHelper.closeQuietly(is);
      }
   }
864035
@SuppressWarnings("unchecked")
    public OsmDroidMapShape toShape(Geometry geometry) {

        OsmDroidMapShape shape = null;

        GeometryType geometryType = geometry.getGeometryType();
        switch (geometryType) {
            case POINT:
                shape = new OsmDroidMapShape(geometryType,
                    OsmMapShapeType.LAT_LNG, toLatLng((Point) geometry));
                break;
            case LINESTRING:
                shape = new OsmDroidMapShape(geometryType,
                    OsmMapShapeType.POLYLINE_OPTIONS,
                    toPolyline((LineString) geometry));
                break;
            case POLYGON:
                shape = new OsmDroidMapShape(geometryType,
                    OsmMapShapeType.POLYGON_OPTIONS,
                    toPolygon((Polygon) geometry));
                break;
            case MULTIPOINT:
                shape = new OsmDroidMapShape(geometryType,
                    OsmMapShapeType.MULTI_LAT_LNG,
                    toLatLngs((MultiPoint) geometry));
                break;
            case MULTILINESTRING:
                shape = new OsmDroidMapShape(geometryType,
                    OsmMapShapeType.MULTI_POLYLINE_OPTIONS,
                    toPolylines((MultiLineString) geometry));
                break;
            case MULTIPOLYGON:
                shape = new OsmDroidMapShape(geometryType,
                    OsmMapShapeType.MULTI_POLYGON_OPTIONS,
                    toPolygons((MultiPolygon) geometry));
                break;
            case CIRCULARSTRING:
                shape = new OsmDroidMapShape(geometryType,
                    OsmMapShapeType.POLYLINE_OPTIONS,
                    toPolyline((CircularString) geometry));
                break;
            case COMPOUNDCURVE:
                shape = new OsmDroidMapShape(geometryType,
                    OsmMapShapeType.MULTI_POLYLINE_OPTIONS,
                    toPolylines((CompoundCurve) geometry));
                break;
            case CURVEPOLYGON:
                shape = new OsmDroidMapShape(geometryType,
                    OsmMapShapeType.POLYGON_OPTIONS,
                    toCurvePolygon((CurvePolygon) geometry));
                break;
            case POLYHEDRALSURFACE:
                shape = new OsmDroidMapShape(geometryType,
                    OsmMapShapeType.MULTI_POLYGON_OPTIONS,
                    toPolygons((PolyhedralSurface) geometry));
                break;
            case TIN:
                shape = new OsmDroidMapShape(geometryType,
                    OsmMapShapeType.MULTI_POLYGON_OPTIONS,
                    toPolygons((TIN) geometry));
                break;
            case TRIANGLE:
                shape = new OsmDroidMapShape(geometryType,
                    OsmMapShapeType.POLYGON_OPTIONS,
                    toPolygon((Triangle) geometry));
                break;
            case GEOMETRYCOLLECTION:
                shape = new OsmDroidMapShape(geometryType,
                    OsmMapShapeType.COLLECTION,
                    toShapes((GeometryCollection<Geometry>) geometry));
                break;
            default:
                throw new GeoPackageException("Unsupported Geometry Type: "
                    + geometryType.getName());
        }

        return shape;
    }
1280295
public static void copyFile(File from, File to) throws IOException {
        InputStream in = new BufferedInputStream(new FileInputStream(from));
        try {
            OutputStream out = new BufferedOutputStream(new FileOutputStream(to));
            try {
                IoUtils.copyAllBytes(in, out);
            } finally {
                IoUtils.safeClose(out);
            }
        } finally {
            IoUtils.safeClose(in);
        }
    }
192613
private static URL createOsmUrl(Envelope geometryEnvelope) {
        try {
            return new URL(OSM_API_URL + "map?bbox=" + geometryEnvelope.getMinX() + ","
                    + geometryEnvelope.getMinY()
                    + "," + geometryEnvelope.getMaxX() + "," + geometryEnvelope.getMaxY());
        } catch (MalformedURLException e) {
            throw new IllegalStateException(e);
        }
    }