List of usage examples for org.apache.commons.io FileUtils copyFileToDirectory
public static void copyFileToDirectory(File srcFile, File destDir) throws IOException
From source file:org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScriptTest.java
@Test public void testClasspathWithClassDirectory() throws Exception { r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); GlobalMatrixAuthorizationStrategy gmas = new GlobalMatrixAuthorizationStrategy(); gmas.add(Jenkins.READ, "devel"); for (Permission p : Item.PERMISSIONS.getPermissions()) { gmas.add(p, "devel"); }// w w w . ja v a 2 s.co m r.jenkins.setAuthorizationStrategy(gmas); // Copy jar files to temporary directory, then overwrite them with updated jar files. File tmpDir = tmpFolderRule.newFolder(); for (File jarfile : getAllJarFiles()) { Expand e = new Expand(); e.setSrc(jarfile); e.setDest(tmpDir); e.execute(); } List<ClasspathEntry> classpath = new ArrayList<ClasspathEntry>(); classpath.add(new ClasspathEntry(tmpDir.getAbsolutePath())); final String testingDisplayName = "TESTDISPLAYNAME"; FreeStyleProject p = r.createFreeStyleProject(); p.getPublishersList() .add(new TestGroovyRecorder(new SecureGroovyScript(String.format( "import org.jenkinsci.plugins.scriptsecurity.testjar.BuildUtil;" + "BuildUtil.setDisplayNameWhitelisted(build, \"%s\");" + "\"\"", testingDisplayName), true, classpath))); // Fail as the classpath is not approved. { FreeStyleBuild b = p.scheduleBuild2(0).get(); r.assertBuildStatus(Result.FAILURE, b); assertNotEquals(testingDisplayName, b.getDisplayName()); } // Approve classpath. { List<ScriptApproval.PendingClasspathEntry> pcps = ScriptApproval.get().getPendingClasspathEntries(); assertNotEquals(0, pcps.size()); for (ScriptApproval.PendingClasspathEntry pcp : pcps) { ScriptApproval.get().approveClasspathEntry(pcp.getHash()); } } // Success as approved. { FreeStyleBuild b = p.scheduleBuild2(0).get(); r.assertBuildStatusSuccess(b); assertEquals(testingDisplayName, b.getDisplayName()); } // add new file in tmpDir. { File f = tmpFolderRule.newFile(); FileUtils.copyFileToDirectory(f, tmpDir); } // Fail as the class directory is updated. { FreeStyleBuild b = p.scheduleBuild2(0).get(); r.assertBuildStatus(Result.FAILURE, b); assertNotEquals(testingDisplayName, b.getDisplayName()); } // Approve classpath. { List<ScriptApproval.PendingClasspathEntry> pcps = ScriptApproval.get().getPendingClasspathEntries(); assertNotEquals(0, pcps.size()); for (ScriptApproval.PendingClasspathEntry pcp : pcps) { ScriptApproval.get().approveClasspathEntry(pcp.getHash()); } } // Success as approved. { FreeStyleBuild b = p.scheduleBuild2(0).get(); r.assertBuildStatusSuccess(b); assertEquals(testingDisplayName, b.getDisplayName()); } }
From source file:org.jodconverter.cli.ConvertITest.java
@Test public void convert_WithOutputFormat_ShouldSucceed() throws Exception { final File inputFile = new File(SOURCE_FILE); FileUtils.copyFileToDirectory(inputFile, testFolder.getRoot()); final File inputFileTmp = new File(testFolder.getRoot(), FilenameUtils.getName(SOURCE_FILE)); final File outputFile = new File(testFolder.getRoot(), FilenameUtils.getBaseName(inputFile.getName()) + ".pdf"); assertThat(outputFile).doesNotExist(); try {//from ww w. j a v a 2 s . com Convert.main(new String[] { "-k", "-f", "pdf", inputFileTmp.getPath() }); // Be sure the ExitException exception is thrown. fail(); } catch (Exception ex) { try { assertThat(ex).isExactlyInstanceOf(ExitException.class).hasFieldOrPropertyWithValue("status", 0); assertThat(outputFile).isFile(); assertThat(outputFile.length()).isGreaterThan(0L); } finally { FileUtils.deleteQuietly(outputFile); // Prevent further test failure. } } }
From source file:org.jsweet.input.typescriptdef.TypescriptDef2Java.java
public static Context translate( // List<File> tsDefFiles, // List<File> tsDefDependencies, // File outputDir, // File cacheDir, // boolean fetchJavadoc, // boolean copyTsDefs) throws Throwable { // comp.compile(fileObjects); logger.info("input files: " + tsDefFiles); logger.info("dependencies: " + tsDefDependencies); logger.info("output directory: " + outputDir.getAbsolutePath()); outputDir.mkdirs();// w w w. j a v a 2s. co m Context context = new Context(tsDefFiles, tsDefDependencies, fetchJavadoc); context.verbose = false; context.cacheDir = cacheDir; logger.info("all definitions: " + context.getAllDefinitions()); for (File f : context.getAllDefinitions()) { parse(context, f); } translateAst(context); printAst(outputDir, context); // copies core built-in srcs // if (context.getLibrariesDefinitions() // .contains(new File(JSweetDefTranslatorConfig.TS_LIBS_DIR_NAME + // "/lib.core/lib.core.d.ts"))) { // logger.info("copying built-in core '" + getBuiltInDir() + "' -> '" + // outputDir); // FileUtils.copyDirectory(new File(getBuiltInDir()), outputDir, new // FileFilter() { // // @Override // public boolean accept(File file) { // return !file.getName().startsWith("."); // } // }); // } // copies core packages' package-info if necessary // File jsweetRootPackageDir = new File(outputDir, "jsweet"); // if (jsweetRootPackageDir.isDirectory()) { // for (File jsweetSubSourceDir : jsweetRootPackageDir.listFiles()) { // File packageInfo = new File(BUILT_IN_DIR, // "jsweet/" + jsweetSubSourceDir.getName() + "/package-info.java"); // logger.info("copying package-info for '" + jsweetSubSourceDir + "' // from " + packageInfo); // FileUtils.copyFileToDirectory(packageInfo, jsweetSubSourceDir); // } // } // ===== if (copyTsDefs) { File tsdefDir = new File(outputDir, JSweetDefTranslatorConfig.TS_LIBS_DIR_NAME); logger.info("copying tsdef: '" + context.getAllDefinitions() + "' -> '" + tsdefDir); tsdefDir.mkdirs(); for (File tsDefFile : context.getAllDefinitions()) { File destDir = new File( // tsdefDir, // tsDefFile.getParentFile().getName() + "_" + tsDefFile.getName()); FileUtils.copyFileToDirectory(tsDefFile, destDir); File extFile = new File(tsDefFile.getParentFile(), tsDefFile.getName().replace(".d.ts", ".ext.d.ts")); if (extFile.isFile() && extFile.canRead()) { FileUtils.copyFileToDirectory(tsDefFile, destDir); logger.info("ext file '" + extFile + "' copied as well"); } } mergeExtFiles(tsdefDir); // createLibFile(tsdefDir); // mergeDomToCore(tsdefDir); } return context; }
From source file:org.jumpmind.symmetric.util.SnapshotUtil.java
public static File createSnapshot(ISymmetricEngine engine) { String dirName = engine.getEngineName().replaceAll(" ", "-") + "-" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); IParameterService parameterService = engine.getParameterService(); File tmpDir = new File(parameterService.getTempDirectory(), dirName); tmpDir.mkdirs();/*from w w w . ja v a 2 s .c om*/ File logDir = null; String parameterizedLogDir = parameterService.getString("server.log.dir"); if (isNotBlank(parameterizedLogDir)) { logDir = new File(parameterizedLogDir); } if (logDir != null && logDir.exists()) { log.info("Using server.log.dir setting as the location of the log files"); } else { logDir = new File("logs"); if (!logDir.exists()) { File file = findSymmetricLogFile(); if (file != null) { logDir = file.getParentFile(); } } if (!logDir.exists()) { logDir = new File("../logs"); } if (!logDir.exists()) { logDir = new File("target"); } if (logDir.exists()) { File[] files = logDir.listFiles(); if (files != null) { for (File file : files) { if (file.getName().toLowerCase().endsWith(".log")) { try { FileUtils.copyFileToDirectory(file, tmpDir); } catch (IOException e) { log.warn("Failed to copy " + file.getName() + " to the snapshot directory", e); } } } } } } ITriggerRouterService triggerRouterService = engine.getTriggerRouterService(); List<TriggerHistory> triggerHistories = triggerRouterService.getActiveTriggerHistories(); TreeSet<Table> tables = new TreeSet<Table>(); for (TriggerHistory triggerHistory : triggerHistories) { Table table = engine.getDatabasePlatform().getTableFromCache(triggerHistory.getSourceCatalogName(), triggerHistory.getSourceSchemaName(), triggerHistory.getSourceTableName(), false); if (table != null && !table.getName().toUpperCase() .startsWith(engine.getSymmetricDialect().getTablePrefix().toUpperCase())) { tables.add(table); } } List<Trigger> triggers = triggerRouterService.getTriggers(true); for (Trigger trigger : triggers) { Table table = engine.getDatabasePlatform().getTableFromCache(trigger.getSourceCatalogName(), trigger.getSourceSchemaName(), trigger.getSourceTableName(), false); if (table != null) { tables.add(table); } } FileWriter fwriter = null; try { fwriter = new FileWriter(new File(tmpDir, "config-export.csv")); engine.getDataExtractorService().extractConfigurationStandalone(engine.getNodeService().findIdentity(), fwriter, TableConstants.SYM_NODE, TableConstants.SYM_NODE_SECURITY, TableConstants.SYM_NODE_IDENTITY, TableConstants.SYM_NODE_HOST, TableConstants.SYM_NODE_CHANNEL_CTL, TableConstants.SYM_CONSOLE_USER); } catch (IOException e) { log.warn("Failed to export symmetric configuration", e); } finally { IOUtils.closeQuietly(fwriter); } FileOutputStream fos = null; try { fos = new FileOutputStream(new File(tmpDir, "table-definitions.xml")); DbExport export = new DbExport(engine.getDatabasePlatform()); export.setFormat(Format.XML); export.setNoData(true); export.exportTables(fos, tables.toArray(new Table[tables.size()])); } catch (IOException e) { log.warn("Failed to export table definitions", e); } finally { IOUtils.closeQuietly(fos); } String tablePrefix = engine.getTablePrefix(); DbExport export = new DbExport(engine.getDatabasePlatform()); export.setFormat(Format.CSV); export.setNoCreateInfo(true); extract(export, new File(tmpDir, "identity.csv"), TableConstants.getTableName(tablePrefix, TableConstants.SYM_NODE_IDENTITY)); extract(export, new File(tmpDir, "node.csv"), TableConstants.getTableName(tablePrefix, TableConstants.SYM_NODE)); extract(export, new File(tmpDir, "nodesecurity.csv"), TableConstants.getTableName(tablePrefix, TableConstants.SYM_NODE_SECURITY)); extract(export, new File(tmpDir, "nodehost.csv"), TableConstants.getTableName(tablePrefix, TableConstants.SYM_NODE_HOST)); extract(export, new File(tmpDir, "triggerhist.csv"), TableConstants.getTableName(tablePrefix, TableConstants.SYM_TRIGGER_HIST)); extract(export, new File(tmpDir, "lock.csv"), TableConstants.getTableName(tablePrefix, TableConstants.SYM_LOCK)); extract(export, new File(tmpDir, "nodecommunication.csv"), TableConstants.getTableName(tablePrefix, TableConstants.SYM_NODE_COMMUNICATION)); extract(export, 5000, new File(tmpDir, "outgoingbatch.csv"), TableConstants.getTableName(tablePrefix, TableConstants.SYM_OUTGOING_BATCH)); extract(export, 5000, new File(tmpDir, "incomingbatch.csv"), TableConstants.getTableName(tablePrefix, TableConstants.SYM_INCOMING_BATCH)); final int THREAD_INDENT_SPACE = 50; fwriter = null; try { fwriter = new FileWriter(new File(tmpDir, "threads.txt")); ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); long[] threadIds = threadBean.getAllThreadIds(); for (long l : threadIds) { ThreadInfo info = threadBean.getThreadInfo(l, 100); if (info != null) { String threadName = info.getThreadName(); fwriter.append(StringUtils.rightPad(threadName, THREAD_INDENT_SPACE)); StackTraceElement[] trace = info.getStackTrace(); boolean first = true; for (StackTraceElement stackTraceElement : trace) { if (!first) { fwriter.append(StringUtils.rightPad("", THREAD_INDENT_SPACE)); } else { first = false; } fwriter.append(stackTraceElement.getClassName()); fwriter.append("."); fwriter.append(stackTraceElement.getMethodName()); fwriter.append("()"); int lineNumber = stackTraceElement.getLineNumber(); if (lineNumber > 0) { fwriter.append(": "); fwriter.append(Integer.toString(stackTraceElement.getLineNumber())); } fwriter.append("\n"); } fwriter.append("\n"); } } } catch (IOException e) { log.warn("Failed to export thread information", e); } finally { IOUtils.closeQuietly(fwriter); } fos = null; try { fos = new FileOutputStream(new File(tmpDir, "parameters.properties")); Properties effectiveParameters = engine.getParameterService().getAllParameters(); SortedProperties parameters = new SortedProperties(); parameters.putAll(effectiveParameters); parameters.remove("db.password"); parameters.store(fos, "parameters.properties"); } catch (IOException e) { log.warn("Failed to export parameter information", e); } finally { IOUtils.closeQuietly(fos); } fos = null; try { fos = new FileOutputStream(new File(tmpDir, "parameters-changed.properties")); Properties defaultParameters = new Properties(); InputStream in = SnapshotUtil.class.getResourceAsStream("/symmetric-default.properties"); defaultParameters.load(in); IOUtils.closeQuietly(in); in = SnapshotUtil.class.getResourceAsStream("/symmetric-console-default.properties"); if (in != null) { defaultParameters.load(in); IOUtils.closeQuietly(in); } Properties effectiveParameters = engine.getParameterService().getAllParameters(); Properties changedParameters = new SortedProperties(); Map<String, ParameterMetaData> parameters = ParameterConstants.getParameterMetaData(); for (String key : parameters.keySet()) { String defaultValue = defaultParameters.getProperty((String) key); String currentValue = effectiveParameters.getProperty((String) key); if (defaultValue == null && currentValue != null || (defaultValue != null && !defaultValue.equals(currentValue))) { changedParameters.put(key, currentValue == null ? "" : currentValue); } } changedParameters.remove("db.password"); changedParameters.store(fos, "parameters-changed.properties"); } catch (IOException e) { log.warn("Failed to export parameters-changed information", e); } finally { IOUtils.closeQuietly(fos); } writeRuntimeStats(engine, tmpDir); writeJobsStats(engine, tmpDir); if ("true".equals(System.getProperty(SystemConstants.SYSPROP_STANDALONE_WEB))) { writeDirectoryListing(engine, tmpDir); } fos = null; try { fos = new FileOutputStream(new File(tmpDir, "system.properties")); SortedProperties props = new SortedProperties(); props.putAll(System.getProperties()); props.store(fos, "system.properties"); } catch (IOException e) { log.warn("Failed to export thread information", e); } finally { IOUtils.closeQuietly(fos); } try { File jarFile = new File(getSnapshotDirectory(engine), tmpDir.getName() + ".zip"); JarBuilder builder = new JarBuilder(tmpDir, jarFile, new File[] { tmpDir }, Version.version()); builder.build(); FileUtils.deleteDirectory(tmpDir); return jarFile; } catch (IOException e) { throw new IoException("Failed to package snapshot files into archive", e); } }
From source file:org.kalypso.calculation.plc.postprocessing.PLCPreprocessingSimulation.java
/** * move flood outputs to status quo/* ww w .j av a2 s .c om*/ */ private void doFloodModel(final ISimulationDataProvider inputProvider, final File statusQuoFolder) throws SimulationException, IOException { if (!inputProvider.hasID(INPUT_FLOOD_MODEL)) return; final File actualFloodModel = FileUtils.toFile((URL) inputProvider.getInputForID(INPUT_FLOOD_MODEL)); FileUtils.copyFileToDirectory(actualFloodModel, new File(statusQuoFolder, "models")); //$NON-NLS-1$ final File actualFloodResults = FileUtils .toFile((URL) inputProvider.getInputForID(INPUT_FLOOD_RESULT_FOLDER)); final File statusQuoFloodResults = new File(statusQuoFolder, "events"); //$NON-NLS-1$ FileUtils.moveDirectory(actualFloodResults, statusQuoFloodResults); }
From source file:org.kalypso.calculation.plc.postprocessing.PLCPreprocessingSimulation.java
/** * move risk outputs to status quo/*from w ww .ja va 2s . c o m*/ */ private void doRiskModel(final ISimulationDataProvider inputProvider, final File statusQuoFolder) throws SimulationException, IOException { if (!inputProvider.hasID(INPUT_RISK_MODEL)) return; final File actualRasterModel = FileUtils.toFile((URL) inputProvider.getInputForID(INPUT_RISK_MODEL)); FileUtils.copyFileToDirectory(actualRasterModel, statusQuoFolder); final File actualRasterFolderOutput = FileUtils .toFile((URL) inputProvider.getInputForID(INPUT_RISK_RESULT_FOLDER)); final File statusQuoRasterFolderOutput = new File(statusQuoFolder, "raster/output"); //$NON-NLS-1$ FileUtils.moveDirectory(actualRasterFolderOutput, statusQuoRasterFolderOutput); }
From source file:org.kalypso.commons.java.io.FileUtilities.java
public static void copyShapeFileToDirectory(final String shapeBase, final File target) { File _shp;//from w w w. ja va 2 s .com File _dbf; File _shx; File _sbn; File _sbx; if (target.isDirectory()) { try { _shp = new File(shapeBase + ".shp"); //$NON-NLS-1$ if (_shp.exists()) FileUtils.copyFileToDirectory(_shp, target); else return; _dbf = new File(shapeBase + ".dbf"); //$NON-NLS-1$ if (_dbf.exists()) FileUtils.copyFileToDirectory(_dbf, target); else return; _shx = new File(shapeBase + ".shx"); //$NON-NLS-1$ if (_shx.exists()) FileUtils.copyFileToDirectory(_shx, target); else return; _sbn = new File(shapeBase + ".sbn"); //$NON-NLS-1$ if (_sbn.exists()) FileUtils.copyFileToDirectory(_sbn, target); _sbx = new File(shapeBase + ".sbx"); //$NON-NLS-1$ if (_sbn.exists()) FileUtils.copyFileToDirectory(_sbx, target); } catch (final MalformedURLException e) { e.printStackTrace(); } catch (final IOException e) { e.printStackTrace(); } } }
From source file:org.kalypso.gml.processes.constDelaunay.TriangleExe.java
public GM_Triangle[] triangulate(final GM_Polygon[] boundaries, final GM_Curve[] breaklines, final boolean exportZ) { final File triangleExe = ConstraintDelaunayHelper.findTriangleExe(); if (triangleExe == null || !triangleExe.isFile()) throw new IllegalStateException("triangle.exe not found"); //$NON-NLS-1$ // FIXME: put into separate class! BufferedReader nodeReader = null; BufferedReader eleReader = null; PrintStream pwSimuLog;/*from w w w . j a v a 2 s . c om*/ /* prepare */ final List<TriangleVertex> nodeList = new ArrayList<>(); final List<TriangleSegment> segmentList = new ArrayList<>(); final List<TriangleHole> holeList = new ArrayList<>(); int i = 0; final String crs = boundaries[0].getCoordinateSystem(); final IGeoTransformer geoTransformer = GeoTransformerFactory.getGeoTransformer(crs); for (final GM_Polygon boundary : boundaries) { final GM_PolygonPatch surfacePatch = boundary.getSurfacePatch(); { // handle the exterior int k = i; final GM_Position[] exterior = surfacePatch.getExteriorRing(); for (; i - k < exterior.length - 2; i++) { final GM_Position position = exterior[i - k]; final TriangleVertex vertex = createVertex(exportZ, position); nodeList.add(vertex); final TriangleSegment segment = new TriangleSegment(i, i + 1, 1); segmentList.add(segment); } final GM_Position position = exterior[i - k]; final TriangleVertex vertex = createVertex(exportZ, position); nodeList.add(vertex); final TriangleSegment segment = new TriangleSegment(i, k, 1); segmentList.add(segment); i++; } final GM_Position[][] interiorRings = surfacePatch.getInteriorRings(); if (interiorRings != null) { for (final GM_Position[] ring : interiorRings) { // handle the hole int j = i; for (; i - j < ring.length - 2; i++) { final GM_Position position = ring[i - j]; final TriangleVertex vertex = createVertex(exportZ, position); nodeList.add(vertex); final TriangleSegment segment = new TriangleSegment(i, i + 1, 1); segmentList.add(segment); } final GM_Position position = ring[i - j]; final TriangleVertex vertex = createVertex(exportZ, position); nodeList.add(vertex); final TriangleSegment segment = new TriangleSegment(i, j, 1); segmentList.add(segment); final Coordinate[] coordinates = JTSAdapter.export(ring); final com.vividsolutions.jts.geom.GeometryFactory geometryFactory = new com.vividsolutions.jts.geom.GeometryFactory(); final Polygon jtsHolePolygon = geometryFactory .createPolygon(geometryFactory.createLinearRing(coordinates), null); final Point interiorPointJTS = jtsHolePolygon.getInteriorPoint(); try { final GM_Point interiorPoint = (GM_Point) JTSAdapter.wrap(interiorPointJTS, surfacePatch.getCoordinateSystem()); final TriangleHole hole = new TriangleHole(interiorPoint.getPosition()); holeList.add(hole); } catch (final GM_Exception e) { e.printStackTrace(); } i++; } } } if (!ArrayUtils.isEmpty(breaklines)) { // handle the breaklines for (final GM_Curve rawCurve : breaklines) { try { final GM_Curve curve = geoTransformer.transform(rawCurve); final GM_LineString lineString = curve.getAsLineString(); final GM_Position[] positions = lineString.getPositions(); for (int j = 0; j < positions.length - 1; j++) { final GM_Position position = positions[j]; final TriangleVertex vertex = createVertex(exportZ, position); nodeList.add(vertex); final TriangleSegment segment = new TriangleSegment(i, i + 1, 0); segmentList.add(segment); i++; } final GM_Position position = positions[positions.length - 1]; final TriangleVertex vertex = createVertex(exportZ, position); nodeList.add(vertex); i++; } catch (final GM_Exception | GeoTransformerException e) { e.printStackTrace(); } } } // collect the data final TrianglePolyFileData trianglePolyFileData = new TrianglePolyFileData(nodeList, segmentList, holeList); File tempDir = null; try { pwSimuLog = System.out; final String polyFileName = "input.poly"; //$NON-NLS-1$ final String[] args = Arrays.copyOf(m_triangleArgs, m_triangleArgs.length + 2); args[m_triangleArgs.length] = "-p"; //$NON-NLS-1$ args[m_triangleArgs.length + 1] = polyFileName; final IProcess process = KalypsoCommonsExtensions.createProcess( IProcessFactory.DEFAULT_PROCESS_FACTORY_ID, "Triangle", triangleExe.getName(), args);//$NON-NLS-1$ tempDir = new File(new URL(process.getSandboxDirectory()).getFile()); FileUtils.copyFileToDirectory(triangleExe, tempDir); final File polyfile = new File(tempDir, polyFileName); // prepare the polygon for output final IStatus writeStatus = trianglePolyFileData.writePolyFile(polyfile); if (writeStatus != Status.OK_STATUS) return null; // start Triangle process.startProcess(pwSimuLog, System.err, System.in, new ICancelable() { @Override public boolean isCanceled() { return false; } @Override public void cancel() { } }); // get the triangle list final File nodeFile = new File(tempDir, "input.1.node"); //$NON-NLS-1$ final File eleFile = new File(tempDir, "input.1.ele"); //$NON-NLS-1$ if (!nodeFile.exists() || !eleFile.exists()) { pwSimuLog.append( Messages.getString("org.kalypso.gml.processes.constDelaunay.ConstraintDelaunayHelper.31")); //$NON-NLS-1$ pwSimuLog.append( Messages.getString("org.kalypso.gml.processes.constDelaunay.ConstraintDelaunayHelper.32")); //$NON-NLS-1$ pwSimuLog.append( Messages.getString("org.kalypso.gml.processes.constDelaunay.ConstraintDelaunayHelper.33")); //$NON-NLS-1$ return null; } nodeReader = new BufferedReader(new InputStreamReader(new FileInputStream(nodeFile))); eleReader = new BufferedReader(new InputStreamReader(new FileInputStream(eleFile))); final GM_Position[] points = parseTriangleNodeOutput(nodeReader); final List<GM_Triangle> triangles = parseTriangleElementOutput(eleReader, crs, points); return triangles.toArray(new GM_Triangle[triangles.size()]); } catch (final Exception e) { e.printStackTrace(); return null; } finally { IOUtils.closeQuietly(nodeReader); IOUtils.closeQuietly(eleReader); if (tempDir != null && tempDir.exists()) { try { FileUtils.deleteDirectory(tempDir); } catch (final IOException e) { e.printStackTrace(); } } } }
From source file:org.kalypso.model.wspm.pdb.ui.internal.tin.exports.PdbExportOperation.java
@Override public void execute(final Session session) throws PdbConnectException { try {//from www . j av a 2 s . c o m final DhmIndex dhmIndex = m_settingsData.getDhmIndex(); // BUGFIX: ugly hack: oracle does not accept the empty string ('') as non-null. We alswas set the filename // to the unsused 'name' dhmIndex.setName(dhmIndex.getFilename()); /* force geometries to be 3D, else Oracle whines. */ // REMARK: we must make sure that the z value is in the range of valid z values.... final double minZ = m_settingsData.getConnection().getInfo().getSrsMinZ(); final Polygon location = dhmIndex.getLocation(); final LineString exteriorRing = location.getExteriorRing(); final CoordinateSequence coordinateSequence = exteriorRing.getCoordinateSequence(); final int size = coordinateSequence.size(); for (int i = 0; i < size; i++) coordinateSequence.setOrdinate(i, 2, minZ); final IPath demServerPath = m_settingsData.getDemServerPath(); final File[] sourceFiles = m_settingsData.getRealSourceFiles(); session.saveOrUpdate(dhmIndex); /* copy all source files to the server directory */ final File targetDir = demServerPath.toFile(); for (final File sourceFile : sourceFiles) FileUtils.copyFileToDirectory(sourceFile, targetDir); } catch (final HibernateException ex) { throw new PdbConnectException(Messages.getString("PdbExportOperation_1"), ex); //$NON-NLS-1$ } catch (final IOException ex) { throw new PdbConnectException(Messages.getString("PdbExportOperation_2"), ex); //$NON-NLS-1$ } }
From source file:org.kalypso.model.wspm.tuhh.schema.simulation.PolynomeProcessor.java
public File processPolynomes() throws SimulationException { final ISimulationMonitor monitor = m_log.getMonitor(); m_log.log(true, Messages.getString("org.kalypso.model.wspm.tuhh.schema.simulation.PolynomeProcessor.3")); //$NON-NLS-1$ m_log.log(true, Messages.getString("org.kalypso.model.wspm.tuhh.schema.simulation.PolynomeProcessor.4")); //$NON-NLS-1$ final File eingangDir = preparePolynomes(); final File resultDir = new File(m_tmpDir, "02Ausgang"); //$NON-NLS-1$ /* Need to create result-dir, else the calculation does not work */ resultDir.mkdirs();/*from w w w.j a va 2s . c o m*/ if (eingangDir == null) return null; if (monitor.isCanceled()) return null; m_log.log(true, Messages.getString("org.kalypso.model.wspm.tuhh.schema.simulation.PolynomeProcessor.5")); //$NON-NLS-1$ prepareSteuerpoly(); if (monitor.isCanceled()) return null; final File logFile = new File(m_tmpDir, "Polynome1d.log"); //$NON-NLS-1$ final File errFile = new File(m_tmpDir, "Polynome1d.err"); //$NON-NLS-1$ OutputStream logStream = null; OutputStream errStream = null; try { logStream = new BufferedOutputStream(new FileOutputStream(logFile)); errStream = new BufferedOutputStream(new FileOutputStream(errFile)); /* Start the polynome1d process */ final File exeFile = WspmTuhhCalcJob.getExecuteable(m_calculation, m_tmpDir, POLYNOME_1D_EXE_FORMAT, POLYNOME_1D_EXE_PATTERN, monitor); if (exeFile == null) throw new SimulationException("Couldn't resolve Polynome1d.exe"); //$NON-NLS-1$ final String cmdLine = "cmd.exe /C \"" + exeFile.getAbsolutePath() + "\""; //$NON-NLS-1$ //$NON-NLS-2$ ProcessHelper.startProcess(cmdLine, null, m_tmpDir, monitor, TIMEOUT, logStream, errStream, null); logStream.close(); errStream.close(); /* The weir and brigde files are not processed by the polynome.exe, just copy it to the result-folder */ FileUtils.copyFileToDirectory(new File(eingangDir, WEIR_FILE_NAME), resultDir); FileUtils.copyFileToDirectory(new File(eingangDir, BRIDGE_FILE_NAME), resultDir); } catch (final IOException e) { m_log.log(e, Messages.getString("org.kalypso.model.wspm.tuhh.schema.simulation.PolynomeProcessor.8") //$NON-NLS-1$ + e.getLocalizedMessage()); monitor.setFinishInfo(IStatus.ERROR, Messages.getString("org.kalypso.model.wspm.tuhh.schema.simulation.PolynomeProcessor.9")); //$NON-NLS-1$ throw new SimulationException( Messages.getString("org.kalypso.model.wspm.tuhh.schema.simulation.PolynomeProcessor.10") //$NON-NLS-1$ + e.getLocalizedMessage(), e); } catch (final ProcessTimeoutException e) { m_log.log(false, Messages.getString("org.kalypso.model.wspm.tuhh.schema.simulation.PolynomeProcessor.11")); //$NON-NLS-1$ monitor.setFinishInfo(IStatus.ERROR, Messages.getString("org.kalypso.model.wspm.tuhh.schema.simulation.PolynomeProcessor.11")); //$NON-NLS-1$ return null; } finally { IOUtils.closeQuietly(logStream); IOUtils.closeQuietly(errStream); } if (m_log.checkCanceled()) return null; return resultDir; }