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

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

Introduction

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

Prototype

public static String getBaseName(String filename) 

Source Link

Document

Gets the base name, minus the full path and extension, from a full filename.

Usage

From source file:com.springsense.nutch.indexer.SpringSenseIndexingFilter.java

protected String preprocessUrlOrPath(String urlOrPath) {
    if (StringUtils.isBlank(urlOrPath)) {
        return null;
    }/*from www  .  jav a 2s  .c o m*/

    String path = null;

    URL url;
    try {
        url = new URL(urlOrPath);

        path = url.getPath();
    } catch (MalformedURLException e) {
        // Assume we got a file path... We'll attempt to treat it so.
        path = urlOrPath;
    }

    String decodedUrlOrPath = null;
    try {
        decodedUrlOrPath = URLDecoder.decode(path, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        LOG.error(String.format("Couldn't decode URL or path: '%s' due to an error", urlOrPath), e);
        return null;
    }

    String fileBaseNameWithoutExtension = FilenameUtils
            .removeExtension(FilenameUtils.getBaseName(decodedUrlOrPath));

    return splitCamelCase(fileBaseNameWithoutExtension);
}

From source file:gov.nih.nci.caarray.plugins.illumina.SampleProbeProfileHandler.java

/**
 * {@inheritDoc}//w  ww .j  a v  a 2s  .c o  m
 */
@Override
public List<LSID> getReferencedArrayDesignCandidateIds() {
    final InfoHeadingParser p = new InfoHeadingParser();
    processFile(getFile(), p);
    String fileName = p.getValues().get(InfoHeadingParser.KEY_ARRAY_CONTENT);
    if (fileName == null) {
        throw new IllegalStateException("Missing header field '" + InfoHeadingParser.KEY_ARRAY_CONTENT + "'");
    }
    final List<LSID> lsids = new ArrayList<LSID>();
    while (!StringUtils.isEmpty(FilenameUtils.getExtension(fileName))) {
        lsids.add(new LSID(IlluminaCsvDesignHandler.LSID_AUTHORITY, IlluminaCsvDesignHandler.LSID_NAMESPACE,
                fileName));
        fileName = FilenameUtils.getBaseName(fileName);
    }
    lsids.add(new LSID(IlluminaCsvDesignHandler.LSID_AUTHORITY, IlluminaCsvDesignHandler.LSID_NAMESPACE,
            fileName));
    return lsids;
}

From source file:DIA_Umpire_Quant.DIA_Umpire_ProtQuant.java

/**
 * @param args the command line arguments
 *//*ww  w  . ja  va 2s.  c  o  m*/
public static void main(String[] args) throws FileNotFoundException, IOException, Exception {
    System.out.println(
            "=================================================================================================");
    System.out.println(
            "DIA-Umpire protein quantitation module (version: " + UmpireInfo.GetInstance().Version + ")");
    if (args.length != 1) {
        System.out.println(
                "command format error, the correct format should be: java -jar -Xmx10G DIA_Umpire_PortQuant.jar diaumpire_module.params");
        return;
    }
    try {
        ConsoleLogger.SetConsoleLogger(Level.INFO);
        ConsoleLogger.SetFileLogger(Level.DEBUG,
                FilenameUtils.getFullPath(args[0]) + "diaumpire_orotquant.log");
    } catch (Exception e) {
    }

    Logger.getRootLogger().info("Version: " + UmpireInfo.GetInstance().Version);
    Logger.getRootLogger().info("Parameter file:" + args[0]);

    BufferedReader reader = new BufferedReader(new FileReader(args[0]));
    String line = "";
    String WorkFolder = "";
    int NoCPUs = 2;

    String Combined_Prot = "";
    boolean DefaultProtFiltering = true;

    float Freq = 0f;
    int TopNPep = 6;
    int TopNFrag = 6;
    String FilterWeight = "GW";
    float MinWeight = 0.9f;

    TandemParam tandemPara = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600);
    HashMap<String, File> AssignFiles = new HashMap<>();

    boolean ExportSaint = false;
    boolean SAINT_MS1 = false;
    boolean SAINT_MS2 = true;

    HashMap<String, String[]> BaitList = new HashMap<>();
    HashMap<String, String> BaitName = new HashMap<>();
    HashMap<String, String[]> ControlList = new HashMap<>();
    HashMap<String, String> ControlName = new HashMap<>();

    //<editor-fold defaultstate="collapsed" desc="Reading parameter file">
    while ((line = reader.readLine()) != null) {
        line = line.trim();
        Logger.getRootLogger().info(line);
        if (!"".equals(line) && !line.startsWith("#")) {
            //System.out.println(line);
            if (line.equals("==File list begin")) {
                do {
                    line = reader.readLine();
                    line = line.trim();
                    if (line.equals("==File list end")) {
                        continue;
                    } else if (!"".equals(line)) {
                        File newfile = new File(line);
                        if (newfile.exists()) {
                            AssignFiles.put(newfile.getAbsolutePath(), newfile);
                        } else {
                            Logger.getRootLogger().info("File: " + newfile + " does not exist.");
                        }
                    }
                } while (!line.equals("==File list end"));
            }
            if (line.split("=").length < 2) {
                continue;
            }
            String type = line.split("=")[0].trim();
            String value = line.split("=")[1].trim();
            switch (type) {
            case "Path": {
                WorkFolder = value;
                break;
            }
            case "path": {
                WorkFolder = value;
                break;
            }
            case "Thread": {
                NoCPUs = Integer.parseInt(value);
                break;
            }
            case "Fasta": {
                tandemPara.FastaPath = value;
                break;
            }
            case "Combined_Prot": {
                Combined_Prot = value;
                break;
            }
            case "DefaultProtFiltering": {
                DefaultProtFiltering = Boolean.parseBoolean(value);
                break;
            }
            case "DecoyPrefix": {
                if (!"".equals(value)) {
                    tandemPara.DecoyPrefix = value;
                }
                break;
            }
            case "ProteinFDR": {
                tandemPara.ProtFDR = Float.parseFloat(value);
                break;
            }
            case "FilterWeight": {
                FilterWeight = value;
                break;
            }
            case "MinWeight": {
                MinWeight = Float.parseFloat(value);
                break;
            }
            case "TopNFrag": {
                TopNFrag = Integer.parseInt(value);
                break;
            }
            case "TopNPep": {
                TopNPep = Integer.parseInt(value);
                break;
            }
            case "Freq": {
                Freq = Float.parseFloat(value);
                break;
            }
            //<editor-fold defaultstate="collapsed" desc="SaintOutput">
            case "ExportSaintInput": {
                ExportSaint = Boolean.parseBoolean(value);
                break;
            }
            case "QuantitationType": {
                switch (value) {
                case "MS1": {
                    SAINT_MS1 = true;
                    SAINT_MS2 = false;
                    break;
                }
                case "MS2": {
                    SAINT_MS1 = false;
                    SAINT_MS2 = true;
                    break;
                }
                case "BOTH": {
                    SAINT_MS1 = true;
                    SAINT_MS2 = true;
                    break;
                }
                }
                break;
            }
            //                    case "BaitInputFile": {
            //                        SaintBaitFile = value;
            //                        break;
            //                    }
            //                    case "PreyInputFile": {
            //                        SaintPreyFile = value;
            //                        break;
            //                    }
            //                    case "InterationInputFile": {
            //                        SaintInteractionFile = value;
            //                        break;
            //                    }
            default: {
                if (type.startsWith("BaitName_")) {
                    BaitName.put(type.substring(9), value);
                }
                if (type.startsWith("BaitFile_")) {
                    BaitList.put(type.substring(9), value.split("\t"));
                }
                if (type.startsWith("ControlName_")) {
                    ControlName.put(type.substring(12), value);
                }
                if (type.startsWith("ControlFile_")) {
                    ControlList.put(type.substring(12), value.split("\t"));
                }
                break;
            }
            //</editor-fold>                    
            }
        }
    }
    //</editor-fold>

    //Initialize PTM manager using compomics library
    PTMManager.GetInstance();

    //Check if the fasta file can be found
    if (!new File(tandemPara.FastaPath).exists()) {
        Logger.getRootLogger().info("Fasta file :" + tandemPara.FastaPath
                + " cannot be found, the process will be terminated, please check.");
        System.exit(1);
    }

    //Check if the prot.xml file can be found
    if (!new File(Combined_Prot).exists()) {
        Logger.getRootLogger().info("ProtXML file: " + Combined_Prot
                + " cannot be found, the export protein summary table will be empty.");
    }
    LCMSID protID = null;

    //Parse prot.xml and generate protein master list given an FDR 
    if (Combined_Prot != null && !Combined_Prot.equals("")) {
        protID = LCMSID.ReadLCMSIDSerialization(Combined_Prot);
        if (!"".equals(Combined_Prot) && protID == null) {
            protID = new LCMSID(Combined_Prot, tandemPara.DecoyPrefix, tandemPara.FastaPath);
            ProtXMLParser protxmlparser = new ProtXMLParser(protID, Combined_Prot, 0f);
            //Use DIA-Umpire default protein FDR calculation
            if (DefaultProtFiltering) {
                protID.RemoveLowLocalPWProtein(0.8f);
                protID.RemoveLowMaxIniProbProtein(0.9f);
                protID.FilterByProteinDecoyFDRUsingMaxIniProb(tandemPara.DecoyPrefix, tandemPara.ProtFDR);
            }
            //Get protein FDR calculation without other filtering
            else {
                protID.FilterByProteinDecoyFDRUsingLocalPW(tandemPara.DecoyPrefix, tandemPara.ProtFDR);
            }
            protID.LoadSequence();
            protID.WriteLCMSIDSerialization(Combined_Prot);
        }
        Logger.getRootLogger().info("Protein No.:" + protID.ProteinList.size());
    }
    HashMap<String, HashMap<String, FragmentPeak>> IDSummaryFragments = new HashMap<>();

    //Generate DIA file list
    ArrayList<DIAPack> FileList = new ArrayList<>();
    try {
        File folder = new File(WorkFolder);
        if (!folder.exists()) {
            Logger.getRootLogger().info("The path : " + WorkFolder + " cannot be found.");
            System.exit(1);
        }
        for (final File fileEntry : folder.listFiles()) {
            if (fileEntry.isFile()
                    && (fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                            | fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzml"))
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
                AssignFiles.put(fileEntry.getAbsolutePath(), fileEntry);
            }
            if (fileEntry.isDirectory()) {
                for (final File fileEntry2 : fileEntry.listFiles()) {
                    if (fileEntry2.isFile()
                            && (fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                                    | fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzml"))
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
                        AssignFiles.put(fileEntry2.getAbsolutePath(), fileEntry2);
                    }
                }
            }
        }

        Logger.getRootLogger().info("No. of files assigned :" + AssignFiles.size());
        for (File fileEntry : AssignFiles.values()) {
            Logger.getRootLogger().info(fileEntry.getAbsolutePath());
        }

        for (File fileEntry : AssignFiles.values()) {
            String mzXMLFile = fileEntry.getAbsolutePath();
            if (mzXMLFile.toLowerCase().endsWith(".mzxml") | mzXMLFile.toLowerCase().endsWith(".mzml")) {
                DIAPack DiaFile = new DIAPack(mzXMLFile, NoCPUs);
                Logger.getRootLogger().info(
                        "=================================================================================================");
                Logger.getRootLogger().info("Processing " + mzXMLFile);
                if (!DiaFile.LoadDIASetting()) {
                    Logger.getRootLogger().info("Loading DIA setting failed, job is incomplete");
                    System.exit(1);
                }
                if (!DiaFile.LoadParams()) {
                    Logger.getRootLogger().info("Loading parameters failed, job is incomplete");
                    System.exit(1);
                }
                Logger.getRootLogger().info("Loading identification results " + mzXMLFile + "....");

                //If the serialization file for ID file existed
                if (DiaFile.ReadSerializedLCMSID()) {
                    DiaFile.IDsummary.ReduceMemoryUsage();
                    DiaFile.IDsummary.ClearAssignPeakCluster();
                    FileList.add(DiaFile);
                    HashMap<String, FragmentPeak> FragMap = new HashMap<>();
                    IDSummaryFragments.put(FilenameUtils.getBaseName(mzXMLFile), FragMap);
                }
            }
        }

        //<editor-fold defaultstate="collapsed" desc="Peptide and fragment selection">

        Logger.getRootLogger().info("Peptide and fragment selection across the whole dataset");
        ArrayList<LCMSID> SummaryList = new ArrayList<>();
        for (DIAPack diafile : FileList) {
            if (protID != null) {
                //Generate protein list according to mapping of peptide ions for each DIA file to the master protein list
                diafile.IDsummary.GenerateProteinByRefIDByPepSeq(protID, true);
                diafile.IDsummary.ReMapProPep();
            }
            if ("GW".equals(FilterWeight)) {
                diafile.IDsummary.SetFilterByGroupWeight();
            } else if ("PepW".equals(FilterWeight)) {
                diafile.IDsummary.SetFilterByWeight();
            }
            SummaryList.add(diafile.IDsummary);
        }
        FragmentSelection fragselection = new FragmentSelection(SummaryList);
        fragselection.freqPercent = Freq;
        fragselection.GeneratePepFragScoreMap();
        fragselection.GenerateTopFragMap(TopNFrag);
        fragselection.GenerateProtPepScoreMap(MinWeight);
        fragselection.GenerateTopPepMap(TopNPep);
        //</editor-fold>

        //<editor-fold defaultstate="collapsed" desc="Writing general reports">                 
        ExportTable export = new ExportTable(WorkFolder, SummaryList, IDSummaryFragments, protID,
                fragselection);
        export.Export(TopNPep, TopNFrag, Freq);
        //</editor-fold>

        //<editor-fold defaultstate="collapsed" desc="//<editor-fold defaultstate="collapsed" desc="Generate SAINT input files">
        if (ExportSaint && protID != null) {
            HashMap<String, DIAPack> Filemap = new HashMap<>();
            for (DIAPack DIAfile : FileList) {
                Filemap.put(DIAfile.GetBaseName(), DIAfile);
            }

            FileWriter baitfile = new FileWriter(WorkFolder + "SAINT_Bait_" + DateTimeTag.GetTag() + ".txt");
            FileWriter preyfile = new FileWriter(WorkFolder + "SAINT_Prey_" + DateTimeTag.GetTag() + ".txt");
            FileWriter interactionfileMS1 = null;
            FileWriter interactionfileMS2 = null;
            if (SAINT_MS1) {
                interactionfileMS1 = new FileWriter(
                        WorkFolder + "SAINT_Interaction_MS1_" + DateTimeTag.GetTag() + ".txt");
            }
            if (SAINT_MS2) {
                interactionfileMS2 = new FileWriter(
                        WorkFolder + "SAINT_Interaction_MS2_" + DateTimeTag.GetTag() + ".txt");
            }
            HashMap<String, String> PreyID = new HashMap<>();

            for (String samplekey : ControlName.keySet()) {
                String name = ControlName.get(samplekey);
                for (String file : ControlList.get(samplekey)) {
                    baitfile.write(FilenameUtils.getBaseName(file) + "\t" + name + "\t" + "C\n");
                    LCMSID IDsummary = Filemap.get(FilenameUtils.getBaseName(file)).IDsummary;
                    if (SAINT_MS1) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS1, file, name, PreyID,
                                1);
                    }
                    if (SAINT_MS2) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS2, file, name, PreyID,
                                2);
                    }
                }
            }
            for (String samplekey : BaitName.keySet()) {
                String name = BaitName.get(samplekey);
                for (String file : BaitList.get(samplekey)) {
                    baitfile.write(FilenameUtils.getBaseName(file) + "\t" + name + "\t" + "T\n");
                    LCMSID IDsummary = Filemap.get(FilenameUtils.getBaseName(file)).IDsummary;
                    if (SAINT_MS1) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS1, file, name, PreyID,
                                1);
                    }
                    if (SAINT_MS2) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS2, file, name, PreyID,
                                2);
                    }
                }
            }
            baitfile.close();
            if (SAINT_MS1) {
                interactionfileMS1.close();
            }
            if (SAINT_MS2) {
                interactionfileMS2.close();
            }
            for (String AccNo : PreyID.keySet()) {
                preyfile.write(AccNo + "\t" + PreyID.get(AccNo) + "\n");
            }
            preyfile.close();
        }

        //</editor-fold>

        Logger.getRootLogger().info("Job done");
        Logger.getRootLogger().info(
                "=================================================================================================");

    } catch (Exception e) {
        Logger.getRootLogger().error(ExceptionUtils.getStackTrace(e));
        throw e;
    }
}

From source file:de.uzk.hki.da.grid.FakeGridFacade.java

/**
 * Scans AIP for marker file to mark this file as corrupted for sing in 
 * acceptance testing on DEV machines/*from  w  w  w  .  ja  v  a 2  s .c o  m*/
 * @author Jens Peters
 * @param custodyFile
 * @return
 */
private boolean checkForCorruptedMarker(File custodyFile) {
    try {

        FileUtils.copyFileToDirectory(custodyFile, new File(tmpFolder), false);
        String packname = custodyFile.getName();
        String dirname = FilenameUtils.getBaseName(custodyFile.getName());

        ArchiveBuilderFactory.getArchiveBuilderForFile(new File("/tmp/" + packname))
                .unarchiveFolder(new File(tmpFolder + packname), new File("/tmp/"));
        logger.debug("Extracting " + packname + " to + " + tmpFolder + dirname);

        IOFileFilter filter = new WildcardFileFilter("DESTROYED*");
        Collection<File> files = FileUtils.listFiles(new File(tmpFolder + dirname), filter,
                DirectoryFileFilter.DIRECTORY);

        if (files.size() > 0) {
            logger.debug("found destroy marker");
            FolderUtils.deleteDirectorySafe(new File(tmpFolder + dirname));
            return true;
        } else
            FolderUtils.deleteDirectorySafe(new File(tmpFolder + dirname));
    } catch (Exception e) {
        logger.error("Error while checking validity on fakedGridfacade on " + custodyFile.getAbsolutePath()
                + ": " + e.getMessage());
    }
    logger.debug("found no destroy marker!");
    return false;
}

From source file:com.haulmont.cuba.gui.theme.ThemeConstantsRepository.java

public String parseThemeName(String fileName) {
    String name = FilenameUtils.getBaseName(fileName);
    if (name.endsWith("-theme")) {
        int dashIndex = name.lastIndexOf("-theme");
        return name.substring(0, dashIndex);
    } else {/*from  ww w . ja v  a  2 s .c  o  m*/
        return name;
    }
}

From source file:io.stallion.contentPublishing.UploadRequestProcessor.java

protected File downloadExternalToLocalFile(U uploaded) {

    URI uri = URI.create(urlToFetch);

    String fullFileName = FilenameUtils.getName(uri.getPath());
    String extension = FilenameUtils.getExtension(fullFileName);
    String fileName = truncate(fullFileName, 85);
    String relativePath = GeneralUtils.slugify(truncate(FilenameUtils.getBaseName(fullFileName), 75)) + "-"
            + DateUtils.mils() + "." + extension;
    relativePath = "stallion-file-" + uploaded.getId() + "/" + GeneralUtils.secureRandomToken(8) + "/"
            + relativePath;/*from  w w w  .  jav a  2 s . c o  m*/

    String destPath = uploadsFolder + relativePath;
    try {
        FileUtils.forceMkdir(new File(destPath).getParentFile());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    uploaded.setCloudKey(relativePath).setExtension(extension).setName(fileName)
            .setOwnerId(Context.getUser().getId()).setUploadedAt(DateUtils.utcNow())
            .setType(fileController.getTypeForExtension(extension));

    // Make raw URL
    String url = makeRawUrlForFile(uploaded, "org");
    uploaded.setRawUrl(url);

    fileController.save(uploaded);

    File outFile = new File(destPath);

    try {
        IOUtils.copy(Unirest.get(urlToFetch).asBinary().getRawBody(),
                org.apache.commons.io.FileUtils.openOutputStream(outFile));
    } catch (UnirestException e) {
        throw new ClientException("Error downloading file from " + url + ": " + e.getMessage(), 400, e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return outFile;

}

From source file:ee.ria.DigiDoc.activity.OpenExternalFileActivity.java

public ContainerFacade createContainer(Uri uri) {
    String fileName = FileUtils.resolveFileName(uri, getContentResolver());
    if (OpenExternalFileActivity.containerExt.contains(FilenameUtils.getExtension(fileName))) {
        try {//w ww . j av a  2s  . c  o m
            return ContainerBuilder.aContainer(this).fromExternalContainer(uri).build();
        } catch (ContainerBuilder.ExternalContainerSaveException e) {
            Timber.e(e, "Failed to create container");
            return null;
        }
    } else {
        return ContainerBuilder.aContainer(this).withDataFile(uri)
                .withContainerName(FilenameUtils.getBaseName(fileName) + "." + getContainerFormat()).build();
    }
}

From source file:de.xirp.profile.ProfileGenerator.java

/**
 * Generates a BOT file with the given path from the given 
 * {@link de.xirp.profile.CommunicationSpecification comm-spec} 
 * bean./*from  w  w  w . j  av a2s.c o m*/
 * 
 * @param commSpec
 *          The comm-spec to generate the XML for. 
 * @param cmsFile
 *          The file to write the result to. Must be the full path.
 * 
 * @throws JAXBException if the given comm-spec was null, or something 
 *                    went wrong generating the xml.
 * @throws FileNotFoundException if something went wrong generating the xml.
 */
public static void generateCMS(CommunicationSpecification commSpec, File cmsFile)
        throws JAXBException, FileNotFoundException {

    if (commSpec == null) {
        throw new JAXBException(I18n.getString("ProfileGenerator.exception.comSpecNull")); //$NON-NLS-1$
    }

    String fileName = FilenameUtils.getBaseName(cmsFile.getName());

    JAXBContext jc = JAXBContext.newInstance(CommunicationSpecification.class);
    Marshaller m = jc.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    m.marshal(commSpec, new FileOutputStream(
            Constants.CONF_COMMSPECS_DIR + File.separator + fileName + Constants.COMM_SPEC_POSTFIX));
}

From source file:net.mitnet.tools.pdf.book.pdf.builder.ui.cli.PdfBookBuilderCLI.java

public PdfBookBuilderConfig parseConfig(String[] args) throws Exception {

    PdfBookBuilderConfig config = new PdfBookBuilderConfig();

    CommandLineParser commandLineParser = new PosixParser();
    CommandLine commandLine = commandLineParser.parse(CLI_OPTIONS, args);
    CommandLineHelper commandLineHelper = new CommandLineHelper(commandLine);

    if (!commandLineHelper.hasOption(CliOptions.OPTION_INPUT_DIR)) {
        System.err.println("Must specify " + CliOptions.OPTION_INPUT_DIR.getDescription());
        showHelp();//w  ww  .j  a v  a 2  s.c om
    }
    File inputDir = commandLineHelper.getOptionValueAsFile(CliOptions.OPTION_INPUT_DIR);
    config.setInputDir(inputDir);

    if (!commandLineHelper.hasOption(CliOptions.OPTION_OUTPUT_BOOK_FILE)) {
        System.err.println("Must specify " + CliOptions.OPTION_OUTPUT_BOOK_FILE.getDescription());
        showHelp();
    }
    File outputBookFile = commandLineHelper.getOptionValueAsFile(CliOptions.OPTION_OUTPUT_BOOK_FILE);
    config.setOutputBookFile(outputBookFile);

    Rectangle pageSize = ConfigHelper.parsePageSize(commandLineHelper);
    config.setPageSize(pageSize);

    boolean debug = false;
    if (commandLineHelper.hasOption(CliOptions.OPTION_DEBUG)) {
        debug = true;
    }
    config.setDebugEnabled(debug);

    boolean verbose = false;
    if (commandLineHelper.hasOption(CliOptions.OPTION_VERBOSE)) {
        verbose = true;
    }
    config.setVerboseEnabled(verbose);

    String metaTitle = FilenameUtils.getBaseName(outputBookFile.getName());
    if (metaTitle != null) {
        metaTitle = metaTitle.toUpperCase();
    }
    if (commandLineHelper.hasOption(CliOptions.OPTION_META_TITLE)) {
        metaTitle = commandLineHelper.getOptionValue(CliOptions.OPTION_META_TITLE);
    }
    config.setMetaTitle(metaTitle);

    String metaAuthor = System.getProperty("user.name");
    if (commandLineHelper.hasOption(CliOptions.OPTION_META_AUTHOR)) {
        metaAuthor = commandLineHelper.getOptionValue(CliOptions.OPTION_META_AUTHOR);
    }
    config.setMetaAuthor(metaAuthor);

    int nup = CliDefaultValues.DEFAULT_NUP;
    if (commandLineHelper.hasOption(CliOptions.OPTION_NUP)) {
        nup = commandLineHelper.getOptionValueAsInt(CliOptions.OPTION_NUP);
    }
    config.setNup(nup);

    PdfPageEvent pdfPageEventListener = new PdfPageEventLogger();
    config.setPdfPageEventListener(pdfPageEventListener);

    config.setBuildTocEnabled(true);
    TocBuilder tocBuilder = new TocBuilder();
    // config.setTocBuilder(tocBuilder);
    config.setTocRowChangeListener(tocBuilder);

    return config;
}

From source file:eu.udig.catalog.jgrass.workspacecreation.NewJGrassLocationFromFileWizard.java

@Override
public boolean performFinish() {
    try {/*from ww  w .j  a va  2 s .c  o  m*/
        String importFilePath = props.importFilePath;
        File mapFile = new File(importFilePath);
        CoordinateReferenceSystem fileCrs = null;
        GridCoverage2D geodata = null;
        if (mapFile.getName().endsWith(".asc")) {
            ArcGridReader arcGridReader = new ArcGridReader(mapFile);
            geodata = arcGridReader.read(null);
            geodata = geodata.view(ViewType.GEOPHYSICS);
            geodata = JGrassCatalogUtilities.removeNovalues(geodata);
            fileCrs = arcGridReader.getCrs();
        } else if (mapFile.getName().endsWith(".tif") || mapFile.getName().endsWith(".tiff")) {
            GeoTiffReader geotiffGridReader = new GeoTiffReader(mapFile);
            geodata = geotiffGridReader.read(null);
            geodata = geodata.view(ViewType.GEOPHYSICS);
            geodata = JGrassCatalogUtilities.removeNovalues(geodata);
            fileCrs = geotiffGridReader.getCrs();
        }

        HashMap<String, Double> regionParams = JGrassCatalogUtilities.getRegionParamsFromGridCoverage(geodata);
        double n = regionParams.get(JGrassCatalogUtilities.NORTH);
        double s = regionParams.get(JGrassCatalogUtilities.SOUTH);
        double e = regionParams.get(JGrassCatalogUtilities.EAST);
        double w = regionParams.get(JGrassCatalogUtilities.WEST);
        double xres = regionParams.get(JGrassCatalogUtilities.XRES);
        double yres = regionParams.get(JGrassCatalogUtilities.YRES);

        // create the location and mapset
        JGrassRegion window = new JGrassRegion(w, e, s, n, xres, yres);
        File baseFolderFile = new File(props.basePath);
        File locationFile = new File(baseFolderFile, props.locationName);
        File mapsetFile = new File(locationFile, props.mapsetName);
        String locationPath = locationFile.getAbsolutePath();
        JGrassCatalogUtilities.createLocation(locationPath, fileCrs, window);
        JGrassCatalogUtilities.createMapset(locationPath, mapsetFile.getName(), null, null);
        JGrassRegion.writeWINDToMapset(mapsetFile.getAbsolutePath(), window);

        // write the map into it
        String mapName = mapFile.getName();
        mapName = FilenameUtils.getBaseName(mapName);
        JGrassMapEnvironment mapEnvironment = new JGrassMapEnvironment(mapsetFile, mapName);
        GrassCoverageFormat format = new GrassCoverageFormatFactory().createFormat();
        GrassCoverageWriter writer = format.getWriter(mapEnvironment.getCELL(), null);
        GeneralParameterValue[] readParams = null;
        writer.write(geodata, readParams);

        JGrassCatalogUtilities.addServiceToCatalog(
                locationPath + File.separator + JGrassCatalogUtilities.JGRASS_WORKSPACE_FILENAME,
                new NullProgressMonitor());
    } catch (IOException e) {
        JGrassPlugin.log(
                "JGrassPlugin problem: eu.hydrologis.udig.catalog.workspacecreation.wizard#NewJGrassLocationWizard#performFinish", //$NON-NLS-1$
                e);
        e.printStackTrace();
    }

    return true;
}