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

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

Introduction

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

Prototype

public static String getName(String filename) 

Source Link

Document

Gets the name minus the path from a full filename.

Usage

From source file:com.splunk.shuttl.archiver.filesystem.PathResolverTest.java

public void resolvePathForBucketMetadata_bucketAndFile_hasFileNameOfMetadataFile() {
    File metadataFile = createFile("metadata.file");
    String metadataPath = pathResolver.resolvePathForBucketMetadata(bucket, metadataFile);
    assertEquals(metadataFile.getName(), FilenameUtils.getName(metadataPath));
}

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

private void loadCache(Node node, JobDef jd, EntityManager em) throws JqmPayloadException {
    jqmlogger.debug("Resolving classpath for job definition " + jd.getApplicationName());

    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"));
    File libDirExtracted = new File(FilenameUtils.concat(jarDir.getAbsolutePath(), "libFromJar"));
    File pomFile = new File(FilenameUtils.concat(jarDir.getAbsolutePath(), "pom.xml"));

    if (!jarFile.canRead()) {
        jqmlogger.warn("Cannot read file at " + jarFile.getAbsolutePath()
                + ". Job instance will crash. Check job definition or permissions on file.");
        throw new JqmPayloadException("File " + jarFile.getAbsolutePath() + " cannot be read");
    }/*from   w  ww .j av  a 2  s  . co m*/

    // POM file should be deleted if it comes from the jar file. Otherwise, it would stay into place and modifications to the internal
    // pom would be ignored.
    boolean pomFromJar = false;

    // 1st: if no pom, no lib dir => find a pom inside the JAR. (& copy it, we will read later)
    if (!pomFile.exists() && !libDir.exists()) {
        jqmlogger.trace("No pom inside jar directory. Checking for a pom inside the jar file");
        InputStream is = null;
        FileOutputStream os = null;
        ZipFile zf = null;

        try {
            zf = new ZipFile(jarFile);
            Enumeration<? extends ZipEntry> zes = zf.entries();
            while (zes.hasMoreElements()) {
                ZipEntry ze = zes.nextElement();
                if (ze.getName().endsWith("pom.xml")) {

                    is = zf.getInputStream(ze);
                    os = new FileOutputStream(pomFile);
                    IOUtils.copy(is, os);
                    pomFromJar = true;
                    break;
                }
            }
        } catch (Exception e) {
            throw new JqmPayloadException("Could not handle pom inside jar", e);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
            Helpers.closeQuietly(zf);
        }
    }

    // 2nd: no pom, no pom inside jar, no lib dir => find a lib dir inside the jar
    if (!pomFile.exists() && !libDir.exists()) {
        jqmlogger.trace("Checking for a lib directory inside jar");
        InputStream is = null;
        FileOutputStream os = null;
        ZipFile zf = null;
        FileUtils.deleteQuietly(libDirExtracted);

        try {
            zf = new ZipFile(jarFile);
            Enumeration<? extends ZipEntry> zes = zf.entries();
            while (zes.hasMoreElements()) {
                ZipEntry ze = zes.nextElement();
                if (ze.getName().startsWith("lib/") && ze.getName().endsWith(".jar")) {
                    if (!libDirExtracted.isDirectory() && !libDirExtracted.mkdir()) {
                        throw new JqmPayloadException("Could not extract libraries from jar");
                    }

                    is = zf.getInputStream(ze);
                    os = new FileOutputStream(FilenameUtils.concat(libDirExtracted.getAbsolutePath(),
                            FilenameUtils.getName(ze.getName())));
                    IOUtils.copy(is, os);
                }
            }
        } catch (Exception e) {
            throw new JqmPayloadException("Could not handle internal lib directory", e);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
            Helpers.closeQuietly(zf);
        }

        // If libs were extracted, put in cache and return
        if (libDirExtracted.isDirectory()) {
            FileFilter fileFilter = new WildcardFileFilter("*.jar");
            File[] files = libDirExtracted.listFiles(fileFilter);
            URL[] libUrls = new URL[files.length];
            try {
                for (int i = 0; i < files.length; i++) {
                    libUrls[i] = files[i].toURI().toURL();
                }
            } catch (Exception e) {
                throw new JqmPayloadException("Could not handle internal lib directory", e);
            }

            // Put in cache
            putInCache(libUrls, jd.getApplicationName());
            return;
        }
    }

    // 3rd: if pom, use pom!
    if (pomFile.exists() && !libDir.exists()) {
        jqmlogger.trace("Reading a pom file");

        ConfigurableMavenResolverSystem resolver = LibraryResolverMaven.getMavenResolver(em);

        // Resolve
        File[] depFiles = null;
        try {
            depFiles = resolver.loadPomFromFile(pomFile).importRuntimeDependencies().resolve()
                    .withTransitivity().asFile();
        } catch (IllegalArgumentException e) {
            // Happens when no dependencies inside pom, which is a weird use of the feature...
            jqmlogger.trace("No dependencies inside pom.xml file - no libs will be used", e);
            depFiles = new File[0];
        }

        // Extract results
        URL[] tmp = LibraryResolverMaven.extractMavenResults(depFiles);

        // Put in cache
        putInCache(tmp, jd.getApplicationName());

        // Cleanup
        if (pomFromJar && !pomFile.delete()) {
            jqmlogger.warn("Could not delete the temp pom file extracted from the jar.");
        }
        return;
    }

    // 4: if lib, use lib... (lib has priority over pom)
    if (libDir.exists()) {
        jqmlogger.trace(
                "Using the lib directory " + libDir.getAbsolutePath() + " as the source for dependencies");
        FileFilter fileFilter = new WildcardFileFilter("*.jar");
        File[] files = libDir.listFiles(fileFilter);
        URL[] tmp = new URL[files.length];
        for (int i = 0; i < files.length; i++) {
            try {
                tmp[i] = files[i].toURI().toURL();
            } catch (MalformedURLException e) {
                throw new JqmPayloadException("incorrect file inside lib directory", e);
            }
        }

        // Put in cache
        putInCache(tmp, jd.getApplicationName());
        return;
    }

    throw new JqmPayloadException(
            "There is no lib dir or no pom.xml inside the directory containing the jar or inside the jar. The jar cannot be launched.");
}

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

private void loadCache(Node node, JobDef jd, EntityManager em) throws JqmPayloadException {
    jqmlogger.debug("Resolving classpath for job definition " + jd.getApplicationName());

    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"));
    File libDirExtracted = new File(FilenameUtils.concat(jarDir.getAbsolutePath(), "libFromJar"));
    File pomFile = new File(FilenameUtils.concat(jarDir.getAbsolutePath(), "pom.xml"));

    // POM file should be deleted if it comes from the jar file. Otherwise, it would stay into place and modifications to the internal
    // pom would be ignored.
    boolean pomFromJar = false;

    // 1st: if no pom, no lib dir => find a pom inside the JAR. (& copy it, we will read later)
    if (!pomFile.exists() && !libDir.exists()) {
        jqmlogger.trace("No pom inside jar directory. Checking for a pom inside the jar file");
        InputStream is = null;//  w  w w.j a va2 s. c  o m
        FileOutputStream os = null;

        try {
            ZipFile zf = new ZipFile(jarFile);
            Enumeration<? extends ZipEntry> zes = zf.entries();
            while (zes.hasMoreElements()) {
                ZipEntry ze = zes.nextElement();
                if (ze.getName().endsWith("pom.xml")) {

                    is = zf.getInputStream(ze);
                    os = new FileOutputStream(pomFile);
                    IOUtils.copy(is, os);
                    pomFromJar = true;
                    break;
                }
            }
            zf.close();
        } catch (Exception e) {
            throw new JqmPayloadException("Could not handle pom inside jar", e);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
        }
    }

    // 2nd: no pom, no pom inside jar, no lib dir => find a lib dir inside the jar
    if (!pomFile.exists() && !libDir.exists()) {
        jqmlogger.trace("Checking for a lib directory inside jar");
        InputStream is = null;
        FileOutputStream os = null;
        ZipFile zf = null;
        FileUtils.deleteQuietly(libDirExtracted);

        try {
            zf = new ZipFile(jarFile);
            Enumeration<? extends ZipEntry> zes = zf.entries();
            while (zes.hasMoreElements()) {
                ZipEntry ze = zes.nextElement();
                if (ze.getName().startsWith("lib/") && ze.getName().endsWith(".jar")) {
                    if (!libDirExtracted.isDirectory() && !libDirExtracted.mkdir()) {
                        throw new JqmPayloadException("Could not extract libraries from jar");
                    }

                    is = zf.getInputStream(ze);
                    os = new FileOutputStream(FilenameUtils.concat(libDirExtracted.getAbsolutePath(),
                            FilenameUtils.getName(ze.getName())));
                    IOUtils.copy(is, os);
                    IOUtils.closeQuietly(is);
                    IOUtils.closeQuietly(os);
                }
            }
        } catch (Exception e) {
            throw new JqmPayloadException("Could not handle internal lib directory", e);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
            try {
                zf.close();
            } catch (Exception e) {
                jqmlogger.warn("could not close jar file", e);
            }
        }

        // If libs were extracted, put in cache and return
        if (libDirExtracted.isDirectory()) {
            FileFilter fileFilter = new WildcardFileFilter("*.jar");
            File[] files = libDirExtracted.listFiles(fileFilter);
            URL[] libUrls = new URL[files.length];
            try {
                for (int i = 0; i < files.length; i++) {
                    libUrls[i] = files[i].toURI().toURL();
                }
            } catch (Exception e) {
                throw new JqmPayloadException("Could not handle internal lib directory", e);
            }

            // Put in cache
            putInCache(libUrls, jd.getApplicationName());
            return;
        }
    }

    // 3rd: if pom, use pom!
    if (pomFile.exists() && !libDir.exists()) {
        jqmlogger.trace("Reading a pom file");

        // Retrieve resolver configuration
        List<GlobalParameter> repolist = em
                .createQuery("SELECT gp FROM GlobalParameter gp WHERE gp.key = :repo", GlobalParameter.class)
                .setParameter("repo", "mavenRepo").getResultList();
        List<GlobalParameter> settings = em
                .createQuery("SELECT gp FROM GlobalParameter gp WHERE gp.key = :k", GlobalParameter.class)
                .setParameter("k", "mavenSettingsCL").getResultList();
        List<GlobalParameter> settingFiles = em
                .createQuery("SELECT gp FROM GlobalParameter gp WHERE gp.key = :k", GlobalParameter.class)
                .setParameter("k", "mavenSettingsFile").getResultList();

        boolean withCentral = false;
        String withCustomSettings = null;
        String withCustomSettingsFile = null;
        if (settings.size() == 1 && settingFiles.isEmpty()) {
            jqmlogger.trace("Custom settings file will be used: " + settings.get(0).getValue());
            withCustomSettings = settings.get(0).getValue();
        }
        if (settingFiles.size() == 1) {
            jqmlogger.trace("Custom settings file will be used: " + settingFiles.get(0).getValue());
            withCustomSettingsFile = settingFiles.get(0).getValue();
        }

        // Configure resolver
        ConfigurableMavenResolverSystem resolver = Maven.configureResolver();
        if (withCustomSettings != null && withCustomSettingsFile == null) {
            resolver.fromClassloaderResource(withCustomSettings);
        }
        if (withCustomSettingsFile != null) {
            resolver.fromFile(withCustomSettingsFile);
        }

        for (GlobalParameter gp : repolist) {
            if (gp.getValue().contains("repo1.maven.org")) {
                withCentral = true;
            }
            resolver = resolver.withRemoteRepo(MavenRemoteRepositories
                    .createRemoteRepository(gp.getId().toString(), gp.getValue(), "default")
                    .setUpdatePolicy(MavenUpdatePolicy.UPDATE_POLICY_NEVER));
        }
        resolver.withMavenCentralRepo(withCentral);

        // Resolve
        File[] depFiles = null;
        try {
            depFiles = resolver.loadPomFromFile(pomFile).importRuntimeDependencies().resolve()
                    .withTransitivity().asFile();
        } catch (IllegalArgumentException e) {
            // Happens when no dependencies inside pom, which is a weird use of the feature...
            jqmlogger.trace("No dependencies inside pom.xml file - no libs will be used", e);
            depFiles = new File[0];
        }

        // Extract results
        int size = 0;
        for (File artifact : depFiles) {
            if (!"pom".equals(FilenameUtils.getExtension(artifact.getName()))) {
                size++;
            }
        }
        URL[] tmp = new URL[size];
        int i = 0;
        for (File artifact : depFiles) {
            if ("pom".equals(FilenameUtils.getExtension(artifact.getName()))) {
                continue;
            }
            try {
                tmp[i] = artifact.toURI().toURL();
            } catch (MalformedURLException e) {
                throw new JqmPayloadException("Incorrect dependency in POM file", e);
            }
            i++;
        }

        // Put in cache
        putInCache(tmp, jd.getApplicationName());

        // Cleanup
        if (pomFromJar && !pomFile.delete()) {
            jqmlogger.warn("Could not delete the temp pom file extracted from the jar.");
        }
        return;
    }

    // 4: if lib, use lib... (lib has priority over pom)
    if (libDir.exists()) {
        jqmlogger.trace(
                "Using the lib directory " + libDir.getAbsolutePath() + " as the source for dependencies");
        FileFilter fileFilter = new WildcardFileFilter("*.jar");
        File[] files = libDir.listFiles(fileFilter);
        URL[] tmp = new URL[files.length];
        for (int i = 0; i < files.length; i++) {
            try {
                tmp[i] = files[i].toURI().toURL();
            } catch (MalformedURLException e) {
                throw new JqmPayloadException("incorrect file inside lib directory", e);
            }
        }

        // Put in cache
        putInCache(tmp, jd.getApplicationName());
        return;
    }

    throw new JqmPayloadException(
            "There is no lib dir or no pom.xml inside the directory containing the jar or inside the jar. The jar cannot be launched.");
}

From source file:eu.prestoprime.plugin.irods.IRODSTasks.java

@WfService(name = "irods_get", version = "2.0.0")
public void get(Map<String, String> sParams, Map<String, String> dParamsString, Map<String, File> dParamsFile)
        throws TaskExecutionFailedException {

    // get static parameters
    String host = sParams.get("irods.host");
    int port = Integer.parseInt(sParams.get("irods.port"));
    String username = sParams.get("irods.username");
    String password = sParams.get("irods.password");
    String homeDir = sParams.get("irods.home.dir");
    String zone = sParams.get("irods.zone");
    String defaultResource = sParams.get("irods.default.resource");

    // get dynamic parameters
    String dipID = dParamsString.get("dipID");
    String targetFolder = dParamsString.get("targetFolder");

    IRODSFileSystem irodsFileSystem = null;

    try {/*from  w  w w .  j  a v a 2  s .com*/

        DIP dip = P4DataManager.getInstance().getDIPByID(dipID);

        String irodsFilePath = dip.getAVMaterial("application/mxf", "IRODS").get(0);

        irodsFileSystem = IRODSFileSystem.instance();

        IRODSAccount account = IRODSAccount.instance(host, port, username, password, homeDir, zone,
                defaultResource);

        IRODSFileFactory fileFactory = irodsFileSystem.getIRODSFileFactory(account);

        logger.debug("IRODS File Path: " + irodsFilePath);

        //IRODSFileInputStream sourceFileIS = fileFactory.instanceIRODSFileInputStream(irodsFilePath);

        File targetFile = new File(targetFolder, FilenameUtils.getName(irodsFilePath));

        //IOUtils.copy(sourceFileIS, new FileOutputStream(targetFile));

        //new stuff for parallel transfer using iRODS
        TransferOptions transferOptions = new TransferOptions();
        transferOptions.setComputeAndVerifyChecksumAfterTransfer(true);

        TransferControlBlock transferControlBlock = DefaultTransferControlBlock.instance();
        transferControlBlock.setTransferOptions(transferOptions);

        DataTransferOperations dataTransferOperations = irodsFileSystem.getIRODSAccessObjectFactory()
                .getDataTransferOperations(account);

        IRODSFile irodsFile = fileFactory.instanceIRODSFile(irodsFilePath);
        dataTransferOperations.getOperation(irodsFile, targetFile, null, transferControlBlock);

        //end new stuff

    } catch (JargonException e) {
        e.printStackTrace();
        throw new TaskExecutionFailedException("Unable to connect with IRODS...");
    } catch (DataException e) {
        e.printStackTrace();
        throw new TaskExecutionFailedException("Unable to retrieve SIP...");
    } catch (IPException e) {
        e.printStackTrace();
        throw new TaskExecutionFailedException("Unable to retrieve AV Material...");
    } /*catch (IOException e) {
       e.printStackTrace();
       throw new TaskExecutionFailedException("Unable to execute file operation...");
      } */finally {
        try {
            if (irodsFileSystem != null)
                irodsFileSystem.close();
        } catch (JargonException e) {
        }
    }
}

From source file:com.legstar.jaxb.AbstractJaxbGenTest.java

/**
 * Check a result against a reference./* ww  w .j  av a2  s.  c o m*/
 * <p/>
 * Here result is a folder as well a reference. In check mode all file are
 * compared in creation mode all reference files are created as copies from
 * the results.
 * <p/>
 * ObjectFactories are not compared because their content is not ordered in
 * a consistent way.
 * 
 * @param refFolder the reference folder (containing reference files)
 * @param resultFolder the result folder (containing generated files)
 * @param extension the files extension to process
 * @throws Exception if something fails
 */
public void check(final File refFolder, final File resultFolder, final String extension) throws Exception {

    if (isCreateReferences()) {
        Collection<File> resultFiles = FileUtils.listFiles(resultFolder, new String[] { extension }, false);
        for (File resultFile : resultFiles) {
            FileUtils.copyFileToDirectory(resultFile, refFolder);
        }
    } else {
        Collection<File> referenceFiles = FileUtils.listFiles(refFolder, new String[] { extension }, false);
        for (File referenceFile : referenceFiles) {
            if (referenceFile.getName().equals("ObjectFactory.java")) {
                continue;
            }
            File resultFile = new File(resultFolder, FilenameUtils.getName(referenceFile.getPath()));
            assertEquals(referenceFile, resultFile);
        }
    }

}

From source file:de.tudarmstadt.ukp.clarin.webanno.webapp.remoteapi.RemoteApiController.java

/**
 * Create a new project./* ww w .jav  a2  s.  c  om*/
 *
 * To test, use the Linux "curl" command.
 *
 * curl -v -F 'file=@test.zip' -F 'name=Test' -F 'filetype=tcf'
 * 'http://USERNAME:PASSWORD@localhost:8080/de.tudarmstadt.ukp.clarin.webanno.webapp/api/project
 * '
 *
 * @param aName
 *            the name of the project to create.
 * @param aFileType
 *            the type of the files contained in the ZIP. The possible file types are configured
 *            in the formats.properties configuration file of WebAnno.
 * @param aFile
 *            a ZIP file containing the project data.
 * @throws Exception if there was en error.
 */
@RequestMapping(value = "/project", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public @ResponseStatus(HttpStatus.NO_CONTENT) void createProject(@RequestParam("file") MultipartFile aFile,
        @RequestParam("name") String aName, @RequestParam("filetype") String aFileType) throws Exception {
    LOG.info("Creating project [" + aName + "]");

    if (!ZipUtils.isZipStream(aFile.getInputStream())) {
        throw new InvalidFileNameException("", "is an invalid Zip file");
    }

    // Get current user
    String username = SecurityContextHolder.getContext().getAuthentication().getName();
    User user = userRepository.get(username);
    Project project = null;

    // Configure project
    if (!projectRepository.existsProject(aName)) {
        project = new Project();
        project.setName(aName);

        // Create the project and initialize tags
        projectRepository.createProject(project, user);
        annotationService.initializeTypesForProject(project, user, new String[] {}, new String[] {},
                new String[] {}, new String[] {}, new String[] {}, new String[] {}, new String[] {},
                new String[] {});
        // Create permission for this user
        ProjectPermission permission = new ProjectPermission();
        permission.setLevel(PermissionLevel.ADMIN);
        permission.setProject(project);
        permission.setUser(username);
        projectRepository.createProjectPermission(permission);

        permission = new ProjectPermission();
        permission.setLevel(PermissionLevel.USER);
        permission.setProject(project);
        permission.setUser(username);
        projectRepository.createProjectPermission(permission);
    }
    // Existing project
    else {
        throw new IOException("The project with name [" + aName + "] exists");
    }

    // Iterate through all the files in the ZIP

    // If the current filename does not start with "." and is in the root folder of the ZIP,
    // import it as a source document
    File zimpFile = File.createTempFile(aFile.getOriginalFilename(), ".zip");
    aFile.transferTo(zimpFile);
    ZipFile zip = new ZipFile(zimpFile);

    for (Enumeration<?> zipEnumerate = zip.entries(); zipEnumerate.hasMoreElements();) {
        //
        // Get ZipEntry which is a file or a directory
        //
        ZipEntry entry = (ZipEntry) zipEnumerate.nextElement();

        // If it is the zip name, ignore it
        if ((FilenameUtils.removeExtension(aFile.getOriginalFilename()) + "/").equals(entry.toString())) {
            continue;
        }
        // IF the current filename is META-INF/webanno/source-meta-data.properties store it
        // as
        // project meta data
        else if (entry.toString().replace("/", "")
                .equals((META_INF + "webanno/source-meta-data.properties").replace("/", ""))) {
            InputStream zipStream = zip.getInputStream(entry);
            projectRepository.savePropertiesFile(project, zipStream, entry.toString());

        }
        // File not in the Zip's root folder OR not
        // META-INF/webanno/source-meta-data.properties
        else if (StringUtils.countMatches(entry.toString(), "/") > 1) {
            continue;
        }
        // If the current filename does not start with "." and is in the root folder of the
        // ZIP, import it as a source document
        else if (!FilenameUtils.getExtension(entry.toString()).equals("")
                && !FilenameUtils.getName(entry.toString()).equals(".")) {

            uploadSourceDocument(zip, entry, project, user, aFileType);
        }

    }

    LOG.info("Successfully created project [" + aName + "] for user [" + username + "]");

}

From source file:edu.emory.cci.aiw.cvrg.eureka.servlet.JobSubmitServlet.java

private Long submitJob(HttpServletRequest request, Principal principal)
        throws FileUploadException, IOException, ClientException, ParseException {

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

    /*/*from  ww w. j  a v  a2  s  . com*/
     *Set the size threshold, above which content will be stored on disk.
     */
    fileItemFactory.setSizeThreshold(5 * 1024 * 1024); //5 MB
    /*
     * Set the temporary directory to store the uploaded files of size above threshold.
     */
    fileItemFactory.setRepository(this.tmpDir);

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    /*
     * Parse the request
     */
    List items = uploadHandler.parseRequest(request);
    Properties fields = new Properties();
    for (Iterator itr = items.iterator(); itr.hasNext();) {
        FileItem item = (FileItem) itr.next();
        /*
         * Handle Form Fields.
         */
        if (item.isFormField()) {
            fields.setProperty(item.getFieldName(), item.getString());
        }
    }

    JobSpec jobSpec = MAPPER.readValue(fields.getProperty("jobSpec"), JobSpec.class);

    for (Iterator itr = items.iterator(); itr.hasNext();) {
        FileItem item = (FileItem) itr.next();
        if (!item.isFormField()) {
            //Handle Uploaded files.
            log("Spreadsheet upload for user " + principal.getName() + ": Field Name = " + item.getFieldName()
                    + ", File Name = " + item.getName() + ", Content type = " + item.getContentType()
                    + ", File Size = " + item.getSize());
            if (item.getSize() > 0) {
                InputStream is = item.getInputStream();
                try {
                    this.servicesClient.upload(FilenameUtils.getName(item.getName()),
                            jobSpec.getSourceConfigId(), item.getFieldName(), is);
                    log("File '" + item.getName() + "' uploaded successfully");
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException ignore) {
                        }
                    }
                }
            } else {
                log("File '" + item.getName() + "' ignored because it was zero length");
            }
        }
    }

    URI uri = this.servicesClient.submitJob(jobSpec);
    String uriStr = uri.toString();
    Long jobId = Long.valueOf(uriStr.substring(uriStr.lastIndexOf("/") + 1));
    log("Job " + jobId + " submitted for user " + principal.getName());
    return jobId;
}

From source file:com.kodemore.servlet.control.ScDropzone.java

private void tryHandleUpload() {
    try {//ww w. ja  va  2  s  .  co m
        KmList<FileItem> files = getData().getUploadedFiles();

        for (FileItem item : files)
            try (BufferedInputStream in = Kmu.toBufferedInputStream(item.getInputStream())) {
                String fileName = FilenameUtils.getName(item.getName());
                byte[] data = Kmu.readBytesFrom(in);

                getUploadHandler().upload(fileName, data);
            }
    } catch (IOException ex) {
        KmLog.error(ex, "Dropzone upload failure.");
    }
}

From source file:ddf.content.endpoint.rest.ContentEndpoint.java

/**
 * Create an entry in the Content Repository and/or the Metadata Catalog based on the request's
 * directive. The input request is in multipart/form-data format, with the expected parts of the
 * body being the directive (STORE, PROCESS, STORE_AND_PROCESS), and the file, with optional
 * filename specified, followed by the contents to be stored. If the filename is not specified
 * for the contents in the body of the input request, then the default filename "file" will be
 * used, with the file extension determined based upon the MIME type.
 * /* ww  w.j av  a2 s.  co  m*/
 * A sample multipart/form-data request would look like: Content-Type: multipart/form-data;
 * boundary=ARCFormBoundaryfqeylm5unubx1or
 * 
 * --ARCFormBoundaryfqeylm5unubx1or Content-Disposition: form-data; name="directive"
 * 
 * STORE_AND_PROCESS --ARCFormBoundaryfqeylm5unubx1or-- Content-Disposition: form-data;
 * name="myfile.json"; filename="C:\DDF\geojson_valid.json" Content-Type:
 * application/json;id=geojson
 * 
 * <contents to store go here>
 * 
 * @param multipartBody
 *            the multipart/form-data formatted body of the request
 * @param requestUriInfo
 * @return
 * @throws ContentEndpointException
 */
@POST
@Path("/")
public Response create(MultipartBody multipartBody, @Context UriInfo requestUriInfo)
        throws ContentEndpointException {
    logger.trace("ENTERING: create");

    String directive = multipartBody.getAttachmentObject(DIRECTIVE_ATTACHMENT_CONTENT_ID, String.class);
    logger.debug("directive = " + directive);

    String contentUri = multipartBody.getAttachmentObject("contentUri", String.class);
    logger.debug("contentUri = " + contentUri);

    InputStream stream = null;
    String filename = null;
    String contentType = null;

    // TODO: For DDF-1970 (multiple files in single create request)
    // Would access List<Attachment> = multipartBody.getAllAttachments() and loop
    // through them getting all of the "file" attachments (and skipping the "directive")
    // But how to support a "contentUri" parameter *per* file attachment? Can it be
    // just another parameter to the name="file" Content-Disposition?
    Attachment contentPart = multipartBody.getAttachment(FILE_ATTACHMENT_CONTENT_ID);
    if (contentPart != null) {
        // Example Content-Type header:
        // Content-Type: application/json;id=geojson
        if (contentPart.getContentType() != null) {
            contentType = contentPart.getContentType().toString();
        }

        filename = contentPart.getContentDisposition()
                .getParameter(FILENAME_CONTENT_DISPOSITION_PARAMETER_NAME);

        // Only interested in attachments for file uploads. Any others should be covered by
        // the FormParam arguments.
        if (StringUtils.isEmpty(filename)) {
            logger.debug("No filename parameter provided - generating default filename");
            String fileExtension = DEFAULT_FILE_EXTENSION;
            try {
                fileExtension = mimeTypeMapper.getFileExtensionForMimeType(contentType); // DDF-2307
                if (StringUtils.isEmpty(fileExtension)) {
                    fileExtension = DEFAULT_FILE_EXTENSION;
                }
            } catch (MimeTypeResolutionException e) {
                logger.debug("Exception getting file extension for contentType = " + contentType);
            }
            filename = DEFAULT_FILE_NAME + fileExtension; // DDF-2263
            logger.debug("No filename parameter provided - default to " + filename);
        } else {
            filename = FilenameUtils.getName(filename);
        }

        // Get the file contents as an InputStream and ensure the stream is positioned
        // at the beginning
        try {
            stream = contentPart.getDataHandler().getInputStream();
            if (stream != null && stream.available() == 0) {
                stream.reset();
            }
        } catch (IOException e) {
            logger.warn("IOException reading stream from file attachment in multipart body", e);
        }
    } else {
        logger.debug("No file contents attachment found");
    }

    Response response = doCreate(stream, contentType, directive, filename, contentUri, requestUriInfo);

    logger.trace("EXITING: create");

    return response;
}

From source file:com.silverpeas.attachment.servlets.DragAndDrop.java

/**
 * Method declaration/*from w  ww. j  a  v  a 2 s . c  o m*/
 * @param req
 * @param res
 * @throws IOException
 * @throws ServletException
 * @see
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_ENTER_METHOD");
    if (!FileUploadUtil.isRequestMultipart(req)) {
        res.getOutputStream().println("SUCCESS");
        return;
    }
    ResourceLocator settings = new ResourceLocator("com.stratelia.webactiv.util.attachment.Attachment", "");
    boolean actifyPublisherEnable = settings.getBoolean("ActifyPublisherEnable", false);
    try {
        req.setCharacterEncoding("UTF-8");
        String componentId = req.getParameter("ComponentId");
        SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                "componentId = " + componentId);
        String id = req.getParameter("PubId");
        SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "id = " + id);
        String userId = req.getParameter("UserId");
        SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "userId = " + userId);
        String context = req.getParameter("Context");
        boolean bIndexIt = StringUtil.getBooleanValue(req.getParameter("IndexIt"));

        List<FileItem> items = FileUploadUtil.parseRequest(req);
        for (FileItem item : items) {
            SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                    "item = " + item.getFieldName());
            SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                    "item = " + item.getName() + "; " + item.getString("UTF-8"));

            if (!item.isFormField()) {
                String fileName = item.getName();
                if (fileName != null) {
                    String physicalName = saveFileOnDisk(item, componentId, context);
                    String mimeType = AttachmentController.getMimeType(fileName);
                    long size = item.getSize();
                    SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                            "item size = " + size);
                    // create AttachmentDetail Object
                    AttachmentDetail attachment = new AttachmentDetail(
                            new AttachmentPK(null, "useless", componentId), physicalName, fileName, null,
                            mimeType, size, context, new Date(), new AttachmentPK(id, "useless", componentId));
                    attachment.setAuthor(userId);
                    try {
                        AttachmentController.createAttachment(attachment, bIndexIt);
                    } catch (Exception e) {
                        // storing data into DB failed, delete file just added on disk
                        deleteFileOnDisk(physicalName, componentId, context);
                        throw e;
                    }
                    // Specific case: 3d file to convert by Actify Publisher
                    if (actifyPublisherEnable) {
                        String extensions = settings.getString("Actify3dFiles");
                        StringTokenizer tokenizer = new StringTokenizer(extensions, ",");
                        // 3d native file ?
                        boolean fileForActify = false;
                        SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                                "nb tokenizer =" + tokenizer.countTokens());
                        String type = FileRepositoryManager.getFileExtension(fileName);
                        while (tokenizer.hasMoreTokens() && !fileForActify) {
                            String extension = tokenizer.nextToken();
                            fileForActify = type.equalsIgnoreCase(extension);
                        }
                        if (fileForActify) {
                            String dirDestName = "a_" + componentId + "_" + id;
                            String actifyWorkingPath = settings.getString("ActifyPathSource")
                                    + File.separatorChar + dirDestName;

                            String destPath = FileRepositoryManager.getTemporaryPath() + actifyWorkingPath;
                            if (!new File(destPath).exists()) {
                                FileRepositoryManager.createGlobalTempPath(actifyWorkingPath);
                            }
                            String normalizedFileName = FilenameUtils.normalize(fileName);
                            if (normalizedFileName == null) {
                                normalizedFileName = FilenameUtils.getName(fileName);
                            }
                            String destFile = FileRepositoryManager.getTemporaryPath() + actifyWorkingPath
                                    + File.separatorChar + normalizedFileName;
                            FileRepositoryManager
                                    .copyFile(AttachmentController.createPath(componentId, "Images")
                                            + File.separatorChar + physicalName, destFile);
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        SilverTrace.error("attachment", "DragAndDrop.doPost", "ERREUR", e);
        res.getOutputStream().println("ERROR");
        return;
    }
    res.getOutputStream().println("SUCCESS");
}