Example usage for java.lang String length

List of usage examples for java.lang String length

Introduction

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

Prototype

public int length() 

Source Link

Document

Returns the length of this string.

Usage

From source file:HLA.java

public static void main(String[] args) throws IOException {

    if (!isVersionOrHigher()) {
        System.err.println("JRE of 1.8+ is required to run Kourami. Exiting.");
        System.exit(1);/* ww w.ja v  a2s  . c o  m*/
    }

    CommandLineParser parser = new DefaultParser();
    Options options = HLA.createOption();
    Options helponlyOpts = HLA.createHelpOption();
    String[] bams = null;
    CommandLine line = null;
    boolean exitRun = false;
    try {
        CommandLine helpcheck = new DefaultParser().parse(helponlyOpts, args, true);
        if (helpcheck.getOptions().length > 0)
            HLA.help(options);
        else {
            line = parser.parse(options, args);
            if (line.hasOption("h"))//help"))
                HLA.help(options);
            else {
                if (line.hasOption("a"))
                    HLA.TYPEADDITIONAL = true;

                HLA.OUTPREFIX = line.getOptionValue("o");//outfilePrefix");
                String tmploc = line.getOptionValue("d");//msaDirectory");
                HLA.MSAFILELOC = tmploc;
                if (tmploc.endsWith(File.separator))
                    HLA.MSAFILELOC = tmploc.substring(0, tmploc.length() - 1);
                if (!new File(HLA.MSAFILELOC).exists() || !new File(HLA.MSAFILELOC).isDirectory()) {
                    System.err.println("Given msaDirectory: " + HLA.MSAFILELOC
                            + "\t does NOT exist or is NOT a directory.");
                    exitRun = true;
                } else if (!new File(HLA.MSAFILELOC + File.separator + "hla_nom_g.txt").exists()) {
                    System.err.println("hla_nom_g.txt NOT FOUND in " + HLA.MSAFILELOC);
                    System.err
                            .println("Please download hla_nom_g.txt from the same IMGT Release as msa files.");
                    exitRun = true;
                }
            }
            bams = line.getArgs();

            if (bams.length < 1 || (bams.length == 1 && bams[bams.length - 1].equals("DEBUG1228")))
                throw new ParseException("At least 1 bam file is required. See Usage:");
            else {
                if (bams.length > 1 && bams[bams.length - 1].equals("DEBUG1228")) {
                    String[] tmpbams = new String[bams.length - 1];
                    for (int i = 0; i < bams.length - 1; i++)
                        tmpbams[i] = bams[i];
                    bams = tmpbams;
                    HLA.DEBUG = true;
                }

                for (String b : bams)
                    if (!new File(b).exists()) {
                        System.err
                                .println("Input bam : " + b + " DOES NOT exist. Please check the bam exists.");
                        exitRun = true;
                    }
            }

        }
        if (exitRun)
            throw new ParseException("Exitting . . .");
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        //System.err.println("Failed to parse command line args. Check usage.");
        HLA.help(options);
    }

    String[] list = { "A", "B", "C", "DQA1", "DQB1", "DRB1" };

    String[] extList = { "A", "B", "C", "DQA1", "DQB1", "DRB1", "DOA", "DMA", "DMB", "DPA1", "DPB1", "DRA",
            "DRB3", "DRB5", "F", "G", "H", "J", "L" };
    //,"DPA1", "DPB1", "DRA",  "DRB4", "F", "G" , "H", "J" ,"K", "L", "V"};
    //,"DPA1", "DPB1", "DRA", "DRB3", "DRB4", "F", "G" , "H", "J" ,"K", "L", "V"};

    if (HLA.TYPEADDITIONAL)
        list = extList;

    File[] bamfiles = new File[bams.length];

    for (int i = 0; i < bams.length; i++)
        bamfiles[i] = new File(bams[i]);

    //check if <HLA.OUTPREFIX>.result is writable
    //if not exit.
    BufferedWriter resultWriter = null;
    try {
        resultWriter = new BufferedWriter(new FileWriter(HLA.OUTPREFIX + ".result"));
    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.err.println("\n\n>>> CANNOT open output file: " + HLA.OUTPREFIX + ".result <<<\n\n");
        HLA.help(options);
    }

    HLA.log = new LogHandler();
    for (int i = 0; i < args.length; i++)
        HLA.log.append(" " + args[i]);
    HLA.log.appendln();

    try {
        System.err.println("----------------REF GRAPH CONSTRUCTION--------------");

        HLA.log.appendln("----------------REF GRAPH CONSTRUCTION--------------");
        HLA hla = new HLA(list, HLA.MSAFILELOC + File.separator + "hla_nom_g.txt");

        //1. bubble counting before loading reads.
        //System.err.println("----------------BUBBLE COUNTING: REF GRAPH--------------");
        //HLA.log.appendln("----------------BUBBLE COUNTING: REF GRAPH--------------");
        //hla.countStems();

        System.err.println("----------------     READ LOADING     --------------");

        HLA.log.appendln("----------------     READ LOADING     --------------");

        hla.loadReads(bamfiles);

        System.err.println("----------------    GRAPH CLEANING    --------------");
        HLA.log.appendln("----------------    GRAPH CLEANING    --------------");

        hla.flattenInsertionNodes(list);
        hla.removeUnused(list);
        hla.removeStems(list);

        /*updating error prob*/
        hla.updateErrorProb();

        hla.log.flush();

        StringBuffer resultBuffer = new StringBuffer();

        HLA.DEBUG3 = HLA.DEBUG;

        hla.countBubblesAndMerge(list, resultBuffer);

        hla.writeResults(resultBuffer, resultWriter);
    } catch (Exception e) {
        e.printStackTrace();
        HLA.log.outToFile();
        System.exit(-1);
    }
    /*printingWeights*/
    //hla.printWeights();
    HLA.log.outToFile();
    HLA.log.appendln("NEW_NODE_ADDED:\t" + HLA.NEW_NODE_ADDED);
    HLA.log.appendln("HOPPPING:\t" + HLA.HOPPING);
    HLA.log.appendln("INSERTION_NODE_ADDED:\t" + HLA.INSERTION_NODE_ADDED);
    HLA.log.appendln("INSERTION_WITH_NO_NEW_NODE:\t" + HLA.INSERTION_WITH_NO_NEW_NODE);
    HLA.log.appendln("INSERTION_COUNTS:\t" + HLA.INSERTION);
}

From source file:com.github.fritaly.graphml4j.samples.GradleDependenciesWithGroupsAndBuffering.java

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.out.println(String.format("%s <output-file>",
                GradleDependenciesWithGroupsAndBuffering.class.getSimpleName()));
        System.exit(1);/*from w  w w  .j  av  a2s . co m*/
    }

    final File file = new File(args[0]);

    System.out.println("Writing GraphML file to " + file.getAbsolutePath() + " ...");

    FileWriter fileWriter = null;
    Reader reader = null;
    LineNumberReader lineReader = null;

    try {
        fileWriter = new FileWriter(file);

        final com.github.fritaly.graphml4j.datastructure.Graph graph = new Graph();

        // The dependency graph has been generated by Gradle with the
        // command "gradle dependencies". The output of this command has
        // been saved to a text file which will be parsed to rebuild the
        // dependency graph
        reader = new InputStreamReader(
                GradleDependenciesWithGroupsAndBuffering.class.getResourceAsStream("gradle-dependencies.txt"));
        lineReader = new LineNumberReader(reader);

        String line = null;

        // Stack containing the nodes per depth inside the dependency graph
        // (the topmost dependency is the first one in the stack)
        final Stack<Node> parentNodes = new Stack<Node>();

        while ((line = lineReader.readLine()) != null) {
            // Determine the depth of the current dependency inside the
            // graph. The depth can be inferred from the indentation used by
            // Gradle. Each level of depth adds 5 more characters of
            // indentation
            final int initialLength = line.length();

            // Remove the strings used by Gradle to indent dependencies
            line = StringUtils.replace(line, "+--- ", "");
            line = StringUtils.replace(line, "|    ", "");
            line = StringUtils.replace(line, "\\--- ", "");
            line = StringUtils.replace(line, "     ", "");

            // The depth can easily be inferred now
            final int depth = (initialLength - line.length()) / 5;

            // Remove unnecessary node ids
            while (depth <= parentNodes.size()) {
                parentNodes.pop();
            }

            final Artifact artifact = createArtifact(line);

            Node node = graph.getNodeByData(artifact);

            // Has this dependency already been added to the graph ?
            if (node == null) {
                // No, add the node
                node = graph.addNode(artifact);
            }

            parentNodes.push(node);

            if (parentNodes.size() > 1) {
                // Generate an edge between the current node and its parent
                graph.addEdge("Depends on", parentNodes.get(parentNodes.size() - 2), node);
            }
        }

        // Create the groups after creating the nodes & edges
        for (Node node : graph.getNodes()) {
            final Artifact artifact = (Artifact) node.getData();

            final String groupId = artifact.group;

            Node groupNode = graph.getNodeByData(groupId);

            if (groupNode == null) {
                groupNode = graph.addNode(groupId);
            }

            // add the node to the group
            node.setParent(groupNode);
        }

        graph.toGraphML(fileWriter, new Renderer() {

            @Override
            public String getNodeLabel(Node node) {
                return node.isGroup() ? node.getData().toString() : ((Artifact) node.getData()).getLabel();
            }

            @Override
            public boolean isGroupOpen(Node node) {
                return true;
            }

            @Override
            public NodeStyle getNodeStyle(Node node) {
                // Customize the rendering of nodes
                final NodeStyle nodeStyle = new NodeStyle();
                nodeStyle.setWidth(250.0f);

                return nodeStyle;
            }

            @Override
            public GroupStyles getGroupStyles(Node node) {
                return new GroupStyles();
            }

            @Override
            public EdgeStyle getEdgeStyle(Edge edge) {
                return new EdgeStyle();
            }
        });

        System.out.println("Done");
    } finally {
        // Calling GraphMLWriter.close() is necessary to dispose the underlying resources
        fileWriter.close();
        lineReader.close();
        reader.close();
    }
}

From source file:org.eclipse.swt.snippets.Snippet205.java

public static void main(String[] args) {
    Display display = new Display();
    final Shell shell = new Shell(display, SWT.SHELL_TRIM | SWT.DOUBLE_BUFFERED);
    shell.setText("Embedding objects in text");
    final Image[] images = { new Image(display, 32, 32), new Image(display, 20, 40),
            new Image(display, 40, 20) };
    int[] colors = { SWT.COLOR_BLUE, SWT.COLOR_MAGENTA, SWT.COLOR_GREEN };
    for (int i = 0; i < images.length; i++) {
        GC gc = new GC(images[i]);
        gc.setBackground(display.getSystemColor(colors[i]));
        gc.fillRectangle(images[i].getBounds());
        gc.dispose();//  ww  w.  j  a  va  2s . c om
    }

    final Button button = new Button(shell, SWT.PUSH);
    button.setText("Button");
    button.pack();
    String text = "Here is some text with a blue image \uFFFC, a magenta image \uFFFC, a green image \uFFFC, and a button: \uFFFC.";
    final int[] imageOffsets = { 36, 55, 72 };
    final TextLayout layout = new TextLayout(display);
    layout.setText(text);
    for (int i = 0; i < images.length; i++) {
        Rectangle bounds = images[i].getBounds();
        TextStyle imageStyle = new TextStyle(null, null, null);
        imageStyle.metrics = new GlyphMetrics(bounds.height, 0, bounds.width);
        layout.setStyle(imageStyle, imageOffsets[i], imageOffsets[i]);
    }
    Rectangle bounds = button.getBounds();
    TextStyle buttonStyle = new TextStyle(null, null, null);
    buttonStyle.metrics = new GlyphMetrics(bounds.height, 0, bounds.width);
    final int buttonOffset = text.length() - 2;
    layout.setStyle(buttonStyle, buttonOffset, buttonOffset);

    shell.addListener(SWT.Paint, event -> {
        GC gc = event.gc;
        Point margin = new Point(10, 10);
        layout.setWidth(shell.getClientArea().width - 2 * margin.x);
        layout.draw(event.gc, margin.x, margin.y);
        for (int i = 0; i < images.length; i++) {
            int offset = imageOffsets[i];
            int lineIndex1 = layout.getLineIndex(offset);
            FontMetrics lineMetrics1 = layout.getLineMetrics(lineIndex1);
            Point point1 = layout.getLocation(offset, false);
            GlyphMetrics glyphMetrics1 = layout.getStyle(offset).metrics;
            gc.drawImage(images[i], point1.x + margin.x,
                    point1.y + margin.y + lineMetrics1.getAscent() - glyphMetrics1.ascent);
        }
        int lineIndex2 = layout.getLineIndex(buttonOffset);
        FontMetrics lineMetrics2 = layout.getLineMetrics(lineIndex2);
        Point point2 = layout.getLocation(buttonOffset, false);
        GlyphMetrics glyphMetrics2 = layout.getStyle(buttonOffset).metrics;
        button.setLocation(point2.x + margin.x,
                point2.y + margin.y + lineMetrics2.getAscent() - glyphMetrics2.ascent);
    });

    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    layout.dispose();
    for (int i = 0; i < images.length; i++) {
        images[i].dispose();
    }
    display.dispose();
}

From source file:TextLayoutImageControl.java

public static void main(String[] args) {
    Display display = new Display();
    final Shell shell = new Shell(display, SWT.SHELL_TRIM | SWT.DOUBLE_BUFFERED);
    shell.setText("Embedding objects in text");
    final Image[] images = { new Image(display, 32, 32), new Image(display, 20, 40),
            new Image(display, 40, 20) };
    int[] colors = { SWT.COLOR_BLUE, SWT.COLOR_MAGENTA, SWT.COLOR_GREEN };
    for (int i = 0; i < images.length; i++) {
        GC gc = new GC(images[i]);
        gc.setBackground(display.getSystemColor(colors[i]));
        gc.fillRectangle(images[i].getBounds());
        gc.dispose();/*from  w w  w.ja  v  a2  s  .  c  om*/
    }

    final Button button = new Button(shell, SWT.PUSH);
    button.setText("Button");
    button.pack();
    String text = "Here is some text with a blue image \uFFFC, a magenta image \uFFFC, a green image \uFFFC, and a button: \uFFFC.";
    final int[] imageOffsets = { 36, 55, 72 };
    final TextLayout layout = new TextLayout(display);
    layout.setText(text);
    for (int i = 0; i < images.length; i++) {
        Rectangle bounds = images[i].getBounds();
        TextStyle imageStyle = new TextStyle(null, null, null);
        imageStyle.metrics = new GlyphMetrics(bounds.height, 0, bounds.width);
        layout.setStyle(imageStyle, imageOffsets[i], imageOffsets[i]);
    }
    Rectangle bounds = button.getBounds();
    TextStyle buttonStyle = new TextStyle(null, null, null);
    buttonStyle.metrics = new GlyphMetrics(bounds.height, 0, bounds.width);
    final int buttonOffset = text.length() - 2;
    layout.setStyle(buttonStyle, buttonOffset, buttonOffset);

    shell.addListener(SWT.Paint, new Listener() {
        public void handleEvent(Event event) {
            GC gc = event.gc;
            Point margin = new Point(10, 10);
            layout.setWidth(shell.getClientArea().width - 2 * margin.x);
            layout.draw(event.gc, margin.x, margin.y);
            for (int i = 0; i < images.length; i++) {
                int offset = imageOffsets[i];
                int lineIndex = layout.getLineIndex(offset);
                FontMetrics lineMetrics = layout.getLineMetrics(lineIndex);
                Point point = layout.getLocation(offset, false);
                GlyphMetrics glyphMetrics = layout.getStyle(offset).metrics;
                gc.drawImage(images[i], point.x + margin.x,
                        point.y + margin.y + lineMetrics.getAscent() - glyphMetrics.ascent);
            }
            int lineIndex = layout.getLineIndex(buttonOffset);
            FontMetrics lineMetrics = layout.getLineMetrics(lineIndex);
            Point point = layout.getLocation(buttonOffset, false);
            GlyphMetrics glyphMetrics = layout.getStyle(buttonOffset).metrics;
            button.setLocation(point.x + margin.x,
                    point.y + margin.y + lineMetrics.getAscent() - glyphMetrics.ascent);
        }
    });

    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    layout.dispose();
    for (int i = 0; i < images.length; i++) {
        images[i].dispose();
    }
    display.dispose();
}

From source file:kilim.tools.Weaver.java

/**
 * <pre>//from   w w w  . j  a v a 2  s.  c  o m
 * Usage: java kilim.tools.Weaver -d &lt;output directory&gt; {source classe, jar, directory ...}
 * </pre>
 * 
 * If directory names or jar files are given, all classes in that container are processed. It is
 * perfectly fine to specify the same directory for source and output like this: 
 * <pre>
 *    java kilim.tools.Weaver -d ./classes ./classes
 * </pre>
 * Ensure that all classes to be woven are in the classpath. The output directory does not have to be 
 * in the classpath during weaving.
 *   
 * @see #weave(List) for run-time weaving.
 */
public static void main(String[] args) throws IOException {
    // System.out.println(System.getProperty("java.class.path"));

    Detector detector = Detector.DEFAULT;

    String currentName = null;
    for (String name : parseArgs(args)) {
        try {
            if (name.endsWith(".class")) {
                if (exclude(name))
                    continue;
                currentName = name;
                weaveFile(name, new BufferedInputStream(new FileInputStream(name)), detector);
            } else if (name.endsWith(".jar")) {
                for (FileLister.Entry fe : new FileLister(name)) {
                    currentName = fe.getFileName();
                    if (currentName.endsWith(".class")) {
                        currentName = currentName.substring(0, currentName.length() - 6).replace('/', '.');
                        if (exclude(currentName))
                            continue;
                        weaveFile(currentName, fe.getInputStream(), detector);
                    }
                }
            } else if (new File(name).isDirectory()) {
                for (FileLister.Entry fe : new FileLister(name)) {
                    currentName = fe.getFileName();
                    if (currentName.endsWith(".class")) {
                        if (exclude(currentName))
                            continue;
                        weaveFile(currentName, fe.getInputStream(), detector);
                    }
                }
            } else {
                weaveClass(name, detector);
            }
        } catch (KilimException ke) {
            log.error("Error weaving " + currentName + ". " + ke.getMessage());
            // ke.printStackTrace();
            System.exit(1);
        } catch (IOException ioe) {
            log.error("Unable to find/process '" + currentName + "'");
            System.exit(1);
        } catch (Throwable t) {
            log.error("Error weaving " + currentName);
            t.printStackTrace();
            System.exit(1);
        }
    }
    System.exit(err);
}

From source file:Main.java

public static void main(String[] args) {
    String url = "jdbc:mySubprotocol:myDataSource";

    Connection con;/*from ww w .ja  v  a  2s  .com*/
    Statement stmt;
    try {
        Class.forName("myDriver.ClassName");

    } catch (java.lang.ClassNotFoundException e) {
        System.err.print("ClassNotFoundException: ");
        System.err.println(e.getMessage());
    }

    try {
        con = DriverManager.getConnection(url, "myLogin", "myPassword");

        stmt = con.createStatement();

        Vector dataTypes = getDataTypes(con);

        String tableName;
        String columnName;
        String sqlType;
        String prompt = "Enter the new table name and hit Return: ";
        tableName = getInput(prompt);
        String createTableString = "create table " + tableName + " (";

        String commaAndSpace = ", ";
        boolean firstTime = true;
        while (true) {
            System.out.println("");
            prompt = "Enter a column name " + "(or nothing when finished) \nand hit Return: ";
            columnName = getInput(prompt);
            if (firstTime) {
                if (columnName.length() == 0) {
                    System.out.print("Need at least one column;");
                    System.out.println(" please try again");
                    continue;
                } else {
                    createTableString += columnName + " ";
                    firstTime = false;
                }
            } else if (columnName.length() == 0) {
                break;
            } else {
                createTableString += commaAndSpace + columnName + " ";
            }

            String localTypeName = null;
            String paramString = "";
            while (true) {
                System.out.println("");
                System.out.println("LIST OF TYPES YOU MAY USE:  ");
                boolean firstPrinted = true;
                int length = 0;
                for (int i = 0; i < dataTypes.size(); i++) {
                    DataType dataType = (DataType) dataTypes.get(i);
                    if (!dataType.needsToBeSet()) {
                        if (!firstPrinted)
                            System.out.print(commaAndSpace);
                        else
                            firstPrinted = false;
                        System.out.print(dataType.getSQLType());
                        length += dataType.getSQLType().length();
                        if (length > 50) {
                            System.out.println("");
                            length = 0;
                            firstPrinted = true;
                        }
                    }
                }
                System.out.println("");

                int index;
                prompt = "Enter a column type " + "from the list and hit Return:  ";
                sqlType = getInput(prompt);
                for (index = 0; index < dataTypes.size(); index++) {
                    DataType dataType = (DataType) dataTypes.get(index);
                    if (dataType.getSQLType().equalsIgnoreCase(sqlType) && !dataType.needsToBeSet()) {
                        break;
                    }
                }

                localTypeName = null;
                paramString = "";
                if (index < dataTypes.size()) { // there was a match
                    String params;
                    DataType dataType = (DataType) dataTypes.get(index);
                    params = dataType.getParams();
                    localTypeName = dataType.getLocalType();
                    if (params != null) {
                        prompt = "Enter " + params + ":  ";
                        paramString = "(" + getInput(prompt) + ")";
                    }
                    break;
                } else { // use the name as given
                    prompt = "Are you sure?  " + "Enter 'y' or 'n' and hit Return:  ";
                    String check = getInput(prompt) + " ";
                    check = check.toLowerCase().substring(0, 1);
                    if (check.equals("n"))
                        continue;
                    else {
                        localTypeName = sqlType;
                        break;
                    }
                }
            }

            createTableString += localTypeName + paramString;

        }

        createTableString += ")";
        System.out.println("");
        System.out.print("Your CREATE TABLE statement as ");
        System.out.println("sent to your DBMS:  ");
        System.out.println(createTableString);
        System.out.println("");

        stmt.executeUpdate(createTableString);

        stmt.close();
        con.close();

    } catch (SQLException ex) {
        System.err.println("SQLException: " + ex.getMessage());
    }
}

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  . j  ava  2s  .  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:com.genentech.chemistry.openEye.apps.SDFEStateCalculator.java

/**
 * @param args/*from  www.j a  va  2 s.  com*/
 */
public static void main(String... args) throws IOException { // create command line Options object
    Options options = new Options();
    Option opt = new Option(OPT_INFILE, true,
            "input file oe-supported Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_OUTFILE, true, "output file oe-supported. Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_ESTATE_COUNT, false, "Output the the counts (occurrence) for each E-state atom group."
            + " E-state counts will be output if no output option is specified");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_ESTATE_SUM, false, "Output the sum of the E-state indices for each E-state atom group"
            + " in addition to the output of the" + " E-state atom groups.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_ESTATE_SYMBOL, false, "Output the E-state atom group symbol");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_UNASSIGNED_ATOMS, false,
            "Output atoms in the given molecules that" + " could not be assigned to an E-state atom group");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_UNASSIGNED_COUNT, false, "Output the number of atoms in the given molecules that"
            + " could not be assigned to an E-state atom group");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_ESTATE_INDICE, false,
            "Output the E-state indice of all atoms in the given molecule" + " in one field.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_SMARTS, true, "Description of the group of interest. If specified, the"
            + " E-state indice of atoms matching the SMARTS are output" + " in separated fields.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_PRINT_DETAILS, false, "Output the details of the calculation to stderr");
    opt.setRequired(false);
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();

    if (cmd.hasOption("d")) {
        System.err.println("Start debugger and press return:");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    String inFile = cmd.getOptionValue(OPT_INFILE);
    String outFile = cmd.getOptionValue(OPT_OUTFILE);
    String smarts = cmd.getOptionValue(OPT_SMARTS);
    boolean outputESIndex = cmd.hasOption(OPT_ESTATE_INDICE);
    boolean outputESCount = cmd.hasOption(OPT_ESTATE_COUNT);
    boolean outputESSum = cmd.hasOption(OPT_ESTATE_SUM);
    boolean outputESSymbol = cmd.hasOption(OPT_ESTATE_SYMBOL);
    boolean outputUnkCount = cmd.hasOption(OPT_UNASSIGNED_COUNT);
    boolean outputUnkAtoms = cmd.hasOption(OPT_UNASSIGNED_ATOMS);
    boolean printDetails = cmd.hasOption(OPT_PRINT_DETAILS);
    SDFEStateCalculator calculator = new SDFEStateCalculator(outFile);

    if (!outputESCount && !outputESSum && !outputUnkCount && !outputESSymbol && !outputESIndex
            && (smarts == null || smarts.length() == 0))
        outputESCount = true;

    try {
        calculator.prepare(outputESCount, outputESSum, outputESSymbol, outputUnkCount, outputUnkAtoms,
                outputESIndex, smarts, printDetails);
        calculator.run(inFile);
    } finally {
        calculator.close();
    }
}

From source file:com.cisco.dvbu.ps.deploytool.DeployManagerUtil.java

@SuppressWarnings("rawtypes")
public static void main(String[] args) {

    if (logger.isDebugEnabled()) {
        logger.debug("Entering Main method");
    }//from  www .j  a  v  a 2  s . c o  m

    if (args == null || args.length <= 1) {
        throw new ValidationException("Invalid Arguments");
    }

    initSpring();

    logger.info("--------------------------------------------------------");
    logger.info("------------------ DEPLOYMENT MANAGER ------------------");
    logger.info("--------------------------------------------------------");

    try {
        boolean validMethod = false;
        initAdapter();
        DeployManager deployManager = getDeployManager();
        Class deployManagerClass = deployManager.getClass();
        Method[] methods = deployManagerClass.getMethods();
        // Number of method arguments
        int numInputArgs = args.length - 1;
        for (int i = 0; i < methods.length; i++) {
            String method = methods[i].getName();
            int numMethodArgs = methods[i].getParameterTypes().length;
            if (methods[i].getName().equals(args[0]) && numMethodArgs == numInputArgs) {
                validMethod = true;
                try {

                    if (logger.isInfoEnabled()) {
                        logger.info("Calling Action " + args[0]);
                    }

                    // Determine which parameter is the password parameter when invoking methods.  
                    // The list and parameter number are contained in DeployManager.methodList.
                    int maskParamNum = CommonUtils.getMaskParamNum(args[0], numInputArgs,
                            DeployManager.methodList);

                    String[] methodArgs = new String[args.length - 1];
                    for (int j = 0; j < args.length; j++) {
                        //Skip arg[0] - method name
                        if (j > 0) {
                            methodArgs[j - 1] = args[j];

                            String arg = "";
                            if (args[j] != null) {
                                arg = args[j].trim();
                            }
                            if (logger.isDebugEnabled()) {
                                // This is a special case.  If a method in the DeployManager.methodList is being invoked then it has the potential of 
                                //  containing a password.  If it does that password is blanked out on display with "********".
                                if (maskParamNum != j) {
                                    logger.debug("arg[" + j + "]=" + arg);
                                } else {
                                    if (arg.length() == 0) {
                                        logger.debug("arg[" + j + "]=" + arg);
                                    } else {
                                        logger.debug("arg[" + j + "]=********");
                                    }
                                }
                            }
                        }
                    }

                    // Invoke the action
                    Object returnValue = methods[i].invoke(deployManager, (Object[]) methodArgs);

                    if (logger.isDebugEnabled()) {
                        logger.debug(" Result from invoking method " + args[0] + " " + returnValue);
                    }

                } catch (IllegalArgumentException e) {
                    logger.error("Error while invoking method " + args[0], e);
                    throw new ValidationException(e.getMessage(), e);
                } catch (IllegalAccessException e) {
                    logger.error("Error while invoking method " + args[0], e);
                    throw new ValidationException(e.getMessage(), e);
                } catch (InvocationTargetException e) {
                    logger.error("Error while invoking method " + args[0], e);
                    throw new ValidationException(e.getMessage(), e);
                } catch (Throwable e) {
                    throw new ValidationException(e.getMessage(), e);
                }
            }
        }

        if (!validMethod) {
            logger.error("Passed in method " + args[0]
                    + " does not exist or does not match the number of required arguments.");
            throw new ValidationException("Passed in method  " + args[0]
                    + " does not exist or does not match the number of required arguments.");
        }

    } catch (CompositeException e) {
        logger.error("Error occured while executing ", e);
        throw e;
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Leaving Main method");
    }

}

From source file:com.github.fritaly.graphml4j.samples.GradleDependencies.java

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.out.println(String.format("%s <output-file>", GradleDependencies.class.getSimpleName()));
        System.exit(1);/*w  w w.j a v a  2  s. com*/
    }

    final File file = new File(args[0]);

    System.out.println("Writing GraphML file to " + file.getAbsolutePath() + " ...");

    FileWriter fileWriter = null;
    GraphMLWriter graphWriter = null;
    Reader reader = null;
    LineNumberReader lineReader = null;

    try {
        fileWriter = new FileWriter(file);
        graphWriter = new GraphMLWriter(fileWriter);

        // Customize the rendering of nodes
        final NodeStyle nodeStyle = graphWriter.getNodeStyle();
        nodeStyle.setWidth(250.0f);

        graphWriter.setNodeStyle(nodeStyle);

        // The dependency graph has been generated by Gradle with the
        // command "gradle dependencies". The output of this command has
        // been saved to a text file which will be parsed to rebuild the
        // dependency graph
        reader = new InputStreamReader(GradleDependencies.class.getResourceAsStream("gradle-dependencies.txt"));
        lineReader = new LineNumberReader(reader);

        String line = null;

        // Stack containing the node identifiers per depth inside the
        // dependency graph (the topmost dependency is the first one in the
        // stack)
        final Stack<String> parentIds = new Stack<String>();

        // Open the graph
        graphWriter.graph();

        // Map storing the node identifiers per label
        final Map<String, String> nodeIdsByLabel = new TreeMap<String, String>();

        while ((line = lineReader.readLine()) != null) {
            // Determine the depth of the current dependency inside the
            // graph. The depth can be inferred from the indentation used by
            // Gradle. Each level of depth adds 5 more characters of
            // indentation
            final int initialLength = line.length();

            // Remove the strings used by Gradle to indent dependencies
            line = StringUtils.replace(line, "+--- ", "");
            line = StringUtils.replace(line, "|    ", "");
            line = StringUtils.replace(line, "\\--- ", "");
            line = StringUtils.replace(line, "     ", "");

            // The depth can easily be inferred now
            final int depth = (initialLength - line.length()) / 5;

            // Remove unnecessary node ids
            while (depth <= parentIds.size()) {
                parentIds.pop();
            }

            // Compute a nice label from the dependency (group, artifact,
            // version) tuple
            final String label = computeLabel(line);

            // Has this dependency already been added to the graph ?
            if (!nodeIdsByLabel.containsKey(label)) {
                // No, add the node
                nodeIdsByLabel.put(label, graphWriter.node(label));
            }

            final String nodeId = nodeIdsByLabel.get(label);

            parentIds.push(nodeId);

            if (parentIds.size() > 1) {
                // Generate an edge between the current node and its parent
                graphWriter.edge(parentIds.get(parentIds.size() - 2), nodeId);
            }
        }

        // Close the graph
        graphWriter.closeGraph();

        System.out.println("Done");
    } finally {
        // Calling GraphMLWriter.close() is necessary to dispose the underlying resources
        graphWriter.close();
        fileWriter.close();
        lineReader.close();
        reader.close();
    }
}