Example usage for org.apache.commons.cli ParseException ParseException

List of usage examples for org.apache.commons.cli ParseException ParseException

Introduction

In this page you can find the example usage for org.apache.commons.cli ParseException ParseException.

Prototype

public ParseException(String message) 

Source Link

Document

Construct a new ParseException with the specified detail message.

Usage

From source file:org.dcm4che3.tool.unvscp.UnvSCP.java

private static void configureManualUploading(UnvSCP main, CommandLine cl) throws ParseException {
    if (cl.hasOption("upl-dir")) {
        if (!cl.hasOption("upl-bad-files-dir")) {
            throw new MissingOptionException(rb.getString("missing-upl-bad-files"));
        }//from w  w  w.  j a va2s.  co m

        File uplDir = new File(cl.getOptionValue("upl-dir"));
        if (!uplDir.exists()) {
            throw new ParseException("upl-dir '" + uplDir.getPath()
                    + "' doesn't exist. Create the directory or change option --upl-dir");
        }
        if (!uplDir.isDirectory()) {
            throw new ParseException(
                    "upl-dir '" + uplDir.getPath() + "' is not a directory. Change option --upl-dir");
        }
        if (!uplDir.canRead()) {
            throw new ParseException("Can not read from upl-dir '" + uplDir.getPath()
                    + "'. Check access permissions or change option --upl-dir");
        }
        if (!uplDir.canWrite()) {
            throw new ParseException("Can not write to upl-dir '" + uplDir.getPath()
                    + "'. Check access permissions or change option --upl-dir");
        }

        File uplBadFilesDir = new File(cl.getOptionValue("upl-bad-files-dir"));
        if (!uplBadFilesDir.exists()) {
            throw new ParseException("upl-bad-files-dir '" + uplBadFilesDir.getPath()
                    + "' doesn't exist. Create the directory or change option --upl-bad-files-dir");
        }
        if (!uplBadFilesDir.isDirectory()) {
            throw new ParseException("upl-bad-files-dir '" + uplBadFilesDir.getPath()
                    + "' is not a directory. Change option --upl-bad-files-dir");
        }
        if (!uplBadFilesDir.canRead()) {
            throw new ParseException("Can not read from upl-bad-files-dir '" + uplBadFilesDir.getPath()
                    + "'. Check access permissions or change option --upl-bad-files-dir");
        }
        if (!uplBadFilesDir.canWrite()) {
            throw new ParseException("Can not write to upl-bad-files-dir '" + uplBadFilesDir.getPath()
                    + "'. Check access permissions or change option --upl-bad-files-dir");
        }

        main.uplDir = uplDir;
        main.uplBadFilesDir = uplBadFilesDir;
        try {
            main.uplSleepTime = Integer.parseInt(cl.getOptionValue("upl-sleep-interval", "5"));
        } catch (NumberFormatException nfe) {
            throw new ParseException("\"" + cl.getOptionValue("upl-sleep-interval")
                    + "\" is not a valid integer value for --upl-sleep-interval");
        }

        if (cl.hasOption("source-override")) {
            UnvWebClient.setSourceOverride(cl.getOptionValue("source-override"));
        }

        if (cl.hasOption("store-upl-failures")) {
            final Integer days;
            try {
                days = Integer.parseInt(cl.getOptionValue("store-upl-failures"));
            } catch (NumberFormatException nfe) {
                throw new ParseException("--store-upl-failures can not accept \""
                        + cl.getOptionValue("store-upl-failures") + "\" (only integer values are allowed)");
            }

            FileFilter filter = new FileFilter() {
                private Date theDate = new Date();
                {
                    Calendar c = Calendar.getInstance();
                    c.setTime(theDate);
                    c.add(Calendar.DATE, -1 * Math.abs(days));
                    theDate = c.getTime();
                }

                @Override
                public boolean accept(File file) {
                    return file.isDirectory() || file.lastModified() < this.theDate.getTime();
                }
            };

            doRecursiveCleanUp(uplBadFilesDir, true, filter);
        }
    }
}

From source file:org.dcm4che3.tool.unvscp.UnvSCP.java

private static void configureCompression(UnvSCP main, CommandLine cl) throws ParseException {
    if (cl.hasOption("compression")) {
        try {/*  w  w  w  .ja v  a2s.c om*/
            Integer level = Integer.parseInt(cl.getOptionValue("compression"));
            main.compressionLevel = (level == 0 ? null : level);
        } catch (NumberFormatException nfe) {
            throw new ParseException("--compression can not accept \"" + cl.getOptionValue("compression")
                    + "\" (only integer values are allowed)");
        }
    }
}

From source file:org.dcm4che3.tool.unvscp.UnvSCP.java

private static void configurePushMethod(UnvSCP main, CommandLine cl) throws ParseException {
    String method = null;/*ww  w  . ja va  2  s  . c  o m*/
    if (cl.hasOption("push-http-method") && !"".equals(method = cl.getOptionValue("push-http-method"))) {
        if (HttpPost.METHOD_NAME.equalsIgnoreCase(method)) {
            UnvWebClient.setUploadingFilesHttpMethod(HttpPost.METHOD_NAME);
        } else if (HttpPut.METHOD_NAME.equalsIgnoreCase(method)) {
            UnvWebClient.setUploadingFilesHttpMethod(HttpPut.METHOD_NAME);
        } else {
            throw new ParseException(
                    "--push-http-method accepts only POST|PUT. Method \"" + method + "\" is not supported.");
        }
    } else {
        UnvWebClient.setUploadingFilesHttpMethod(HttpPut.METHOD_NAME);
    }

    LOG.info("Using http method \"{}\" for uploading files", UnvWebClient.getUploadingFilesHttpMethod());
}

From source file:org.dcm4che3.tool.unvscp.UnvSCP.java

private static void configureLog(UnvSCP main, CommandLine cl)
        throws ParseException, FileNotFoundException, IOException {
    File logDir = null;/*from  w  ww .ja  v a2  s  .c  o m*/
    if (cl.hasOption("log-dir")) {
        logDir = new File(cl.getOptionValue("log-dir"));
        if (!logDir.exists()) {
            throw new ParseException("log-dir '" + logDir.getPath()
                    + "' doesn't exist. Create the directory or change option --log-dir");
        }
        if (!logDir.isDirectory()) {
            throw new ParseException(
                    "log-dir '" + logDir.getPath() + "' is not a directory. Change option --log-dir");
        }
        if (!logDir.canRead()) {
            throw new ParseException("Can not read from log-dir '" + logDir.getPath()
                    + "'. Check access permissions or change option --log-dir");
        }
        if (!logDir.canWrite()) {
            throw new ParseException("Can not write to log-dir '" + logDir.getPath()
                    + "'. Check access permissions or change option --log-dir");
        }

        Properties log4jProps = new Properties();
        InputStream configStream = main.getClass().getResourceAsStream("/log4j.properties");
        log4jProps.load(configStream);
        configStream.close();

        log4jProps.setProperty("log4j.rootLogger", "INFO, stdout, file");
        //log4jProps.setProperty("log4j.appender.file", "org.apache.log4j.DailyRollingFileAppender");
        log4jProps.setProperty("log4j.appender.file", "org.apache.log4j.rolling.RollingFileAppender");
        log4jProps.setProperty("log4j.appender.file.File", new File(logDir, "latest.log").getPath());
        log4jProps.setProperty("log4j.appender.file.ImmediateFlush", "true");
        log4jProps.setProperty("log4j.appender.file.Append", "true");
        //log4jProps.setProperty("log4j.appender.file.DatePattern", "'-'yyyy-MM-dd-mm-ss'.log'");
        //log4jProps.setProperty("log4j.appender.file.MaxBackupIndex", "7");
        //log4jProps.setProperty("log4j.appender.file.triggeringPolicy", "org.apache.log4j.rolling.TimeBasedRollingPolicy");
        //log4jProps.setProperty("log4j.appender.file.triggeringPolicy.FileNamePattern", new File(logDir, "%d{yyyy-MM-dd-mm-ss}.log").getPath());
        log4jProps.setProperty("log4j.appender.file.RollingPolicy",
                "org.apache.log4j.rolling.TimeBasedRollingPolicy");
        log4jProps.setProperty("log4j.appender.file.RollingPolicy.FileNamePattern",
                new File(logDir, "%d{yyyy-MM-dd}.log").getPath());
        log4jProps.setProperty("log4j.appender.file.layout", "org.apache.log4j.PatternLayout");
        log4jProps.setProperty("log4j.appender.file.layout.ConversionPattern",
                "%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n");

        LogManager.resetConfiguration();
        PropertyConfigurator.configure(log4jProps);

    } else {
        if (cl.hasOption("store-log")) {
            throw new MissingOptionException(rb.getString("missing-log-dir"));
        }
    }

    if (cl.hasOption("store-log")) {
        final Integer days;
        try {
            days = Integer.parseInt(cl.getOptionValue("store-log"));
        } catch (NumberFormatException nfe) {
            throw new ParseException("--store-log can not accept \"" + cl.getOptionValue("store-log")
                    + "\" (only integer values are allowed)");
        }

        // Temporary Solution for Log clean up
        FileFilter filter = new FileFilter() {
            private Date theDate = new Date();
            {
                Calendar c = Calendar.getInstance();
                c.setTime(theDate);
                c.add(Calendar.DATE, -1 * Math.abs(days));
                theDate = c.getTime();
            }

            @Override
            public boolean accept(File file) {
                return file.isFile() && file.lastModified() < this.theDate.getTime()
                        && file.getName().matches("^\\d\\d\\d\\d-\\d\\d-\\d\\d\\.(?i)(log)$");
            }
        };

        File[] logFilesToRemove = logDir.listFiles(filter);
        if (logFilesToRemove.length > 0) {
            LOG.info("Cleaning up the log dir (There are {} old log files to remove)", logFilesToRemove.length);
        }
        for (File f : logFilesToRemove) {
            if (!f.delete()) {
                LOG.warn(
                        "Can not delete log file {}. The file may be in use or the system settings do not allow this operation",
                        f.getName());
            }
        }
    }
}

From source file:org.deegree.commons.tools.CommandUtils.java

/**
 * Parse a command line argument as integer.
 * //from ww  w .ja  v  a 2 s .  c  o m
 * @param line
 *            the parsed command line
 * @param optName
 *            the option name
 * @param defaultValue
 *            the default value
 * @return the parsed integer argument or <code>defaulValue</code>, if the argument is missing
 * @throws ParseException
 *             if the argument is not a number
 */
public static int getIntOption(CommandLine line, String optName, int defaultValue) throws ParseException {
    String stringValue = line.getOptionValue(optName);
    if (stringValue == null) {
        return defaultValue;
    }
    try {
        return Integer.parseInt(stringValue);
    } catch (NumberFormatException ex) {
        throw new ParseException(optName + " is not a number");
    }
}

From source file:org.deegree.commons.tools.CommandUtils.java

/**
 * Parse a command line argument as float.
 * //from  w ww. ja  va  2  s. com
 * @param line
 *            the parsed command line
 * @param optName
 *            the option name
 * @param defaultValue
 *            the default value
 * @return the parsed float argument or <code>defaulValue</code>, if the argument is missing
 * @throws ParseException
 *             if the argument is not a number
 */
public static float getFloatOption(CommandLine line, String optName, float defaultValue) throws ParseException {
    String stringValue = line.getOptionValue(optName);
    if (stringValue == null) {
        return defaultValue;
    }
    try {
        return Float.parseFloat(stringValue);
    } catch (NumberFormatException ex) {
        throw new ParseException(optName + " is not a number");
    }
}

From source file:org.deegree.coverage.tools.RasterCommandUtils.java

/**
 * Returns an InterpolationType for a string shortcut.
 *
 * @param type//from  w w  w .j  a v  a2 s.c o m
 *            bl or nn
 * @return the interpolation type
 * @throws ParseException
 *             if the type is not supported
 */
public static InterpolationType getInterpolationType(String type) throws ParseException {
    if (type == null) {
        return InterpolationType.NEAREST_NEIGHBOR; // default
    }
    if (type.equalsIgnoreCase("bl")) {
        return InterpolationType.BILINEAR;
    }
    if (type.equalsIgnoreCase("nn")) {
        return InterpolationType.NEAREST_NEIGHBOR;
    }
    throw new ParseException("interpolation type " + type + " is not supported");
}

From source file:org.deegree.coverage.tools.RasterCommandUtils.java

/**
 * Retruns an envelope for given bbox string.
 *
 * @param bbox//from   w w  w  .j  a  va  2 s.c  o  m
 *            comma separated bbox
 * @return the parsed envelope
 * @throws ParseException
 *             if the bbox is invalid
 */
public static Envelope parseBBOX(String bbox) throws ParseException {
    String[] parts = bbox.split(",");
    float[] coords = new float[4];
    try {
        for (int i = 0; i < 4; i++) {
            coords[i] = Float.parseFloat(parts[i]);
        }
    } catch (IndexOutOfBoundsException ex) {
        throw new ParseException("invalid bbox '" + bbox + "' doesn't contain four values");
    } catch (NumberFormatException ex) {
        throw new ParseException("invalid bbox '" + bbox + "' doesn't contain four float values");
    }

    GeometryFactory geomFactory = new GeometryFactory();
    Envelope result = geomFactory.createEnvelope(new double[] { coords[0], coords[1] },
            new double[] { coords[2], coords[3] }, null);

    return result;
}

From source file:org.deegree.coverage.tools.RasterCommandUtils.java

/**
 * Parse a background value which is either a 0xdecafbad hex value or a float value. Float values will be returned
 * as a 4-byte array.//from  w w  w  . j  av a 2  s . c  o m
 *
 * @param background
 * @return a byte array with the parsed value
 * @throws ParseException
 */
public static byte[] parseBackgroundValue(String background) throws ParseException {

    if (background.toLowerCase().startsWith("0x")) {
        byte[] result = null;
        String hexValues = background.substring(2);
        try {
            if (hexValues.length() == 3 || hexValues.length() == 4) {
                result = new byte[hexValues.length()];
                for (int i = 0; i < result.length; i++) {
                    result[i] = parseHexToByte("" + hexValues.charAt(i) + hexValues.charAt(i));
                }
            } else if (hexValues.length() == 6 || hexValues.length() == 8) {
                result = new byte[hexValues.length() / 2];
                for (int i = 0; i < result.length; i++) {
                    result[i] = parseHexToByte("" + hexValues.charAt(i * 2) + hexValues.charAt(i * 2 + 1));
                }
            } else {
                throw new ParseException("not a valid hex color value (like 0xff0, or 0x0ab4f8)");
            }
        } catch (NumberFormatException ex) {
            throw new ParseException("not a valid hex color value (like 0xff0, or 0x0ab4f8)");
        }

        return result;
    }
    ByteBuffer tmp = ByteBuffer.allocate(4);
    tmp.putFloat(Float.parseFloat(background));
    return tmp.array();
}

From source file:org.deegree.coverage.tools.RasterOptionsParser.java

/**
 * Read options from the command line and create a {@link RasterIOOptions} from them.
 * /*from   w  w  w .  j  ava2 s  . c o m*/
 * @param line
 * @return the raster io options parsed from the command line.
 * @throws ParseException
 */
public static RasterIOOptions parseRasterIOOptions(CommandLine line) throws ParseException {
    OriginLocation originLocation = getLocation(line.getOptionValue(OPT_ORIGIN));

    String inputType = line.getOptionValue(OPT_INPUT_TYPE);
    try {
        File f = getRasterLocation(line);
        if (f.isFile()) {
            inputType = FileUtils.getFileExtension(f);
        } else {
            if (inputType == null) {
                LOG.warn("Setting input type to all (*)");
                inputType = "*";
            }
        }
    } catch (IOException e) {
        throw new ParseException("The intput location does not reference a file.");
    }
    String crs = line.getOptionValue(OPT_CRS);
    String noDataValue = line.getOptionValue(OPT_NO_DATA);
    String cacheDir = line.getOptionValue(OPT_RASTER_CACHE_DIR);
    String dataType = line.getOptionValue(OPT_NO_DATA_TYPE);
    DataType noDataType = DataType.fromString(dataType);

    RasterIOOptions options = new RasterIOOptions(originLocation);
    options.add(RasterIOOptions.OPT_FORMAT, inputType);
    options.add(RasterIOOptions.CRS, crs);
    if (noDataType != DataType.UNDEFINED) {
        byte[] noDatas = RasterIOOptions.createNoData(new String[] { noDataValue }, noDataType);
        options.setNoData(noDatas);
    }
    if (cacheDir != null) {
        File cd = new File(cacheDir);
        if (cd.exists() && cd.isDirectory()) {
            options.add(RasterIOOptions.RASTER_CACHE_DIR, cacheDir);
        } else {
            LOG.warn("Using default cache dir: " + RasterCache.DEFAULT_CACHE_DIR
                    + " because given cache directory: " + cacheDir
                    + " does not exist or is a file (and not a directory.)");
        }
    }
    return options;
}