Example usage for java.lang String replace

List of usage examples for java.lang String replace

Introduction

In this page you can find the example usage for java.lang String replace.

Prototype

public String replace(CharSequence target, CharSequence replacement) 

Source Link

Document

Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.

Usage

From source file:ms1quant.MS1Quant.java

/**
 * @param args the command line arguments MS1Quant parameterfile
 *//*from   w  w w .ja v  a2  s .com*/
public static void main(String[] args) throws Exception {

    BufferedReader reader = null;
    try {
        System.out.println(
                "=================================================================================================");
        System.out.println("Umpire MS1 quantification and feature detection analysis (version: "
                + UmpireInfo.GetInstance().Version + ")");
        if (args.length < 3 || !args[1].startsWith("-mode")) {
            System.out
                    .println("command : java -jar -Xmx10G MS1Quant.jar ms1quant.params -mode[1 or 2] [Option]");
            System.out.println("\n-mode");
            System.out.println("\t1:Single file mode--> mzXML_file PepXML_file");
            System.out.println("\t\tEx: -mode1 file1.mzXML file1.pep.xml");
            System.out.println(
                    "\t2:Folder mode--> mzXML_Folder PepXML_Folder, all generated csv tables will be merged into a single csv file");
            System.out.println("\t\tEx: -mode2 /data/mzxml/ /data/pepxml/");
            System.out.println("\nOptions");
            System.out.println(
                    "\t-C\tNo of concurrent files to be processed (only for folder mode), Ex. -C5, default:1");
            System.out.println("\t-p\tMinimum probability, Ex. -p0.9, default:0.9");
            System.out.println("\t-ID\tDetect identified feature only");
            System.out.println("\t-O\toutput folder, Ex. -O/data/");
            return;
        }
        ConsoleLogger consoleLogger = new ConsoleLogger();
        consoleLogger.SetConsoleLogger(Level.DEBUG);
        consoleLogger.SetFileLogger(Level.DEBUG, FilenameUtils.getFullPath(args[0]) + "ms1quant_debug.log");
        Logger logger = Logger.getRootLogger();
        logger.debug("Command: " + Arrays.toString(args));
        logger.info("MS1Quant version: " + UmpireInfo.GetInstance().Version);

        String parameterfile = args[0];
        logger.info("Parameter file: " + parameterfile);
        File paramfile = new File(parameterfile);
        if (!paramfile.exists()) {
            logger.error("Parameter file " + paramfile.getAbsolutePath()
                    + " cannot be found. The program will exit.");
        }

        reader = new BufferedReader(new FileReader(paramfile.getAbsolutePath()));
        String line = "";
        InstrumentParameter param = new InstrumentParameter(InstrumentParameter.InstrumentType.TOF5600);
        int NoCPUs = 2;
        int NoFile = 1;
        param.DetermineBGByID = false;
        param.EstimateBG = true;

        //<editor-fold defaultstate="collapsed" desc="Read parameter file">
        while ((line = reader.readLine()) != null) {
            if (!"".equals(line) && !line.startsWith("#")) {
                logger.info(line);
                //System.out.println(line);
                if (line.split("=").length < 2) {
                    continue;
                }
                if (line.split("=").length < 2) {
                    continue;
                }
                String type = line.split("=")[0].trim();
                if (type.startsWith("para.")) {
                    type = type.replace("para.", "SE.");
                }
                String value = line.split("=")[1].trim();
                switch (type) {
                case "Thread": {
                    NoCPUs = Integer.parseInt(value);
                    break;
                }
                //<editor-fold defaultstate="collapsed" desc="instrument parameters">

                case "SE.MS1PPM": {
                    param.MS1PPM = Float.parseFloat(value);
                    break;
                }
                case "SE.MS2PPM": {
                    param.MS2PPM = Float.parseFloat(value);
                    break;
                }
                case "SE.SN": {
                    param.SNThreshold = Float.parseFloat(value);
                    break;
                }
                case "SE.MS2SN": {
                    param.MS2SNThreshold = Float.parseFloat(value);
                    break;
                }
                case "SE.MinMSIntensity": {
                    param.MinMSIntensity = Float.parseFloat(value);
                    break;
                }
                case "SE.MinMSMSIntensity": {
                    param.MinMSMSIntensity = Float.parseFloat(value);
                    break;
                }
                case "SE.MinRTRange": {
                    param.MinRTRange = Float.parseFloat(value);
                    break;
                }
                case "SE.MaxNoPeakCluster": {
                    param.MaxNoPeakCluster = Integer.parseInt(value);
                    param.MaxMS2NoPeakCluster = Integer.parseInt(value);
                    break;
                }
                case "SE.MinNoPeakCluster": {
                    param.MinNoPeakCluster = Integer.parseInt(value);
                    param.MinMS2NoPeakCluster = Integer.parseInt(value);
                    break;
                }
                case "SE.MinMS2NoPeakCluster": {
                    param.MinMS2NoPeakCluster = Integer.parseInt(value);
                    break;
                }
                case "SE.MaxCurveRTRange": {
                    param.MaxCurveRTRange = Float.parseFloat(value);
                    break;
                }
                case "SE.Resolution": {
                    param.Resolution = Integer.parseInt(value);
                    break;
                }
                case "SE.RTtol": {
                    param.RTtol = Float.parseFloat(value);
                    break;
                }
                case "SE.NoPeakPerMin": {
                    param.NoPeakPerMin = Integer.parseInt(value);
                    break;
                }
                case "SE.StartCharge": {
                    param.StartCharge = Integer.parseInt(value);
                    break;
                }
                case "SE.EndCharge": {
                    param.EndCharge = Integer.parseInt(value);
                    break;
                }
                case "SE.MS2StartCharge": {
                    param.MS2StartCharge = Integer.parseInt(value);
                    break;
                }
                case "SE.MS2EndCharge": {
                    param.MS2EndCharge = Integer.parseInt(value);
                    break;
                }
                case "SE.NoMissedScan": {
                    param.NoMissedScan = Integer.parseInt(value);
                    break;
                }
                case "SE.Denoise": {
                    param.Denoise = Boolean.valueOf(value);
                    break;
                }
                case "SE.EstimateBG": {
                    param.EstimateBG = Boolean.valueOf(value);
                    break;
                }
                case "SE.RemoveGroupedPeaks": {
                    param.RemoveGroupedPeaks = Boolean.valueOf(value);
                    break;
                }
                case "SE.MinFrag": {
                    param.MinFrag = Integer.parseInt(value);
                    break;
                }
                case "SE.IsoPattern": {
                    param.IsoPattern = Float.valueOf(value);
                    break;
                }
                case "SE.StartRT": {
                    param.startRT = Float.valueOf(value);
                }
                case "SE.EndRT": {
                    param.endRT = Float.valueOf(value);
                }

                //</editor-fold>
                }
            }
        }
        //</editor-fold>

        int mode = 1;
        if (args[1].equals("-mode2")) {
            mode = 2;
        } else if (args[1].equals("-mode1")) {
            mode = 1;
        } else {
            logger.error("-mode number not recongized. The program will exit.");
        }

        String mzXML = "";
        String pepXML = "";
        String mzXMLPath = "";
        String pepXMLPath = "";
        File mzXMLfile = null;
        File pepXMLfile = null;
        File mzXMLfolder = null;
        File pepXMLfolder = null;
        int idx = 0;
        if (mode == 1) {
            mzXML = args[2];
            logger.info("Mode1 mzXML file: " + mzXML);
            mzXMLfile = new File(mzXML);
            if (!mzXMLfile.exists()) {
                logger.error("Mode1 mzXML file " + mzXMLfile.getAbsolutePath()
                        + " cannot be found. The program will exit.");
                return;
            }
            pepXML = args[3];
            logger.info("Mode1 pepXML file: " + pepXML);
            pepXMLfile = new File(pepXML);
            if (!pepXMLfile.exists()) {
                logger.error("Mode1 pepXML file " + pepXMLfile.getAbsolutePath()
                        + " cannot be found. The program will exit.");
                return;
            }
            idx = 4;
        } else if (mode == 2) {
            mzXMLPath = args[2];
            logger.info("Mode2 mzXML folder: " + mzXMLPath);
            mzXMLfolder = new File(mzXMLPath);
            if (!mzXMLfolder.exists()) {
                logger.error("Mode2 mzXML folder " + mzXMLfolder.getAbsolutePath()
                        + " does not exist. The program will exit.");
                return;
            }
            pepXMLPath = args[3];
            logger.info("Mode2 pepXML folder: " + pepXMLPath);
            pepXMLfolder = new File(pepXMLPath);
            if (!pepXMLfolder.exists()) {
                logger.error("Mode2 pepXML folder " + pepXMLfolder.getAbsolutePath()
                        + " does not exist. The program will exit.");
                return;
            }
            idx = 4;
        }

        String outputfolder = "";
        float MinProb = 0f;
        for (int i = idx; i < args.length; i++) {
            if (args[i].startsWith("-")) {
                if (args[i].equals("-ID")) {
                    param.TargetIDOnly = true;
                    logger.info("Detect ID feature only: true");
                }
                if (args[i].startsWith("-O")) {
                    outputfolder = args[i].substring(2);
                    logger.info("Output folder: " + outputfolder);

                    File outputfile = new File(outputfolder);
                    if (!outputfolder.endsWith("\\") | outputfolder.endsWith("/")) {
                        outputfolder += "/";
                    }
                    if (!outputfile.exists()) {
                        outputfile.mkdir();
                    }
                }
                if (args[i].startsWith("-C")) {
                    try {
                        NoFile = Integer.parseInt(args[i].substring(2));
                        logger.info("No of concurrent files: " + NoFile);
                    } catch (Exception ex) {
                        logger.error(args[i]
                                + " is not a correct integer format, will process only one file at a time.");
                    }
                }
                if (args[i].startsWith("-p")) {
                    try {
                        MinProb = Float.parseFloat(args[i].substring(2));
                        logger.info("probability threshold: " + MinProb);
                    } catch (Exception ex) {
                        logger.error(args[i] + " is not a correct format, will use 0 as threshold instead.");
                    }
                }
            }
        }

        reader.close();
        TandemParam tandemparam = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600);
        PTMManager.GetInstance();

        if (param.TargetIDOnly) {
            param.EstimateBG = false;
            param.ApexDelta = 1.5f;
            param.NoMissedScan = 10;
            param.MiniOverlapP = 0.2f;
            param.RemoveGroupedPeaks = false;
            param.CheckMonoIsotopicApex = false;
            param.DetectByCWT = false;
            param.FillGapByBK = false;
            param.IsoCorrThreshold = -1f;
            param.SmoothFactor = 3;
        }

        if (mode == 1) {
            logger.info("Processing " + mzXMLfile.getAbsolutePath() + "....");
            long time = System.currentTimeMillis();
            LCMSPeakMS1 LCMS1 = new LCMSPeakMS1(mzXMLfile.getAbsolutePath(), NoCPUs);
            LCMS1.SetParameter(param);

            LCMS1.Resume = false;
            if (!param.TargetIDOnly) {
                LCMS1.CreatePeakFolder();
            }
            LCMS1.ExportPeakClusterTable = true;

            if (pepXMLfile.exists()) {
                tandemparam.InteractPepXMLPath = pepXMLfile.getAbsolutePath();
                LCMS1.ParsePepXML(tandemparam, MinProb);
                logger.info("No. of PSMs included: " + LCMS1.IDsummary.PSMList.size());
                logger.info("No. of Peptide ions included: " + LCMS1.IDsummary.GetPepIonList().size());
            }

            if (param.TargetIDOnly) {
                LCMS1.SaveSerializationFile = false;
            }

            if (param.TargetIDOnly || !LCMS1.ReadPeakCluster()) {
                LCMS1.PeakClusterDetection();
            }

            if (pepXMLfile.exists()) {
                LCMS1.AssignQuant(false);
                LCMS1.IDsummary.ExportPepID(outputfolder);
            }
            time = System.currentTimeMillis() - time;
            logger.info(LCMS1.ParentmzXMLName + " processed time:"
                    + String.format("%d hour, %d min, %d sec", TimeUnit.MILLISECONDS.toHours(time),
                            TimeUnit.MILLISECONDS.toMinutes(time)
                                    - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(time)),
                            TimeUnit.MILLISECONDS.toSeconds(time)
                                    - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time))));
            LCMS1.BaseClearAllPeaks();
            LCMS1.SetSpectrumParser(null);
            LCMS1.IDsummary = null;
            LCMS1 = null;
            System.gc();
        } else if (mode == 2) {

            LCMSID IDsummary = new LCMSID("", "", "");
            logger.info("Parsing all pepXML files in " + pepXMLPath + "....");
            for (File file : pepXMLfolder.listFiles()) {
                if (file.getName().toLowerCase().endsWith("pep.xml")
                        || file.getName().toLowerCase().endsWith("pepxml")) {
                    PepXMLParser pepXMLParser = new PepXMLParser(IDsummary, file.getAbsolutePath(), MinProb);
                }
            }
            HashMap<String, LCMSID> LCMSIDMap = IDsummary.GetLCMSIDFileMap();

            ExecutorService executorPool = null;
            executorPool = Executors.newFixedThreadPool(NoFile);

            logger.info("Processing all mzXML files in " + mzXMLPath + "....");
            for (File file : mzXMLfolder.listFiles()) {
                if (file.getName().toLowerCase().endsWith("mzxml")) {
                    LCMSID id = LCMSIDMap.get(FilenameUtils.getBaseName(file.getName()));
                    if (id == null || id.PSMList == null) {
                        logger.warn("No IDs found in :" + FilenameUtils.getBaseName(file.getName())
                                + ". Quantification for this file is skipped");
                        continue;
                    }
                    if (!id.PSMList.isEmpty()) {
                        MS1TargetQuantThread thread = new MS1TargetQuantThread(file, id, NoCPUs, outputfolder,
                                param);
                        executorPool.execute(thread);
                    }
                }
            }
            LCMSIDMap.clear();
            LCMSIDMap = null;
            IDsummary = null;
            executorPool.shutdown();
            try {
                executorPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
            } catch (InterruptedException e) {
                logger.info("interrupted..");
            }

            if (outputfolder == null | outputfolder.equals("")) {
                outputfolder = mzXMLPath;
            }

            logger.info("Merging PSM files..");
            File output = new File(outputfolder);
            FileWriter writer = new FileWriter(output.getAbsolutePath() + "/PSM_merge.csv");
            boolean header = false;
            for (File csvfile : output.listFiles()) {
                if (csvfile.getName().toLowerCase().endsWith("_psms.csv")) {
                    BufferedReader outreader = new BufferedReader(new FileReader(csvfile));
                    String outline = outreader.readLine();
                    if (!header) {
                        writer.write(outline + "\n");
                        header = true;
                    }
                    while ((outline = outreader.readLine()) != null) {
                        writer.write(outline + "\n");
                    }
                    outreader.close();
                    csvfile.delete();
                }
            }
            writer.close();
        }
        logger.info("MS1 quant module is complete.");
    } catch (Exception e) {
        Logger.getRootLogger().error(ExceptionUtils.getStackTrace(e));
        throw e;
    }
}

From source file:edu.uthscsa.ric.papaya.builder.Builder.java

public static void main(final String[] args) {
    final Builder builder = new Builder();

    // process command line
    final CommandLine cli = builder.createCLI(args);
    builder.setUseSample(cli.hasOption(ARG_SAMPLE));
    builder.setUseAtlas(cli.hasOption(ARG_ATLAS));
    builder.setLocal(cli.hasOption(ARG_LOCAL));
    builder.setPrintHelp(cli.hasOption(ARG_HELP));
    builder.setUseImages(cli.hasOption(ARG_IMAGE));
    builder.setSingleFile(cli.hasOption(ARG_SINGLE));
    builder.setUseParamFile(cli.hasOption(ARG_PARAM_FILE));
    builder.setUseTitle(cli.hasOption(ARG_TITLE));

    // print help, if necessary
    if (builder.isPrintHelp()) {
        builder.printHelp();//from  ww  w. ja  v a2  s  .co m
        return;
    }

    // find project root directory
    if (cli.hasOption(ARG_ROOT)) {
        try {
            builder.projectDir = (new File(cli.getOptionValue(ARG_ROOT))).getCanonicalFile();
        } catch (final IOException ex) {
            System.err.println("Problem finding root directory.  Reason: " + ex.getMessage());
        }
    }

    if (builder.projectDir == null) {
        builder.projectDir = new File(System.getProperty("user.dir"));
    }

    // clean output dir
    final File outputDir = new File(builder.projectDir + "/" + OUTPUT_DIR);
    System.out.println("Cleaning output directory...");
    try {
        builder.cleanOutputDir(outputDir);
    } catch (final IOException ex) {
        System.err.println("Problem cleaning build directory.  Reason: " + ex.getMessage());
    }

    if (builder.isLocal()) {
        System.out.println("Building for local usage...");
    }

    // write JS
    final File compressedFileJs = new File(outputDir, OUTPUT_JS_FILENAME);

    // build properties
    try {
        final File buildFile = new File(builder.projectDir + "/" + BUILD_PROP_FILE);

        builder.readBuildProperties(buildFile);
        builder.buildNumber++; // increment build number
        builder.writeBuildProperties(compressedFileJs, true);
        builder.writeBuildProperties(buildFile, false);
    } catch (final IOException ex) {
        System.err.println("Problem handling build properties.  Reason: " + ex.getMessage());
    }

    String htmlParameters = null;

    if (builder.isUseParamFile()) {
        final String paramFileArg = cli.getOptionValue(ARG_PARAM_FILE);

        if (paramFileArg != null) {
            try {
                System.out.println("Including parameters...");

                final String parameters = FileUtils.readFileToString(new File(paramFileArg), "UTF-8");
                htmlParameters = "var params = " + parameters + ";";
            } catch (final IOException ex) {
                System.err.println("Problem reading parameters file! " + ex.getMessage());
            }
        }
    }

    String title = null;
    if (builder.isUseTitle()) {
        String str = cli.getOptionValue(ARG_TITLE);
        if (str != null) {
            str = str.trim();
            str = str.replace("\"", "");
            str = str.replace("'", "");

            if (str.length() > 0) {
                title = str;
                System.out.println("Using title: " + title);
            }
        }
    }

    try {
        final JSONArray loadableImages = new JSONArray();

        // sample image
        if (builder.isUseSample()) {
            System.out.println("Including sample image...");

            final File sampleFile = new File(builder.projectDir + "/" + SAMPLE_IMAGE_NII_FILE);
            final String filename = Utilities
                    .replaceNonAlphanumericCharacters(Utilities.removeNiftiExtensions(sampleFile.getName()));

            if (builder.isLocal()) {
                loadableImages.put(new JSONObject("{\"nicename\":\"Sample Image\",\"name\":\"" + filename
                        + "\",\"encode\":\"" + filename + "\"}"));
                final String sampleEncoded = Utilities.encodeImageFile(sampleFile);
                FileUtils.writeStringToFile(compressedFileJs,
                        "var " + filename + "= \"" + sampleEncoded + "\";\n", "UTF-8", true);
            } else {
                loadableImages.put(new JSONObject("{\"nicename\":\"Sample Image\",\"name\":\"" + filename
                        + "\",\"url\":\"" + SAMPLE_IMAGE_NII_FILE + "\"}"));
                FileUtils.copyFile(sampleFile, new File(outputDir + "/" + SAMPLE_IMAGE_NII_FILE));
            }
        }

        // atlas
        if (builder.isUseAtlas()) {
            Atlas atlas = null;

            try {
                String atlasArg = cli.getOptionValue(ARG_ATLAS);

                if (atlasArg == null) {
                    atlasArg = (builder.projectDir + "/" + SAMPLE_DEFAULT_ATLAS_FILE);
                }

                final File atlasXmlFile = new File(atlasArg);

                System.out.println("Including atlas " + atlasXmlFile);

                atlas = new Atlas(atlasXmlFile);
                final File atlasJavaScriptFile = atlas.createAtlas(builder.isLocal());
                System.out.println("Using atlas image file " + atlas.getImageFile());

                if (builder.isLocal()) {
                    loadableImages.put(
                            new JSONObject("{\"nicename\":\"Atlas\",\"name\":\"" + atlas.getImageFileNewName()
                                    + "\",\"encode\":\"" + atlas.getImageFileNewName() + "\",\"hide\":true}"));
                } else {
                    final File atlasImageFile = atlas.getImageFile();
                    final String atlasPath = "data/" + atlasImageFile.getName();

                    loadableImages.put(new JSONObject("{\"nicename\":\"Atlas\",\"name\":\""
                            + atlas.getImageFileNewName() + "\",\"url\":\"" + atlasPath + "\",\"hide\":true}"));
                    FileUtils.copyFile(atlasImageFile, new File(outputDir + "/" + atlasPath));
                }

                builder.writeFile(atlasJavaScriptFile, compressedFileJs);
            } catch (final IOException ex) {
                System.err.println("Problem finding atlas file.  Reason: " + ex.getMessage());
            }
        }

        // additional images
        if (builder.isUseImages()) {
            final String[] imageArgs = cli.getOptionValues(ARG_IMAGE);

            if (imageArgs != null) {
                for (final String imageArg : imageArgs) {
                    final File file = new File(imageArg);
                    System.out.println("Including image " + file);

                    final String filename = Utilities
                            .replaceNonAlphanumericCharacters(Utilities.removeNiftiExtensions(file.getName()));

                    if (builder.isLocal()) {
                        loadableImages.put(new JSONObject(
                                "{\"nicename\":\"" + Utilities.removeNiftiExtensions(file.getName())
                                        + "\",\"name\":\"" + filename + "\",\"encode\":\"" + filename + "\"}"));
                        final String sampleEncoded = Utilities.encodeImageFile(file);
                        FileUtils.writeStringToFile(compressedFileJs,
                                "var " + filename + "= \"" + sampleEncoded + "\";\n", "UTF-8", true);
                    } else {
                        final String filePath = "data/" + file.getName();
                        loadableImages.put(new JSONObject(
                                "{\"nicename\":\"" + Utilities.removeNiftiExtensions(file.getName())
                                        + "\",\"name\":\"" + filename + "\",\"url\":\"" + filePath + "\"}"));
                        FileUtils.copyFile(file, new File(outputDir + "/" + filePath));
                    }
                }
            }
        }

        File tempFileJs = null;

        try {
            tempFileJs = builder.createTempFile();
        } catch (final IOException ex) {
            System.err.println("Problem creating temp write file.  Reason: " + ex.getMessage());
        }

        // write image refs
        FileUtils.writeStringToFile(tempFileJs,
                "var " + PAPAYA_LOADABLE_IMAGES + " = " + loadableImages.toString() + ";\n", "UTF-8", true);

        // compress JS
        tempFileJs = builder.concatenateFiles(JS_FILES, "js", tempFileJs);

        System.out.println("Compressing JavaScript... ");
        FileUtils.writeStringToFile(compressedFileJs, "\n", "UTF-8", true);
        builder.compressJavaScript(tempFileJs, compressedFileJs, new YuiCompressorOptions());
        //tempFileJs.deleteOnExit();
    } catch (final IOException ex) {
        System.err.println("Problem concatenating JavaScript.  Reason: " + ex.getMessage());
    }

    // compress CSS
    final File compressedFileCss = new File(outputDir, OUTPUT_CSS_FILENAME);

    try {
        final File concatFile = builder.concatenateFiles(CSS_FILES, "css", null);
        System.out.println("Compressing CSS... ");
        builder.compressCSS(concatFile, compressedFileCss, new YuiCompressorOptions());
        concatFile.deleteOnExit();
    } catch (final IOException ex) {
        System.err.println("Problem concatenating CSS.  Reason: " + ex.getMessage());
    }

    // write HTML
    try {
        System.out.println("Writing HTML... ");
        if (builder.singleFile) {
            builder.writeHtml(outputDir, compressedFileJs, compressedFileCss, htmlParameters, title);
        } else {
            builder.writeHtml(outputDir, htmlParameters, title);
        }
    } catch (final IOException ex) {
        System.err.println("Problem writing HTML.  Reason: " + ex.getMessage());
    }

    System.out.println("Done!  Output files located at " + outputDir);
}

From source file:net.securnetwork.itebooks.downloader.EbookDownloader.java

/**
 * Program main method.//from w  w w  . java 2  s .  c o  m
 * 
 * @param args the program arguments
 */
public static void main(String[] args) {
    if (validateArguments(args)) {
        int start = MIN_EBOOK_INDEX;
        int end = getLastEbookIndex();
        String destinationFolder = null;
        // Check if resume mode
        if (args.length == 1 && args[0].equals(RESUME_ARG)) {
            start = Integer.parseInt(prefs.get(LAST_SAVED_EBOOK_PREF, MIN_EBOOK_INDEX - 1 + "")) + 1; //$NON-NLS-1$
            destinationFolder = prefs.get(OUTPUT_FOLDER_PREF, null);
        } else {
            destinationFolder = getDestinationFolder(args);
        }

        if (destinationFolder == null) {
            System.err.println(Messages.getString("EbookDownloader.NoDestinationFolderFound")); //$NON-NLS-1$
            return;
        } else {
            // Possibly fix the destination folder path
            destinationFolder = destinationFolder.replace("\\", "/");
            if (!destinationFolder.endsWith("/")) {
                destinationFolder += "/";
            }
            prefs.put(OUTPUT_FOLDER_PREF, destinationFolder);
        }

        if (args.length == 3) {
            start = getStartIndex(args);
            end = getEndIndex(args);
        }
        try {
            for (int i = start; i <= end; i++) {
                String ebookPage = BASE_EBOOK_URL + i + SLASH;
                Source sourceHTML = new Source(new URL(ebookPage));
                List<Element> allTables = sourceHTML.getAllElements(HTMLElementName.TABLE);
                Element detailsTable = allTables.get(0);
                // Try to build an info bean for the ebook
                String bookTitle = EbookPageParseUtils.getTitle(detailsTable);
                if (bookTitle != null) {
                    EbookInfo ebook = createEbookInfo(bookTitle, i, detailsTable);
                    String filename = destinationFolder + Misc.getValidFilename(ebook.getTitle(),
                            ebook.getSubTitle(), ebook.getYear(), ebook.getFileFormat());
                    System.out.print(MessageFormat.format(Messages.getString("EbookDownloader.InfoDownloading"), //$NON-NLS-1$
                            new Object[] { ebook.getSiteId() }));
                    try {
                        URL ebookPageURL = new URL(ebook.getDownloadLink());
                        HttpURLConnection con = (HttpURLConnection) ebookPageURL.openConnection();
                        con.setRequestMethod("GET");
                        con.setRequestProperty("Referer", ebookPage);
                        InputStream conIS = con.getInputStream();
                        FileUtils.copyInputStreamToFile(conIS, new File(filename));
                        System.out.println(Messages.getString("EbookDownloader.DownloadingOK")); //$NON-NLS-1$
                        prefs.put(LAST_SAVED_EBOOK_PREF, i + ""); //$NON-NLS-1$
                        conIS.close();
                    } catch (Exception e) {
                        System.out.println(Messages.getString("EbookDownloader.DownloadingKO")); //$NON-NLS-1$
                    }
                }
            }

        } catch (Exception e) {
            System.err.println(Messages.getString("EbookDownloader.FatalError")); //$NON-NLS-1$
            e.printStackTrace();
        }
    } else {
        printHelp();
    }
}

From source file:de.ipbhalle.metfusion.main.SubstructureSearch.java

public static void main(String[] args) {
    String token = "eeca1d0f-4c03-4d81-aa96-328cdccf171a";
    //String token = "a1004d0f-9d37-47e0-acdd-35e58e34f603";
    //test();//from w w  w  .  j a v a 2 s.c  om

    //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/136m0498_MSMS.mf");
    //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/148m0859_MSMS.mf");
    //      File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/164m0445a_MSMS.mf");
    //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/192m0757a_MSMS.mf");
    //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/naringenin.mf");

    //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/Known_BT_MSMS_ChemSp/1MeBT_MSMS.mf");

    //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/Unknown_BT_MSMS_ChemSp/mf_with_substruct_formula/150m0655a_MSMS.mf");
    File file = new File(
            "C:/Users/Michael/Dropbox/Eawag_IPB_Shared_MassBank/BTs/Unknown_BT_MSMS_ChemSp/mf_with_substruct_formula/192m0757b_MSMS.mf");

    MetFusionBatchFileHandler mbf = new MetFusionBatchFileHandler(file);
    try {
        mbf.readFile();
    } catch (IOException e) {
        //System.out.println(e.getMessage());
        System.err.println(
                "Error reading from MetFusion settings file [" + file.getAbsolutePath() + "]. Aborting!");
        System.exit(-1);
    }

    MetFusionBatchSettings settings = mbf.getBatchSettings();
    List<String> absent = settings.getSubstrucAbsent();
    List<String> present = settings.getSubstrucPresent();
    for (String s : present) {
        System.out.println("present -> " + s);
    }
    for (String s : absent) {
        System.out.println("absent -> " + s);
    }
    String formula = settings.getMfFormula();
    System.out.println("formula -> " + formula);

    boolean useFormulaAsQuery = true;
    boolean useSDF = false;
    String sdfFile = "";
    if (useSDF) {
        sdfFile = "C:/Users/Michael/Dropbox/Eawag_IPB_Shared_MassBank/BTs/Unknown_BT_MSMS_ChemSp/mf_with_substruct_formula/results_afterFormulaQuery/192m0757b_MSMS.sdf";
        if (sdfFile.isEmpty()) { // TODO alternatively use SDF file from query file?
            System.err.println("SDF file needs to be specified! Exiting.");
            System.exit(-1);
        }
    }

    SubstructureSearch ss = new SubstructureSearch(present, absent, token, formula, mbf, useFormulaAsQuery,
            useSDF, sdfFile);
    ss.run();
    List<ResultSubstructure> remaining = ss.getResultsRemaining();
    List<Result> resultsForSDF = new ArrayList<Result>();

    StringBuilder sb = new StringBuilder();
    String sep = ",";
    for (ResultSubstructure rs : remaining) {
        sb.append(rs.getId()).append(sep);

        Result r = new Result(rs.getPort(), rs.getId(), rs.getName(), rs.getScore());
        r.setMol(rs.getMol());
        r.setSmiles(rs.getSmiles());
        r.setInchi(rs.getInchi());
        r.setInchikey(rs.getInchikey());
        resultsForSDF.add(r);
    }
    String ids = sb.toString();

    String fileSep = System.getProperty("file.separator");
    if (!ids.isEmpty()) {
        ids = ids.substring(0, ids.length() - 1);
        System.out.println("ids -> " + ids);
        settings.setMfDatabaseIDs(ids);
        String filename = file.getName();
        String prefix = filename.substring(0, filename.lastIndexOf("."));
        filename = filename.replace(prefix, prefix + "_ids");
        String dir = file.getParent();
        System.out.println("dir -> " + dir);
        if (!dir.endsWith(fileSep))
            dir += fileSep;

        File output = new File(file.getParent(), filename);
        mbf.writeFile(output, settings);
        SDFOutputHandler so = new SDFOutputHandler(dir + prefix + ".sdf");
        boolean writeOK = so.writeOriginalResults(resultsForSDF, false);
        if (!writeOK)
            System.err.println("Error writing SDF [" + so.getFilename());
    }
}

From source file:ch.kostceco.tools.siardexcerpt.SIARDexcerpt.java

/** Die Eingabe besteht aus mind 3 Parameter: [0] Pfad zur SIARD-Datei oder Verzeichnis [1]
 * configfile [2] Modul/*from www. ja v a  2s.  co  m*/
 * 
 * bersicht der Module: --init --search --extract sowie --finish
 * 
 * bei --search kommen danach noch die Suchtexte und bei --extract die Schlssel
 * 
 * @param args
 * @throws IOException */

public static void main(String[] args) throws IOException {
    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:config/applicationContext.xml");

    /** SIARDexcerpt: Aufbau des Tools
     * 
     * 1) init: Config Kopieren und ggf SIARD-Datei ins Workverzeichnis entpacken
     * 
     * 2) search: gemss config die Tabelle mit Suchtext befragen und Ausgabe des Resultates
     * 
     * 3) extract: mit den Keys anhand der config einen Records herausziehen und anzeigen
     * 
     * 4) finish: Config-Kopie sowie Workverzeichnis lschen */

    /* TODO: siehe Bemerkung im applicationContext-services.xml bezglich Injection in der
     * Superklasse aller Impl-Klassen ValidationModuleImpl validationModuleImpl =
     * (ValidationModuleImpl) context.getBean("validationmoduleimpl"); */

    SIARDexcerpt siardexcerpt = (SIARDexcerpt) context.getBean("siardexcerpt");

    // Ist die Anzahl Parameter (mind 3) korrekt?
    if (args.length < 3) {
        System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_PARAMETER_USAGE));
        System.exit(1);
    }

    String module = new String(args[2]);
    File siardDatei = new File(args[0]);
    File configFile = new File(args[1]);

    /* arg 1 gibt den Pfad zur configdatei an. Da dieser in ConfigurationServiceImpl hartcodiert
     * ist, wird diese nach "configuration/SIARDexcerpt.conf.xml" kopiert. */
    File configFileHard = new File("configuration" + File.separator + "SIARDexcerpt.conf.xml");

    // excerpt ist der Standardwert wird aber anhand der config dann gesetzt
    File directoryOfOutput = new File("excerpt");

    // temp_SIARDexcerpt ist der Standardwert wird aber anhand der config dann gesetzt
    File tmpDir = new File("temp_SIARDexcerpt");

    boolean okA = false;
    boolean okB = false;
    boolean okC = false;

    // die Anwendung muss mindestens unter Java 6 laufen
    String javaRuntimeVersion = System.getProperty("java.vm.version");
    if (javaRuntimeVersion.compareTo("1.6.0") < 0) {
        System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_WRONG_JRE));
        System.exit(1);
    }

    if (module.equalsIgnoreCase("--init")) {

        /** 1) init: Config Kopieren und ggf SIARD-Datei ins Workverzeichnis entpacken
         * 
         * a) config muss existieren und SIARDexcerpt.conf.xml noch nicht
         * 
         * b) Excerptverzeichnis mit schreibrechte und ggf anlegen
         * 
         * c) Workverzeichnis muss leer sein und mit schreibrechte
         * 
         * d) SIARD-Datei entpacken
         * 
         * e) Struktur-Check SIARD-Verzeichnis
         * 
         * TODO: Erledigt */

        System.out.println("SIARDexcerpt: init");

        /** a) config muss existieren und SIARDexcerpt.conf.xml noch nicht */
        if (!configFile.exists()) {
            System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_CONFIGFILE_FILENOTEXISTING,
                    configFile.getAbsolutePath()));
            System.exit(1);
        }

        if (configFileHard.exists()) {
            System.out
                    .println(siardexcerpt.getTextResourceService().getText(ERROR_CONFIGFILEHARD_FILEEXISTING));
            System.exit(1);
        }
        Util.copyFile(configFile, configFileHard);

        /** b) Excerptverzeichnis mit schreibrechte und ggf anlegen */
        String pathToOutput = siardexcerpt.getConfigurationService().getPathToOutput();

        directoryOfOutput = new File(pathToOutput);

        if (!directoryOfOutput.exists()) {
            directoryOfOutput.mkdir();
        }

        // Im Logverzeichnis besteht kein Schreibrecht
        if (!directoryOfOutput.canWrite()) {
            System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_LOGDIRECTORY_NOTWRITABLE,
                    directoryOfOutput));
            // Lschen des configFileHard, falls eines angelegt wurde
            if (configFileHard.exists()) {
                Util.deleteDir(configFileHard);
            }
            System.exit(1);
        }

        if (!directoryOfOutput.isDirectory()) {
            System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_LOGDIRECTORY_NODIRECTORY));
            // Lschen des configFileHard, falls eines angelegt wurde
            if (configFileHard.exists()) {
                Util.deleteDir(configFileHard);
            }
            System.exit(1);
        }

        /** c) Workverzeichnis muss leer sein und mit schreibrechte */
        String pathToWorkDir = siardexcerpt.getConfigurationService().getPathToWorkDir();

        tmpDir = new File(pathToWorkDir);

        /* bestehendes Workverzeichnis Abbruch wenn nicht leer, da am Schluss das Workverzeichnis
         * gelscht wird und entsprechend bestehende Dateien gelscht werden knnen */
        if (tmpDir.exists()) {
            if (tmpDir.isDirectory()) {
                // Get list of file in the directory. When its length is not zero the folder is not empty.
                String[] files = tmpDir.list();
                if (files.length > 0) {
                    System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_WORKDIRECTORY_EXISTS,
                            pathToWorkDir));
                    // Lschen des configFileHard, falls eines angelegt wurde
                    if (configFileHard.exists()) {
                        Util.deleteDir(configFileHard);
                    }
                    System.exit(1);
                }
            }
        }
        if (!tmpDir.exists()) {
            tmpDir.mkdir();
        }

        // Im Workverzeichnis besteht kein Schreibrecht
        if (!tmpDir.canWrite()) {
            System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_WORKDIRECTORY_NOTWRITABLE,
                    pathToWorkDir));
            // Lschen des configFileHard, falls eines angelegt wurde
            if (configFileHard.exists()) {
                Util.deleteDir(configFileHard);
            }
            System.exit(1);
        }

        /** d) SIARD-Datei entpacken */
        if (!siardDatei.exists()) {
            // SIARD-Datei existiert nicht
            System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_SIARDFILE_FILENOTEXISTING,
                    siardDatei.getAbsolutePath()));
            // Lschen des configFileHard, falls eines angelegt wurde
            if (configFileHard.exists()) {
                Util.deleteDir(configFileHard);
            }
            System.exit(1);
        }

        if (!siardDatei.isDirectory()) {

            /* SIARD-Datei ist eine Datei
             * 
             * Die Datei muss ins Workverzeichnis extrahiert werden. Dies erfolgt im Modul A.
             * 
             * danach der Pfad zu SIARD-Datei dorthin zeigen lassen */

            Controllerexcerpt controllerexcerpt = (Controllerexcerpt) context.getBean("controllerexcerpt");
            File siardDateiNew = new File(pathToWorkDir + File.separator + siardDatei.getName());
            okA = controllerexcerpt.executeA(siardDatei, siardDateiNew, "");

            if (!okA) {
                // SIARD Datei konte nicht entpackt werden
                System.out.println(MESSAGE_XML_MODUL_A);
                System.out.println(ERROR_XML_A_CANNOTEXTRACTZIP);

                // Lschen des Arbeitsverzeichnisses und configFileHard, falls eines angelegt wurde
                if (tmpDir.exists()) {
                    Util.deleteDir(tmpDir);
                }
                if (configFileHard.exists()) {
                    Util.deleteDir(configFileHard);
                }
                // Fehler Extraktion --> invalide
                System.exit(2);
            } else {
                @SuppressWarnings("unused")
                File siardDateiOld = siardDatei;
                siardDatei = siardDateiNew;
            }

        } else {
            /* SIARD-Datei entpackt oder Datei war bereits ein Verzeichnis.
             * 
             * Gerade bei grsseren SIARD-Dateien ist es sinnvoll an einer Stelle das ausgepackte SIARD
             * zu haben, damit diese nicht immer noch extrahiert werden muss */
        }

        /** e) Struktur-Check SIARD-Verzeichnis */
        File content = new File(siardDatei.getAbsolutePath() + File.separator + "content");
        File header = new File(siardDatei.getAbsolutePath() + File.separator + "header");
        File xsd = new File(
                siardDatei.getAbsolutePath() + File.separator + "header" + File.separator + "metadata.xsd");
        File metadata = new File(
                siardDatei.getAbsolutePath() + File.separator + "header" + File.separator + "metadata.xml");

        if (!content.exists() || !header.exists() || !xsd.exists() || !metadata.exists()) {
            System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_XML_B_STRUCTURE));
            // Lschen des Arbeitsverzeichnisses und configFileHard, falls eines angelegt wurde
            if (tmpDir.exists()) {
                Util.deleteDir(tmpDir);
            }
            if (configFileHard.exists()) {
                Util.deleteDir(configFileHard);
            }
            // Fehler Extraktion --> invalide
            System.exit(2);
        } else {
            // Struktur sieht plausibel aus, extraktion kann starten
        }

    } // End init

    if (module.equalsIgnoreCase("--search")) {

        /** 2) search: gemss config die Tabelle mit Suchtext befragen und Ausgabe des Resultates
         * 
         * a) Ist die Anzahl Parameter (mind 4) korrekt? arg4 = Suchtext
         * 
         * b) Suchtext einlesen
         * 
         * c) search.xml vorbereiten (Header) und xsl in Output kopieren
         * 
         * d) grep ausfhren
         * 
         * e) Suchergebnis speichern und anzeigen (via GUI)
         * 
         * TODO: Noch offen */

        System.out.println("SIARDexcerpt: search");

        String pathToOutput = siardexcerpt.getConfigurationService().getPathToOutput();

        directoryOfOutput = new File(pathToOutput);

        if (!directoryOfOutput.exists()) {
            directoryOfOutput.mkdir();
        }

        /** a) Ist die Anzahl Parameter (mind 4) korrekt? arg4 = Suchtext */
        if (args.length < 4) {
            System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_PARAMETER_USAGE));
            System.exit(1);
        }

        if (!siardDatei.isDirectory()) {
            File siardDateiNew = new File(tmpDir.getAbsolutePath() + File.separator + siardDatei.getName());
            if (!siardDateiNew.exists()) {
                System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_NOINIT));
                System.exit(1);
            } else {
                siardDatei = siardDateiNew;
            }
        }

        /** b) Suchtext einlesen */
        String searchString = new String(args[3]);

        /** c) search.xml vorbereiten (Header) und xsl in Output kopieren */
        // Zeitstempel der Datenextraktion
        java.util.Date nowStartS = new java.util.Date();
        java.text.SimpleDateFormat sdfStartS = new java.text.SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
        String ausgabeStartS = sdfStartS.format(nowStartS);

        /* Der SearchString kann zeichen enthalten, welche nicht im Dateinamen vorkommen drfen.
         * Entsprechend werden diese normalisiert */
        String searchStringFilename = searchString.replaceAll("/", "_");
        searchStringFilename = searchStringFilename.replaceAll(">", "_");
        searchStringFilename = searchStringFilename.replaceAll("<", "_");
        searchStringFilename = searchStringFilename.replace(".*", "_");
        searchStringFilename = searchStringFilename.replaceAll("___", "_");
        searchStringFilename = searchStringFilename.replaceAll("__", "_");

        String outDateiNameS = siardDatei.getName() + "_" + searchStringFilename + "_SIARDsearch.xml";
        outDateiNameS = outDateiNameS.replaceAll("__", "_");

        // Informationen zum Archiv holen
        String archiveS = siardexcerpt.getConfigurationService().getArchive();

        // Konfiguration des Outputs, ein File Logger wird zustzlich erstellt
        LogConfigurator logConfiguratorS = (LogConfigurator) context.getBean("logconfigurator");
        String outFileNameS = logConfiguratorS.configure(directoryOfOutput.getAbsolutePath(), outDateiNameS);
        File outFileSearch = new File(outFileNameS);
        // Ab hier kann ins Output geschrieben werden...

        // Informationen zum XSL holen
        String pathToXSLS = siardexcerpt.getConfigurationService().getPathToXSLsearch();

        File xslOrigS = new File(pathToXSLS);
        File xslCopyS = new File(directoryOfOutput.getAbsolutePath() + File.separator + xslOrigS.getName());
        if (!xslCopyS.exists()) {
            Util.copyFile(xslOrigS, xslCopyS);
        }

        LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_HEADER, xslCopyS.getName()));
        LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_START, ausgabeStartS));
        LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_ARCHIVE, archiveS));
        LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_INFO));

        /** d) search: dies ist in einem eigenen Modul realisiert */
        Controllerexcerpt controllerexcerptS = (Controllerexcerpt) context.getBean("controllerexcerpt");

        okB = controllerexcerptS.executeB(siardDatei, outFileSearch, searchString);

        /** e) Ausgabe und exitcode */
        if (!okB) {
            // Suche konnte nicht erfolgen
            LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_MODUL_B));
            LOGGER.logError(siardexcerpt.getTextResourceService().getText(ERROR_XML_B_CANNOTSEARCHRECORD));
            LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_LOGEND));
            System.out.println(MESSAGE_XML_MODUL_B);
            System.out.println(ERROR_XML_B_CANNOTSEARCHRECORD);
            System.out.println("");

            // Lschen des Arbeitsverzeichnisses und configFileHard erfolgt erst bei schritt 4 finish

            // Fehler Extraktion --> invalide
            System.exit(2);
        } else {
            // Suche konnte durchgefhrt werden
            LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_LOGEND));
            // Lschen des Arbeitsverzeichnisses und configFileHard erfolgt erst bei schritt 4 finish

            // Record konnte extrahiert werden
            System.exit(0);
        }

    } // End search

    if (module.equalsIgnoreCase("--excerpt")) {

        /** 3) extract: mit den Keys anhand der config einen Records herausziehen und anzeigen
         * 
         * a) Ist die Anzahl Parameter (mind 4) korrekt? arg4 = Suchtext
         * 
         * b) extract.xml vorbereiten (Header) und xsl in Output kopieren
         * 
         * c) extraktion: dies ist in einem eigenen Modul realisiert
         * 
         * d) Ausgabe und exitcode
         * 
         * TODO: Erledigt */

        System.out.println("SIARDexcerpt: extract");

        String pathToOutput = siardexcerpt.getConfigurationService().getPathToOutput();

        directoryOfOutput = new File(pathToOutput);

        if (!directoryOfOutput.exists()) {
            directoryOfOutput.mkdir();
        }

        /** a) Ist die Anzahl Parameter (mind 4) korrekt? arg4 = Suchtext */
        if (args.length < 4) {
            System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_PARAMETER_USAGE));
            System.exit(1);
        }

        if (!siardDatei.isDirectory()) {
            File siardDateiNew = new File(tmpDir.getAbsolutePath() + File.separator + siardDatei.getName());
            if (!siardDateiNew.exists()) {
                System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_NOINIT));
                System.exit(1);
            } else {
                siardDatei = siardDateiNew;
            }
        }

        /** b) extract.xml vorbereiten (Header) und xsl in Output kopieren */
        // Zeitstempel der Datenextraktion
        java.util.Date nowStart = new java.util.Date();
        java.text.SimpleDateFormat sdfStart = new java.text.SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
        String ausgabeStart = sdfStart.format(nowStart);

        String excerptString = new String(args[3]);
        String outDateiName = siardDatei.getName() + "_" + excerptString + "_SIARDexcerpt.xml";

        // Informationen zum Archiv holen
        String archive = siardexcerpt.getConfigurationService().getArchive();

        // Konfiguration des Outputs, ein File Logger wird zustzlich erstellt
        LogConfigurator logConfigurator = (LogConfigurator) context.getBean("logconfigurator");
        String outFileName = logConfigurator.configure(directoryOfOutput.getAbsolutePath(), outDateiName);
        File outFile = new File(outFileName);
        // Ab hier kann ins Output geschrieben werden...

        // Informationen zum XSL holen
        String pathToXSL = siardexcerpt.getConfigurationService().getPathToXSL();

        File xslOrig = new File(pathToXSL);
        File xslCopy = new File(directoryOfOutput.getAbsolutePath() + File.separator + xslOrig.getName());
        if (!xslCopy.exists()) {
            Util.copyFile(xslOrig, xslCopy);
        }

        LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_HEADER, xslCopy.getName()));
        LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_START, ausgabeStart));
        LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_ARCHIVE, archive));
        LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_INFO));

        /** c) extraktion: dies ist in einem eigenen Modul realisiert */
        Controllerexcerpt controllerexcerpt = (Controllerexcerpt) context.getBean("controllerexcerpt");

        okC = controllerexcerpt.executeC(siardDatei, outFile, excerptString);

        /** d) Ausgabe und exitcode */
        if (!okC) {
            // Record konnte nicht extrahiert werden
            LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_MODUL_C));
            LOGGER.logError(siardexcerpt.getTextResourceService().getText(ERROR_XML_C_CANNOTEXTRACTRECORD));
            LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_LOGEND));
            System.out.println(MESSAGE_XML_MODUL_C);
            System.out.println(ERROR_XML_C_CANNOTEXTRACTRECORD);
            System.out.println("");

            // Lschen des Arbeitsverzeichnisses und configFileHard erfolgt erst bei schritt 4 finish

            // Fehler Extraktion --> invalide
            System.exit(2);
        } else {
            // Record konnte extrahiert werden
            LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_LOGEND));
            // Lschen des Arbeitsverzeichnisses und configFileHard erfolgt erst bei schritt 4 finish

            // Record konnte extrahiert werden
            System.exit(0);

        }

    } // End extract

    if (module.equalsIgnoreCase("--finish")) {

        /** 4) finish: Config-Kopie sowie Workverzeichnis lschen
         * 
         * TODO: Erledigt */

        System.out.println("SIARDexcerpt: finish");

        // Lschen des Arbeitsverzeichnisses und confiFileHard, falls eines angelegt wurde
        if (tmpDir.exists()) {
            Util.deleteDir(tmpDir);
        }
        if (configFileHard.exists()) {
            Util.deleteDir(configFileHard);
        }

    } // End finish

}

From source file:com.makkajai.ObjCToCpp.java

/**
 * Main Method//w ww  . j  av  a2  s .c  om
 *
 * @param args - First argument is the input directory to scan and second is the output directory to write files to.
 * @throws IOException
 */
public static void main(String[] args) throws IOException {

    if (args.length < 2) {
        System.out.println("Invalid Arguments!");
        System.out.println(
                "Usage: java com.makkajai.ObjCToCpp \"<directory to scan for .h and .m files>\" \"<directory to write .h and .cpp files>\"");
        return;
    }

    String inputDirectory = args[0];
    String outputDirectory = args[1];
    //     String inputDirectory = "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/scenes";
    //     String outputDirectory = "/Users/administrator/playground/projarea/monster-math-cross-platform/monster-math-2/Classes/Makkajai/scenes";

    List<String> exceptFiles = new ArrayList<String>();

    if (args.length == 3) {
        BufferedReader bufferedInputStream = new BufferedReader(new FileReader(args[2]));
        String exceptFile = null;
        while ((exceptFile = bufferedInputStream.readLine()) != null) {
            if (exceptFile.equals(""))
                continue;
            exceptFiles.add(exceptFile);
        }
    }

    //Getting all the files from the input directory.
    final List<File> files = new ArrayList<File>(FileUtils.listFiles(new File(inputDirectory),
            new RegexFileFilter(FILE_NAME_WITH_H_OR_M), DirectoryFileFilter.DIRECTORY));

    //        String fileName =
    ////                "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/Utils/MakkajaiEnum"
    ////                "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/Utils/MakkajaiUtil"
    ////                "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/Home"
    ////                "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/Activities/gnumchmenu/PlayStrategy"
    ////                "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/Characters/Character"
    //                "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/Activities/gnumchmenu/GnumchScene"
    ////                "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/ParentScene"
    ////                "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/BaseSkillView"
    ////                "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/YDLayerBase"
    //                ;
    //The instance of the translator.
    ObjCToCppTranslator visitor = new ObjCToCppTranslator();

    for (int i = 0; i < files.size();) {
        File currentFile = files.get(i);
        String filePathRelativeToInput = currentFile.getAbsolutePath().replace(inputDirectory, "");
        Date startTime = new Date();
        try {
            final TranslateFileInput translateFileInput = new TranslateFileInput(inputDirectory,
                    outputDirectory, filePathRelativeToInput, false);
            if (nextFileIsM(currentFile, files, i)) {
                try {
                    if (isIgnoredFile(filePathRelativeToInput, exceptFiles))
                        continue;
                    translateFileInput.dryRun = true;
                    visitor.translateFile(translateFileInput);
                    Date stopTime = new Date();
                    System.out.println("Dry run File: " + translateFileInput.filePathRelativeToInput
                            + " Time Taken: " + getDelta(startTime, stopTime));

                    Date startTime1 = new Date();
                    translateFileInput.filePathRelativeToInput = filePathRelativeToInput.replace(H, M);
                    translateFileInput.dryRun = false;
                    visitor.translateFile(translateFileInput);
                    stopTime = new Date();
                    System.out.println("Processed File: " + translateFileInput.filePathRelativeToInput
                            + " Time Taken: " + getDelta(startTime1, stopTime));

                    Date startTime2 = new Date();
                    translateFileInput.filePathRelativeToInput = filePathRelativeToInput;
                    translateFileInput.dryRun = false;
                    visitor.translateFile(translateFileInput);
                    stopTime = new Date();
                    System.out.println("Processed File: " + translateFileInput.filePathRelativeToInput
                            + " Time Taken: " + getDelta(startTime2, stopTime));
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("###########################Error Processing: " + filePathRelativeToInput
                            + ", Continuing with next set of tiles");
                } finally {
                    i += 2;
                }
                continue;
            }
            if (!isIgnoredFile(filePathRelativeToInput, exceptFiles))
                visitor.translateFile(translateFileInput);
            i++;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("###########################Error Processing: " + filePathRelativeToInput
                    + ", Continuing with next set of tiles");
        } finally {
            Date stopTime = new Date();
            //                System.out.println("Processed File(s): " + filePathRelativeToInput.replaceAll(H_OR_M, "") + " Time Taken: " + getDelta(startTime, stopTime));
        }
    }
}

From source file:com.thed.zapi.cloud.sample.CycleExecutionReportByVersion.java

public static void main(String[] args) throws JSONException, URISyntaxException, ParseException, IOException {

    String API_GET_EXECUTIONS = "{SERVER}/public/rest/api/1.0/executions/search/cycle/";
    String API_GET_CYCLES = "{SERVER}/public/rest/api/1.0/cycles/search?";
    // Delimiter used in CSV file
    final String NEW_LINE_SEPARATOR = "\n";
    final String fileName = "F:\\cycleExecutionReport.csv";

    /** Declare JIRA,Zephyr URL,access and secret Keys */
    // JIRA Cloud URL of the instance
    String jiraBaseURL = "https://demo.atlassian.net";
    // Replace zephyr baseurl <ZAPI_Cloud_URL> shared with the user for ZAPI Cloud Installation
    String zephyrBaseUrl = "<ZAPI_Cloud_URL>";
    // zephyr accessKey , we can get from Addons >> zapi section
    String accessKey = "YjE2MjdjMGEtNzExNy0zYjY1LWFkMzQtNjcwMDM3OTljFkbWluIGFkbWlu";
    // zephyr secretKey , we can get from Addons >> zapi section
    String secretKey = "qufnbimi96Ob2hq3ISF08yZ8Qw4c1eHGeGlk";

    /** Declare parameter values here */
    String userName = "admin";
    String versionId = "-1";
    String projectId = "10100";
    String projectName = "Support";
    String versionName = "Unscheduled";

    ZFJCloudRestClient client = ZFJCloudRestClient.restBuilder(zephyrBaseUrl, accessKey, secretKey, userName)
            .build();//  ww  w.java  2 s  .  c o m
    /**
     * Get List of Cycles by Project and Version
     */

    final String getCyclesUri = API_GET_CYCLES.replace("{SERVER}", zephyrBaseUrl) + "projectId=" + projectId
            + "&versionId=" + versionId;

    Map<String, String> cycles = getCyclesByProjectVersion(getCyclesUri, client, accessKey);
    // System.out.println("cycles :"+ cycles.toString());

    /**
     * Iterating over the Cycles and writing the report to CSV
     * 
     */

    FileWriter fileWriter = null;
    System.out.println("Writing CSV file.....");
    try {
        fileWriter = new FileWriter(fileName);

        // Write the CSV file header

        fileWriter.append("Cycle Execution Report By Version and Project");
        fileWriter.append(NEW_LINE_SEPARATOR);
        fileWriter.append("PROJECT:" + "," + projectName);
        fileWriter.append(NEW_LINE_SEPARATOR);
        fileWriter.append("VERSION:" + "," + versionName);
        fileWriter.append(NEW_LINE_SEPARATOR);

        JSONArray executions;
        int totalUnexecutedCount = 0;
        int totalExecutionCount = 0;

        for (String key : cycles.keySet()) {
            int executionCount = 0;
            int unexecutedCount = 0;
            final String getExecutionsUri = API_GET_EXECUTIONS.replace("{SERVER}", zephyrBaseUrl) + key
                    + "?projectId=" + projectId + "&versionId=" + versionId;
            fileWriter.append("Cycle:" + "," + cycles.get(key));
            fileWriter.append(NEW_LINE_SEPARATOR);
            executions = getExecutionsByCycleId(getExecutionsUri, client, accessKey);
            // System.out.println("executions :" + executions.toString());

            HashMap<String, Integer> counter = new HashMap<String, Integer>();

            String[] statusName = new String[executions.length()];
            for (int i = 0; i < executions.length(); i++) {
                JSONObject executionObj = executions.getJSONObject(i).getJSONObject("execution");
                // System.out.println("executionObj
                // "+executionObj.toString());
                JSONObject statusObj = executionObj.getJSONObject("status");
                // System.out.println("statusObj :"+statusObj.toString());
                statusName[i] = statusObj.getString("name");
            }

            if (statusName.length != 0) {
                // System.out.println(statusName.toString());
                for (String a : statusName) {
                    if (counter.containsKey(a)) {
                        int oldValue = counter.get(a);
                        counter.put(a, oldValue + 1);
                    } else {
                        counter.put(a, 1);
                    }
                }
                for (String status : counter.keySet()) {
                    fileWriter.append(" " + "," + " " + "," + status + "," + counter.get(status));
                    fileWriter.append(NEW_LINE_SEPARATOR);
                    if (status.equalsIgnoreCase("UNEXECUTED")) {
                        unexecutedCount += counter.get(status);
                    } else {
                        executionCount += counter.get(status);
                    }

                }
            }
            totalExecutionCount += executionCount;
            totalUnexecutedCount += unexecutedCount;

            fileWriter.append(NEW_LINE_SEPARATOR);
        }

        fileWriter.append(NEW_LINE_SEPARATOR);
        fileWriter.append("TOTAL CYCLES:" + "," + cycles.size());
        fileWriter.append(NEW_LINE_SEPARATOR);
        fileWriter.append("TOTAL EXECUTIONS:" + "," + totalExecutionCount);
        fileWriter.append(NEW_LINE_SEPARATOR);
        fileWriter.append("TOTAL ASSIGNED:" + "," + (totalUnexecutedCount + totalExecutionCount));

        System.out.println("CSV file was created successfully !!!");
    } catch (Exception e) {
        System.out.println("Error in CsvFileWriter !!!");
        e.printStackTrace();
    } finally {
        try {
            fileWriter.flush();
            fileWriter.close();
        } catch (IOException e) {
            System.out.println("Error while flushing/closing fileWriter !!!");
            e.printStackTrace();
        }
    }

}

From source file:AndroidUninstallStock.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    try {//  ww w. j  a  v a2  s  . c  o  m
        String lang = Locale.getDefault().getLanguage();
        GnuParser cmdparser = new GnuParser();
        Options cmdopts = new Options();
        for (String fld : Arrays.asList("shortOpts", "longOpts", "optionGroups")) {
            // hack for printOptions
            java.lang.reflect.Field fieldopt = cmdopts.getClass().getDeclaredField(fld);
            fieldopt.setAccessible(true);
            fieldopt.set(cmdopts, new LinkedHashMap<>());
        }
        cmdopts.addOption("h", "help", false, "Help");
        cmdopts.addOption("t", "test", false, "Show only report");
        cmdopts.addOption(OptionBuilder.withLongOpt("adb").withArgName("file").hasArg()
                .withDescription("Path to ADB from Android SDK").create("a"));
        cmdopts.addOption(OptionBuilder.withLongOpt("dev").withArgName("device").hasArg()
                .withDescription("Select device (\"adb devices\")").create("d"));
        cmdopts.addOption(null, "restore", false,
                "If packages have not yet removed and are disabled, " + "you can activate them again");
        cmdopts.addOption(null, "google", false, "Delete packages are in the Google section");
        cmdopts.addOption(null, "unapk", false, "Delete /system/app/ *.apk *.odex *.dex"
                + System.lineSeparator() + "(It is required to repeat command execution)");
        cmdopts.addOption(null, "unlib", false, "Delete /system/lib/[libs in apk]");
        //cmdopts.addOption(null, "unfrw", false, "Delete /system/framework/ (special list)");
        cmdopts.addOption(null, "scanlibs", false,
                "(Dangerous!) Include all the libraries of selected packages." + " Use with --unlib");

        cmdopts.addOptionGroup(new OptionGroup() {
            {
                addOption(OptionBuilder.withLongOpt("genfile").withArgName("file").hasArg().isRequired()
                        .withDescription("Create file with list packages").create());
                addOption(OptionBuilder.withLongOpt("lang").withArgName("ISO 639").hasArg().create());
            }
        });
        cmdopts.getOption("lang").setDescription(
                "See hl= in Google URL (default: " + lang + ") " + "for description from Google Play Market");
        CommandLine cmd = cmdparser.parse(cmdopts, args);

        if (args.length == 0 || cmd.hasOption("help")) {
            PrintWriter console = new PrintWriter(System.out);
            HelpFormatter cmdhelp = new HelpFormatter();
            cmdhelp.setOptionComparator(new Comparator<Option>() {
                @Override
                public int compare(Option o1, Option o2) {
                    return 0;
                }
            });
            console.println("WARNING: Before use make a backup with ClockworkMod Recovery!");
            console.println();
            console.println("AndroidUninstallStock [options] [AndroidListSoft.xml]");
            cmdhelp.printOptions(console, 80, cmdopts, 3, 2);
            console.flush();
            return;
        }

        String adb = cmd.getOptionValue("adb", "adb");
        try {
            run(adb, "start-server");
        } catch (IOException e) {
            System.out.println("Error: Not found ADB! Use -a or --adb");
            return;
        }

        final boolean NotTest = !cmd.hasOption("test");

        String deverror = getDeviceStatus(adb, cmd.getOptionValue("dev"));
        if (!deverror.isEmpty()) {
            System.out.println(deverror);
            return;
        }

        System.out.println("Getting list packages:");
        LinkedHashMap<String, String> apklist = new LinkedHashMap<String, String>();
        for (String ln : run(adb, "-s", lastdevice, "shell", "pm list packages -s -f")) {
            // "pm list packages" give list sorted by packages ;)
            String pckg = ln.substring("package:".length());
            String pckgname = ln.substring(ln.lastIndexOf('=') + 1);
            pckg = pckg.substring(0, pckg.length() - pckgname.length() - 1);
            if (!pckgname.equals("android") && !pckgname.equals("com.android.vending")/*Google Play Market*/) {
                apklist.put(pckg, pckgname);
            }
        }
        for (String ln : run(adb, "-s", lastdevice, "shell", "ls /system/app/")) {
            String path = "/system/app/" + ln.replace(".odex", ".apk").replace(".dex", ".apk");
            if (!apklist.containsKey(path)) {
                apklist.put(path, "");
            }
        }
        apklist.remove("/system/app/mcRegistry");
        for (Map.Entry<String, String> info : sortByValues(apklist).entrySet()) {
            System.out.println(info.getValue() + " = " + info.getKey());
        }

        String genfile = cmd.getOptionValue("genfile");
        if (genfile != null) {
            Path genpath = Paths.get(genfile);
            try (BufferedWriter gen = Files.newBufferedWriter(genpath, StandardCharsets.UTF_8,
                    new StandardOpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING,
                            StandardOpenOption.WRITE })) {
                if (cmd.getOptionValue("lang") != null) {
                    lang = cmd.getOptionValue("lang");
                }

                LinkedHashSet<String> listsystem = new LinkedHashSet<String>() {
                    {
                        add("com.android");
                        add("com.google.android");
                        //add("com.sec.android.app");
                        add("com.monotype.android");
                        add("eu.chainfire.supersu");
                    }
                };

                // \r\n for Windows Notepad
                gen.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
                gen.write("<!-- & raplace with &amp; or use <![CDATA[ ]]> -->\r\n");
                gen.write("<AndroidUninstallStock>\r\n\r\n");
                gen.write("<Normal>\r\n");
                System.out.println();
                System.out.println("\tNormal:");
                writeInfo(gen, apklist, lang, listsystem, true);
                gen.write("\t<apk name=\"Exclude Google and etc\">\r\n");
                for (String exc : listsystem) {
                    gen.write("\t\t<exclude global=\"true\" in=\"package\" pattern=\"" + exc + "\" />\r\n");
                }
                gen.write("\t</apk>\r\n");
                gen.write("</Normal>\r\n\r\n");
                gen.write("<Google>\r\n");
                System.out.println();
                System.out.println("\tGoogle:");
                writeInfo(gen, apklist, lang, listsystem, false);
                gen.write("</Google>\r\n\r\n");
                gen.write("</AndroidUninstallStock>\r\n");
                System.out.println("File " + genpath.toAbsolutePath() + " created.");
            }
            return;
        }

        String[] FileName = cmd.getArgs();
        if (!(FileName.length > 0 && Files.isReadable(Paths.get(FileName[0])))) {
            System.out.println("Error: File " + FileName[0] + " not found!");
            return;
        }

        DocumentBuilderFactory xmlfactory = getXmlDocFactory();

        // DocumentBuilder.setErrorHandler() for print errors
        Document xml = xmlfactory.newDocumentBuilder().parse(new File(FileName[0]));

        LinkedList<AusInfo> Normal = new LinkedList<AusInfo>();
        LinkedList<AusInfo> Google = new LinkedList<AusInfo>();

        NodeList ndaus = xml.getElementsByTagName("AndroidUninstallStock").item(0).getChildNodes();
        for (int ndausx = 0, ndausc = ndaus.getLength(); ndausx < ndausc; ndausx++) {
            Node ndnow = ndaus.item(ndausx);
            NodeList nd = ndnow.getChildNodes();
            String ndname = ndnow.getNodeName();
            for (int ndx = 0, ndc = nd.getLength(); ndx < ndc; ndx++) {
                if (!nd.item(ndx).getNodeName().equalsIgnoreCase("apk")) {
                    continue;
                }
                if (ndname.equalsIgnoreCase("Normal")) {
                    Normal.add(getApkInfo(nd.item(ndx)));
                } else if (ndname.equalsIgnoreCase("Google")) {
                    Google.add(getApkInfo(nd.item(ndx)));
                }
            }
        }

        // FIXME This part must be repeated until the "pm uninstall" will not issue "Failure" on all packages.
        //       Now requires a restart.
        System.out.println();
        System.out.println("Include and Exclude packages (Normal):");
        LinkedHashMap<String, String> apkNormal = getApkFromPattern(apklist, Normal, false);
        System.out.println();
        System.out.println("Global Exclude packages (Normal):");
        apkNormal = getApkFromPattern(apkNormal, Normal, true);
        System.out.println();
        System.out.println("Final list packages (Normal):");
        for (Map.Entry<String, String> info : sortByValues(apkNormal).entrySet()) {
            System.out.println(info.getValue() + " = " + info.getKey());
        }

        LinkedHashMap<String, String> apkGoogle = new LinkedHashMap<String, String>();
        if (cmd.hasOption("google")) {
            System.out.println();
            System.out.println("Include and Exclude packages (Google):");
            apkGoogle = getApkFromPattern(apklist, Google, false);
            System.out.println();
            System.out.println("Global Exclude packages (Google):");
            apkGoogle = getApkFromPattern(apkGoogle, Google, true);
            System.out.println();
            System.out.println("Final list packages (Google):");
            for (Map.Entry<String, String> info : sortByValues(apkGoogle).entrySet()) {
                System.out.println(info.getValue() + " = " + info.getKey());
            }
        }

        if (NotTest) {
            if (!hasRoot(adb)) {
                System.out.println("No Root");
                System.out.println();
                System.out.println("FINISH :)");
                return;
            }
        }

        if (cmd.hasOption("restore")) {
            System.out.println();
            System.out.println("Enable (Restore) packages (Normal):");
            damage(adb, "pm enable ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Enable (Restore) packages (Google):");
                damage(adb, "pm enable ", NotTest, apkGoogle, 2);
            }
            System.out.println();
            System.out.println("FINISH :)");
            return;
        } else {
            System.out.println();
            System.out.println("Disable packages (Normal):");
            damage(adb, "pm disable ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Disable packages (Google):");
                damage(adb, "pm disable ", NotTest, apkGoogle, 2);
            }
        }

        if (!cmd.hasOption("unapk") && !cmd.hasOption("unlib")) {
            System.out.println();
            System.out.println("FINISH :)");
            return;
        }

        // Reboot now not needed
        /*if (NotTest) {
        reboot(adb, "-s", lastdevice, "reboot");
        if (!hasRoot(adb)) {
            System.out.println("No Root");
            System.out.println();
            System.out.println("FINISH :)");
            return;
        }
        }*/

        if (cmd.hasOption("unlib")) {
            // "find" not found
            System.out.println();
            System.out.println("Getting list libraries:");
            LinkedList<String> liblist = new LinkedList<String>();
            liblist.addAll(run(adb, "-s", lastdevice, "shell", "ls -l /system/lib/"));
            String dircur = "/system/lib/";
            for (int x = 0; x < liblist.size(); x++) {
                if (liblist.get(x).startsWith("scan:")) {
                    dircur = liblist.get(x).substring("scan:".length());
                    liblist.remove(x);
                    x--;
                } else if (liblist.get(x).startsWith("d")) {
                    String dir = liblist.get(x).substring(liblist.get(x).lastIndexOf(':') + 4) + "/";
                    liblist.remove(x);
                    x--;
                    liblist.add("scan:/system/lib/" + dir);
                    liblist.addAll(run(adb, "-s", lastdevice, "shell", "ls -l /system/lib/" + dir));
                    continue;
                }
                liblist.set(x, dircur + liblist.get(x).substring(liblist.get(x).lastIndexOf(':') + 4));
                System.out.println(liblist.get(x));
            }

            final boolean scanlibs = cmd.hasOption("scanlibs");
            LinkedHashMap<String, String> libNormal = getLibFromPatternInclude(adb, liblist, apkNormal, Normal,
                    "Normal", scanlibs);
            libNormal = getLibFromPatternGlobalExclude(libNormal, Normal, "Normal");
            System.out.println();
            System.out.println("Final list libraries (Normal):");
            for (Map.Entry<String, String> info : sortByValues(libNormal).entrySet()) {
                System.out.println(info.getKey() + " = " + info.getValue());
            }

            LinkedHashMap<String, String> libGoogle = new LinkedHashMap<String, String>();
            if (cmd.hasOption("google")) {
                libGoogle = getLibFromPatternInclude(adb, liblist, apkGoogle, Google, "Google", scanlibs);
                libGoogle = getLibFromPatternGlobalExclude(libGoogle, Google, "Google");
                System.out.println();
                System.out.println("Final list libraries (Google):");
                for (Map.Entry<String, String> info : sortByValues(libGoogle).entrySet()) {
                    System.out.println(info.getKey() + " = " + info.getValue());
                }
            }

            LinkedHashMap<String, String> apkExclude = new LinkedHashMap<String, String>(apklist);
            for (String key : apkNormal.keySet()) {
                apkExclude.remove(key);
            }
            for (String key : apkGoogle.keySet()) {
                apkExclude.remove(key);
            }

            System.out.println();
            System.out.println("Include libraries from Exclude packages:");
            LinkedHashMap<String, String> libExclude = getLibFromPackage(adb, liblist, apkExclude);
            System.out.println();
            System.out.println("Enclude libraries from Exclude packages (Normal):");
            for (Map.Entry<String, String> info : sortByValues(libNormal).entrySet()) {
                if (libExclude.containsKey(info.getKey())) {
                    System.out.println("exclude: " + info.getKey() + " = " + libExclude.get(info.getKey()));
                    libNormal.remove(info.getKey());
                }
            }
            System.out.println();
            System.out.println("Enclude libraries from Exclude packages (Google):");
            for (Map.Entry<String, String> info : sortByValues(libGoogle).entrySet()) {
                if (libExclude.containsKey(info.getKey())) {
                    System.out.println("exclude: " + info.getKey() + " = " + libExclude.get(info.getKey()));
                    libGoogle.remove(info.getKey());
                }
            }

            System.out.println();
            System.out.println("Delete libraries (Normal):");
            damage(adb, "rm ", NotTest, libNormal, 1);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Delete libraries (Google):");
                damage(adb, "rm ", NotTest, libGoogle, 1);
            }
        }

        if (cmd.hasOption("unapk")) {
            System.out.println();
            System.out.println("Cleaning data packages (Normal):");
            damage(adb, "pm clear ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Cleaning data packages (Google):");
                damage(adb, "pm clear ", NotTest, apkGoogle, 2);
            }

            System.out.println();
            System.out.println("Uninstall packages (Normal):");
            damage(adb, "pm uninstall ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Uninstall packages (Google):");
                damage(adb, "pm uninstall ", NotTest, apkGoogle, 2);
            }
        }

        if (cmd.hasOption("unapk")) {
            System.out.println();
            System.out.println("Delete packages (Normal):");
            LinkedHashMap<String, String> dexNormal = new LinkedHashMap<String, String>();
            for (Map.Entry<String, String> apk : apkNormal.entrySet()) {
                dexNormal.put(apk.getKey(), apk.getValue());
                dexNormal.put(apk.getKey().replace(".apk", ".dex"), apk.getValue());
                dexNormal.put(apk.getKey().replace(".apk", ".odex"), apk.getValue());
            }
            damage(adb, "rm ", NotTest, dexNormal, 1);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Delete packages (Google):");
                LinkedHashMap<String, String> dexGoogle = new LinkedHashMap<String, String>();
                for (Map.Entry<String, String> apk : apkGoogle.entrySet()) {
                    dexGoogle.put(apk.getKey(), apk.getValue());
                    dexGoogle.put(apk.getKey().replace(".apk", ".dex"), apk.getValue());
                    dexGoogle.put(apk.getKey().replace(".apk", ".odex"), apk.getValue());
                }
                damage(adb, "rm ", NotTest, dexGoogle, 1);
            }
        }

        if (NotTest) {
            run(adb, "-s", lastdevice, "reboot");
        }
        System.out.println();
        System.out.println("FINISH :)");
    } catch (SAXException e) {
        System.out.println("Error parsing list: " + e);
    } catch (Throwable e) {
        e.printStackTrace();
    }
}

From source file:javazoom.jlgui.player.amp.Player.java

/**
 * Entry point.// w ww.  j  av a  2 s. co  m
 */
public static void main(String[] args) {
    Player theGUI;
    String currentArg = null;
    String currentValue = null;
    String skin = null;
    for (int i = 0; i < args.length; i++) {
        currentArg = args[i];
        if (currentArg.startsWith("-")) {
            if (currentArg.toLowerCase().equals("-init")) {
                i++;
                if (i >= args.length)
                    usage("init value missing");
                currentValue = args[i];
                if (Config.startWithProtocol(currentValue))
                    initConfig = currentValue;
                else
                    initConfig = currentValue.replace('\\', '/').replace('/', java.io.File.separatorChar);
            } else if (currentArg.toLowerCase().equals("-song")) {
                i++;
                if (i >= args.length)
                    usage("song value missing");
                currentValue = args[i];
                if (Config.startWithProtocol(currentValue))
                    initSong = currentValue;
                else
                    initSong = currentValue.replace('\\', '/').replace('/', java.io.File.separatorChar);
            } else if (currentArg.toLowerCase().equals("-start")) {
                autoRun = true;
            } else if (currentArg.toLowerCase().equals("-showplaylist")) {
                showPlaylist = "true";
            } else if (currentArg.toLowerCase().equals("-showequalizer")) {
                showEqualizer = "true";
            } else if (currentArg.toLowerCase().equals("-skin")) {
                i++;
                if (i >= args.length)
                    usage("skin value missing");
                currentValue = args[i];
                if (Config.startWithProtocol(currentValue))
                    skin = currentValue;
                else
                    skin = currentValue.replace('\\', '/').replace('/', java.io.File.separatorChar);
            } else if (currentArg.toLowerCase().equals("-v")) {
                i++;
                if (i >= args.length)
                    usage("skin version value missing");
                skinVersion = args[i];
            } else
                usage("Unknown parameter : " + currentArg);
        } else {
            usage("Invalid parameter :" + currentArg);
        }
    }
    // Instantiate AWT front-end.      
    theGUI = new Player(skin, new Frame(TITLETEXT));
    // Instantiate low-level player.
    BasicPlayer bplayer = new BasicPlayer();
    // Register the front-end to low-level player events.
    bplayer.addBasicPlayerListener(theGUI);
    // Adds controls for front-end to low-level player.
    theGUI.setController(bplayer);
    // Display.
    theGUI.show();
    if (autoRun == true)
        theGUI.pressStart();
}

From source file:br.com.thiagomoreira.bancodobrasil.Main.java

/**
 * @param args//ww  w .  j a  va2s .  c om
 */
public static void main(String[] args) throws Exception {
    if (args != null) {
        NumberFormat formatter = NumberFormat.getNumberInstance(new Locale("pt", "BR"));

        formatter.setMaximumFractionDigits(2);
        formatter.setMinimumFractionDigits(2);

        double total = 0;

        for (String arg : args) {
            File input = new File(arg);
            if (input.exists()) {
                List<String> lines = IOUtils.readLines(new FileInputStream(input), "ISO-8859-1");

                Parser parser = new DefaultParser();

                List<Transaction> transactions = parser.parse(lines);

                TransactionList transactionList = new TransactionList();
                transactionList.setStart(parser.getStartDate());
                transactionList.setEnd(parser.getEndDate());
                transactionList.setTransactions(transactions);

                CreditCardAccountDetails creditCardAccountDetails = new CreditCardAccountDetails();
                creditCardAccountDetails.setAccountNumber("7616-3");
                creditCardAccountDetails.setAccountKey(parser.getAccountKey());

                CreditCardStatementResponse creditCardStatementResponse = new CreditCardStatementResponse();
                creditCardStatementResponse.setAccount(creditCardAccountDetails);
                creditCardStatementResponse.setCurrencyCode("BRL");
                creditCardStatementResponse.setTransactionList(transactionList);

                Status status = new Status();
                status.setCode(Status.KnownCode.SUCCESS);
                status.setSeverity(Status.Severity.INFO);

                CreditCardStatementResponseTransaction statementResponse = new CreditCardStatementResponseTransaction();
                statementResponse.setClientCookie(UUID.randomUUID().toString());
                statementResponse.setStatus(status);
                statementResponse.setUID(UUID.randomUUID().toString());
                statementResponse.setMessage(creditCardStatementResponse);

                CreditCardResponseMessageSet creditCardResponseMessageSet = new CreditCardResponseMessageSet();
                creditCardResponseMessageSet.setStatementResponse(statementResponse);

                SortedSet<ResponseMessageSet> messageSets = new TreeSet<ResponseMessageSet>();
                messageSets.add(creditCardResponseMessageSet);

                ResponseEnvelope envelope = new ResponseEnvelope();
                envelope.setUID(UUID.randomUUID().toString());
                envelope.setSecurity(ApplicationSecurity.NONE);
                envelope.setMessageSets(messageSets);

                double brazilianRealsamount = parser.getBrazilianRealsAmount();
                double dolarsAmount = parser.getDolarsAmount();
                double cardTotal = dolarsAmount * parser.getExchangeRate() + brazilianRealsamount;
                total += cardTotal;

                System.out.println(creditCardAccountDetails.getAccountKey());
                System.out.println("TOTAL EM RS " + formatter.format(brazilianRealsamount));
                System.out.println("TOTAL EM US " + formatter.format(dolarsAmount));
                System.out.println("TOTAL FATURA EM RS " + formatter.format(cardTotal));
                System.out.println();

                if (!transactions.isEmpty()) {
                    String parent = System.getProperty("user.home") + "/Downloads";
                    String fileName = arg.replace(".txt", ".ofx");
                    File output = new File(parent, fileName);
                    FileOutputStream fos = new FileOutputStream(output);

                    OFXV1Writer writer = new OFXV1Writer(fos);
                    writer.setWriteAttributesOnNewLine(true);

                    AggregateMarshaller marshaller = new AggregateMarshaller();
                    marshaller.setConversion(new MyFinanceStringConversion());
                    marshaller.marshal(envelope, writer);

                    writer.flush();
                    writer.close();
                }
            }
        }
        System.out.println("TOTAL FATURAS EM RS " + formatter.format(total));
    }

}