Example usage for java.nio.file Files move

List of usage examples for java.nio.file Files move

Introduction

In this page you can find the example usage for java.nio.file Files move.

Prototype

public static Path move(Path source, Path target, CopyOption... options) throws IOException 

Source Link

Document

Move or rename a file to a target file.

Usage

From source file:net.rptools.maptool.util.PersistenceUtil.java

public static void saveCampaign(Campaign campaign, File campaignFile) throws IOException {
    CodeTimer saveTimer; // FJE Previously this was 'private static' -- why?
    saveTimer = new CodeTimer("CampaignSave");
    saveTimer.setThreshold(5);//w ww .j  a  va 2s. c  o m
    saveTimer.setEnabled(log.isDebugEnabled()); // Don't bother keeping track if it won't be displayed...

    // Strategy: save the file to a tmp location so that if there's a failure the original file
    // won't be touched. Then once we're finished, replace the old with the new.
    File tmpDir = AppUtil.getTmpDir();
    File tmpFile = new File(tmpDir.getAbsolutePath(), campaignFile.getName());
    if (tmpFile.exists())
        tmpFile.delete();

    PackedFile pakFile = null;
    try {
        pakFile = new PackedFile(tmpFile);
        // Configure the meta file (this is for legacy support)
        PersistedCampaign persistedCampaign = new PersistedCampaign();

        persistedCampaign.campaign = campaign;

        // Keep track of the current view
        ZoneRenderer currentZoneRenderer = MapTool.getFrame().getCurrentZoneRenderer();
        if (currentZoneRenderer != null) {
            persistedCampaign.currentZoneId = currentZoneRenderer.getZone().getId();
            persistedCampaign.currentView = currentZoneRenderer.getZoneScale();
        }
        // Save all assets in active use (consolidate duplicates between maps)
        saveTimer.start("Collect all assets");
        Set<MD5Key> allAssetIds = campaign.getAllAssetIds();
        for (MD5Key key : allAssetIds) {
            // Put in a placeholder; all we really care about is the MD5Key for now...
            persistedCampaign.assetMap.put(key, null);
        }
        saveTimer.stop("Collect all assets");

        // And store the asset elsewhere
        saveTimer.start("Save assets");
        saveAssets(allAssetIds, pakFile);
        saveTimer.stop("Save assets");

        try {
            saveTimer.start("Set content");
            pakFile.setContent(persistedCampaign);
            pakFile.setProperty(PROP_VERSION, MapTool.getVersion());
            pakFile.setProperty(PROP_CAMPAIGN_VERSION, CAMPAIGN_VERSION);
            saveTimer.stop("Set content");

            saveTimer.start("Save");
            pakFile.save();
            saveTimer.stop("Save");
        } catch (OutOfMemoryError oom) {
            /*
             * This error is normally because the heap space has been
             * exceeded while trying to save the campaign. Since MapTool
             * caches the images used by the current Zone, and since the
             * VersionManager must keep the XML for objects in memory in
             * order to apply transforms to them, the memory usage can spike
             * very high during the save() operation. A common solution is
             * to switch to an empty map and perform the save from there;
             * this causes MapTool to unload any images that it may have had
             * cached and this can frequently free up enough memory for the
             * save() to work. We'll tell the user all this right here and
             * then fail the save and they can try again.
             */
            saveTimer.start("OOM Close");
            pakFile.close(); // Have to close the tmpFile first on some OSes
            pakFile = null;
            tmpFile.delete(); // Delete the temporary file
            saveTimer.stop("OOM Close");
            if (log.isDebugEnabled()) {
                log.debug(saveTimer);
            }
            MapTool.showError("msg.error.failedSaveCampaignOOM");
            return;
        }
    } finally {
        saveTimer.start("Close");
        try {
            if (pakFile != null)
                pakFile.close();
        } catch (Exception e) {
        }
        saveTimer.stop("Close");
        pakFile = null;
    }

    /*
     * Copy to the new location. Not the fastest solution in the world if
     * renameTo() fails, but worth the safety net it provides. (Jamz had
     * issues with renameTo() keeping DropBox files locked on Windows.
     * Changed to use Files.move() from Java 7.)
     */
    saveTimer.start("Backup");
    File bakFile = new File(tmpDir.getAbsolutePath(), campaignFile.getName() + ".bak");
    bakFile.delete();
    if (campaignFile.exists()) {
        saveTimer.start("Backup campaign file: " + campaignFile);
        try {
            Files.move(campaignFile.toPath(), bakFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (Exception ex) {
            try {
                FileUtil.copyFile(campaignFile, bakFile);
            } catch (Exception e) {
                MapTool.showError("msg.error.failedSaveCampaign");
                return;
            }
        } finally {
            saveTimer.stop("Backup campaign file: " + campaignFile);
        }
    }

    saveTimer.start("Backup tmpFile to campaign file");
    try {
        Files.move(tmpFile.toPath(), campaignFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    } catch (Exception e) {
        FileUtil.copyFile(campaignFile, bakFile);
        tmpFile.delete(); // Only delete if the copy didn't throw an exception
    }
    saveTimer.stop("Backup tmpFile to campaign file");
    bakFile.delete();
    saveTimer.stop("Backup");

    // Save the campaign thumbnail
    saveTimer.start("Thumbnail");
    saveCampaignThumbnail(campaignFile.getName());
    saveTimer.stop("Thumbnail");

    if (log.isDebugEnabled()) {
        log.debug(saveTimer);
    }
}

From source file:com.stimulus.archiva.store.MessageStore.java

public void backupMessage(File file) throws MessageStoreException {
    logger.debug("backupMessage()");
    File noArchiveFile = getNoArchiveFile();
    logger.warn("copying email to no archive queue {dest='" + noArchiveFile.getAbsolutePath() + "'}");

    //Mod start Seolhwa.kim 2017-04-13

    //boolean renamed = file.renameTo(noArchiveFile);

    boolean renamed;
    try {//from  w ww .j  av a2 s  . c  o  m
        Files.move(Paths.get(file.getAbsolutePath()), Paths.get(noArchiveFile.getAbsolutePath()),
                StandardCopyOption.REPLACE_EXISTING);
        renamed = true;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        renamed = false;
        e.printStackTrace();
    }

    //Mod End Seolhwa.kim 2017-04-13

    if (!renamed) {
        throw new MessageStoreException("failed to copy message to noarchive queue", logger);
    }
}

From source file:de.fabianonline.telegram_backup.DownloadManager.java

private static boolean downloadFileFromDc(TelegramClient client, String target, TLAbsInputFileLocation loc,
        Integer dcID, int size) throws RpcErrorException, IOException {
    FileOutputStream fos = null;/*from  w  w w  . j  a  v  a2s.c  om*/
    try {
        String temp_filename = target + ".downloading";
        logger.debug("Downloading file {}", target);
        logger.trace("Temporary filename: {}", temp_filename);

        int offset = 0;
        if (new File(temp_filename).isFile()) {
            logger.info("Temporary filename already exists; continuing this file");
            offset = (int) new File(temp_filename).length();
            if (offset >= size) {
                logger.warn("Temporary file size is >= the target size. Assuming corrupt file & deleting it");
                new File(temp_filename).delete();
                offset = 0;
            }
        }
        logger.trace("offset before the loop is {}", offset);
        fos = new FileOutputStream(temp_filename, true);
        TLFile response;
        do {
            int block_size = size;
            logger.trace("offset: {} block_size: {} size: {}", offset, block_size, size);
            TLRequestUploadGetFile req = new TLRequestUploadGetFile(loc, offset, block_size);
            if (dcID == null) {
                response = (TLFile) download_client.executeRpcQuery(req);
            } else {
                response = (TLFile) download_client.executeRpcQuery(req, dcID);
            }

            offset += response.getBytes().getData().length;
            logger.trace("response: {} total size: {}", response.getBytes().getData().length, offset);

            fos.write(response.getBytes().getData());
            fos.flush();
            try {
                TimeUnit.MILLISECONDS.sleep(Config.DELAY_AFTER_GET_FILE);
            } catch (InterruptedException e) {
            }
        } while (offset < size && response.getBytes().getData().length > 0);
        fos.close();
        if (offset < size) {
            System.out.println("Requested file " + target + " with " + size + " bytes, but got only " + offset
                    + " bytes.");
            new File(temp_filename).delete();
            System.exit(1);
        }
        logger.trace("Renaming {} to {}", temp_filename, target);
        int rename_tries = 0;
        IOException last_exception = null;
        while (rename_tries <= Config.RENAMING_MAX_TRIES) {
            rename_tries++;
            try {
                Files.move(new File(temp_filename).toPath(), new File(target).toPath(),
                        StandardCopyOption.REPLACE_EXISTING);
                last_exception = null;
                break;
            } catch (IOException e) {
                logger.debug("Exception during move. rename_tries: {}. Exception: {}", rename_tries, e);
                last_exception = e;
                try {
                    TimeUnit.MILLISECONDS.sleep(Config.RENAMING_DELAY);
                } catch (InterruptedException e2) {
                }
            }
        }
        if (last_exception != null) {
            throw last_exception;
        }
        last_download_succeeded = true;
        return true;
    } catch (java.io.IOException ex) {
        if (fos != null)
            fos.close();
        System.out.println("IOException happened while downloading " + target);
        throw ex;
    } catch (RpcErrorException ex) {
        if (fos != null)
            fos.close();
        if (ex.getCode() == 500) {
            if (!last_download_succeeded) {
                System.out.println(
                        "Got an Internal Server Error from Telegram. Since the file downloaded before also happened to get this error, we will stop downloading now. Please try again later.");
                throw ex;
            }
            last_download_succeeded = false;
            System.out.println(
                    "Got an Internal Server Error from Telegram. Skipping this file for now. Next run of telegram_backup will continue to download this file.");
            logger.warn(ex.toString());
            return false;
        }
        System.out.println("RpcErrorException happened while downloading " + target);
        throw ex;
    }
}

From source file:org.codice.ddf.configuration.admin.ConfigurationAdminMigrationTest.java

@Test
public void testInitMovesFilesWithAnInvalidTypeToFailedDirectory() throws Exception {

    setUpTwoConfigFileIterator(configurationDirectoryStream);

    when(configurationFileFactory.createConfigurationFile(CONFIG_PATH1))
            .thenThrow(new ConfigurationFileException(""));
    when(configurationFileFactory.createConfigurationFile(CONFIG_PATH2))
            .thenThrow(new ConfigurationFileException(""));
    when(Files.move(CONFIG_PATH1, PROCESSED_DIRECTORY_PATH, REPLACE_EXISTING))
            .thenReturn(FAILED_DIRECTORY_PATH);
    when(Files.move(CONFIG_PATH2, PROCESSED_DIRECTORY_PATH, REPLACE_EXISTING))
            .thenReturn(FAILED_DIRECTORY_PATH);

    ConfigurationAdminMigration configurationAdminMigration = new ConfigurationAdminMigration(
            configurationDirectoryStream, PROCESSED_DIRECTORY_PATH, FAILED_DIRECTORY_PATH,
            configurationFileFactory, configurationFilePoller, configurationAdmin,
            CONFIGURATION_FILE_EXTENSION);

    configurationAdminMigration.init();/*  w w  w  .j  av  a 2  s . c o m*/

    verifyStatic();
    Files.move(CONFIG_PATH1, CONFIG_FILE_IN_FAILED_DIRECTORY.resolve(CONFIG_FILE_PATH1), REPLACE_EXISTING);
    Files.move(CONFIG_PATH2, CONFIG_FILE_IN_FAILED_DIRECTORY.resolve(CONFIG_FILE_PATH2), REPLACE_EXISTING);
    verify(configurationDirectoryStream).iterator();
    verify(configurationFileFactory).createConfigurationFile(CONFIG_PATH1);
    verify(configurationFileFactory).createConfigurationFile(CONFIG_PATH2);
    verify(configurationDirectoryStream).close();
}

From source file:org.caleydo.data.importer.tcga.FirehoseProvider.java

private TCGAFileInfo extractFileFromTarGzArchive(URL inUrl, String fileToExtract, File outputDirectory,
        boolean hasTumor) {
    log.info(inUrl + " download and extract: " + fileToExtract);
    File targetFile = new File(outputDirectory, fileToExtract);

    // use cached
    if (targetFile.exists() && !settings.isCleanCache()) {
        log.fine(inUrl + " cache hit");
        return new TCGAFileInfo(targetFile, inUrl, fileToExtract);
    }//from  www  .  j  ava 2 s .  c  o m

    File notFound = new File(outputDirectory, fileToExtract + "-notfound");
    if (notFound.exists() && !settings.isCleanCache()) {
        log.warning(inUrl + " marked as not found");
        return null;
    }

    String alternativeName = fileToExtract;
    if (hasTumor) {
        alternativeName = "/" + tumor.getBaseName() + fileToExtract;
        fileToExtract = "/" + tumor + fileToExtract;
    }

    TarArchiveInputStream tarIn = null;
    OutputStream out = null;
    try {
        InputStream in = new BufferedInputStream(inUrl.openStream());

        // ok we have the file
        tarIn = new TarArchiveInputStream(new GZIPInputStream(in));

        // search the correct entry
        ArchiveEntry act = tarIn.getNextEntry();
        while (act != null && !act.getName().endsWith(fileToExtract)
                && !act.getName().endsWith(alternativeName)) {
            act = tarIn.getNextEntry();
        }
        if (act == null) // no entry found
            throw new FileNotFoundException("no entry named: " + fileToExtract + " found");

        byte[] buf = new byte[4096];
        int n;
        targetFile.getParentFile().mkdirs();
        // use a temporary file to recognize if we have aborted between run
        String tmpFile = targetFile.getAbsolutePath() + ".tmp";
        out = new BufferedOutputStream(new FileOutputStream(tmpFile));
        while ((n = tarIn.read(buf, 0, 4096)) > -1)
            out.write(buf, 0, n);
        out.close();
        Files.move(new File(tmpFile).toPath(), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);

        log.info(inUrl + " extracted " + fileToExtract);
        return new TCGAFileInfo(targetFile, inUrl, fileToExtract);
    } catch (FileNotFoundException e) {
        log.log(Level.WARNING, inUrl + " can't extract" + fileToExtract + ": file not found", e);
        // file was not found, create a marker to remember this for quicker checks
        notFound.getParentFile().mkdirs();
        try {
            notFound.createNewFile();
        } catch (IOException e1) {
            log.log(Level.WARNING, inUrl + " can't create not-found marker", e);
        }
        return null;
    } catch (Exception e) {
        log.log(Level.SEVERE, inUrl + " can't extract" + fileToExtract + ": " + e.getMessage(), e);
        return null;
    } finally {
        Closeables.closeQuietly(tarIn);
        Closeables.closeQuietly(out);
    }
}

From source file:org.apache.storm.daemon.supervisor.SyncSupervisorEvent.java

/**
 * Downloading to permanent location is atomic
 * // w w  w  .  j ava  2s . c om
 * @param conf
 * @param stormId
 * @param masterCodeDir
 * @param localizer
 * @throws Exception
 */
private void downloadDistributeStormCode(Map conf, String stormId, String masterCodeDir, Localizer localizer)
        throws Exception {

    String tmproot = ConfigUtils.supervisorTmpDir(conf) + Utils.FILE_PATH_SEPARATOR + Utils.uuid();
    String stormroot = ConfigUtils.supervisorStormDistRoot(conf, stormId);
    ClientBlobStore blobStore = Utils.getClientBlobStoreForSupervisor(conf);
    FileUtils.forceMkdir(new File(tmproot));
    if (Utils.isOnWindows()) {
        if (Utils.getBoolean(conf.get(Config.SUPERVISOR_RUN_WORKER_AS_USER), false)) {
            throw new RuntimeException("ERROR: Windows doesn't implement setting the correct permissions");
        }
    } else {
        Utils.restrictPermissions(tmproot);
    }
    String stormJarKey = ConfigUtils.masterStormJarKey(stormId);
    String stormCodeKey = ConfigUtils.masterStormCodeKey(stormId);
    String stormConfKey = ConfigUtils.masterStormConfKey(stormId);
    String jarPath = ConfigUtils.supervisorStormJarPath(tmproot);
    String codePath = ConfigUtils.supervisorStormCodePath(tmproot);
    String confPath = ConfigUtils.supervisorStormConfPath(tmproot);
    Utils.downloadResourcesAsSupervisor(stormJarKey, jarPath, blobStore);
    Utils.downloadResourcesAsSupervisor(stormCodeKey, codePath, blobStore);
    Utils.downloadResourcesAsSupervisor(stormConfKey, confPath, blobStore);
    blobStore.shutdown();
    Utils.extractDirFromJar(jarPath, ConfigUtils.RESOURCES_SUBDIR, tmproot);
    downloadBlobsForTopology(conf, confPath, localizer, tmproot);
    if (didDownloadBlobsForTopologySucceed(confPath, tmproot)) {
        LOG.info("Successfully downloaded blob resources for storm-id {}", stormId);
        if (Utils.isOnWindows()) {
            // Files/move with non-empty directory doesn't work well on Windows
            FileUtils.moveDirectory(new File(tmproot), new File(stormroot));
        } else {
            FileUtils.forceMkdir(new File(stormroot));
            Files.move(new File(tmproot).toPath(), new File(stormroot).toPath(),
                    StandardCopyOption.ATOMIC_MOVE);
        }
    } else {
        LOG.info("Failed to download blob resources for storm-id ", stormId);
        Utils.forceDelete(tmproot);
    }
}

From source file:org.openecomp.sdnc.uebclient.SdncUebCallback.java

private void handleSuccessfulDownload(INotificationData data, String svcName, String resourceName,
        IArtifactInfo artifact, File spoolFile, File archiveDir) {

    if ((data != null) && (artifact != null)) {
        // Send Download Status
        IDistributionClientResult sendDownloadStatus = client.sendDownloadStatus(
                buildStatusMessage(client, data, artifact, DistributionStatusEnum.DOWNLOAD_OK));
    }/*from w ww. j  a  va  2s .c  om*/

    // If an override file exists, read that instead of the file we just downloaded
    ArtifactTypeEnum artifactEnum = ArtifactTypeEnum.YANG_XML;

    boolean toscaYamlType = false;
    if (artifact != null) {
        String artifactTypeString = artifact.getArtifactType();
        if (artifactTypeString.contains("TOSCA_TEMPLATE")) {
            toscaYamlType = true;
        }
    } else {
        if (spoolFile.toString().contains(".yml") || spoolFile.toString().contains(".csar")) {
            toscaYamlType = true;
        }
    }
    String overrideFileName = config.getOverrideFile();
    if ((overrideFileName != null) && (overrideFileName.length() > 0)) {
        File overrideFile = new File(overrideFileName);

        if (overrideFile.exists()) {
            artifactEnum = ArtifactTypeEnum.YANG_XML;
            spoolFile = overrideFile;
        }

    }

    if (toscaYamlType == true) {
        processToscaYaml(data, svcName, resourceName, artifact, spoolFile, archiveDir);

        try {
            Path source = spoolFile.toPath();
            Path targetDir = archiveDir.toPath();

            Files.move(source, targetDir.resolve(source.getFileName()), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            LOG.warn("Could not move " + spoolFile.getAbsolutePath() + " to " + archiveDir.getAbsolutePath(),
                    e);
        }

        return;
    }

    // Process spool file
    Document spoolDoc = null;
    File transformedFile = null;

    // Apply XSLTs and get Doc object
    try {
        if (!spoolFile.isDirectory()) {
            transformedFile = applyXslts(spoolFile);
        }
    } catch (Exception e) {
        LOG.error("Caught exception trying to parse XML file", e);
    }

    if (transformedFile != null) {
        try {

            try {

                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();

                spoolDoc = db.parse(transformedFile);
            } catch (Exception e) {
                LOG.error("Caught exception trying to parse transformed XML file "
                        + transformedFile.getAbsolutePath(), e);
            }

        } catch (Exception e) {
            LOG.error("Caught exception trying to deploy file", e);
        }
    }

    if (spoolDoc != null) {
        // Analyze file type
        SdncArtifactType artifactType = analyzeFileType(artifactEnum, spoolFile, spoolDoc);

        if (artifactType != null) {

            scheduleDeployment(artifactType, svcName, resourceName, artifact, spoolFile.getName(),
                    transformedFile);

        }

        // SDNGC-2660 : Move file to archive directory even if it is an unrecognized type so that
        // we do not keep trying and failing to process it.
        try {
            Path source = spoolFile.toPath();
            Path targetDir = archiveDir.toPath();

            Files.move(source, targetDir.resolve(source.getFileName()), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            LOG.warn("Could not move " + spoolFile.getAbsolutePath() + " to " + archiveDir.getAbsolutePath(),
                    e);
        }
    }

}

From source file:org.codice.ddf.configuration.admin.ConfigurationAdminMigrationTest.java

@Test
public void testInitMovesFilesThatCannotBeReadToFailedDirectory() throws Exception {

    setUpTwoConfigFileIterator(configurationDirectoryStream);
    setUpConfigurationFileFactoryForTwoFiles();

    doThrow(new ConfigurationFileException("")).when(configFile1).createConfig();
    doThrow(new ConfigurationFileException("")).when(configFile2).createConfig();

    when(Files.move(CONFIG_PATH1, PROCESSED_DIRECTORY_PATH, REPLACE_EXISTING))
            .thenReturn(FAILED_DIRECTORY_PATH);

    when(Files.move(CONFIG_PATH2, PROCESSED_DIRECTORY_PATH, REPLACE_EXISTING))
            .thenReturn(FAILED_DIRECTORY_PATH);

    ConfigurationAdminMigration configurationAdminMigrator = new ConfigurationAdminMigration(
            configurationDirectoryStream, PROCESSED_DIRECTORY_PATH, FAILED_DIRECTORY_PATH,
            configurationFileFactory, configurationFilePoller, configurationAdmin,
            CONFIGURATION_FILE_EXTENSION);

    configurationAdminMigrator.init();//from   www .  j  a  v  a  2s .c om

    verifyStatic();
    Files.move(CONFIG_PATH1, CONFIG_FILE_IN_FAILED_DIRECTORY.resolve(CONFIG_FILE_PATH1), REPLACE_EXISTING);
    Files.move(CONFIG_PATH2, CONFIG_FILE_IN_FAILED_DIRECTORY.resolve(CONFIG_FILE_PATH2), REPLACE_EXISTING);
    verify(configurationDirectoryStream).close();
}

From source file:com.ut.healthelink.controller.HealtheConnectController.java

/**
 * The '/submitFileUpload' POST request will submit the new file and run the file through various validations. If a single validation fails the batch will be put in a error validation status and the file will be removed from the system. The user will receive an error message on the screen letting them know which validations have failed and be asked to upload a new file.
 *
 * The following validations will be taken place. - File is not empty - Proper file type (as determined in the configuration set up) - Proper delimiter (as determined in the configuration set up) - Does not exceed file size (as determined in the configuration set up)
 *///from  w  w  w  . j  av a 2 s .c o  m
@RequestMapping(value = "/submitFileUpload", method = RequestMethod.POST)
public @ResponseBody ModelAndView submitFileUpload(RedirectAttributes redirectAttr, HttpSession session,
        @RequestParam(value = "configId", required = true) Integer configId,
        @RequestParam(value = "uploadedFile", required = true) MultipartFile uploadedFile) throws Exception {

    /* Get the organization details for the source (Sender) organization */
    User userInfo = (User) session.getAttribute("userDetails");

    configuration configDetails = null;
    configurationTransport transportDetails = null;
    configurationMessageSpecs messageSpecs = null;
    String delimChar = null;
    boolean multipleMessageTypes = false;

    /* 
     When Multiple Message Types is selected we need to find one config Id attached to the user in order
     to pull the information to process the file.
     */
    if (configId == 0) {

        /* Need to get list of available configurations for the user */
        List<configuration> configurations = configurationManager
                .getActiveConfigurationsByUserId(userInfo.getId(), 1);

        /* Pull the first configuration in the list */
        configId = configurations.get(0).getId();

        /* Need to get the details of the configuration */
        configDetails = configurationManager.getConfigurationById(configId);
        transportDetails = configurationtransportmanager.getTransportDetails(configId);
        messageSpecs = configurationManager.getMessageSpecs(configId);

        delimChar = (String) messageTypeDAO.getDelimiterChar(transportDetails.getfileDelimiter());

        multipleMessageTypes = true;
    } else {
        /* Need to get the details of the configuration */
        configDetails = configurationManager.getConfigurationById(configId);
        transportDetails = configurationtransportmanager.getTransportDetails(configId);
        messageSpecs = configurationManager.getMessageSpecs(configId);

        delimChar = (String) messageTypeDAO.getDelimiterChar(transportDetails.getfileDelimiter());

    }

    try {

        /* Need to add the file to the batchUploads table */
        /* Create the batch name (TransportMethodId+OrgId+MessageTypeId+Date/Time/Seconds) */
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssS");
        Date date = new Date();
        //adding transport method id to UT batch name
        String batchName = new StringBuilder().append("1").append(userInfo.getOrgId())
                .append(configDetails.getMessageTypeId()).append(dateFormat.format(date)).toString();

        /* Upload the file */
        Map<String, String> batchResults = null;

        fileSystem dir = new fileSystem();
        dir.setDirByName("/");

        //need to write the file first, we will write it to our process folder
        String uploadedFileName = transactionInManager.copyUplaodedPath(transportDetails, uploadedFile);
        String oldFilePath = dir.getDir() + transportDetails.getfileLocation();
        oldFilePath = oldFilePath.replace("bowlink///", "");
        File oldFile = new File(oldFilePath + uploadedFileName);
        Path source = oldFile.toPath();

        String processFilePath = dir.setPath(processPath);
        String strProcessFile = processFilePath + uploadedFileName;
        File processFile = new File(strProcessFile);

        //right now we only support id 2, Base64
        if (transportDetails.getEncodingId() == 2) {
            String strDecode = filemanager.decodeFileToBase64Binary(oldFile);
            filemanager.writeFile((processFilePath + uploadedFileName), strDecode);
        } else {
            processFile = oldFile;
        }
        //we decode file and pass it into uploadedFile
        batchResults = transactionInManager.chkUploadBatchFile(transportDetails, processFile);
        //we delete the temp file here
        if (transportDetails.getEncodingId() == 2) {
            processFile.delete();
        }

        //we set archive path
        File archiveFile = new File(dir.setPath(archivePath) + batchName
                + batchResults.get("fileName").substring(batchResults.get("fileName").lastIndexOf(".")));
        Path archive = archiveFile.toPath();

        if (transportDetails.getEncodingId() == 1) {
            String strEncodedFile = filemanager.encodeFileToBase64Binary(oldFile);
            Files.move(source, archive, REPLACE_EXISTING);
            //we replace file with encoded
            filemanager.writeFile(oldFile.getAbsolutePath(), strEncodedFile);
        } else { // already encoded
            Files.copy(source, archive);
        }

        /* Submit a new batch */
        batchUploads batchUpload = new batchUploads();
        batchUpload.setOrgId(userInfo.getOrgId());
        batchUpload.setuserId(userInfo.getId());
        batchUpload.setutBatchName(batchName);
        batchUpload.settransportMethodId(1);
        batchUpload.setoriginalFileName(batchName);
        batchUpload.setoriginalFileName(batchResults.get("fileName"));
        batchUpload.setFileLocation(transportDetails.getfileLocation());
        batchUpload.setContainsHeaderRow(messageSpecs.getcontainsHeaderRow());
        batchUpload.setDelimChar(delimChar);
        batchUpload.setEncodingId(transportDetails.getEncodingId());

        if (multipleMessageTypes == true) {
            batchUpload.setConfigId(0);
        } else {
            batchUpload.setConfigId(configId);
        }

        /* Set the status to the batch as SFV (Source Failed Validation) */
        batchUpload.setstatusId(1);

        Integer batchId = (Integer) transactionInManager.submitBatchUpload(batchUpload);

        List<Integer> errorCodes = new ArrayList<Integer>();

        Object emptyFileVal = batchResults.get("emptyFile");
        if (emptyFileVal != null) {
            errorCodes.add(1);
        }

        Object wrongSizeVal = batchResults.get("wrongSize");
        if (wrongSizeVal != null) {
            errorCodes.add(2);
        }

        Object wrongFileTypeVal = batchResults.get("wrongFileType");
        if (wrongFileTypeVal != null) {
            errorCodes.add(3);
        }

        Object wrongDelimVal = batchResults.get("wrongDelim");
        if (wrongDelimVal != null) {
            errorCodes.add(4);
        }

        /* Make sure the org doesn't have multiple configurations with different delims, headers, etc */
        if (multipleMessageTypes == true) {
            List<configurationTransport> transportTypes = configurationtransportmanager
                    .getDistinctConfigTransportForOrg(userInfo.getOrgId(), 1);

            if (transportTypes.size() != 1) {
                errorCodes.add(5);
            }
        }

        /* If Passed validation update the status to Source Submission Accepted */
        if (0 == errorCodes.size()) {
            /* Get the details of the batch */
            batchUploads batch = transactionInManager.getBatchDetails(batchId);
            batch.setstatusId(2);

            transactionInManager.submitBatchUploadChanges(batch);

            /* Redirect to the list of uploaded batches */
            redirectAttr.addFlashAttribute("savedStatus", "uploaded");

        } else {
            redirectAttr.addFlashAttribute("savedStatus", "error");
            redirectAttr.addFlashAttribute("errorCodes", errorCodes);
        }

        try {
            //log user activity
            UserActivity ua = new UserActivity();
            ua.setUserId(userInfo.getId());
            ua.setFeatureId(featureId);
            ua.setAccessMethod("POST");
            ua.setPageAccess("/submitFileUpload");
            ua.setActivity("Uploaded a new file");
            ua.setBatchUploadId(batchId);
            usermanager.insertUserLog(ua);
        } catch (Exception ex) {
            System.err.println("submitFileUpload = error logging user " + ex.getCause());
            ex.printStackTrace();
        }

        ModelAndView mav = new ModelAndView(new RedirectView("upload"));
        return mav;

    } catch (Exception e) {
        throw new Exception("Error occurred uploading a new file. configId: " + configId, e);
    }

}

From source file:org.caleydo.data.importer.tcga.FirehoseProvider.java

private static File parseMAF(File maf) {

    File out = new File(maf.getParentFile(), "P" + maf.getName());
    if (out.exists())
        return out;
    log.fine(maf.getAbsolutePath() + " parsing maf file");
    final String TAB = "\t";

    try (BufferedReader reader = Files.newBufferedReader(maf.toPath(), Charset.forName("UTF-8"))) {
        List<String> header = Arrays.asList(reader.readLine().split(TAB));
        int geneIndex = header.indexOf("Hugo_Symbol");
        int sampleIndex = header.indexOf("Tumor_Sample_Barcode");
        // gene x sample x mutated
        Table<String, String, Boolean> mutated = TreeBasedTable.create();
        String line = null;/*from  w w w  .  j a v  a 2  s .com*/
        while ((line = reader.readLine()) != null) {
            String[] columns = line.split(TAB);
            mutated.put(columns[geneIndex], columns[sampleIndex], Boolean.TRUE);
        }

        File tmp = new File(out.getParentFile(), out.getName() + ".tmp");
        PrintWriter w = new PrintWriter(tmp);
        w.append("Hugo_Symbol");
        List<String> cols = new ArrayList<>(mutated.columnKeySet());
        for (String sample : cols) {
            w.append(TAB).append(sample);
        }
        w.println();
        Set<String> rows = mutated.rowKeySet();
        for (String gene : rows) {
            w.append(gene);
            for (String sample : cols) {
                w.append(TAB).append(mutated.contains(gene, sample) ? '1' : '0');
            }
            w.println();
        }
        w.close();
        Files.move(tmp.toPath(), out.toPath(), StandardCopyOption.REPLACE_EXISTING);

        log.fine(maf.getAbsolutePath() + " parsed maf file stats: " + mutated.size() + " " + rows.size() + " "
                + cols.size());
        return out;
    } catch (IOException e) {
        log.log(Level.SEVERE, maf.getAbsolutePath() + " maf parsing error: " + e.getMessage(), e);
    }
    return null;
}