Example usage for org.apache.commons.io FilenameUtils concat

List of usage examples for org.apache.commons.io FilenameUtils concat

Introduction

In this page you can find the example usage for org.apache.commons.io FilenameUtils concat.

Prototype

public static String concat(String basePath, String fullFilenameToAdd) 

Source Link

Document

Concatenates a filename to a base path using normal command line style rules.

Usage

From source file:com.enderville.enderinstaller.util.InstallerConfig.java

/**
 * The image to initially display, saved at config/logo.png
 *
 * @return/*from  w  w  w.  j a v a2  s  .com*/
 */
public static String getLogoFile() {
    return FilenameUtils.concat(installerDir, "config/logo.png");
}

From source file:net.sf.jvifm.control.MiscFileCommand.java

public void execute() {

    if (cmd.equals("du") && args != null && args.length > 0) {
        // infos[]=[size,dirCount,fileCount];
        long[] infos = new long[] { 0, 0, 0 };
        for (int i = 0; i < args.length; i++) {
            File file = new File(args[i]);
            fileModelManager.calcDirInfo(file, infos);
        }//from w  w w.j  a  v a 2  s .  c o m
        fileManager.setStatusInfo(
                infos[1] + " dirs," + infos[2] + " files, total size is " + StringUtil.formatSize(infos[0]));
        return;
    }

    if (cmd.equals("md5sum") && args != null && args.length > 0) {
        try {
            String md5sum = Digest.digest(args[0], "MD5");
            fileManager.setStatusInfo("md5sum is: " + md5sum);
        } catch (Exception e) {
            fileManager.setStatusInfo("md5sum can't calculate");
        }
        return;
    }
    if (cmd.equals("sha1sum") && args != null && args.length > 0) {
        try {
            String md5sum = Digest.digest(args[0], "SHA");
            fileManager.setStatusInfo("sha1sum is: " + md5sum);
        } catch (Exception e) {
            fileManager.setStatusInfo("sha1sum can't calculate");
        }
        return;
    }

    if (cmd.equals("tabnew")) {
        fileManager.tabnew(pwd, FileLister.FS_ROOT);
        return;
    }

    if (cmd.equals("cd") && args != null && args.length > 0) {
        String newPath = FilenameUtils.concat(pwd, args[0]);
        if (newPath != null)
            if (newPath.endsWith(File.separator) && !newPath.equals(File.separator))
                newPath = newPath.substring(0, newPath.length() - 1);
        fileLister.visit(newPath);
        return;
    }
    if (cmd.equals("swap")) {
        fileManager.swapPanel();
    }

    if (cmd.equals("sort")) {
        String[] options = new String[] { Messages.getString("MiscFileCommand.name"), //$NON-NLS-1$
                Messages.getString("MiscFileCommand.lastModified"), //$NON-NLS-1$
                Messages.getString("MiscFileCommand.size") };//$NON-NLS-1$

        String result = new Util().openConfirmWindow(options, Messages.getString("MiscFileCommand.title"), //$NON-NLS-1$ 
                Messages.getString("MiscFileCommand.tipInfo"), //$NON-NLS-1$ 
                OptionShell.WARN);
        if (result == null)
            return;

        if (result.equals(Messages.getString("MiscFileCommand.size"))) {
            fileLister.sort("size");
        } else if (result.equals(Messages.getString("MiscFileCommand.lastModified"))) {
            fileLister.sort("date");
        } else if (result.equals(Messages.getString("MiscFileCommand.name"))) {
            fileLister.sort("name");
        }

        return;
    }
}

From source file:de.iai.ilcd.xml.read.SourceReader.java

@Override
public Source parse(JXPathContext context, PrintWriter out) {

    context.registerNamespace("ilcd", "http://lca.jrc.it/ILCD/Source");

    Source source = new Source();

    // OK, now read in all fields common to all DataSet types
    readCommonFields(source, DataSetType.SOURCE, context);

    IMultiLangString shortName = parserHelper.getIMultiLanguageString("//common:shortName");
    IMultiLangString citation = parserHelper.getIMultiLanguageString("//ilcd:sourceCitation");
    String publicationType = parserHelper.getStringValue("//ilcd:publicationType");
    PublicationTypeValue publicationTypeValue = PublicationTypeValue.UNDEFINED;
    if (publicationType != null) {
        try {/*  w w w .ja va  2s .  c  o m*/
            publicationTypeValue = PublicationTypeValue.fromValue(publicationType);
        } catch (Exception e) {
            if (out != null) {
                out.println("Warning: the field publicationType has an illegal value " + publicationType);
            }
        }
    }

    IMultiLangString description = parserHelper.getIMultiLanguageString("//ilcd:sourceDescriptionOrComment");

    source.setShortName(shortName);
    source.setName(shortName);
    source.setCitation(citation);
    source.setPublicationType(publicationTypeValue);
    source.setDescription(description);

    List<String> digitalFileReferences = parserHelper.getStringValues("//ilcd:referenceToDigitalFile", "uri");
    for (String digitalFileReference : digitalFileReferences) {
        logger.info("raw source data set file name is {}", getDataSetFileName());
        String baseDirectory = FilenameUtils.getFullPath(getDataSetFileName());
        // get rid of any leading/trailing white space
        digitalFileReference = digitalFileReference.trim();
        String absoluteFileName = FilenameUtils.concat(baseDirectory, digitalFileReference);
        absoluteFileName = FilenameUtils.normalize(absoluteFileName);
        logger.info("normalized form of digital file name is {}", absoluteFileName);
        logger.debug("reference to digital file: " + absoluteFileName);
        File file = new File(absoluteFileName);
        DigitalFile digitalFile = new DigitalFile();
        logger.debug("canread:" + (file.canRead()));
        String fileName = null;
        if (file.canRead()) {
            fileName = absoluteFileName; // file will be imported and Name
            // stripped after importing
        } else if (absoluteFileName.toLowerCase().endsWith(".jpg")
                || absoluteFileName.toLowerCase().endsWith(".jpeg")
                || absoluteFileName.toLowerCase().endsWith(".gif")
                || absoluteFileName.toLowerCase().endsWith(".pdf")) {
            // in case we're on a case sensitive filesystem and the case of the extension is not correct, we'll try
            // to fix this
            // TO DO this could be a little more elegant

            java.io.File parentDir = file.getParentFile();
            String fileNotFound = file.getName();
            String[] matches = parentDir.list(new CaseInsensitiveFilenameFilter(fileNotFound));
            if (matches != null && matches.length == 1) {
                fileName = parentDir + File.separator + matches[0];
                logger.debug(fileName);
            } else {
                fileName = digitalFileReference;
            }
        } else {
            logger.debug("file could not be read from " + file.getAbsolutePath());
            fileName = digitalFileReference; // Not a local filename, likely
            // be an URL to external
            // resource
        } // logger.debug("found reference to digital file: " + fileName);
        logger.info("set filename of digital file to {}", fileName);
        digitalFile.setFileName(fileName);
        source.addFile(digitalFile);
    }

    List<GlobalReference> contacts = commonReader.getGlobalReferences("//ilcd:referenceToContact", out);
    for (GlobalReference contact : contacts) {
        source.addContact(contact);
    }

    return source;
}

From source file:com.xiaomi.linden.core.TestMultiLindenCore.java

@Test
public void testDocNumDivision() throws Exception {
    String path = FilenameUtils.concat(INDEX_DIR, "size/");
    lindenConfig.setIndexDirectory(path).setLindenCoreMode(LindenConfig.LindenCoreMode.HOTSWAP)
            .setMultiIndexDivisionType(LindenConfig.MultiIndexDivisionType.DOC_NUM)
            .setMultiIndexDocNumLimit(100).setMultiIndexMaxLiveIndexNum(4);

    Deencapsulation.setField(DocNumLimitMultiIndexStrategy.class, "INDEX_CHECK_INTERVAL_MILLISECONDS", -10);

    lindenCore = new MultiLindenCoreImpl(lindenConfig);

    for (int i = 0; i < 400; ++i) {
        JSONObject json = new JSONObject();
        json.put("type", "index");
        JSONObject content = new JSONObject();
        content.put("id", i);
        content.put("title", "test " + i);
        json.put("content", content);
        handleRequest(json.toJSONString());
    }//from   w w w.  jav  a  2 s . c om
    lindenCore.commit();
    lindenCore.refresh();

    Assert.assertEquals(4, lindenCore.getServiceInfo().getIndexNamesSize());
    Assert.assertEquals(400, lindenCore.getServiceInfo().getDocsNum());

    String bql = "select * from linden source";
    LindenSearchRequest request = bqlCompiler.compile(bql).getSearchRequest();
    LindenResult result = lindenCore.search(request);
    Assert.assertEquals(400, result.getTotalHits());

    for (int i = 0; i < 400; ++i) {
        JSONObject json = new JSONObject();
        json.put("type", "index");
        JSONObject content = new JSONObject();
        content.put("id", i + 400);
        content.put("title", "test " + i);
        json.put("content", content);
        handleRequest(json.toJSONString());
    }

    lindenCore.commit();
    lindenCore.refresh();

    LindenServiceInfo serviceInfo = lindenCore.getServiceInfo();
    Assert.assertEquals(4, serviceInfo.getIndexNamesSize());
    Assert.assertEquals(400, serviceInfo.getDocsNum());
    lindenCore.close();
}

From source file:com.enioka.jqm.api.ServiceSimple.java

@GET
@Path("stdout")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public InputStream getLogOut(@QueryParam("id") int id) {
    res.setHeader("Content-Disposition", "attachment; filename=" + id + ".stdout.txt");
    return getFile(FilenameUtils.concat("./logs", StringUtils.leftPad("" + id, 10, "0") + ".stdout.log"));
}

From source file:io.github.retz.cli.CommandGetFile.java

@Override
public int handle(ClientCLIConfig fileConfig, boolean verbose) throws Throwable {
    LOG.debug("Configuration: {}", fileConfig.toString());

    try (Client webClient = Client.newBuilder(fileConfig.getUri())
            .setAuthenticator(fileConfig.getAuthenticator()).checkCert(!fileConfig.insecure())
            .setVerboseLog(verbose).build()) {

        if (verbose) {
            LOG.info("Getting file {} (offset={}, length={}) of a job(id={})", filename, offset, length, id);
        }//from   w  w w.j a  va 2s . c  o  m

        if (isBinary) {
            if ("-".equals(resultDir)) {
                LOG.error("--binary must be with -R option, to download the file.");
                return -1;
            } else if (poll) {
                LOG.error("--binary cannot work with --poll");
                return -1;
            }

            String fullpath = FilenameUtils.concat(resultDir, FilenameUtils.getName(filename));
            LOG.info("Binary mode: ignoring offset and length but downloading while file to '{}/{}'.",
                    resultDir, filename);
            try (FileOutputStream out = new FileOutputStream(fullpath)) {
                ClientHelper.getWholeBinaryFile(webClient, id, filename, out);
                return 0;
            }
        }

        Date start = Calendar.getInstance().getTime();
        Callable<Boolean> timedout;
        if (timeout > 0) {
            timedout = () -> {
                Date now = Calendar.getInstance().getTime();
                long diff = now.getTime() - start.getTime();
                return diff / 60 > timeout * 60;
            };
        } else {
            timedout = () -> false;
        }

        OutputStream out = this.tentativeOutputStream(webClient, resultDir, filename);
        if (length < 0) {
            try {
                ClientHelper.getWholeFileWithTerminator(webClient, id, filename, poll, out, timedout);
            } catch (TimeoutException e) {
                webClient.kill(id);
                LOG.error("Job(id={}) has been killed due to timeout after {} minute(s)", id, timeout);
                return -1;
            }
            return 0;
        }

        Response res = webClient.getFile(id, filename, offset, length);

        if (res instanceof GetFileResponse) {
            GetFileResponse getFileResponse = (GetFileResponse) res;

            if (getFileResponse.job().isPresent()) {
                Job job = getFileResponse.job().get();

                if (getFileResponse.file().isPresent()) {
                    if (verbose) {
                        LOG.info("offset={}", getFileResponse.file().get().offset());
                    }
                    out.write(getFileResponse.file().get().data().getBytes(UTF_8));

                } else if (verbose) {
                    LOG.info("Job: {}", job);
                }

                if (out != null && "-".equals(resultDir)) {
                    out.close();
                }
                return 0;

            } else {
                LOG.error("No such job: id={}", id);
            }
        } else {
            ErrorResponse errorResponse = (ErrorResponse) res;
            LOG.error("Error: {}", errorResponse.status());
        }
    }
    return -1;
}

From source file:com.cubeia.jetty.JettyEmbed.java

/** 
 * Takes a relative to the cwd (current work dir, poker-uar) path and 
 * creates the absolute path to the war file.
 * <p>//from w  w w  . ja  v a  2s.  c  o m
 * TODO: this needs to be changed to use either java or firebase mechanics
 * to determine cwd and the war location in a more elegant (ideally 
 * generic) way.
 *
 * @return the absolute path to the war
 */
public String getWarPath(String warFile) {
    File sarFile;
    String sarRoot;
    try {
        sarFile = new File(
                caller.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
        sarRoot = sarFile.getParent();
    } catch (URISyntaxException ex) {
        log.debug(null, ex);
        sarRoot = "";
    }
    String libDir = FilenameUtils.concat(sarRoot, "META-INF/lib");
    String filename = this.finalFileName(libDir, warFile);
    String warPath = FilenameUtils.concat(libDir, filename);
    log.debug("warPath : " + warPath);
    return warPath;
}

From source file:com.enioka.jqm.tools.LibraryCache.java

/**
 * Returns true if the libraries should be loaded in cache. Two cases: never loaded and should be reloaded (jar is more recent than
 * cache)/*  w  w w  .  ja  v a2s  .  c  om*/
 */
private boolean shouldLoad(Node node, JobDef jd) {
    if (!cache.containsKey(jd.getApplicationName())) {
        return true;
    }
    // If here: cache exists.
    JobDefLibrary libs = cache.get(jd.getApplicationName());

    // Is cache stale?
    Date lastLoaded = libs.loadTime;
    File jarFile = new File(FilenameUtils.concat(new File(node.getRepo()).getAbsolutePath(), jd.getJarPath()));
    File jarDir = jarFile.getParentFile();
    File libDir = new File(FilenameUtils.concat(jarDir.getAbsolutePath(), "lib"));

    if (lastLoaded.before(new Date(jarFile.lastModified()))
            || lastLoaded.before(new Date(jarDir.lastModified()))
            || lastLoaded.before(new Date(libDir.lastModified()))) {
        jqmlogger.info("The cache for application " + jd.getApplicationName() + " will be reloaded");
        return true;
    }

    // If here, the cache is OK
    return false;
}

From source file:edu.indiana.d2i.sloan.CreateVM.java

@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)/*from   ww w. java 2 s. co m*/
public Response getResourcePost(@FormParam("imagename") String imageName,
        @FormParam("loginusername") String loginusername, @FormParam("loginpassword") String loginpassword,
        @DefaultValue("1024") @FormParam("memory") int memory, @DefaultValue("1") @FormParam("vcpu") int vcpu,
        @Context HttpHeaders httpHeaders, @Context HttpServletRequest httpServletRequest) {
    String userName = httpServletRequest.getHeader(Constants.USER_NAME);
    String userEmail = httpServletRequest.getHeader(Constants.USER_EMAIL);
    if (userEmail == null)
        userEmail = "";

    // check input
    if (userName == null) {
        logger.error("Username is not present in http header.");
        return Response.status(500).entity(new ErrorBean(500, "Username is not present in http header."))
                .build();
    }

    if (imageName == null || loginusername == null || loginpassword == null) {
        return Response.status(400)
                .entity(new ErrorBean(400, "Image name, login username and login password cannot be empty!"))
                .build();
    }

    try {
        DBOperations.getInstance().insertUserIfNotExists(userName, userEmail);

        // check if image name is valid
        String imagePath = DBOperations.getInstance().getImagePath(imageName);
        if (imagePath == null) {
            return Response.status(400)
                    .entity(new ErrorBean(400, String.format("Image %s does not exist!", imageName))).build();
        }

        // check if policy name is valid

        int volumeSizeInGB = Integer.valueOf(Configuration.getInstance()
                .getString(Configuration.PropertyName.VOLUME_SIZE_IN_GB, Constants.DEFAULT_VOLUME_SIZE_IN_GB));

        // vm parameters
        String vmid = UUID.randomUUID().toString();
        String workDir = FilenameUtils.concat(
                Configuration.getInstance().getString(Configuration.PropertyName.DEFAULT_VM_WORKDIR_PREFIX),
                vmid);
        CreateVmRequestBean request = new CreateVmRequestBean(userName, imageName, vmid, loginusername,
                loginpassword, memory, vcpu, volumeSizeInGB, workDir);
        logger.info("User " + userName + " tries to create vm " + request);

        // check quota
        if (!DBOperations.getInstance().quotasNotExceedLimit(request)) {
            logger.info("Quota exceeds limit for user " + userName);
            return Response.status(400).entity(new ErrorBean(400, "Quota exceeds limit!")).build();
        }

        // schedule & update db
        VmInfoBean vminfo = SchedulerFactory.getInstance().schedule(request);

        // nonblocking call to hypervisor
        vminfo.setImagePath(imagePath);
        HypervisorProxy.getInstance().addCommand(new CreateVMCommand(vminfo));

        return Response.status(200).entity(new CreateVmResponseBean(vmid)).build();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return Response.status(500).entity(new ErrorBean(500, e.getMessage())).build();
    }
}

From source file:de.tudarmstadt.ukp.dkpro.keyphrases.bookindexing.evaluation.phrasematch.LineReader.java

private String getPath(String baseName) {
    return FilenameUtils.separatorsToSystem(
            FilenameUtils.concat(pathName, baseName) + ((suffix.startsWith(".")) ? suffix : "." + suffix));
}