Example usage for org.apache.commons.io FileUtils writeByteArrayToFile

List of usage examples for org.apache.commons.io FileUtils writeByteArrayToFile

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils writeByteArrayToFile.

Prototype

public static void writeByteArrayToFile(File file, byte[] data) throws IOException 

Source Link

Document

Writes a byte array to a file creating the file if it does not exist.

Usage

From source file:org.example.Serializer.java

public void serializeTo(SerializationMethod method, File output) throws IOException, Exception {
    parse();/*from w w w.  j  a  v a  2 s.c o  m*/
    FileUtils.writeByteArrayToFile(output, serialize(method));
}

From source file:org.fao.geonet.api.records.MetadataInsertDeleteApi.java

@ApiOperation(value = "Add a map metadata record from OGC OWS context", notes = "Add record in the catalog by uploading a map context.", nickname = "insertOgcMapContextFile")
@RequestMapping(value = "/importfrommap", method = { RequestMethod.POST, }, produces = {
        MediaType.APPLICATION_JSON_VALUE })
@ApiResponses(value = { @ApiResponse(code = 201, message = API_PARAM_REPORT_ABOUT_IMPORTED_RECORDS),
        @ApiResponse(code = 403, message = ApiParams.API_RESPONSE_NOT_ALLOWED_ONLY_EDITOR) })
@PreAuthorize("hasRole('Editor')")
@ResponseStatus(HttpStatus.CREATED)/*from  w  ww  .j a  v  a 2 s. c  o  m*/
@ResponseBody
public SimpleMetadataProcessingReport insertOgcMapContextFile(
        @ApiParam(value = "A map title", required = true) @RequestParam(value = "title", required = true) final String title,
        @ApiParam(value = "A map abstract", required = false) @RequestParam(value = "recordAbstract", required = false) final String recordAbstract,
        @ApiParam(value = "OGC OWS context as string", required = false) @RequestParam(value = "xml", required = false) final String xml,
        @ApiParam(value = "OGC OWS context file name", required = false) @RequestParam(value = "filename", required = false) final String filename,
        @ApiParam(value = "OGC OWS context URL", required = false) @RequestParam(value = "url", required = false) final String url,
        @ApiParam(value = "A map viewer URL to visualize the map", required = false) @RequestParam(value = "viewerUrl", required = false) final String viewerUrl,
        @ApiParam(value = "Map overview as PNG (base64 encoded)", required = false) @RequestParam(value = "overview", required = false) final String overview,
        @ApiParam(value = "Map overview filename", required = false) @RequestParam(value = "overviewFilename", required = false) final String overviewFilename,
        @ApiParam(value = "Topic category", required = false) @RequestParam(value = "topic", required = false) final String topic,
        @ApiParam(value = API_PARAM_RECORD_UUID_PROCESSING, required = false, defaultValue = "NOTHING") @RequestParam(required = false, defaultValue = "NOTHING") final MEFLib.UuidAction uuidProcessing,
        @ApiParam(value = API_PARAP_RECORD_GROUP, required = false) @RequestParam(required = false) final String group,
        HttpServletRequest request) throws Exception {
    if (StringUtils.isEmpty(xml) && StringUtils.isEmpty(url)) {
        throw new IllegalArgumentException(String.format("A context as XML or a remote URL MUST be provided."));
    }
    if (StringUtils.isEmpty(xml) && StringUtils.isEmpty(filename)) {
        throw new IllegalArgumentException(
                String.format("A context as XML will be saved as a record attachement. "
                        + "You MUST provide a filename in this case."));
    }

    ServiceContext context = ApiUtils.createServiceContext(request);
    ApplicationContext applicationContext = ApplicationContextHolder.get();
    GeonetworkDataDirectory dataDirectory = applicationContext.getBean(GeonetworkDataDirectory.class);
    String styleSheetWmc = dataDirectory.getWebappDir() + File.separator + Geonet.Path.IMPORT_STYLESHEETS
            + File.separator + "OGCWMC-OR-OWSC-to-ISO19139.xsl";

    FilePathChecker.verify(filename);

    // Convert the context in an ISO19139 records
    Map<String, Object> xslParams = new HashMap<String, Object>();
    xslParams.put("viewer_url", viewerUrl);
    xslParams.put("map_url", url);
    xslParams.put("topic", topic);
    xslParams.put("title", title);
    xslParams.put("abstract", recordAbstract);
    xslParams.put("lang", context.getLanguage());

    // Assign current user to the record
    UserSession us = context.getUserSession();

    if (us != null) {
        xslParams.put("currentuser_name", us.getName() + " " + us.getSurname());
        // phone number is georchestra-specific
        // xslParams.put("currentuser_phone", us.getPrincipal().getPhone());
        xslParams.put("currentuser_mail", us.getEmailAddr());
        xslParams.put("currentuser_org", us.getOrganisation());
    }

    // 1. JDOMize the string
    Element wmcDoc = Xml.loadString(xml, false);
    // 2. Apply XSL (styleSheetWmc)
    Element transformedMd = Xml.transform(wmcDoc, new File(styleSheetWmc).toPath(), xslParams);

    // 4. Inserts the metadata (does basically the same as the metadata.insert.paste
    // service (see Insert.java)
    String uuid = UUID.randomUUID().toString();
    SettingManager sm = applicationContext.getBean(SettingManager.class);
    DataManager dm = applicationContext.getBean(DataManager.class);
    SchemaManager schemaMan = applicationContext.getBean(SchemaManager.class);

    String date = new ISODate().toString();
    SimpleMetadataProcessingReport report = new SimpleMetadataProcessingReport();

    final List<String> id = new ArrayList<String>();
    final List<Element> md = new ArrayList<Element>();

    md.add(transformedMd);

    // Import record
    Importer.importRecord(uuid, uuidProcessing, md, "iso19139", 0, sm.getSiteId(), sm.getSiteName(), null,
            context, id, date, date, group, MetadataType.METADATA);

    // Save the context if no context-url provided
    if (StringUtils.isEmpty(url)) {
        Path dataDir = Lib.resource.getDir(context, Params.Access.PUBLIC, id.get(0));
        Files.createDirectories(dataDir);
        Path outFile = dataDir.resolve(filename);
        Files.deleteIfExists(outFile);
        FileUtils.writeStringToFile(outFile.toFile(), Xml.getString(wmcDoc));

        // Update the MD
        Map<String, Object> onlineSrcParams = new HashMap<String, Object>();
        onlineSrcParams.put("protocol", "WWW:DOWNLOAD-OGC:OWS-C");
        onlineSrcParams.put("url",
                sm.getNodeURL() + String.format("api/records/%s/attachments/%s", uuid, filename));
        onlineSrcParams.put("name", filename);
        onlineSrcParams.put("desc", title);
        transformedMd = Xml.transform(transformedMd,
                schemaMan.getSchemaDir("iso19139").resolve("process").resolve("onlinesrc-add.xsl"),
                onlineSrcParams);
        dm.updateMetadata(context, id.get(0), transformedMd, false, true, false, context.getLanguage(), null,
                true);
    }

    if (StringUtils.isNotEmpty(overview) && StringUtils.isNotEmpty(overviewFilename)) {
        Path dataDir = Lib.resource.getDir(context, Params.Access.PUBLIC, id.get(0));
        Files.createDirectories(dataDir);
        Path outFile = dataDir.resolve(overviewFilename);
        Files.deleteIfExists(outFile);
        byte[] data = Base64.decodeBase64(overview);
        FileUtils.writeByteArrayToFile(outFile.toFile(), data);

        // Update the MD
        Map<String, Object> onlineSrcParams = new HashMap<String, Object>();
        onlineSrcParams.put("thumbnail_url",
                sm.getNodeURL() + String.format("api/records/%s/attachments/%s", uuid, overviewFilename));
        transformedMd = Xml.transform(transformedMd,
                schemaMan.getSchemaDir("iso19139").resolve("process").resolve("thumbnail-add.xsl"),
                onlineSrcParams);
        dm.updateMetadata(context, id.get(0), transformedMd, false, true, false, context.getLanguage(), null,
                true);
    }

    dm.indexMetadata(id);
    report.addMetadataInfos(Integer.parseInt(id.get(0)), uuid);

    triggerCreationEvent(request, uuid);

    report.incrementProcessedRecords();
    report.close();
    return report;
}

From source file:org.fao.geonet.services.mef.ImportWebMap.java

@Override
@Deprecated/*w  w  w  .  ja va  2s  . c  o  m*/
public Element serviceSpecificExec(Element params, ServiceContext context) throws Exception {
    String mapString = Util.getParam(params, "map_string");
    String mapUrl = Util.getParam(params, "map_url", "");
    String viewerUrl = Util.getParam(params, "map_viewer_url", "");
    String groupId = Util.getParam(params, "group_id", null);
    String mapAbstract = Util.getParam(params, "map_abstract", "");
    String title = Util.getParam(params, "map_title", "");
    String mapFileName = Util.getParam(params, "map_filename", "map-context.ows");
    String mapImage = Util.getParam(params, "map_image", "");
    String mapImageFilename = Util.getParam(params, "map_image_filename", "map.png");

    FilePathChecker.verify(mapFileName);

    String topic = Util.getParam(params, "topic", "");

    Map<String, Object> xslParams = new HashMap<String, Object>();
    xslParams.put("viewer_url", viewerUrl);
    xslParams.put("map_url", mapUrl);
    xslParams.put("topic", topic);
    xslParams.put("title", title);
    xslParams.put("abstract", mapAbstract);
    xslParams.put("lang", context.getLanguage());

    UserSession us = context.getUserSession();

    if (us != null) {
        xslParams.put("currentuser_name", us.getName() + " " + us.getSurname());
        // phone number is georchestra-specific
        //xslParams.put("currentuser_phone", us.getPrincipal().getPhone());
        xslParams.put("currentuser_mail", us.getEmailAddr());
        xslParams.put("currentuser_org", us.getOrganisation());
    }

    // 1. JDOMize the string
    Element wmcDoc = Xml.loadString(mapString, false);
    // 2. Apply XSL (styleSheetWmc)
    Element transformedMd = Xml.transform(wmcDoc, new File(styleSheetWmc).toPath(), xslParams);

    // 4. Inserts the metadata (does basically the same as the metadata.insert.paste service (see Insert.java)
    String uuid = UUID.randomUUID().toString();
    GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
    SettingManager sm = context.getBean(SettingManager.class);
    DataManager dm = gc.getBean(DataManager.class);
    SchemaManager schemaMan = context.getBean(SchemaManager.class);

    String uuidAction = Util.getParam(params, Params.UUID_ACTION, Params.NOTHING);

    String date = new ISODate().toString();

    final List<String> id = new ArrayList<String>();
    final List<Element> md = new ArrayList<Element>();

    md.add(transformedMd);

    // Import record
    Importer.importRecord(uuid, MEFLib.UuidAction.parse(uuidAction), md, "iso19139", 0, sm.getSiteId(),
            sm.getSiteName(), null, context, id, date, date, groupId, MetadataType.METADATA);

    // Save the context if no context-url provided
    if (StringUtils.isEmpty(mapUrl)) {
        Path dataDir = Lib.resource.getDir(context, Params.Access.PUBLIC, id.get(0));
        Files.createDirectories(dataDir);
        Path outFile = dataDir.resolve(mapFileName);
        Files.deleteIfExists(outFile);
        FileUtils.writeStringToFile(outFile.toFile(), Xml.getString(wmcDoc));

        // Update the MD
        Map<String, Object> onlineSrcParams = new HashMap<String, Object>();
        onlineSrcParams.put("protocol", "WWW:DOWNLOAD-OGC:OWS-C");
        onlineSrcParams.put("url",
                sm.getNodeURL() + String.format("api/records/%s/attachments/%s", uuid, mapFileName));
        onlineSrcParams.put("name", mapFileName);
        onlineSrcParams.put("desc", title);
        Element mdWithOLRes = Xml.transform(transformedMd,
                schemaMan.getSchemaDir("iso19139").resolve("process").resolve("onlinesrc-add.xsl"),
                onlineSrcParams);
        dm.updateMetadata(context, id.get(0), mdWithOLRes, false, true, true, context.getLanguage(), null,
                true);
    }

    if (StringUtils.isNotEmpty(mapImage) && StringUtils.isNotEmpty(mapImageFilename)) {
        Path dataDir = Lib.resource.getDir(context, Params.Access.PUBLIC, id.get(0));
        Files.createDirectories(dataDir);
        Path outFile = dataDir.resolve(mapImageFilename);
        Files.deleteIfExists(outFile);
        byte[] data = Base64.decodeBase64(mapImage);
        FileUtils.writeByteArrayToFile(outFile.toFile(), data);

        // Update the MD
        Map<String, Object> onlineSrcParams = new HashMap<String, Object>();
        onlineSrcParams.put("thumbnail_url",
                sm.getNodeURL() + String.format("api/records/%s/attachments/%s", uuid, mapFileName));
        Element mdWithOLRes = Xml.transform(transformedMd,
                schemaMan.getSchemaDir("iso19139").resolve("process").resolve("thumbnail-add.xsl"),
                onlineSrcParams);
        dm.updateMetadata(context, id.get(0), mdWithOLRes, false, true, true, context.getLanguage(), null,
                true);
    }

    dm.indexMetadata(id);

    Element result = new Element("uuid");
    result.setText(uuid);

    return result;
}

From source file:org.freeciv.servlet.LoadServlet.java

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    InputStream in = request.getInputStream();

    String encodedFile = IOUtils.toString(in, Charset.forName("UTF-8"));
    byte[] compressedFile = Base64.decodeBase64(encodedFile);

    String savename = "" + request.getParameter("savename");
    String username = "" + request.getParameter("username");
    String savegameHash = DigestUtils.shaHex(username + savename + encodedFile);

    if (!p.matcher(username).matches()) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid username");
        return;//from w  w  w . ja  va 2s  . c o  m
    }

    Connection conn = null;
    try {
        Context env = (Context) (new InitialContext().lookup("java:comp/env"));
        DataSource ds = (DataSource) env.lookup("jdbc/freeciv_mysql");
        conn = ds.getConnection();

        PreparedStatement stmt = conn.prepareStatement(
                "select count(*) from savegames where username = ? and title = ? and digest = ?");
        stmt.setString(1, username);
        stmt.setString(2, savename);
        stmt.setString(3, savegameHash);

        ResultSet rs = stmt.executeQuery();
        if (rs.next()) {
            if (rs.getInt(1) != 1) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid savegame");
                return;
            }
        } else {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid savegame");
            return;
        }

        String relativeWebPath = "/savegames/" + username + ".sav.bz2";
        String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
        File file = new File(absoluteDiskPath);
        FileUtils.writeByteArrayToFile(file, compressedFile);

    } catch (Exception err) {
        err.printStackTrace();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Savegame digest failed.");
        return;

    } finally {
        if (conn != null)
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
    }

    in.close();

    response.getOutputStream().print("success");

}

From source file:org.geoserver.catalog.impl.CatalogBuilderIntTest.java

private void createTimeMosaic(File mosaic, int fileCount) throws Exception {
    if (mosaic.exists()) {
        if (mosaic.isDirectory()) {
            FileUtils.deleteDirectory(mosaic);
        } else {/*  w ww  . j  ava 2  s. c o m*/
            mosaic.delete();
        }
    }
    mosaic.mkdir();
    System.out.println(mosaic.getAbsolutePath());

    // build the reference coverage into a byte array
    GridCoverageFactory factory = new GridCoverageFactory();
    BufferedImage bi = new BufferedImage(10, 10, BufferedImage.TYPE_4BYTE_ABGR);
    ReferencedEnvelope envelope = new ReferencedEnvelope(0, 10, 0, 10, CRS.decode("EPSG:4326"));
    GridCoverage2D test = factory.create("test", bi, envelope);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    GeoTiffWriter writer = new GeoTiffWriter(bos);
    writer.write(test, null);
    writer.dispose();

    // create the lot of files
    byte[] bytes = bos.toByteArray();
    for (int i = 0; i < fileCount; i++) {
        String pad = "";
        if (i < 10) {
            pad = "000";
        } else if (i < 100) {
            pad = "00";
        } else if (i < 1000) {
            pad = "0";
        }
        File target = new File(mosaic, "tile_" + pad + i + ".tiff");
        FileUtils.writeByteArrayToFile(target, bytes);
    }

    // create the mosaic indexer property file
    Properties p = new Properties();
    p.put("ElevationAttribute", "elevation");
    p.put("Schema", "*the_geom:Polygon,location:String,elevation:Integer");
    p.put("PropertyCollectors", "IntegerFileNameExtractorSPI[elevationregex](elevation)");
    FileOutputStream fos = new FileOutputStream(new File(mosaic, "indexer.properties"));
    p.store(fos, null);
    fos.close();
    // and the regex itself
    p.clear();
    p.put("regex", "(?<=_)(\\d{4})");
    fos = new FileOutputStream(new File(mosaic, "elevationregex.properties"));
    p.store(fos, null);
    fos.close();
}

From source file:org.geoserver.geopkg.GeoPackageGetMapOutputFormatTest.java

public static void main(String[] args) throws Exception {
    GeoPackage geopkg = new GeoPackage(new File("/Users/jdeolive/geopkg.db"));
    ;//from   w w w . jav  a2s .  c  o  m
    File d = new File("/Users/jdeolive/tiles");
    d.mkdir();

    TileEntry te = geopkg.tiles().get(0);
    TileReader r = geopkg.reader(te, null, null, null, null, null, null);
    while (r.hasNext()) {
        Tile t = r.next();
        File f = new File(d, String.format("%d-%d-%d.png", t.getZoom(), t.getColumn(), t.getRow()));

        FileUtils.writeByteArrayToFile(f, t.getData());
    }
}

From source file:org.geoserver.geopkg.wps.gs.GeoPackageProcessTileTest.java

@Test
public void testGeoPackageProcessTilesTopLeftTile() throws Exception {
    String urlPath = string(post("wps", getXmlTilesWorld())).trim();
    String resourceUrl = urlPath.substring("http://localhost:8080/geoserver/".length());
    MockHttpServletResponse response = getAsServletResponse(resourceUrl);
    File file = new File(getDataDirectory().findOrCreateDir("tmp"), "worldtest.gpkg");
    FileUtils.writeByteArrayToFile(file, getBinary(response));
    assertNotNull(file);/*from  w w w.j a v  a2s . co  m*/
    assertEquals("worldtest.gpkg", file.getName());
    assertTrue(file.exists());

    GeoPackage gpkg = new GeoPackage(file);
    Tile topLeftTile = gpkg.reader(gpkg.tiles().get(0), 1, 1, 0, 0, 0, 0).next();
    BufferedImage tileImg = ImageIO.read(new ByteArrayInputStream(topLeftTile.getData()));

    ImageAssert.assertEquals(URLs.urlToFile(getClass().getResource("wps_toplefttile.png")), tileImg, 250);
    gpkg.close();
}

From source file:org.geoserver.kml.KMLReflectorTest.java

protected void doTestRasterPlacemark(boolean doPlacemarks) throws Exception {
    // the style selects a single feature
    final String requestUrl = "wms/kml?layers=" + getLayerId(MockData.BASIC_POLYGONS)
            + "&styles=&mode=download&kmscore=0&format_options=kmplacemark:" + doPlacemarks + "&format="
            + KMZMapOutputFormat.MIME_TYPE;
    MockHttpServletResponse response = getAsServletResponse(requestUrl);
    assertEquals(KMZMapOutputFormat.MIME_TYPE, response.getContentType());

    ZipFile zipFile = null;// w w w. ja  v a  2  s .  c  o  m
    try {
        // create the kmz
        File tempDir = org.geoserver.data.util.IOUtils.createRandomDirectory("./target", "kmplacemark", "test");
        tempDir.deleteOnExit();

        File zip = new File(tempDir, "kmz.zip");
        zip.deleteOnExit();

        FileOutputStream output = new FileOutputStream(zip);
        FileUtils.writeByteArrayToFile(zip, getBinary(response));

        output.flush();
        output.close();

        assertTrue(zip.exists());

        // unzip and test it
        zipFile = new ZipFile(zip);

        ZipEntry entry = zipFile.getEntry("wms.kml");
        assertNotNull(entry);
        assertNotNull(zipFile.getEntry("images/layers_0.png"));

        // unzip the wms.kml to file
        byte[] buffer = new byte[1024];
        int len;

        InputStream inStream = zipFile.getInputStream(entry);
        File temp = File.createTempFile("test_out", "kmz", tempDir);
        temp.deleteOnExit();
        BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(temp));

        while ((len = inStream.read(buffer)) >= 0)
            outStream.write(buffer, 0, len);
        inStream.close();
        outStream.close();

        // read in the wms.kml and check its contents
        Document document = dom(new BufferedInputStream(new FileInputStream(temp)));
        // print(document);

        assertEquals("kml", document.getDocumentElement().getNodeName());
        if (doPlacemarks) {
            assertEquals(getFeatureSource(MockData.BASIC_POLYGONS).getFeatures().size(),
                    document.getElementsByTagName("Placemark").getLength());
            XMLAssert.assertXpathEvaluatesTo("3", "count(//kml:Placemark//kml:Point)", document);
        } else {
            assertEquals(0, document.getElementsByTagName("Placemark").getLength());
        }

    } finally {
        if (zipFile != null) {
            zipFile.close();
        }
    }
}

From source file:org.geoserver.wcs.responses.GHRSSTWCSTest.java

/**
 * Test NetCDF output from a coverage view having the required GHRSST bands/variables
 *//*from w  w w .ja  va 2  s  .  co  m*/
@Test
public void testGHRSST() throws Exception {
    MockHttpServletResponse response = getAsServletResponse("ows?request=GetCoverage&service=WCS&version=2.0.1"
            + "&coverageid=" + getLayerId(SST).replace(":", "__") + "&format=application/x-netcdf");
    assertEquals(200, response.getStatus());
    assertEquals("application/x-netcdf", response.getContentType());

    // hope the file name structure is correct, not 100% sure 
    String contentDispostion = response.getHeader("Content-disposition");
    assertEquals("inline; filename=19121213214553-EUR-L3U_GHRSST-SSTint-AVHRR_METOP_A-v02.0-fv01.0.nc",
            contentDispostion);
    byte[] responseBytes = getBinary(response);
    File file = File.createTempFile("ghrsst", ".nc", new File("./target"));
    FileUtils.writeByteArrayToFile(file, responseBytes);
    try (NetcdfDataset dataset = NetcdfDataset.openDataset(file.getAbsolutePath(), true, null)) {
        assertNotNull(dataset);

        // check global attributes
        Map<String, Attribute> globalAttributes = getGlobalAttributeMap(dataset);
        assertNotNull(globalAttributes.get("uuid"));
        UUID.fromString(globalAttributes.get("uuid").getStringValue());
        assertNotNull(globalAttributes.get("date_created"));
        assertNotNull(globalAttributes.get("spatial_resolution"));
        // input test file is a freak that really has this resolution, as verified with gdalinfo
        // e.g. gdalinfo NETCDF:"sst-orbit053.nc":"sea_surface_temperature"
        assertEquals("179.9499969482422 degrees", globalAttributes.get("spatial_resolution").getStringValue());
        // likewise, it really has time time
        assertNotNull(globalAttributes.get("start_time"));
        assertNotNull(globalAttributes.get("time_coverage_start"));
        assertEquals("19121213T204553Z", globalAttributes.get("start_time").getStringValue());
        assertEquals("19121213T204553Z", globalAttributes.get("time_coverage_start").getStringValue());
        assertNotNull(globalAttributes.get("stop_time"));
        assertNotNull(globalAttributes.get("time_coverage_end"));
        assertEquals("19121213T204553Z", globalAttributes.get("stop_time").getStringValue());
        assertEquals("19121213T204553Z", globalAttributes.get("time_coverage_end").getStringValue());
        // and these bounds
        double EPS = 1e-3;
        assertNotNull(globalAttributes.get("northernmost_latitude"));
        assertNotNull(globalAttributes.get("southernmost_latitude"));
        assertNotNull(globalAttributes.get("westernmost_longitude"));
        assertNotNull(globalAttributes.get("easternmost_longitude"));
        assertEquals(119.925, globalAttributes.get("northernmost_latitude").getNumericValue().doubleValue(),
                EPS);
        assertEquals(-119.925, globalAttributes.get("southernmost_latitude").getNumericValue().doubleValue(),
                EPS);
        assertEquals(-269.925, globalAttributes.get("westernmost_longitude").getNumericValue().doubleValue(),
                EPS);
        assertEquals(269.925, globalAttributes.get("easternmost_longitude").getNumericValue().doubleValue(),
                EPS);
        // resolution, take 2
        assertNotNull(globalAttributes.get("geospatial_lat_units"));
        assertNotNull(globalAttributes.get("geospatial_lon_units"));
        assertEquals("degrees", globalAttributes.get("geospatial_lat_units").getStringValue());
        assertEquals("degrees", globalAttributes.get("geospatial_lon_units").getStringValue());

        // sea surface temperature
        Variable sst = dataset.findVariable("sea_surface_temperature");
        assertNotNull(sst);
        assertEquals(DataType.SHORT, sst.getDataType());
        assertNotNull(sst.findAttribute("scale_factor"));
        assertNotNull(sst.findAttribute("add_offset"));
        assertAttributeValue(sst, "comment", "Marine skin surface temperature");
        assertAttributeValue(sst, "long_name", "sea surface skin temperature");
        assertAttributeValue(sst, "standard_name", "sea_surface_skin_temperature");
        assertAttributeValue(sst, "units", "kelvin");
        assertAttributeValue(sst, "depth", "10 micrometres");

        // wind speed
        Variable windSpeed = dataset.findVariable("wind_speed");
        assertNotNull(windSpeed);
        assertEquals(DataType.BYTE, windSpeed.getDataType());
        assertNotNull(windSpeed.findAttribute("scale_factor"));
        assertNotNull(windSpeed.findAttribute("add_offset"));
        assertAttributeValue(windSpeed, "comment",
                "Typically represents surface winds (10 meters above the sea " + "surface)");
        assertAttributeValue(windSpeed, "long_name", "wind speed");
        assertAttributeValue(windSpeed, "standard_name", "wind_speed");
        assertAttributeValue(windSpeed, "units", "m s-1");

        // enable ehancing to check values
        dataset.enhance(NetcdfDataset.getEnhanceAll());
        assertValues(dataset, "sea_surface_temperature",
                new double[] { 301, 302, 303, 304, 305, 306, 307, 308, 309 }, 2e-3);
        assertValues(dataset, "wind_speed", new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 0.2);
    } finally {
        // FileUtils.deleteQuietly(file);
    }
}

From source file:org.geoserver.wcs2_0.WCSNetCDFMosaicTest.java

@Test
public void testRequestCoverageView() throws Exception {

    // http response from the request inside the string
    MockHttpServletResponse response = getAsServletResponse("ows?request=GetCoverage&service=WCS&version=2.0.1"
            + "&coverageId=wcs__dummyView&format=application/x-netcdf&subset=http://www.opengis.net/def/axis/OGC/0/time(\"2013-01-08T00:00:00.000Z\")");
    assertNotNull(response);//from  ww w. j a  va 2 s  .  co m

    assertEquals("application/x-netcdf", response.getContentType());
    byte[] netcdfOut = getBinary(response);
    File file = File.createTempFile("netcdf", "out.nc", new File("./target"));
    try {
        FileUtils.writeByteArrayToFile(file, netcdfOut);

        NetcdfDataset dataset = NetcdfDataset.openDataset(file.getAbsolutePath());
        assertNotNull(dataset);
        dataset.close();
    } finally {
        FileUtils.deleteQuietly(file);
    }
}