org.apache.commons.io.FilenameUtils Java Examples

The following examples show how to use org.apache.commons.io.FilenameUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ZipReport.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
private void zipFile(IWorkspaceDispatcher dispatcher, ZipOutputStream zip, String relativeFile, String zipFolder) throws IOException {

        zipFolder = buildPath(zipFolder, FilenameUtils.getName(relativeFile));

        byte[] buf = new byte[1024];

        zip.putNextEntry(new ZipEntry(zipFolder));

        try (InputStream inputStream = new FileInputStream(dispatcher.getFile(FolderType.REPORT, relativeFile))) {
            int len;
            while ((len = inputStream.read(buf)) > 0) {
                zip.write(buf, 0, len);
            }
        } finally {
            zip.closeEntry();
        }
    }
 
Example #2
Source File: CrushedPNGFileSystem.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public void open(TaskMonitor monitor) throws IOException, CryptoException, CancelledException {
	BinaryReader reader = new BinaryReader(provider, false);

	monitor.setMessage("Opening iOS Crushed PNG...");
	this.png = new ProcessedPNG(reader, monitor);

	String uncrushedPngFilename = getName();

	//Remove the .png extension and then replace with .uncrushed.png extension
	if ("png".equalsIgnoreCase(FilenameUtils.getExtension(uncrushedPngFilename))) {
		uncrushedPngFilename =
			FilenameUtils.removeExtension(uncrushedPngFilename) + ".uncrushed.png";
	}

	pngGFile = GFileImpl.fromFilename(this, root, uncrushedPngFilename, false, 1, null);
}
 
Example #3
Source File: AbstractMultiInstanceResource.java    From entando-components with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Returns the correct name of a resource to be saved in the system.
 * @param masterFileName Original file name
 * @param size Order number of the file being saved
 * @param langCode Language code of file being saved
 * @return Correct name to save file
 */
String getNewInstanceFileName(String masterFileName, int size, String langCode) {
    String baseName = FilenameUtils.getBaseName(masterFileName);
    String extension = FilenameUtils.getExtension(masterFileName);
    String suffix = "";
    if (size >= 0) {
        suffix += "_d" + size;
    }
    if (langCode != null) {
        suffix += "_" + langCode;
    }
    return this.createFileName(
            super.getMultiFileUniqueBaseName(baseName, suffix, extension),
            extension
    );
}
 
Example #4
Source File: ConfigurationUtils.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public static void writeConfig(String configDirPath, Configuration configuration, boolean forceWrite) throws Exception {
  File configDir = new File(configDirPath);
  if (!configDir.exists()) {
    configDir.mkdirs();
  }
  String dirPath = FilenameUtils.concat(configDirPath, configuration.getConfigName());
  File file = new File(dirPath);
  if (!file.exists()) {
    if (!file.mkdir()) {
      //TODO : Throw some exception instead of quietly returning 
      throw new Exception("Cannot create directory on this machine");
    }
  }
    
  if(configuration.isPropertiesFileChanged() || forceWrite) {
    writePropeties(dirPath, configuration);
  }
  if (configuration.isCacheXmlModified() || forceWrite) {
    writeCacheXml(dirPath, configuration);
  }
}
 
Example #5
Source File: AttachmentController.java    From activiti-in-action-codes with Apache License 2.0 6 votes vote down vote up
/**
 * 文件类型的附件
 */
@RequestMapping(value = "new/file")
public String newFile(@RequestParam("taskId") String taskId, @RequestParam(value = "processInstanceId", required = false) String processInstanceId,
                      @RequestParam("attachmentName") String attachmentName, @RequestParam(value = "attachmentDescription", required = false) String attachmentDescription,
                      @RequestParam("file") MultipartFile file, HttpSession session) {
    try {
        String attachmentType = file.getContentType() + ";" + FilenameUtils.getExtension(file.getOriginalFilename());
        identityService.setAuthenticatedUserId(UserUtil.getUserFromSession(session).getId());
        Attachment attachment = taskService.createAttachment(attachmentType, taskId, processInstanceId, attachmentName, attachmentDescription,
                file.getInputStream());
        taskService.saveAttachment(attachment);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "redirect:/chapter6/task/getform/" + taskId;
}
 
Example #6
Source File: ResponseUtils.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Prepares download of a file. The content type will be detected automatically by the file name.
 *
 * @param filename Virtual file name. Any path infos will be truncated.
 * @param response
 * @param ctx der Servletcontext
 * @param attach Download as Attachment
 */
public static void prepareDownload(String filename, HttpServletResponse response, ServletContext ctx, boolean attach)
{
  String mimeType = null;
  try {
    mimeType = ctx.getMimeType(filename);
  } catch (Exception ex) {
    log.info("Exception while getting mime-type (using application/binary): " + ex);
  }
  if (mimeType == null) {
    response.setContentType("application/binary");
  } else {
    response.setContentType(mimeType);
  }
  log.debug("Using content-type " + mimeType);
  final String filenameWithoutPath = FilenameUtils.getName(filename);
  if (attach == true) {
    response.setHeader("Content-disposition", "attachment; filename=\"" + filenameWithoutPath + "\"");
  } else {
    response.setHeader("Content-disposition", "inline; filename=\"" + filenameWithoutPath + "\"");
  }
}
 
Example #7
Source File: CompileDriver.java    From xds-ide with Eclipse Public License 1.0 6 votes vote down vote up
public List<String> getModuleList(String srcFile, String prjFile) {
    final List<String> moduleList = new ArrayList<String>();
    if (prjFile == null) {
        doCompile( sdk, CompilationMode.MAKE_MODULE_LIST
                 , srcFile, null
                 , new ModuleListListener(moduleList, FilenameUtils.getFullPath(srcFile)) );
    } else {
        File workDirectory = (new File(prjFile)).getParentFile();
        String arguments = "-prj=" + prjFile; //$NON-NLS-1$
        doCompile( sdk, CompilationMode.MAKE_MODULE_LIST
                 , srcFile, workDirectory
                 , new ModuleListListener(moduleList, FilenameUtils.getFullPath(srcFile)) 
                 , arguments );
    }
    return moduleList;
}
 
Example #8
Source File: ScriptLoader.java    From logbook with MIT License 6 votes vote down vote up
/**
 * スクリプトを読み込みEventListenerの実装を取得する<br>
 *
 * @param script スクリプト
 * @return スクリプトにより実装されたEventListener、スクリプトエンジンが見つからない、もしくはコンパイル済み関数がEventListenerを実装しない場合null
 * @throws IOException
 * @throws ScriptException
 */
@CheckForNull
public EventListener getEventListener(Path script) throws IOException, ScriptException {
    try (BufferedReader reader = Files.newBufferedReader(script, StandardCharsets.UTF_8)) {
        // 拡張子からScriptEngineを取得
        String ext = FilenameUtils.getExtension(script.toString());
        ScriptEngine engine = this.manager.getEngineByExtension(ext);
        if (engine != null) {
            // eval
            engine.eval(reader);
            // 実装を取得
            EventListener listener = ((Invocable) engine).getInterface(EventListener.class);

            if (listener != null) {
                return new ScriptEventAdapter(listener, script);
            }
        }
        return null;
    }
}
 
Example #9
Source File: MAPO.java    From api-mining with GNU General Public License v3.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {

		// Runtime parameters
		final Parameters params = new Parameters();
		final JCommander jc = new JCommander(params);

		try {
			jc.parse(args);

			// Mine project
			System.out.println("Processing " + FilenameUtils.getBaseName(params.arffFile) + "...");
			mineAPICallSequences(params.arffFile, params.outFolder, 0.4, params.minSupp);

		} catch (final ParameterException e) {
			System.out.println(e.getMessage());
			jc.usage();
		}

	}
 
Example #10
Source File: SdkIniFileWriter.java    From xds-ide with Eclipse Public License 1.0 6 votes vote down vote up
private String mkRelPath(String home, String path) {
    if (path == null || Sdk.NOT_SUPPORTED.equals(path)) {
        return path;
    }
    String file = FilenameUtils.normalize(path);
    boolean isParent;
    if (File.separatorChar == '\\') {
        isParent = file.toLowerCase().startsWith(home.toLowerCase()); // Win
    } else {
        isParent = file.startsWith(home); // Linux
    }
    if (isParent) {
        file = file.substring(home.length());
        if (file.startsWith(File.separator)) {
            file = file.substring(1);
        }
    }
    return file;
}
 
Example #11
Source File: KryoManager.java    From Mundus with Apache License 2.0 6 votes vote down vote up
/**
 * Saves a scene.
 *
 * @param context
 *            project context of the scene
 * @param scene
 *            scene to save
 */
public void saveScene(ProjectContext context, Scene scene) {
    try {
        String sceneDir = FilenameUtils.concat(context.path + "/" + ProjectManager.PROJECT_SCENES_DIR,
                scene.getName() + "." + ProjectManager.PROJECT_SCENE_EXTENSION);

        Output output = new Output(new FileOutputStream(sceneDir));

        SceneDescriptor descriptor = DescriptorConverter.convert(scene);
        kryo.writeObject(output, descriptor);

        output.flush();
        output.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}
 
Example #12
Source File: ShapefileReader.java    From mrgeo with Apache License 2.0 6 votes vote down vote up
@SuppressFBWarnings(value = {"WEAK_FILENAMEUTILS",
    "PATH_TRAVERSAL_IN"}, justification = "Correctly filtered parameters")
private void readObject(ObjectInputStream in) throws ClassNotFoundException, IOException
{
  fileName = in.readUTF();
  source = Source.values()[in.readInt()];

  if (source == Source.FILE)
  {
    File f = new File(FilenameUtils.getFullPath(fileName), FilenameUtils.getName(fileName));
    if (f.exists())
    {
      load(fileName);
    }
  }
  else
  {
    if (HadoopFileUtils.exists(fileName))
    {
      load(new Path(fileName));
    }
  }
}
 
Example #13
Source File: AbstractJaxrsAction.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
protected String contentType(Boolean stream, String fileName) throws Exception {
	String extension = FilenameUtils.getExtension(fileName);
	String type = "";
	if (BooleanUtils.isTrue(stream) || StringUtils.isEmpty(extension)) {
		type = MediaType.APPLICATION_OCTET_STREAM;
	} else {
		type = Config.mimeTypes(extension);
	}
	return type;
}
 
Example #14
Source File: SysSettingController.java    From my_curd with Apache License 2.0 5 votes vote down vote up
/**
 * 导入excel
 */
@SuppressWarnings("Duplicates")
@Before(Tx.class)
public void importExcel() {
    UploadFile uploadFile = getFile();
    if (uploadFile == null) {
        renderFail("上传文件不可为空");
        return;
    }
    if (!FilenameUtils.getExtension(uploadFile.getFileName()).equals("xls")) {
        FileUtils.deleteFile(uploadFile.getFile());
        renderFail("上传文件后缀必须是xls");
        return;
    }

    List<SysSetting> list;
    try {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        list = ExcelImportUtil.importExcel(uploadFile.getFile(), SysSetting.class, params);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        FileUtils.deleteFile(uploadFile.getFile());
        renderFail("模板文件格式错误");
        return;
    }

    for (SysSetting sysSetting : list) {
        sysSetting.setId(IdUtils.id())
                .setUpdater(WebUtils.getSessionUsername(this))
                .setUpdateTime(new Date())
                .save();
    }

    FileUtils.deleteFile(uploadFile.getFile());
    refreshSetting();
    renderSuccess(IMPORT_SUCCESS);
}
 
Example #15
Source File: FileDetector.java    From intellij-swagger with MIT License 5 votes vote down vote up
public boolean isSwaggerContentCompatible(VirtualFile file) {
  return FilenameUtils.isExtension(
      file.getName(),
      new String[] {
        FileConstants.JSON_FILE_EXTENSION,
        FileConstants.YAML_FILE_EXTENSION,
        FileConstants.YML_FILE_EXTENSION
      });
}
 
Example #16
Source File: FileDownloader.java    From frontend-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public void download(String downloadUrl, String destination, String userName, String password) throws DownloadException {
    // force tls to 1.2 since github removed weak cryptographic standards
    // https://blog.github.com/2018-02-02-weak-cryptographic-standards-removal-notice/
    System.setProperty("https.protocols", "TLSv1.2");
    String fixedDownloadUrl = downloadUrl;
    try {
        fixedDownloadUrl = FilenameUtils.separatorsToUnix(fixedDownloadUrl);
        URI downloadURI = new URI(fixedDownloadUrl);
        if ("file".equalsIgnoreCase(downloadURI.getScheme())) {
            FileUtils.copyFile(new File(downloadURI), new File(destination));
        }
        else {
            CloseableHttpResponse response = execute(fixedDownloadUrl, userName, password);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode != 200){
                throw new DownloadException("Got error code "+ statusCode +" from the server.");
            }
            new File(FilenameUtils.getFullPathNoEndSeparator(destination)).mkdirs();
            ReadableByteChannel rbc = Channels.newChannel(response.getEntity().getContent());
            FileOutputStream fos = new FileOutputStream(destination);
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            fos.close();
        }
    } catch (IOException | URISyntaxException e) {
        throw new DownloadException("Could not download " + fixedDownloadUrl, e);
    }
}
 
Example #17
Source File: ActionUpload.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private BBSSubjectAttachment concreteAttachment(StorageMapping mapping, BBSSubjectInfo subject, String name, EffectivePerson effectivePerson, String site) throws Exception {
	BBSSubjectAttachment attachment = new BBSSubjectAttachment();
	String fileName = UUID.randomUUID().toString();
	String extension = FilenameUtils.getExtension( name );
	if ( StringUtils.isNotEmpty(extension)) {
		fileName = fileName + "." + extension;
	}else{
		throw new Exception("file extension is empty.");
	}
	if( name.indexOf( "\\" ) >0 ){
		name = StringUtils.substringAfterLast( name, "\\");
	}
	if( name.indexOf( "/" ) >0 ){
		name = StringUtils.substringAfterLast( name, "/");
	}
	attachment.setExtension(extension);
	attachment.setName(name);
	attachment.setFileName(fileName);
	attachment.setExtension(extension);
	attachment.setFileHost( mapping.getHost() );
	attachment.setFilePath( "" );
	attachment.setStorage( mapping.getName() );
	attachment.setSite(site);
	attachment.setCreateTime( new Date() );
	attachment.setCreatorUid( effectivePerson.getDistinguishedName() );
	if( subject != null ){
		attachment.setDescription( subject.getTitle() );
	}
	attachment.setLastUpdateTime( new Date() );
	attachment.setLength( 0L );
	return attachment;
}
 
Example #18
Source File: ResourceServiceImpl.java    From jwala with Apache License 2.0 5 votes vote down vote up
private void doUnpack(final String hostName, final String destPath) {
    try {
        binaryDistributionService.distributeUnzip(hostName);
        final String zipDestinationOption = FilenameUtils.removeExtension(destPath);
        LOGGER.debug("checking if unpacked destination exists: {}", zipDestinationOption);
        binaryDistributionService.remoteFileCheck(hostName, zipDestinationOption);
        binaryDistributionService.backupFile(hostName, zipDestinationOption);
        binaryDistributionService.remoteUnzipBinary(hostName, destPath, zipDestinationOption, "");
    } catch (CommandFailureException e) {
        LOGGER.error("Failed to execute remote command when unpack to {} ", destPath, e);
        throw new ApplicationException("Failed to execute remote command when unpack to  " + destPath, e);
    }
}
 
Example #19
Source File: FileUtils.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Removes all "." segments and ".." segments.
 * Also replaces backslashes with forward slashes.
 * Handles URLs specifically.
 * 
 * If there is a ".." segment that cannot be removed,
 * returns {@code null} (this can happen if the segment
 * is not preceded by a removable non-".." segment).
 *  
 * @param url - input URL or File path
 * 
 * @return normalized input string or {@code null}
 * 
 * @see FilenameUtils#normalize(String)
 * @see #getPrefixLength(String)
 */
public static String normalize(String url) {
	if (url == null) {
		return null;
	}
	String[] parts = splitFilePath(url);
	String suffix = FilenameUtils.normalize(parts[1], true);
	if (suffix == null) {
		return null;
	}
	String prefix = parts[0];
	Matcher m = getInnerInput(prefix); // only matches archives!
	if (m == null) { // no nested URL, just fix slashes
		prefix = FilenameUtils.separatorsToUnix(prefix);
	} else { // archive
		String inner = normalize(m.group(5)); // recursion
		if (inner == null) {
			return null;
		} else {
			StringBuilder sb = new StringBuilder(m.group(1)); // URL prefix up to '('
			sb.append(inner);
			sb.append(m.group(6)); // '('
			sb.append(m.group(7)); // URL suffix
			
			sb.append(suffix); // sb + suffix, avoid another string concatenation later
			return sb.toString();
		}
	}
	return prefix + suffix; 
}
 
Example #20
Source File: FileUtil.java    From gocd with Apache License 2.0 5 votes vote down vote up
public static String join(File defaultWorkingDir, String actualFileToUse) {
    if (actualFileToUse == null) {
        LOGGER.trace("Using the default Directory->{}", defaultWorkingDir);
        return FilenameUtils.separatorsToUnix(defaultWorkingDir.getPath());
    }
    return applyBaseDirIfRelativeAndNormalize(defaultWorkingDir, new File(actualFileToUse));
}
 
Example #21
Source File: FileTypeHandlerCallback.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Override
protected File valueOf(String text) {
    if (text == null) {
        return null;
    }
    return new File(FilenameUtils.separatorsToUnix(text));
}
 
Example #22
Source File: PerformAlleleFractionSegmentation.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Object doWork() {
    final String sampleName = FilenameUtils.getBaseName(snpCountsFile.getAbsolutePath());
    final AllelicPanelOfNormals allelicPoN =
            allelicPoNFile != null ? AllelicPanelOfNormals.read(allelicPoNFile) : AllelicPanelOfNormals.EMPTY_PON;
    final AllelicCountCollection acc = new AllelicCountCollection(snpCountsFile);
    final AlleleFractionSegmenter segmenter = new AlleleFractionSegmenter(initialNumStates, acc, allelicPoN);
    final List<ModeledSegment> segments = segmenter.getModeledSegments();

    SegmentUtils.writeModeledSegmentFile(outputSegmentsFile, segments, sampleName, true);

    return "SUCCESS";
}
 
Example #23
Source File: MimeMultipartBuilder.java    From blackduck-alert with Apache License 2.0 5 votes vote down vote up
private void addAttachmentBodyParts(final MimeMultipart email) throws MessagingException {
    for (final String filePath : attachmentFilePaths) {
        final MimeBodyPart attachmentBodyPart = new MimeBodyPart();
        final DataSource source = new FileDataSource(filePath);
        attachmentBodyPart.setDataHandler(new DataHandler(source));
        attachmentBodyPart.setFileName(FilenameUtils.getName(filePath));
        email.addBodyPart(attachmentBodyPart);
    }
}
 
Example #24
Source File: InitializerMessageSource.java    From openmrs-module-initializer with MIT License 5 votes vote down vote up
/**
 * Scans a directory for possible message properties files and adds it to the internal map.
 * 
 * @param dirPath The directory to scan.
 */
public void addMessageProperties(String dirPath) {
	
	final File[] propFiles = new File(dirPath).listFiles(new FilenameFilter() {
		
		@Override
		public boolean accept(File dir, String name) {
			String ext = FilenameUtils.getExtension(name);
			if (StringUtils.isEmpty(ext)) { // to be safe, ext can only be null if name is null
				return false;
			}
			if (ext.equals("properties")) {
				return true; // filtering only "*.properties" files
			}
			return false;
		}
	});
	
	if (propFiles != null) {
		if (MapUtils.isEmpty(messagePropertiesMap)) {
			messagePropertiesMap = new LinkedHashMap<File, Locale>();
		}
		for (File file : propFiles) {
			// Now reading the locale info out of the base name
			String baseName = FilenameUtils.getBaseName(file.getName()); // "messages_en_GB"
			try {
				Locale locale = getLocaleFromFileBaseName(baseName); // "en_GB"
				messagePropertiesMap.put(file, locale);
			}
			catch (IllegalArgumentException e) {
				log.error(e);
			}
		}
	}
}
 
Example #25
Source File: YuiCompressorUtils.java    From es with Apache License 2.0 5 votes vote down vote up
public static String getCompressFileName(String fileName) {
    if(hasCompress(fileName)) {
        return fileName;
    }
    String compressFileName = null;
    final String extension = FilenameUtils.getExtension(fileName);
    if("js".equalsIgnoreCase(extension)) {
        compressFileName = fileName.substring(0, fileName.length() - 3) + ".min.js";
    } else if("css".equals(extension)){
        compressFileName = fileName.substring(0, fileName.length() - 4) + ".min.css";
    }
    return compressFileName;
}
 
Example #26
Source File: GATKVariantContextUtils.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Creates a VariantContextWriter whose outputFile type is based on the extension of the output file name.
 * The default options set by VariantContextWriter are cleared before applying ALLOW_MISSING_FIELDS_IN_HEADER (if
 * <code>lenientProcessing</code> is set), followed by the set of options specified by any <code>options</code> args.
 *
 * @param outPath output Path for this writer. May not be null.
 * @param referenceDictionary required if on the fly indexing is set, otherwise can be null
 * @param createMD5 true if an md5 file should be created
 * @param options variable length list of additional Options to be set for this writer
 * @returns VariantContextWriter must be closed by the caller
 */
public static VariantContextWriter createVCFWriter(
        final Path outPath,
        final SAMSequenceDictionary referenceDictionary,
        final boolean createMD5,
        final Options... options)
{
    Utils.nonNull(outPath);

    VariantContextWriterBuilder vcWriterBuilder =
            new VariantContextWriterBuilder().clearOptions().setOutputPath(outPath);

    if (VariantContextWriterBuilder.OutputType.UNSPECIFIED == VariantContextWriterBuilder.determineOutputTypeFromFile(outPath)) {
        // the only way the user has to specify an output type is by file extension, and htsjdk
        // throws if it can't map the file extension to a known vcf type, so fallback to a default
        // of VCF
        logger.warn(String.format(
                "Can't determine output variant file format from output file extension \"%s\". Defaulting to VCF.",
                FilenameUtils.getExtension(outPath.getFileName().toString())));
        vcWriterBuilder = vcWriterBuilder.setOutputFileType(VariantContextWriterBuilder.OutputType.VCF);
    }

    if (createMD5) {
        vcWriterBuilder.setCreateMD5();
    }

    if (null != referenceDictionary) {
        vcWriterBuilder = vcWriterBuilder.setReferenceDictionary(referenceDictionary);
    }

    for (Options opt : options) {
        vcWriterBuilder = vcWriterBuilder.setOption(opt);
    }

    return vcWriterBuilder.build();
}
 
Example #27
Source File: ScenarioTestBase.java    From product-ei with Apache License 2.0 5 votes vote down vote up
protected List<Request> extractRequests(String testCase) throws IOException {
    String relativeRequestFolderLocation = appendSourceFolder(testCase, ScenarioConstants.REQUEST);
    List<String> requestFiles = getFilesFromSourceDirectory(relativeRequestFolderLocation);
    ArrayList<Request> requestArray = new ArrayList();

    for (String file : requestFiles) {
        String fileContent = getFileContent(relativeRequestFolderLocation, file);
        String header = FilenameUtils.removeExtension(file);
        requestArray.add(new Request(fileContent, header));
    }
    return requestArray;
}
 
Example #28
Source File: GatewayConfigImpl.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
public String getGatewayConfDir() {
  // 1st try: using the old style environment/system property name
  @SuppressWarnings("deprecation")
  String configDir = System.getProperty(GATEWAY_CONF_HOME_VAR, System.getenv(GATEWAY_CONF_HOME_VAR));

  // 2nd try: using the new style environment/system property name or use the default value (relative to the GATEWAY_HOME)
  if (StringUtils.isBlank(configDir)) {
    configDir = getVar(KNOX_GATEWAY_CONF_DIR_VAR, getGatewayHomeDir() + File.separator + "conf");
  }
  return FilenameUtils.normalize(configDir);
}
 
Example #29
Source File: PdfFileSourceListAdapter.java    From sejda with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Parse fileset definitions <filelist><fileset>[...]</fileset></filelist> ignoring the rest of the document
 * 
 * @param doc
 * @return a list of string matching the contents of the <filelist><fileset> tags in the document
 * @throws XPathExpressionException
 */
private List<String> parseFileSets(Document doc, File configFile) throws XPathExpressionException {
    List<String> result = new ArrayList<>();

    NodeList nodeList = getNodeListMatchingXpath("//filelist/fileset/file", doc);
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        Node fileSet = node.getParentNode();

        String parentDirPath = nullSafeGetStringAttribute(fileSet, "dir");
        if (parentDirPath == null) {
            parentDirPath = configFile.getAbsoluteFile().getParent();
        }

        String filePath = extractFilePath(node);

        // warn if file in fileset is using absolute path mode
        if (FilenameUtils.getPrefixLength(filePath) > 0) {
            LOG.warn("File " + filePath + " in fileset "
                    + StringUtils.defaultIfBlank(nullSafeGetStringAttribute(fileSet, "dir"), "")
                    + " seems to be an absolute path. Will _not_ be resolved relative to the <fileset>, but as an absolute path. Normally you would want to use relative paths in a //filelist/fileset/file, and absolute paths in a //filelist/file.");
        }

        result.add(FilenameUtils.concat(parentDirPath, filePath));
    }

    return result;
}
 
Example #30
Source File: PrintFileList.java    From phone with Apache License 2.0 5 votes vote down vote up
public static String clearFileType(String filePath){
	if (clearFileType) {
		String fileType = FilenameUtils.getExtension(filePath);
		if (fileType.length()>0) {
			filePath = filePath.substring(0, filePath.length()-fileType.length()-1);
		}
	}
	return filePath;
}