List of usage examples for java.io File toURI
public URI toURI()
From source file:fr.inrialpes.exmo.align.cli.GroupAggreg.java
public void iterateAlignments(File dir) { String prefix = dir.toURI().toString() + File.separator; Set<BasicAlignment> listal = new HashSet<BasicAlignment>(); // for all alignments there, for (String m : listAlgo) { BasicAlignment al = loadAlignment(prefix + m + ".rdf"); if (al != null) listal.add(al);/*from w ww .ja v a 2s.c o m*/ } Alignment result = null; try { // Depends on the method result = BasicAlignment.aggregate(aggMethod, listal); } catch (AlignmentException alex) { logger.debug("IGNORED: cannot aggregate for {}", prefix, alex); return; } // Thresholding try { if (threshold != 0) result.cut(cutMethod, threshold); } catch (AlignmentException alex) { logger.debug("IGNORED: Cannot trim alignment {} {}", cutMethod, threshold, alex); } // This should be printed now print(result, dir.getName() + ".rdf"); }
From source file:com.tobedevoured.solrsail.SolrConfig.java
/** * Install Solr Config to the local file system * /*from w ww .ja v a 2 s . c o m*/ * @throws IOException * @throws URISyntaxException */ @Command public void install() throws IOException, URISyntaxException { File jar = new File(this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI()); if (jar.toURI().getPath().endsWith(".jar") && jar.exists()) { installFromJar(jar); } else { installFromClasspath(); } }
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();// w w w . j ava 2 s.c o m 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.panet.imeta.core.xml.XMLHandler.java
public static final Document loadXMLFile(File resource) throws KettleXMLException { try {/*w w w . j av a 2 s. c om*/ return loadXMLFile(resource.toURI().toURL()); } catch (MalformedURLException e) { throw new KettleXMLException(e); } }
From source file:com.tibco.tgdb.test.lib.TGAdmin.java
/** * Invoke TG admin synchronously. //from www . j a v a2 s . c o m * Admin operation blocks until it is completed. * * @param tgHome TG admin home * @param url Url to connect to TG server * @param user System User name * @param pwd System User password * @param logFile TG admin log file location - Generated by admin * @param logLevel Specify the log level: info/user1/user2/user3/debug/debugmemory/debugwire * @param cmd TG admin command file or command string * @param memSize Specify the maximum memory usage (MB). -1 for default (8 MB) * @param timeout Number of milliseconds allowed to complete admin operation * * @return Output console of admin operation * @throws TGAdminException Admin execution fails or timeout occurs */ public static String invoke(String tgHome, String url, String user, String pwd, String logFile, String logLevel, String cmd, int memSize, long timeout) throws TGAdminException { if (tgHome == null) throw new TGAdminException("TGAdmin - TGDB home is not defined"); File ftgHome = new File(tgHome); if (!ftgHome.exists()) throw new TGAdminException("TGAdmin - TGDB home '" + tgHome + "' does not exist"); ByteArrayOutputStream output = new ByteArrayOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(output); Executor tgExec = new DefaultExecutor(); tgExec.setStreamHandler(psh); tgExec.setWorkingDirectory(new File(tgHome + "/bin")); CommandLine tgCL = new CommandLine((new File(tgHome + "/bin/" + process)).getAbsolutePath()); // Define arguments List<String> args = new ArrayList<String>(); if (url != null) { args.add("--url"); args.add(url); } if (user != null) { args.add("--uid"); args.add(user); } if (pwd != null) { args.add("--pwd"); args.add(pwd); } if (logFile != null) { args.add("--log"); args.add(logFile); } if (logLevel != null) { args.add("--log-level"); args.add(logLevel); } if (memSize >= 0) { args.add("--max-memory"); args.add(Integer.toString(memSize)); } File cmdFile = null; if (cmd == null) throw new TGAdminException("TGAdmin - Command is required."); if (cmd.matches( "(?s)^(kill|show|describe|create|stop|info|checkpoint|dump|set|connect|disconnect|export|import|exit).*$")) { try { cmdFile = new File(tgHome + "/invokeAdminScript.txt"); Files.write(Paths.get(cmdFile.toURI()), cmd.getBytes(StandardCharsets.UTF_8)); } catch (IOException ioe) { throw new TGAdminException("TGAdmin - " + ioe.getMessage()); } } else { cmdFile = new File(cmd); } if (!cmdFile.exists()) { throw new TGAdminException("TGAdmin - Command file '" + cmdFile + "' does not exist"); } args.add("--file"); args.add(cmdFile.getAbsolutePath()); tgCL.addArguments((String[]) args.toArray(new String[args.size()])); ExecuteWatchdog tgWatch = new ExecuteWatchdog(timeout); tgExec.setWatchdog(tgWatch); System.out.println("TGAdmin - Invoking " + StringUtils.toString(tgCL.toStrings(), " ")); long endProcTime = 0; long totalProcTime = 0; try { TGAdmin.startProcTime = System.currentTimeMillis(); tgExec.execute(tgCL); endProcTime = System.currentTimeMillis(); } catch (IOException ee) { if (tgWatch.killedProcess()) throw new TGAdminException("TGAdmin - Operation did not complete within " + timeout + " ms", output.toString()); else { try { Thread.sleep(1000); // make sure output has time to fill up } catch (InterruptedException ie) { ; } throw new TGAdminException("TGAdmin - Execution failed: " + ee.getMessage(), output.toString()); } } if (url != null && !output.toString().contains("Successfully connected to server")) throw new TGAdminException("TGAdmin - Admin could not connect to server " + url + " with user " + user, output.toString()); if (endProcTime != 0) totalProcTime = endProcTime - TGAdmin.startProcTime; if (TGAdmin.showOperationBanner) System.out.println( "TGAdmin - Operation completed" + (totalProcTime > 0 ? " in " + totalProcTime + " msec" : "")); return output.toString(); }
From source file:eu.artist.methodology.mpt.webapp.config.ListFileHandlerBean.java
public void save() throws IOException { String path_to_properties_file = getMptProperties().getProperty("path_to_reports") + "\\" + CurrentSession.getUserName() + "\\mpt" + CurrentSession.getUserName() + ".properties"; checkPropertiesFile(path_to_properties_file); logger.debug("Path to properties file is " + path_to_properties_file); try {//from www . ja v a2 s.c o m File f = new File(path_to_properties_file); URL url = f.toURI().toURL(); logger.debug("File URL is " + url.toString()); logger.info("Configuration saved"); logger.debug("Selected file is " + selectedFile); PropertiesConfiguration config = new PropertiesConfiguration(url); String chosenButton = CurrentSession.getExternalContext().getRequestParameterMap().get("button"); String propertyToSet = null; if ("mat".equalsIgnoreCase(chosenButton)) { propertyToSet = "mat_report"; } else if ("tft".equalsIgnoreCase(chosenButton)) { propertyToSet = "tft_report"; } else if ("bft".equalsIgnoreCase(chosenButton)) { propertyToSet = "bft_report"; } else if ("mig".equalsIgnoreCase(chosenButton)) { propertyToSet = "mig_report"; } config.setProperty(propertyToSet, "\\" + selectedFile); config.save(); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Configuration saved")); } catch (Exception e) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Configuration failed")); logger.error("Configuration not saved"); e.printStackTrace(); } }
From source file:de.tudarmstadt.ukp.dkpro.keyphrases.core.evaluator.KeyphraseEvaluatorTest.java
@Test public void testKeyphraseEvaluator() throws Exception { String documentText = "The added keyphrases should be found in this text. With the exception of one example."; File tmpFile = workdir.newFile(resultFileName); AnalysisEngine ae = AnalysisEngineFactory.createEngine(KeyphraseEvaluator.class, KeyphraseEvaluator.PARAM_N, 3, KeyphraseEvaluator.PARAM_RESULT_FILE, tmpFile.toString(), KeyphraseEvaluator.PARAM_EVAL_TYPE, EvaluatorType.Token.toString(), KeyphraseEvaluator.PARAM_REMOVE_GOLD_AFTER_MATCH, true); JCas jcas = ae.newJCas();/*from ww w . j ava 2s. c o m*/ jcas.setDocumentText(documentText); File testFile = new File("src/test/resources/keyphrase/evaluator/test.txt"); DocumentMetaData meta = DocumentMetaData.create(jcas); meta.setDocumentUri(testFile.toURI().toString()); Keyphrase k1 = new Keyphrase(jcas); k1.setKeyphrase("keyphrases"); k1.setScore(0.7); k1.addToIndexes(); Keyphrase k2 = new Keyphrase(jcas); k2.setKeyphrase("exception"); k2.setScore(0.5); k2.addToIndexes(); Keyphrase k3 = new Keyphrase(jcas); k3.setKeyphrase("not_a_valid_keyphrase"); k3.setScore(0.3); k3.addToIndexes(); ae.process(jcas); ae.collectionProcessComplete(); if (!tmpFile.exists()) { fail("Result file not correctly written."); } System.out.println(FileUtils.readFileToString(tmpFile, "UTF-8")); }
From source file:org.fast.maven.plugin.AssemblyMojo.java
/** * Return relative path// www. j a v a 2s .co m * * @param directory * @param file * @return */ private String getRelativePath(File directory, File file) { return directory.toURI().relativize(file.toURI()).getPath(); }
From source file:org.jresponder.standalone.JrXmlWebApplicationContext.java
@SuppressWarnings({ "rawtypes", "unchecked" }) @Override/*from w w w . j av a 2s. c o m*/ public void setConfigLocations(String[] locations) { List myLocations = new ArrayList(Arrays.asList(locations)); File myConfigFile = JrContextLoaderListener.getExternalConfigFile(); if (myConfigFile != null) { //System.out.println(myConfigFile.toURI().toString()); myLocations.add(myConfigFile.toURI().toString()); } // HACK: this isn't the greatest, but works for now - set the // Spring profile, so we can make certain Spring context files // conditional depending on the deployment mode if (JrContextLoaderListener.isStandaloneMode()) { System.out.println("JrXmlWebApplication - using 'standalone' Spring profile"); getEnvironment().setActiveProfiles("standalone"); } else { System.out.println("JrXmlWebApplication - using 'webapp' Spring profile"); getEnvironment().setActiveProfiles("webapp"); } super.setConfigLocations((String[]) myLocations.toArray(new String[0])); }
From source file:com.evolveum.midpoint.common.LocalizationServiceImpl.java
private URL buildMidpointHomeLocalizationFolderUrl() { String midpointHome = System.getProperty("midpoint.home"); File file = new File(midpointHome, "localization"); try {/* w ww .ja v a 2s . co m*/ return file.toURI().toURL(); } catch (IOException ex) { throw new SystemException("Couldn't transform localization folder file to url", ex); } }