List of usage examples for org.apache.commons.io FileUtils moveFile
public static void moveFile(File srcFile, File destFile) throws IOException
From source file:com.fusesource.example.camel.ingest.FileIngestorRouteBuilderTest.java
@Test public void testInvalidSchema() throws Exception { context.start();//from w ww. j a va2 s . c o m // not really atomic, but it works for tests FileUtils.moveFile( new File("./target/test-classes/com/fusesource/example/camel/ingest/" + "FilIngestorRouteBuilderTest.testInvalidSchema.xml"), new File(pollingFolder, "test.xml")); validateFileMove(true); }
From source file:gov.redhawk.efs.sca.internal.cache.FileCache.java
private void downloadFile(IFileInfo info) throws CoreException { FileOutputStream fileStream = null; InputStream scaInputStream = null; File tmpFile = null;/*from w w w.j a v a 2 s. c om*/ File parentDir = new File( FileCache.getTempDir() + "/" + parent.getRoot() + store.getEntry().getAbsolutePath()) .getParentFile(); if (!parentDir.exists()) { try { FileUtils.forceMkdir(parentDir); } catch (IOException e) { throw new CoreException(new Status(IStatus.ERROR, ScaFileSystemPlugin.ID, "File cache error: Failed to create temporary file cache directory " + parentDir, e)); } } localFile = new File(parentDir, store.getEntry().getName()); if (localFile.exists() && localFile.lastModified() == info.getLastModified()) { if ((localFile.isDirectory() && info.isDirectory()) || (localFile.length() == info.getLength())) { return; } } boolean error = false; try { if (info.isDirectory()) { if (!info.exists()) { FileUtils.forceMkdir(localFile); } } else { FileUtils.deleteQuietly(localFile); try { tmpFile = File.createTempFile(localFile.getName(), ".tmp", parentDir); } catch (IOException e) { throw new CoreException(new Status(IStatus.ERROR, ScaFileSystemPlugin.ID, "File cache error: Failed to create temporary file " + localFile, e)); } tmpFile.deleteOnExit(); scaInputStream = createScaInputStream(); fileStream = new FileOutputStream(tmpFile); FileCache.copyLarge(scaInputStream, fileStream); localFile.setExecutable(info.getAttribute(EFS.ATTRIBUTE_EXECUTABLE)); FileUtils.moveFile(tmpFile, localFile); } localFile.setLastModified(info.getLastModified()); } catch (final FileNotFoundException e) { error = true; throw new CoreException( new Status(IStatus.ERROR, ScaFileSystemPlugin.ID, "File cache error: " + localFile, e)); } catch (final IOException e) { error = true; throw new CoreException( new Status(IStatus.ERROR, ScaFileSystemPlugin.ID, "File cache error: " + localFile, e)); } catch (CoreException e) { error = true; throw new CoreException(new Status(IStatus.ERROR, ScaFileSystemPlugin.ID, "File cache error: " + localFile + "\n" + e.getStatus().getMessage(), e.getStatus().getException())); } catch (InterruptedException e) { error = true; throw new CoreException(new Status(IStatus.ERROR, ScaFileSystemPlugin.ID, "File download interrupted: " + localFile, e)); } catch (ExecutionException e) { error = true; throw new CoreException( new Status(IStatus.ERROR, ScaFileSystemPlugin.ID, "File cache error: " + localFile, e)); } catch (TimeoutException e) { error = true; throw new CoreException( new Status(IStatus.ERROR, ScaFileSystemPlugin.ID, "File download time-out: " + localFile, e)); } finally { IOUtils.closeQuietly(fileStream); IOUtils.closeQuietly(scaInputStream); FileUtils.deleteQuietly(tmpFile); if (error) { if (localFile != null && localFile.exists()) { FileUtils.deleteQuietly(localFile); } localFile = null; } } }
From source file:fr.sanofi.fcl4transmart.controllers.listeners.clinicalData.SetStudyTreeListener.java
@Override public void handleEvent(Event event) { // TODO Auto-generated method stub this.columnsDone = new HashMap<String, Vector<Integer>>(); for (File rawFile : ((ClinicalData) this.dataType).getRawFiles()) { this.columnsDone.put(rawFile.getName(), new Vector<Integer>()); }//from w w w. jav a 2s.c om if (((ClinicalData) this.dataType).getCMF() == null) { this.setStudyTreeUI.displayMessage("Error: no column mapping file"); return; } File file = new File(this.dataType.getPath().toString() + File.separator + this.dataType.getStudy().toString() + ".columns.tmp"); try { FileWriter fw = new FileWriter(file); BufferedWriter out = new BufferedWriter(fw); out.write( "Filename\tCategory Code\tColumn Number\tData Label\tData Label Source\tControlled Vocab Code\n"); try { BufferedReader br = new BufferedReader(new FileReader(((ClinicalData) this.dataType).getCMF())); String line = br.readLine(); while ((line = br.readLine()) != null) { if (line.split("\t", -1)[3].compareTo("SUBJ_ID") == 0 || line.split("\t", -1)[3].compareTo("VISIT_NAME") == 0 || line.split("\t", -1)[3].compareTo("SITE_ID") == 0) { out.write(line + "\n"); this.columnsDone.get(line.split("\t", -1)[0]) .add(Integer.parseInt(line.split("\t", -1)[2])); } else if (line.split("\t", -1)[3].compareTo("OMIT") != 0 && line.split("\t", -1)[3].compareTo("\\") != 0) { File rawFile = new File(this.dataType.getPath() + File.separator + line.split("\t", -1)[0]); this.labels.put( FileHandler.getColumnByNumber(rawFile, Integer.parseInt(line.split("\t", -1)[2])), line.split("\t", -1)[3]); } } br.close(); } catch (Exception e) { this.setStudyTreeUI.displayMessage("File error: " + e.getLocalizedMessage()); e.printStackTrace(); out.close(); } this.writeLine(this.setStudyTreeUI.getRoot(), out, ""); for (String key : this.columnsDone.keySet()) { File rawFile = null; for (File f : ((ClinicalData) this.dataType).getRawFiles()) { if (f.getName().compareTo(key) == 0) { rawFile = f; } } if (rawFile != null) { for (int i = 1; i <= FileHandler.getColumnsNumber(rawFile); i++) { if (!this.columnsDone.get(key).contains(i)) { out.write(key + "\t" + "" + "\t" + i + "\t" + "OMIT" + "\t\t\n"); } } } } out.close(); try { String fileName = ((ClinicalData) this.dataType).getCMF().getName(); ((ClinicalData) this.dataType).getCMF().delete(); File fileDest = new File(this.dataType.getPath() + File.separator + fileName); FileUtils.moveFile(file, fileDest); ((ClinicalData) this.dataType).setCMF(fileDest); } catch (IOException ioe) { this.setStudyTreeUI.displayMessage("File error: " + ioe.getLocalizedMessage()); return; } } catch (Exception e) { this.setStudyTreeUI.displayMessage("Error: " + e.getLocalizedMessage()); e.printStackTrace(); } this.setStudyTreeUI.displayMessage("Column mapping file updated"); WorkPart.updateSteps(); WorkPart.updateFiles(); }
From source file:com.docd.purefm.test.MediaStoreUtilsTest.java
private void testMoveFile(@NonNull final ContentResolver resolver) throws Throwable { final GenericFile test1dir = new JavaFile(TEST_ROOT, "test6.txt"); final GenericFile test2dir = new JavaFile(TEST_ROOT, "test7.txt"); test1dir.mkdir();//from w w w. jav a2 s .c om assertTrue(test1dir.exists()); assertTrue(test1dir.isDirectory()); test2dir.mkdir(); assertTrue(test2dir.exists()); assertTrue(test2dir.isDirectory()); final GenericFile test1file = new JavaFile(test1dir.toFile(), "test8.txt"); final GenericFile test2file = new JavaFile(test2dir.toFile(), "test8.txt"); test1file.createNewFile(); assertTrue(test1file.exists()); assertFalse(test1file.isDirectory()); MediaStoreUtils.addEmptyFileOrDirectory(resolver, test1dir); MediaStoreUtils.addEmptyFileOrDirectory(resolver, test2dir); MediaStoreUtils.addEmptyFileOrDirectory(resolver, test1file); assertTrue(isFileInMediaStore(resolver, test1dir)); assertTrue(isFileInMediaStore(resolver, test2dir)); assertTrue(isFileInMediaStore(resolver, test1file)); FileUtils.moveFile(test1file.toFile(), test2file.toFile()); final List<Pair<GenericFile, GenericFile>> files = new ArrayList<>(1); files.add(new Pair<>(test1file, test2file)); MediaStoreUtils.moveFiles(getContext(), files); assertTrue(isFileInMediaStore(resolver, test1dir)); assertTrue(isFileInMediaStore(resolver, test2dir)); assertFalse(isFileInMediaStore(resolver, test1file)); //there is no waiting for MediaScanner to finish, so we must skip this check //assertTrue(isFileInMediaStore(resolver, test2file)); test2file.delete(); test1dir.delete(); test2dir.delete(); MediaStoreUtils.deleteFileOrDirectory(resolver, test2file); MediaStoreUtils.deleteFileOrDirectory(resolver, test1dir); MediaStoreUtils.deleteFileOrDirectory(resolver, test2dir); assertFalse(isFileInMediaStore(resolver, test1dir)); assertFalse(isFileInMediaStore(resolver, test2dir)); assertFalse(isFileInMediaStore(resolver, test2file)); }
From source file:fr.sanofi.fcl4transmart.controllers.listeners.clinicalData.SetUnitsListener.java
@Override public void handleEvent(Event event) { Vector<String> columns = this.setUnitsUI.getColumns(); Vector<String> units = this.setUnitsUI.getUnits(); if (columns.size() == 1) { if (columns.get(0).compareTo("") == 0 && columns.get(0).compareTo("") == 0) { columns = new Vector<String>(); units = new Vector<String>(); }//from w w w.j av a 2 s. c o m } for (int i = 0; i < columns.size(); i++) { if (columns.get(i).compareTo("") == 0 || units.get(i).compareTo("") == 0) { this.setUnitsUI.displayMessage("Some values are not set"); return; } String columnFileName = columns.get(i).split(" - ", 2)[0]; String unitFileName = units.get(i).split(" - ", 2)[0]; if (columnFileName.compareTo(unitFileName) != 0) { this.setUnitsUI.displayMessage("Columns for value and unit have to been from the same file"); } } if (((ClinicalData) this.dataType).getCMF() == null) { this.setUnitsUI.displayMessage("Error: no column mapping file"); return; } if (!this.checkValues(columns, units)) return; File file = new File(this.dataType.getPath().toString() + File.separator + this.dataType.getStudy().toString() + ".columns.tmp"); try { FileWriter fw = new FileWriter(file); BufferedWriter out = new BufferedWriter(fw); out.write( "Filename\tCategory Code\tColumn Number\tData Label\tData Label Source\tControlled Vocab Code\n"); try { BufferedReader br = new BufferedReader(new FileReader(((ClinicalData) this.dataType).getCMF())); String line = br.readLine(); while ((line = br.readLine()) != null) { if (line.split("\t", -1)[3].compareTo("UNITS") != 0) { out.write(line + "\n"); } } br.close(); } catch (Exception e) { this.setUnitsUI.displayMessage("Error: " + e.getLocalizedMessage()); e.printStackTrace(); out.close(); } for (int i = 0; i < columns.size(); i++) { String fileName = columns.get(i).split(" - ", 2)[0]; int columnColumnNumber = -1; for (File rawFile : ((ClinicalData) this.dataType).getRawFiles()) { if (rawFile.getName().compareTo(fileName) == 0) { columnColumnNumber = FileHandler.getHeaderNumber(rawFile, columns.get(i).split(" - ", 2)[1]); } } int unitColumnNumber = -1; for (File rawFile : ((ClinicalData) this.dataType).getRawFiles()) { if (rawFile.getName().compareTo(fileName) == 0) { unitColumnNumber = FileHandler.getHeaderNumber(rawFile, units.get(i).split(" - ", 2)[1]); } } if (columnColumnNumber != -1 && unitColumnNumber != -1) { out.write(fileName + "\t\t" + String.valueOf(unitColumnNumber) + "\tUNITS\t" + String.valueOf(columnColumnNumber) + "\t\t\n"); } } out.close(); String fileName = ((ClinicalData) this.dataType).getCMF().getName(); FileUtils.deleteQuietly(((ClinicalData) this.dataType).getCMF()); try { File fileDest = new File(this.dataType.getPath() + File.separator + fileName); FileUtils.moveFile(file, fileDest); ((ClinicalData) this.dataType).setCMF(fileDest); } catch (Exception ioe) { this.setUnitsUI.displayMessage("File error: " + ioe.getLocalizedMessage()); return; } } catch (Exception e) { this.setUnitsUI.displayMessage("Error: " + e.getLocalizedMessage()); e.printStackTrace(); } this.setUnitsUI.displayMessage("Column mapping file updated"); WorkPart.updateSteps(); WorkPart.updateFiles(); }
From source file:de.uzk.hki.da.format.DocxConversionStrategy.java
@Override public List<Event> convertFile(ConversionInstruction ci) throws FileNotFoundException { if (ci.getConversion_routine() == null) throw new IllegalStateException("conversionRoutine not set"); if (ci.getConversion_routine().getTarget_suffix().isEmpty()) throw new IllegalStateException("target suffix in conversionRoutine not set"); if (ci.getConversion_routine().getParams() == null) throw new IllegalStateException("add params not set"); if (cliConnector == null) throw new IllegalStateException("Cli Connector is not set"); File result = new File(generateTargetFilePath(ci)); List<Event> results = new ArrayList<Event>(); getHttpclient().setUrl(ci.getConversion_routine().getParams()); getHttpclient()// www . j ava2 s.c o m .setSourceMimeType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); getHttpclient().postFileAndReadResponse(ci.getSource_file().toRegularFile(), result); if (result.exists()) { DAFile daf = new DAFile(pkg, object.getPath("newest").getLastElement(), Utilities.slashize(ci.getTarget_folder()) + result.getName()); logger.debug("new dafile:" + daf); // TODO Doing PDF/A Conversion with a temp file, due to recieve PDF 1.5 from MS instead of PDF/A . // This should be the same command for "normal" PDFs // read it from Database? File tempFile = new File("/" + FilenameUtils.getPath(daf.toRegularFile().getAbsolutePath()) + "_" + daf.toRegularFile().getName()); String commandAsArray[] = new String[] { "gs", "-q", "-dPDFA", "-dPDFACompatibilityPolicy=1", "-dBATCH", "-dNOPAUSE", "-dNOOUTERSAVE", "-dUseCIEColor", "-sProcessColorModel=DeviceCMYK", "-sDEVICE=pdfwrite", "-sOutputFile=" + tempFile.getAbsolutePath(), "conf/PDFA_def.ps", daf.toRegularFile().getAbsolutePath() }; if (!cliConnector.execute(commandAsArray)) { throw new RuntimeException("GS command not succeeded"); } try { if (tempFile.exists()) { result.delete(); FileUtils.moveFile(tempFile, daf.toRegularFile()); } else throw new RuntimeException("temp file " + tempFile.getAbsolutePath() + " was not created!"); } catch (IOException e1) { throw new RuntimeException("MV command not succeeded on temp file " + tempFile.getAbsolutePath(), e1); } PdfService.validatePdfA(daf.toRegularFile()); Event e = new Event(); e.setType("CONVERT"); e.setDetail("Webservice DOCX2PDF " + ci.getConversion_routine().getParams() + " AND " + Utilities.createString(commandAsArray)); e.setSource_file(daf); e.setTarget_file(daf); e.setDate(new Date()); results.add(e); } else throw new RuntimeException("Target File not found! " + result.getAbsolutePath()); return results; }
From source file:com.zimbra.cs.store.Blob.java
public void renameTo(final String newPath) throws IOException { if (!path.equals(newPath)) { File newFile = new File(newPath); FileUtils.moveFile(file, newFile); this.path = newPath; this.file = newFile; }/*from w w w. j ava2 s.c om*/ }
From source file:de.uniwue.info6.database.jaxb.ScenarioExporter.java
/** * * * @param scenario//from w ww . ja va2s .c om */ public File generateScenarioXml(Scenario scenario) { scenario = populateScenario(scenario); File base = new File(scriptSystemPath + File.separator + Cfg.RESOURCE_PATH); File saveDir = new File(base, String.valueOf(scenario.getId())); try { if (!saveDir.exists() && saveDir.getParentFile().exists()) { saveDir.mkdir(); } SimpleDateFormat fmt = new SimpleDateFormat("yyyy_MM_dd-HH_mm_ss"); String baseName = "scenario_" + scenario.getId() + "_export_" + fmt.format(new Date()); String conflict = "VERSION_CONFLICT"; File scenarioXml = new File(saveDir, baseName + ".xml"); File scenarioXmlConflict = new File(saveDir, baseName + "_" + conflict + ".xml"); File scenarioXsd = new File(saveDir, baseName + ".xsd"); File scenarioXsdConflict = new File(saveDir, baseName + "_" + conflict + ".xsd"); File scenarioMain = new File(scriptSystemPath, "reference_schema.xsd"); File scenarioMainConflict = new File(saveDir, baseName + "_" + "REFERENCE_SCHEMA.xsd"); JAXBContext jaxbContext = JAXBContext.newInstance(Scenario.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); // output pretty printed jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(scenario, scenarioXml); SchemaOutputResolver sor = new CustomOutputResolver(saveDir, baseName + ".xsd"); jaxbContext.generateSchema(sor); if (!scenarioMain.exists()) { LOGGER.error("REFERENCE SCHEMA IS MISSING: " + scenarioMain); } if (!scenarioXsd.exists()) { LOGGER.error("GENERATED XSD IS MISSING: " + scenarioXsd); } if (!scenarioXml.exists()) { LOGGER.error("GENERATED XML IS MISSING: " + scenarioXml); } if (scenarioMain.exists() && scenarioXsd.exists() && scenarioXml.exists()) { String referenceMD5 = calculateMD5FromFile(scenarioMain); String newMD5 = calculateMD5FromFile(scenarioXsd); File export = null; boolean falseMD5 = !referenceMD5.equals(newMD5); File conflictReadme = new File(saveDir, conflict + "_README.txt"); if (falseMD5) { FileUtils.moveFile(scenarioXml, scenarioXmlConflict); FileUtils.moveFile(scenarioXsd, scenarioXsdConflict); FileUtils.copyFile(scenarioMain, scenarioMainConflict); scenarioXml = scenarioXmlConflict; scenarioXsd = scenarioXsdConflict; export = new File(saveDir, "scenario_" + scenario.getId() + "_export_" + conflict + ".zip"); String readme = Cfg.inst().getProp(DEF_LANGUAGE, "MISC.XSD_XML_CONFLICT") + "\n" + scenarioMainConflict.getName(); if (conflictReadme.exists()) { conflictReadme.delete(); } if (!conflictReadme.exists()) { conflictReadme.createNewFile(); } PrintWriter out = new PrintWriter(conflictReadme); out.println(readme); out.flush(); out.close(); } else { export = new File(saveDir, "scenario_" + scenario.getId() + "_export.zip"); } ArrayList<File> exportFiles = new ArrayList<File>(); if (scenarioXml.exists()) { exportFiles.add(scenarioXml); } if (scenarioXsd.exists()) { exportFiles.add(scenarioXsd); } if (falseMD5 && conflictReadme.exists() && scenarioMainConflict.exists()) { exportFiles.add(conflictReadme); exportFiles.add(scenarioMainConflict); } if (export.exists()) { export.delete(); } return zip(exportFiles, export); } } catch (Exception e) { LOGGER.error("EXPORT XSD/XML FAILED!", e); } return null; }
From source file:au.org.ala.layers.grid.GridClassBuilder.java
public static HashMap<Integer, GridClass> buildFromGrid(String filePath) throws IOException { File wktDir = new File(filePath); wktDir.mkdirs();/*from www. ja v a2s .com*/ int[] wktMap = null; //track values for the SLD ArrayList<Integer> maxValues = new ArrayList<Integer>(); ArrayList<String> labels = new ArrayList<String>(); HashMap<Integer, GridClass> classes = new HashMap<Integer, GridClass>(); Properties p = new Properties(); p.load(new FileReader(filePath + ".txt")); boolean mergeProperties = false; Map<String, Set<Integer>> groupedKeys = new HashMap<String, Set<Integer>>(); Map<Integer, Integer> translateKeys = new HashMap<Integer, Integer>(); Map<String, Integer> translateValues = new HashMap<String, Integer>(); ArrayList<Integer> keys = new ArrayList<Integer>(); for (String key : p.stringPropertyNames()) { try { int k = Integer.parseInt(key); keys.add(k); //grouping of property file keys by value String value = p.getProperty(key); Set<Integer> klist = groupedKeys.get(value); if (klist == null) klist = new HashSet<Integer>(); else mergeProperties = true; klist.add(k); groupedKeys.put(value, klist); if (!translateValues.containsKey(value)) translateValues.put(value, translateValues.size() + 1); translateKeys.put(k, translateValues.get(value)); } catch (NumberFormatException e) { logger.info("Excluding shape key '" + key + "'"); } catch (Exception e) { logger.error(e.getMessage(), e); } } java.util.Collections.sort(keys); Grid g = new Grid(filePath); boolean generateWkt = false; //((long) g.nrows) * ((long) g.ncols) < (long) Integer.MAX_VALUE; if (mergeProperties) { g.replaceValues(translateKeys); if (!new File(filePath + ".txt.old").exists()) FileUtils.moveFile(new File(filePath + ".txt"), new File(filePath + ".txt.old")); StringBuilder sb = new StringBuilder(); for (String value : translateValues.keySet()) { sb.append(translateValues.get(value)).append("=").append(value).append('\n'); } FileUtils.writeStringToFile(new File(filePath + ".txt"), sb.toString()); return buildFromGrid(filePath); } if (generateWkt) { for (String name : groupedKeys.keySet()) { try { Set<Integer> klist = groupedKeys.get(name); String key = klist.iterator().next().toString(); int k = Integer.parseInt(key); GridClass gc = new GridClass(); gc.setName(name); gc.setId(k); if (klist.size() == 1) klist = null; logger.info("getting wkt for " + filePath + " > " + key); Map wktIndexed = Envelope.getGridSingleLayerEnvelopeAsWktIndexed( filePath + "," + key + "," + key, klist, wktMap); //write class wkt File zipFile = new File(filePath + File.separator + key + ".wkt.zip"); ZipOutputStream zos = null; try { zos = new ZipOutputStream(new FileOutputStream(zipFile)); zos.putNextEntry(new ZipEntry(key + ".wkt")); zos.write(((String) wktIndexed.get("wkt")).getBytes()); zos.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (zos != null) { try { zos.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } BufferedOutputStream bos = null; try { bos = new BufferedOutputStream( new FileOutputStream(filePath + File.separator + key + ".wkt")); bos.write(((String) wktIndexed.get("wkt")).getBytes()); bos.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (bos != null) { try { bos.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } logger.info("wkt written to file"); gc.setArea_km(SpatialUtil.calculateArea((String) wktIndexed.get("wkt")) / 1000.0 / 1000.0); //store map wktMap = (int[]) wktIndexed.get("map"); //write wkt index FileWriter fw = null; try { fw = new FileWriter(filePath + File.separator + key + ".wkt.index"); fw.append((String) wktIndexed.get("index")); fw.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (fw != null) { try { fw.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } //write wkt index a binary, include extents (minx, miny, maxx, maxy) and area (sq km) int minPolygonNumber = 0; int maxPolygonNumber = 0; RandomAccessFile raf = null; try { raf = new RandomAccessFile(filePath + File.separator + key + ".wkt.index.dat", "rw"); String[] index = ((String) wktIndexed.get("index")).split("\n"); for (int i = 0; i < index.length; i++) { if (index[i].length() > 1) { String[] cells = index[i].split(","); int polygonNumber = Integer.parseInt(cells[0]); raf.writeInt(polygonNumber); //polygon number int polygonStart = Integer.parseInt(cells[1]); raf.writeInt(polygonStart); //character offset if (i == 0) { minPolygonNumber = polygonNumber; } else if (i == index.length - 1) { maxPolygonNumber = polygonNumber; } } } } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (raf != null) { try { raf.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } //for SLD maxValues.add(gc.getMaxShapeIdx()); labels.add(name.replace("\"", "'")); gc.setMinShapeIdx(minPolygonNumber); gc.setMaxShapeIdx(maxPolygonNumber); logger.info("getting multipolygon for " + filePath + " > " + key); MultiPolygon mp = Envelope.getGridEnvelopeAsMultiPolygon(filePath + "," + key + "," + key); gc.setBbox(mp.getEnvelope().toText().replace(" (", "(").replace(", ", ",")); classes.put(k, gc); try { //write class kml zos = null; try { zos = new ZipOutputStream( new FileOutputStream(filePath + File.separator + key + ".kml.zip")); zos.putNextEntry(new ZipEntry(key + ".kml")); Encoder encoder = new Encoder(new KMLConfiguration()); encoder.setIndenting(true); encoder.encode(mp, KML.Geometry, zos); zos.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (zos != null) { try { zos.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } logger.info("kml written to file"); final SimpleFeatureType TYPE = DataUtilities.createType("class", "the_geom:MultiPolygon,id:Integer,name:String"); FeatureJSON fjson = new FeatureJSON(); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE); SimpleFeature sf = featureBuilder.buildFeature(null); //write class geojson zos = null; try { zos = new ZipOutputStream( new FileOutputStream(filePath + File.separator + key + ".geojson.zip")); zos.putNextEntry(new ZipEntry(key + ".geojson")); featureBuilder.add(mp); featureBuilder.add(k); featureBuilder.add(name); fjson.writeFeature(sf, zos); zos.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (zos != null) { try { zos.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } logger.info("geojson written to file"); //write class shape file File newFile = new File(filePath + File.separator + key + ".shp"); ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory(); Map<String, Serializable> params = new HashMap<String, Serializable>(); params.put("url", newFile.toURI().toURL()); params.put("create spatial index", Boolean.FALSE); ShapefileDataStore newDataStore = null; try { newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params); newDataStore.createSchema(TYPE); newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84); Transaction transaction = new DefaultTransaction("create"); String typeName = newDataStore.getTypeNames()[0]; SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName); SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource; featureStore.setTransaction(transaction); List<SimpleFeature> features = new ArrayList<SimpleFeature>(); DefaultFeatureCollection collection = new DefaultFeatureCollection(); collection.addAll(features); featureStore.setTransaction(transaction); features.add(sf); featureStore.addFeatures(collection); transaction.commit(); transaction.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (newDataStore != null) { try { newDataStore.dispose(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } zos = null; try { zos = new ZipOutputStream( new FileOutputStream(filePath + File.separator + key + ".shp.zip")); //add .dbf .shp .shx .prj String[] exts = { ".dbf", ".shp", ".shx", ".prj" }; for (String ext : exts) { zos.putNextEntry(new ZipEntry(key + ext)); FileInputStream fis = null; try { fis = new FileInputStream(filePath + File.separator + key + ext); byte[] buffer = new byte[1024]; int size; while ((size = fis.read(buffer)) > 0) { zos.write(buffer, 0, size); } } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } //remove unzipped files new File(filePath + File.separator + key + ext).delete(); } zos.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (zos != null) { try { zos.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } logger.info("shape file written to zip"); } catch (Exception e) { logger.error(e.getMessage(), e); } } catch (Exception e) { logger.error(e.getMessage(), e); } } //write polygon mapping g.writeGrid(filePath + File.separator + "polygons", wktMap, g.xmin, g.ymin, g.xmax, g.ymax, g.xres, g.yres, g.nrows, g.ncols); //copy the header file to get it exactly the same, but change the data type copyHeaderAsInt(filePath + ".grd", filePath + File.separator + "polygons.grd"); } else { //build classes without generating polygons Map<Float, float[]> info = new HashMap<Float, float[]>(); for (int j = 0; j < keys.size(); j++) { info.put(keys.get(j).floatValue(), new float[] { 0, Float.NaN, Float.NaN, Float.NaN, Float.NaN }); } g.getClassInfo(info); for (int j = 0; j < keys.size(); j++) { int k = keys.get(j); String key = String.valueOf(k); String name = p.getProperty(key); GridClass gc = new GridClass(); gc.setName(name); gc.setId(k); //for SLD maxValues.add(Integer.valueOf(key)); labels.add(name.replace("\"", "'")); gc.setMinShapeIdx(Integer.valueOf(key)); gc.setMaxShapeIdx(Integer.valueOf(key)); float[] stats = info.get(keys.get(j).floatValue()); //only include if area > 0 if (stats[0] > 0) { gc.setBbox("POLYGON((" + stats[1] + " " + stats[2] + "," + stats[1] + " " + stats[4] + "," + stats[3] + " " + stats[4] + "," + stats[3] + " " + stats[2] + "," + stats[1] + " " + stats[2] + "))"); gc.setArea_km((double) stats[0]); classes.put(k, gc); } } } //write sld exportSLD(filePath + File.separator + "polygons.sld", new File(filePath + ".txt").getName(), maxValues, labels); writeProjectionFile(filePath + File.separator + "polygons.prj"); //write .classes.json ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(new File(filePath + ".classes.json"), classes); return classes; }
From source file:com.cedarsoft.io.LinkUtils.java
/** * Deletes the symbolic link//from w w w . jav a 2 s. c om * * @param linkFile the link file * @throws IOException if any. */ public static void deleteSymbolicLink(@Nonnull File linkFile) throws IOException { if (!linkFile.exists()) { throw new FileNotFoundException("No such symlink: " + linkFile); } // find the resource of the existing link: File canonicalFile = linkFile.getCanonicalFile(); // rename the resource, thus breaking the link: File temp = createTempFile("symlink", ".tmp", canonicalFile.getParentFile()); try { try { FileUtils.moveFile(canonicalFile, temp); } catch (IOException e) { throw new IOException("Couldn't rename resource when attempting to delete " + linkFile); } // delete the (now) broken link: if (!linkFile.delete()) { throw new IOException("Couldn't delete symlink: " + linkFile + " (was it a real file? is this not a UNIX system?)"); } } finally { // return the resource to its original name: try { FileUtils.moveFile(temp, canonicalFile); } catch (IOException e) { throw new IOException("Couldn't return resource " + temp + " to its original name: " + canonicalFile.getAbsolutePath() + "\n THE RESOURCE'S NAME ON DISK HAS " + "BEEN CHANGED BY THIS ERROR!\n"); } } }