List of usage examples for org.apache.commons.io FilenameUtils removeExtension
public static String removeExtension(String filename)
From source file:com.uwsoft.editor.data.manager.TextureManager.java
public void loadCurrentProjectSpineAnimations(String path, String curResolution) { spineAnimAtlases.clear();/*from w w w . j a v a 2s.c o m*/ FileHandle sourceDir = new FileHandle(path + "orig/spine-animations"); for (FileHandle entry : sourceDir.list()) { if (entry.file().isDirectory()) { String animName = FilenameUtils.removeExtension(entry.file().getName()); TextureAtlas atlas = new TextureAtlas(Gdx.files.internal(path + curResolution + "/spine-animations/" + File.separator + animName + File.separator + animName + ".atlas")); FileHandle animJsonFile = Gdx.files .internal(entry.file().getAbsolutePath() + File.separator + animName + ".json"); SpineAnimData data = new SpineAnimData(); data.atlas = atlas; data.jsonFile = animJsonFile; data.animName = animName; spineAnimAtlases.put(animName, data); } } }
From source file:com.liferay.sync.engine.SyncSystemTest.java
@Test public void run() throws Exception { SyncEngine.start();//w w w . j a v a2 s . c o m _rootFilePathName = FileUtil.getFilePathName(System.getProperty("user.home"), "liferay-sync-test"); _syncAccount = SyncAccountService.addSyncAccount(FileUtil.getFilePathName(_rootFilePathName, "test"), "test@liferay.com", Integer.MAX_VALUE, "test", "test", 5, null, false, "http://localhost:8080"); SyncAccountService.update(_syncAccount); long guestGroupId = SyncSystemTestUtil.getGuestGroupId(_syncAccount.getSyncAccountId()); _syncSiteIds.put("Guest", guestGroupId); BufferedReader bufferedReader = Files.newBufferedReader(_testFilePath, Charset.defaultCharset()); ObjectMapper objectMapper = new ObjectMapper(); JsonNode rootJsonNode = objectMapper.readTree(bufferedReader); executeSteps(_testFilePath, rootJsonNode); Path testFileNameFilePath = _testFilePath.getFileName(); String testFileName = testFileNameFilePath.toString(); _logger.info("Test {} passed.", FilenameUtils.removeExtension(testFileName)); }
From source file:de.uzk.hki.da.cb.ConvertAction.java
private void removeDAFileFromDocument(Object o, DAFile file) { Document doc = o.getDocument(FilenameUtils.removeExtension(file.getRelative_path())); if (doc == null) { throw new IllegalStateException("Cannot add new dafile to document " + FilenameUtils.removeExtension(file.getRelative_path()) + "."); } else {// w ww . j a v a 2 s . c o m logger.debug("Remove from document " + file); boolean removed = doc.removeDAFile(file); if (!removed) logger.warn("Remove from document not succesful for dafile " + file); } }
From source file:edu.cornell.med.icb.goby.modes.RunParallelMode.java
public void execute() throws IOException { final Slice slices[] = new Slice[numParts]; File file = new File(input); if (!(file.isFile() && file.exists() && file.canRead())) { System.err.println("Input file cannot be read: " + input); System.exit(1);// ww w . ja v a 2s . c o m } int i = 0; for (final Slice slice : slices) { slices[i++] = new Slice(); } final long fileLength = file.length(); final long sliceLength = fileLength / numParts; long currentOffset = 0; for (final Slice slice : slices) { slice.startOffset = currentOffset; slice.endOffset = currentOffset + sliceLength; currentOffset = slice.endOffset; } final ObjectOpenHashSet<String> allOutputs = new ObjectOpenHashSet<String>(); final ObjectOpenHashSet<String> allFastq = new ObjectOpenHashSet<String>(); final DoInParallel loop = new DoInParallel(numParts) { IsDone done = new IsDone(); @Override public void action(final DoInParallel forDataAccess, final String inputBasename, final int loopIndex) { try { CompactToFastaMode ctfm = new CompactToFastaMode(); ctfm.setInputFilename(input); ctfm.setOutputFormat(CompactToFastaMode.OutputFormat.FASTQ); ctfm.setStartPosition(slices[loopIndex].startOffset); ctfm.setEndPosition(slices[loopIndex].endOffset); String s = FilenameUtils.getBaseName(FilenameUtils.removeExtension(input)) + "-" + Integer.toString(loopIndex); String fastqFilename = s + "-input.fq"; allFastq.add(fastqFilename); File tmp1 = new File(s + "-tmp"); tmp1.deleteOnExit(); File output = new File(s + "-out"); output.deleteOnExit(); ctfm.setOutputFilename(fastqFilename); LOG.info(String.format("Extracting FASTQ for slice [%d-%d] loopIndex=%d %n", slices[loopIndex].startOffset, slices[loopIndex].endOffset, loopIndex)); ctfm.execute(); if (loopIndex > 0) { while (!done.isDone()) { // wait a bit to give the first thread the time to load the database and establish shared memory pool // System.out.println("sleep 5 thread "+loopIndex); sleep(5); } System.out.println("Thread " + loopIndex + " can now start."); } final Map<String, String> replacements = new HashMap<String, String>(); final String outputFilename = output.getName(); replacements.put("%read.fastq%", fastqFilename); replacements.put("%tmp1%", tmp1.getName()); replacements.put("%output%", outputFilename); final String transformedCommand = transform(processPartCommand, replacements); final DefaultExecutor executor = new DefaultExecutor(); OutputStream logStream = null; try { logStream = new LoggingOutputStream(getClass(), Level.INFO, ""); executor.setStreamHandler( new PumpStreamHandler(new StreamSignal(done, "scanning", logStream))); final CommandLine parse = CommandLine.parse(transformedCommand, replacements); LOG.info("About to execute: " + parse); final int exitValue = executor.execute(parse); LOG.info("Exit value = " + exitValue); if (new File(outputFilename + ".header").exists()) { // found output alignment: System.out.println("found output file: " + outputFilename); allOutputs.add(outputFilename + ".header"); } else { System.out.println("Warning: did not find output alignment: " + outputFilename); } } finally { IOUtils.closeQuietly(logStream); // remove the fastq file new File(fastqFilename).delete(); } } catch (IOException e) { LOG.error("Error processing index " + loopIndex + ", " + inputBasename, e); } } }; String[] parts = new String[numParts]; for (int j = 0; j < numParts; j++) { parts[j] = Integer.toString(j); } try { loop.execute(true, parts); } catch (Exception e) { System.err.println("An error occurred executing a parallel command: "); e.printStackTrace(); } System.out.printf("Preparing to concatenate %d outputs..%n", allOutputs.size()); final ConcatenateAlignmentMode concat = new ConcatenateAlignmentMode(); concat.setInputFileNames(allOutputs.toArray(new String[allOutputs.size()])); concat.setOutputFilename(output); concat.setAdjustQueryIndices(false); concat.setAdjustSampleIndices(false); concat.execute(); }
From source file:edu.cornell.med.icb.goby.alignments.AlignmentReaderImpl.java
/** * Returns true if filename belongs to an alignment basename that can be read. * * @param filename Filename of an alignment component. * @return True if the alignment can be read, false otherwise. *///from ww w . j a v a2s. c o m public static boolean canRead(final String filename) { final String filenameNoExtension = FilenameUtils.removeExtension(filename); String fileExtension = FilenameUtils.getExtension(filename); if (!ArrayUtils.contains(AlignmentReaderImpl.COMPACT_ALIGNMENT_FILE_REQUIRED_EXTS, "." + fileExtension) && !ArrayUtils.contains(AlignmentReaderImpl.COMPACT_ALIGNMENT_FILE_POSSIBLE_EXTS, "." + fileExtension)) { // the file does not contain any of the Goby required or possible extensions. It is not a supported file. return false; } // the file contains a Goby alignment extension, we further check that each needed extension exists: int count = 0; for (final String extension : AlignmentReaderImpl.COMPACT_ALIGNMENT_FILE_REQUIRED_EXTS) { if (RepositionableInputStream.resourceExist(filenameNoExtension + extension)) { // we can read this file. count++; } } return count == AlignmentReaderImpl.COMPACT_ALIGNMENT_FILE_REQUIRED_EXTS.length; }
From source file:it.isislab.dmason.util.SystemManagement.Worker.thrower.DMasonWorker.java
/** * Constructor./*from w ww .j a v a2 s . com*/ * @param ip IP Address of the provider. * @param port Port where the provider is listening. * @param topic */ public DMasonWorker(String ip, String port, String topic) { DMasonWorker.ip = ip; DMasonWorker.port = port; if (!autoStart) { beaconListener = new BeaconMessageListener(); beaconListener.addObserver(this); new Thread(beaconListener).start(); while (!isReady) { lock.lock(); { try { readyCondition.await(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } //wait beacon } lock.unlock(); } isReady = false; } connection = new ConnectionNFieldsWithActiveMQAPI(); ipAddress = new Address(DMasonWorker.ip, DMasonWorker.port); myTopic = topic; // Get the path from which worker was started String path; try { path = URLDecoder.decode( DMasonWorkerWithGui.class.getProtectionDomain().getCodeSource().getLocation().getFile(), "UTF-8"); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); path = ""; } logger.debug("Path: " + path); if (path.contains(".jar")) //from jar { File jarfile = new File(path); Digester dg = new Digester(DigestAlgorithm.MD5); try { InputStream in = new FileInputStream(path); digest = dg.getDigest(in); String fileName = FilenameUtils.removeExtension(jarfile.getName()); //save properties to project root folder dg.storeToPropFile(fileName + ".hash"); } catch (IOException ex) { ex.printStackTrace(); } catch (NoDigestFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { // not from jar digest = null; } }
From source file:com.opendoorlogistics.core.geometry.ImportShapefile.java
/** * Import the shapefile. All geometry is transformed into WGS84. * /*from w w w . j av a2s. c o m*/ * @param file * @param ds */ @SuppressWarnings("deprecation") public static HashMap<ShapefileLink, ODLGeom> importShapefile(File file, boolean isLinkedGeometry, ODLDatastoreAlterable<? extends ODLTableAlterable> ds, boolean returnGeometry) { Spatial.initSpatial(); file = RelativeFiles.validateRelativeFiles(file.getPath(), AppConstants.SHAPEFILES_DIRECTORY); if (file == null) { return new HashMap<>(); } // check if we're actually opening a render optimised geometry file... do something if we are? String ext = FilenameUtils.getExtension(file.getAbsolutePath()); boolean isRog = Strings.equalsStd(ext, RogReaderUtils.RENDER_GEOMETRY_FILE_EXT); File originalFile = file; List<ODLRenderOptimisedGeom> rogs = null; if (isRog) { rogs = new LargeList<>(); RogSingleton.singleton().createLoader(file, rogs); // get the shapefile from the main one String shpFile = FilenameUtils.removeExtension(file.getPath()) + ".shp"; file = new File(shpFile); } SimpleFeatureIterator it = null; DataStore shapefile = null; // create return object HashMap<ShapefileLink, ODLGeom> ret = null; if (returnGeometry) { ret = new HashMap<>(); } try { shapefile = openDataStore(file); if (shapefile == null) { throw new RuntimeException("Could not open shapefile: " + file); } // get the linkfile using the *original file*, not the potentially redirected file String linkFile = RelativeFiles.getFilenameToSaveInLink(originalFile, AppConstants.SHAPEFILES_DIRECTORY); for (String type : shapefile.getTypeNames()) { // make table ODLTableAlterable table = null; if (ds != null) { String tableName = type; if (TableUtils.findTable(ds, tableName) != null) { tableName = TableUtils.getUniqueNumberedTableName(type, ds); } table = ds.createTable(type, -1); } // add columns for each usable feature SimpleFeatureType schema = shapefile.getSchema(type); int nAttrib = schema.getAttributeCount(); int[] mapped = new int[nAttrib]; Arrays.fill(mapped, -1); if (ds != null) { for (int i = 0; i < nAttrib; i++) { AttributeType attributeType = schema.getType(i); Class<?> binding = attributeType.getBinding(); ODLColumnType colType = BeanTypeConversion.getInternalType(binding); if (colType != null) { String attributeName = schema.getDescriptor(i).getLocalName(); if (table.addColumn(i, attributeName, colType, 0) != -1) { mapped[i] = table.getColumnCount() - 1; if (colType == ODLColumnType.GEOM) { table.setColumnTags(mapped[i], Strings.toTreeSet(PredefinedTags.GEOMETRY)); } } } } } // get coord transform to turn into wgs84 long-lat MathTransform toWGS84 = getTransformToWGS84(shapefile, type); SimpleFeatureSource source = shapefile.getFeatureSource(type); SimpleFeatureCollection collection = source.getFeatures(); // parse all features recording all attributes, including geometry it = collection.features(); int objectIndex = 0; while (it.hasNext()) { SimpleFeature feature = it.next(); //System.out.println(feature.getID()); if (SimpleFeature.class.isInstance(feature)) { SimpleFeature sf = (SimpleFeature) feature; // create row if we're outputting to a datastore int row = -1; if (ds != null) { row = table.createEmptyRow(-1); } for (int i = 0; i < nAttrib; i++) { Object value = sf.getAttribute(i); // process geometry ShapefileLink link = null; if (value != null && Geometry.class.isInstance(value)) { if (!isLinkedGeometry || ret != null) { if (rogs != null) { value = rogs.get(objectIndex); } else { // Transform the geometry to wgs84 if we need it value = JTS.transform((Geometry) value, toWGS84); value = new ODLLoadedGeometry((Geometry) value); } } else { // Geometry not needed value = null; } // Create geometry link link = new ShapefileLink(linkFile, type, sf.getID()); // Save the transformed geometry if flagged if (ret != null) { ret.put(link, (ODLGeom) value); } // If we're using linked geometry the value for the table is the link if (isLinkedGeometry) { value = new ODLShapefileLinkGeom(link); } } // save to table if mapped int col = mapped[i]; if (col != -1) { ODLColumnType odlType = table.getColumnType(col); value = ColumnValueProcessor.convertToMe(odlType, value); table.setValueAt(value, row, col); } } objectIndex++; } else { throw new RuntimeException(); } } } } catch (Throwable e) { throw new RuntimeException(e); } finally { if (it != null) { it.close(); } if (shapefile != null) { shapefile.dispose(); } } return ret; }
From source file:de.uzk.hki.da.core.RegisterObjectService.java
/** * Compares the csn/origName pair of a SIP which identifies an object uniquely against the database. * If there is a match, the SIP is considered a delta. If not is considered a primary import. * <br><br>/*www .j a v a2s . c o m*/ * If the SIP is a delta, a new package gets created and attached to the object (which gets fetched from db). * If it is a primary import, a new object gets created. In this case a new technical identifier gets created, which * is base on the nodes urn index and the preservation systems urnNameSpace. The nodes urn index gets incremented when * generating the identifier. The database record gets updated. For security reasons the the object database gets checked of * the identifier does not already exist. * * @param containerName the file name of the SIP container * @param contractor the contractor who owns the container * * @throws UserException when trying to register a delta record for an object which is not archived (<50) yet * @throws IllegalStateException if the system tries to generate an identifier for which an object already exists. * * @return the object. */ public Object registerObject(String containerName, User contractor) { if (!initialized) throw new IllegalStateException("call init first"); if (contractor == null) throw new IllegalArgumentException("contractor is null"); if (contractor.getShort_name() == null || contractor.getShort_name().isEmpty()) throw new IllegalArgumentException("contractor short name not set"); String origName = convertMaskedSlashes(FilenameUtils.removeExtension(containerName)); Object obj; if ((obj = (new ObjectNamedQueryDAO().getUniqueObject(origName, contractor.getShort_name()))) != null) { // is delta then logger.info("Package is a delta record for Object with identifier: " + obj.getIdentifier()); updateExistingObject(obj, containerName); } else { final String technicalIdentifier = convertURNtoTechnicalIdentifier(generateURNForNode(localNodeId)); // check identifier if (getUniqueObject(technicalIdentifier) != null) throw new IllegalStateException("CRITICAL SYSTEM ERROR: DUPLICATE IDENTIFIER"); logger.info("Creating new Object with identifier " + technicalIdentifier); obj = createNewObject(containerName, origName, contractor); obj.setIdentifier(technicalIdentifier); } return obj; }
From source file:com.doplgangr.secrecy.filesystem.encryption.AES_ECB_Crypter.java
@Override public void renameFile(File file, String newName) throws SecrecyCipherStreamException, FileNotFoundException { File parent = file.getParentFile(); newName = FilenameUtils.removeExtension(newName); newName = Base64Coder.encodeString(newName); newName += "." + FilenameUtils.getExtension(file.getName()); file.renameTo(new File(parent, newName)); }
From source file:com.ibm.bluemix.samples.PostgreSQLReportedErrors.java
/** * Retrieve the file information/*from ww w . j a va 2s . co m*/ * * @return JSON object with file information * @throws Exception TODO describe exception */ public JSONObject getFileInfo(String entryId) throws Exception { String sql = "SELECT * FROM reportedErrors WHERE entry_id = " + entryId; Connection connection = null; PreparedStatement statement = null; ResultSet results = null; try { connection = getConnection(); statement = connection.prepareStatement(sql); results = statement.executeQuery(); results.next(); JSONObject infoObject = new JSONObject(); infoObject.put("entry_id", Integer.toString(results.getInt("entry_id"))); infoObject.put("file_name", results.getString("file_name")); infoObject.put("s_language", results.getString("s_language")); infoObject.put("nlp_parser", results.getString("nlp_parser")); infoObject.put("upload_date", results.getDate("upload_date").toString()); infoObject.put("output_name", FilenameUtils.removeExtension(results.getString("file_name")) + ".xml"); return infoObject; } finally { if (results != null) { results.close(); } if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } }