Example usage for java.io IOException getCause

List of usage examples for java.io IOException getCause

Introduction

In this page you can find the example usage for java.io IOException getCause.

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:com.google.api.services.samples.youtube.cmdline.youtube_cmdline_topics_sample.Topics.java

/**
 * Method kicks off a search via the Freebase API for a topics id.  It initializes a YouTube
 * object to search for videos on YouTube (Youtube.Search.List) using that topics id to make the
 * search more specific.  The program then prints the names and thumbnails of each of the videos
 * (only first 5 videos).  Please note, user input is taken for both search on Freebase and on
 * YouTube./*from  w w  w  .jav  a  2s .  com*/
 *
 * @param args command line args not used.
*/
public static void main(String[] args) {
    // Read the developer key from youtube.properties
    Properties properties = new Properties();
    try {
        InputStream in = Topics.class.getResourceAsStream("/" + PROPERTIES_FILENAME);
        properties.load(in);

    } catch (IOException e) {
        System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause() + " : "
                + e.getMessage());
        System.exit(1);
    }

    try {
        // Gets a topic id via the Freebase API based on user input.
        String topicsId = getTopicId();
        if (topicsId.length() < 1) {
            System.out.println("No topic id will be applied to your search.");
        }

        /*
         * Get query term from user.  The "search" parameter is just used as output to clarify that
         * we want a "search" term (vs. a "topics" term).
         */
        String queryTerm = getInputQuery("search");

        /*
         * The YouTube object is used to make all API requests.  The last argument is required, but
         * because we don't need anything initialized when the HttpRequest is initialized, we
         * override the interface and provide a no-op function.
         */
        youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpRequestInitializer() {
            public void initialize(HttpRequest request) throws IOException {
            }
        }).setApplicationName("youtube-cmdline-search-sample").build();

        YouTube.Search.List search = youtube.search().list("id,snippet");
        /*
         * It is important to set your developer key from the Google Developer Console for
         * non-authenticated requests (found under the API Access tab at this link:
         * code.google.com/apis/). This is good practice and increases your quota.
         */
        String apiKey = properties.getProperty("youtube.apikey");
        search.setKey(apiKey);
        search.setQ(queryTerm);
        if (topicsId.length() > 0) {
            search.setTopicId(topicsId);
        }

        /*
         * We are only searching for videos (not playlists or channels).  If we were searching for
         * more, we would add them as a string like this: "video,playlist,channel".
         */
        search.setType("video");
        /*
         * This method reduces the info returned to only the fields we need.  It makes things more
         * efficient, because we are transmitting less data.
         */
        search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
        search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
        SearchListResponse searchResponse = search.execute();

        List<SearchResult> searchResultList = searchResponse.getItems();

        if (searchResultList != null) {
            prettyPrint(searchResultList.iterator(), queryTerm, topicsId);
        } else {
            System.out.println("There were no results for your query.");
        }
    } catch (GoogleJsonResponseException e) {
        System.err.println(
                "There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.mycompany.javaapplicaton3.LerArquivo2.java

/**
 * @param args/* www  . j  ava 2 s  .  c o m*/
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    String SAMPLE_PERSON_DATA_FILE_PATH = "C:/Users/lprates/Documents/arquivo2013.xlsx";

    // Input File initialize
    File file = new File(SAMPLE_PERSON_DATA_FILE_PATH);
    InputStream inputStream = new FileInputStream(file);

    // Excel Cell Mapping
    Map<String, String> cellMapping0150 = new HashMap<String, String>();
    cellMapping0150.put("HEADER",
            "REG,COD_PART,NOME,COD_PAIS,CNPJ,CPF,IE,COD_MUN,SUFRAMA,END,NUM,COMPL,BAIRRO,BPE_VIGENCIA_FIN");
    cellMapping0150.put("A", "reg");
    cellMapping0150.put("B", "codPart");
    cellMapping0150.put("C", "nome");
    cellMapping0150.put("D", "codPais");
    cellMapping0150.put("E", "cnpj");
    cellMapping0150.put("F", "cpf");
    cellMapping0150.put("G", "ie");
    cellMapping0150.put("H", "codMun");
    cellMapping0150.put("I", "suframa");
    cellMapping0150.put("J", "end");
    cellMapping0150.put("K", "num");
    cellMapping0150.put("L", "compl");
    cellMapping0150.put("M", "bairro");
    cellMapping0150.put("N", "bpeVigenciaFin");

    // Excel Cell Mapping
    Map<String, String> cellMapping0200 = new HashMap<String, String>();
    cellMapping0200.put("HEADER",
            "REG,COD_ITEM,DESCR_ITEM,COD_BARRA,COD_ANT_ITEM,UNID_INV,TIPO_ITEM,COD_NCM,EX_IPI,COD_GEN,COD_LST,ALIQ_ICMS");
    cellMapping0200.put("A", "reg");
    cellMapping0200.put("B", "codItem");
    cellMapping0200.put("C", "descrItem");
    cellMapping0200.put("D", "codBarra");
    cellMapping0200.put("E", "codAntItem");
    cellMapping0200.put("F", "unidInv");
    cellMapping0200.put("G", "tipoItem");
    cellMapping0200.put("H", "codNcm");
    cellMapping0200.put("I", "exIpi");
    cellMapping0200.put("J", "codGen");
    cellMapping0200.put("K", "codLst");
    cellMapping0200.put("L", "aliqIcms");

    // Excel Cell Mapping
    Map<String, String> cellMappingC100_C170 = new HashMap<String, String>();
    cellMappingC100_C170.put("A", "campo1");
    cellMappingC100_C170.put("B", "campo2");
    cellMappingC100_C170.put("C", "campo3");
    cellMappingC100_C170.put("D", "campo4");
    cellMappingC100_C170.put("E", "campo5");
    cellMappingC100_C170.put("F", "campo6");
    cellMappingC100_C170.put("G", "campo7");
    cellMappingC100_C170.put("H", "campo8");
    cellMappingC100_C170.put("I", "campo9");
    cellMappingC100_C170.put("J", "campo10");
    cellMappingC100_C170.put("K", "campo11");
    cellMappingC100_C170.put("L", "campo12");
    cellMappingC100_C170.put("M", "campo13");
    cellMappingC100_C170.put("N", "campo14");
    cellMappingC100_C170.put("O", "campo15");
    cellMappingC100_C170.put("P", "campo16");
    cellMappingC100_C170.put("Q", "campo17");
    cellMappingC100_C170.put("R", "campo18");
    cellMappingC100_C170.put("S", "campo19");
    cellMappingC100_C170.put("T", "campo20");
    cellMappingC100_C170.put("U", "campo21");
    cellMappingC100_C170.put("V", "campo22");
    cellMappingC100_C170.put("W", "campo23");
    cellMappingC100_C170.put("X", "campo24");
    cellMappingC100_C170.put("Y", "campo25");
    cellMappingC100_C170.put("Z", "campo26");

    cellMappingC100_C170.put("AA", "campo27");
    cellMappingC100_C170.put("AB", "campo28");
    cellMappingC100_C170.put("AC", "campo29");
    cellMappingC100_C170.put("AD", "campo30");
    cellMappingC100_C170.put("AE", "campo31");
    cellMappingC100_C170.put("AF", "campo32");
    cellMappingC100_C170.put("AG", "campo33");
    cellMappingC100_C170.put("AH", "campo34");
    cellMappingC100_C170.put("AI", "campo35");
    cellMappingC100_C170.put("AJ", "campo36");
    cellMappingC100_C170.put("AK", "campo37");
    cellMappingC100_C170.put("AL", "campo38");
    cellMappingC100_C170.put("AM", "campo39");
    cellMappingC100_C170.put("AN", "campo40");
    cellMappingC100_C170.put("AO", "campo41");
    cellMappingC100_C170.put("AP", "campo42");
    cellMappingC100_C170.put("AQ", "campo43");
    cellMappingC100_C170.put("AR", "campo44");
    cellMappingC100_C170.put("AS", "campo45");
    cellMappingC100_C170.put("AT", "campo46");
    cellMappingC100_C170.put("AU", "campo47");
    cellMappingC100_C170.put("AV", "campo48");
    cellMappingC100_C170.put("AW", "campo49");
    cellMappingC100_C170.put("AX", "campo50");
    cellMappingC100_C170.put("AY", "campo51");
    cellMappingC100_C170.put("AZ", "campo52");

    cellMappingC100_C170.put("BA", "campo53");
    cellMappingC100_C170.put("BB", "campo54");
    cellMappingC100_C170.put("BC", "campo55");
    cellMappingC100_C170.put("BD", "campo56");
    cellMappingC100_C170.put("BE", "campo57");
    cellMappingC100_C170.put("BF", "campo58");
    cellMappingC100_C170.put("BG", "campo59");
    cellMappingC100_C170.put("BH", "campo60");
    cellMappingC100_C170.put("BI", "campo61");
    cellMappingC100_C170.put("BJ", "campo62");
    cellMappingC100_C170.put("BK", "campo63");
    cellMappingC100_C170.put("BL", "campo64");
    cellMappingC100_C170.put("BM", "campo65");
    cellMappingC100_C170.put("BN", "campo66");
    cellMappingC100_C170.put("BO", "campo67");
    cellMappingC100_C170.put("BP", "campo68");
    cellMappingC100_C170.put("BQ", "campo69");
    cellMappingC100_C170.put("BR", "campo70");
    cellMappingC100_C170.put("BS", "campo71");

    // The package open is instantaneous, as it should be.
    OPCPackage pkg = null;
    try {

        ExcelWorkSheetHandler<Reg0150> workSheetHandler = new ExcelWorkSheetHandler<Reg0150>(Reg0150.class,
                cellMapping0150);

        pkg = OPCPackage.open(inputStream);

        ExcelSheetCallback sheetCallback = new ExcelSheetCallback() {
            private int sheetNumber = 0;

            public void startSheet(int sheetNum, String sheetName) {
                this.sheetNumber = sheetNum;
                System.out.println("Started processing sheet number=" + sheetNumber + " and Sheet Name is '"
                        + sheetName + "'");
            }

            @Override
            public void endSheet() {
                System.out.println("Processing completed for sheet number=" + sheetNumber);
            }

            public void startSheet(int sheetNum) {
                System.out.println("Started processing sheet number=" + sheetNum);
            }

        };

        /*** Leitura Registro 0150 ***/

        System.out.println("Constructor: pkg, workSheetHandler, sheetCallback");
        ExcelReader example1 = new ExcelReader(pkg, workSheetHandler, sheetCallback);
        example1.process("0150");

        if (workSheetHandler.getValueList().isEmpty()) {
            // No data present
            LOG.error("sHandler.getValueList() is empty");
        } else {

            LOG.info(workSheetHandler.getValueList().size()
                    + " no. of records read from given excel worksheet successfully.");

            // Displaying data ead from Excel file
            displayPersonList(workSheetHandler.getValueList());
        }

        /*** Leitura Registro 0200 ***/

        ExcelWorkSheetHandler<Reg0200> workSheetHandler0200 = new ExcelWorkSheetHandler<Reg0200>(Reg0200.class,
                cellMapping0200);

        ExcelReader example2 = new ExcelReader(pkg, workSheetHandler0200, null);
        example2.process("0200");

        if (workSheetHandler0200.getValueList().isEmpty()) {

            LOG.error("sHandler.getValueList() is empty");
        } else {

            LOG.info(workSheetHandler0200.getValueList().size()
                    + " no. of records read from given excel worksheet successfully.");

            displayPersonList0200(workSheetHandler0200.getValueList());
        }

        /*** Leitura Registro C100 e C170 ***/

        ExcelWorkSheetHandler<RegC100_C170> workSheetHandlerC100_C170 = new ExcelWorkSheetHandler<RegC100_C170>(
                RegC100_C170.class, cellMappingC100_C170, 4);
        workSheetHandlerC100_C170.setVerifiyHeader(false);

        ExcelReader example3 = new ExcelReader(pkg, workSheetHandlerC100_C170, null);
        example3.process("201302");

        if (workSheetHandlerC100_C170.getValueList().isEmpty()) {

            LOG.error("sHandler.getValueList() is empty");
        } else {

            LOG.info(workSheetHandlerC100_C170.getValueList().size()
                    + " no. of records read from given excel worksheet successfully.");

            displayPersonListC100_C170(workSheetHandlerC100_C170.getValueList());
        }

    } catch (RuntimeException are) {
        LOG.error(are.getMessage(), are.getCause());
    } catch (InvalidFormatException ife) {
        LOG.error(ife.getMessage(), ife.getCause());
    } catch (IOException ioe) {
        LOG.error(ioe.getMessage(), ioe.getCause());
    } finally {
        IOUtils.closeQuietly(inputStream);
        try {
            if (null != pkg) {
                pkg.close();
            }
        } catch (IOException e) {
            // just ignore IO exception
        }
    }
}

From source file:org.asoem.greyfish.cli.GreyfishCLIApplication.java

public static void main(final String[] args) {

    final Optional<String> commitHash = getCommitHash(GreyfishCLIApplication.class);
    if (commitHash.isPresent()) {
        logger.debug("Git Commit Hash for current Jar: %s", commitHash.get());
    }//from ww w .  jav  a2 s . c  o  m

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                closer.close();
            } catch (IOException e) {
                logger.warn("Exception while closing resources", e);
            }
        }
    });

    try {
        final OptionSet optionSet = optionParser.parse(args);

        if (optionSet.has(helpOptionSpec)) {
            printHelp();
            System.exit(0);
        }

        final Module commandLineModule = createCommandLineModule(optionSet);
        final RandomGenerator randomGenerator = RandomGenerators
                .threadLocalGenerator(new Supplier<RandomGenerator>() {
                    @Override
                    public RandomGenerator get() {
                        return new Well19937c();
                    }
                });
        final EventBus eventBus = new EventBus(new SubscriberExceptionHandler() {
            @Override
            public void handleException(final Throwable exception, final SubscriberExceptionContext context) {
                context.getEventBus()
                        .post(new AssertionError("The EventBus could not dispatch event: "
                                + context.getSubscriber() + " to " + context.getSubscriberMethod(),
                                exception.getCause()));
            }
        });
        final Module coreModule = new CoreModule(randomGenerator, eventBus);

        final Injector injector = Guice.createInjector(coreModule, commandLineModule);

        final ExperimentExecutionService experimentExecutionService = injector
                .getInstance(ExperimentExecutionService.class);

        if (!optionSet.has(quietOptionSpec)) {
            final ExperimentMonitorService monitorService = new ExperimentMonitorService(System.out, eventBus);

            monitorService.addListener(new Service.Listener() {
                @Override
                public void starting() {
                }

                @Override
                public void running() {
                }

                @Override
                public void stopping(final Service.State from) {
                }

                @Override
                public void terminated(final Service.State from) {
                }

                @Override
                public void failed(final Service.State from, final Throwable failure) {
                    logger.error("Monitor service failed", failure);
                }
            }, MoreExecutors.sameThreadExecutor());

            experimentExecutionService.addListener(new MonitorServiceController(monitorService),
                    MoreExecutors.sameThreadExecutor());
        }

        // start getSimulation
        experimentExecutionService.startAsync();

        // stop getSimulation on shutdown request (^C)
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                if (experimentExecutionService.isRunning()) {
                    experimentExecutionService.stopAsync().awaitTerminated();
                }
            }
        });

        try {
            experimentExecutionService.awaitTerminated();
        } catch (IllegalStateException e) {
            exitWithErrorMessage("Simulation execution failed", e);
        }
    } catch (OptionException e) {
        exitWithErrorMessage("Failed parsing options: ", e, true);
    } catch (Throwable e) {
        exitWithErrorMessage(String.format(
                "Exception during simulation execution: %s\n" + "Check log file for a stack trace.",
                e.getCause() != null ? e.getCause().getMessage() : e.getMessage()), e);
    }

    System.exit(0);
}

From source file:com.zimbra.cs.zclient.ZMailboxUtil.java

public static void main(String args[]) throws IOException, ServiceException {
    CliUtil.toolSetup();/*from  w ww.  ja va  2 s  .com*/
    SoapTransport.setDefaultUserAgent("zmmailbox", BuildInfo.VERSION);

    ZMailboxUtil pu = new ZMailboxUtil();
    CommandLineParser parser = new GnuParser();
    Options options = new Options();
    options.addOption("a", "admin", true, "admin account name to auth as");
    options.addOption("z", "zadmin", false,
            "use zimbra admin name/password from localconfig for admin/password");
    options.addOption("h", "help", false, "display usage");
    options.addOption("f", "file", true, "use file as input stream");
    options.addOption("u", "url", true, "http[s]://host[:port] of server to connect to");
    options.addOption("r", "protocol", true, "protocol to use for request/response [soap11, soap12, json]");
    options.addOption("m", "mailbox", true, "mailbox to open");
    options.addOption(null, "auth", true, "account name to auth as; defaults to -m unless -A is used");
    options.addOption("A", "admin-priv", false, "execute requests with admin privileges");
    options.addOption("p", "password", true, "auth password");
    options.addOption("P", "passfile", true, "filename with password in it");
    options.addOption("t", "timeout", true, "timeout (in seconds)");
    options.addOption("v", "verbose", false, "verbose mode");
    options.addOption("d", "debug", false, "debug mode");
    options.addOption(SoapCLI.OPT_AUTHTOKEN);
    options.addOption(SoapCLI.OPT_AUTHTOKENFILE);

    CommandLine cl = null;
    boolean err = false;

    try {
        cl = parser.parse(options, args, true);
    } catch (ParseException pe) {
        stderr.println("error: " + pe.getMessage());
        err = true;
    }

    if (err || cl.hasOption('h')) {
        pu.usage();
    }

    try {
        boolean isAdmin = false;
        pu.setVerbose(cl.hasOption('v'));
        if (cl.hasOption('a')) {
            pu.setAdminAccountName(cl.getOptionValue('a'));
            pu.setUrl(DEFAULT_ADMIN_URL, true);
            isAdmin = true;
        }
        if (cl.hasOption('z')) {
            pu.setAdminAccountName(LC.zimbra_ldap_user.value());
            pu.setPassword(LC.zimbra_ldap_password.value());
            pu.setUrl(DEFAULT_ADMIN_URL, true);
            isAdmin = true;
        }

        if (cl.hasOption(SoapCLI.O_AUTHTOKEN) && cl.hasOption(SoapCLI.O_AUTHTOKENFILE))
            pu.usage();
        if (cl.hasOption(SoapCLI.O_AUTHTOKEN)) {
            pu.setAdminAuthToken(ZAuthToken.fromJSONString(cl.getOptionValue(SoapCLI.O_AUTHTOKEN)));
            pu.setUrl(DEFAULT_ADMIN_URL, true);
            isAdmin = true;
        }
        if (cl.hasOption(SoapCLI.O_AUTHTOKENFILE)) {
            String authToken = StringUtil.readSingleLineFromFile(cl.getOptionValue(SoapCLI.O_AUTHTOKENFILE));
            pu.setAdminAuthToken(ZAuthToken.fromJSONString(authToken));
            pu.setUrl(DEFAULT_ADMIN_URL, true);
            isAdmin = true;
        }

        String authAccount, targetAccount;
        if (cl.hasOption('m')) {
            if (!cl.hasOption('p') && !cl.hasOption('P') && !cl.hasOption('y') && !cl.hasOption('Y')
                    && !cl.hasOption('z')) {
                throw ZClientException.CLIENT_ERROR("-m requires one of the -p/-P/-y/-Y/-z options", null);
            }
            targetAccount = cl.getOptionValue('m');
        } else {
            targetAccount = null;
        }
        if ((cl.hasOption("A") || cl.hasOption("auth")) && !cl.hasOption('m')) {
            throw ZClientException.CLIENT_ERROR("-A/--auth requires -m", null);
        }
        if (cl.hasOption("A")) {
            if (!isAdmin) {
                throw ZClientException.CLIENT_ERROR("-A requires admin auth", null);
            }
            if (cl.hasOption("auth")) {
                throw ZClientException.CLIENT_ERROR("-A cannot be combined with --auth", null);
            }
            authAccount = null;
        } else if (cl.hasOption("auth")) {
            authAccount = cl.getOptionValue("auth");
        } else {
            // default case
            authAccount = targetAccount;
        }
        if (!StringUtil.isNullOrEmpty(authAccount))
            pu.setAuthAccountName(authAccount);
        if (!StringUtil.isNullOrEmpty(targetAccount))
            pu.setTargetAccountName(targetAccount);

        if (cl.hasOption('u'))
            pu.setUrl(cl.getOptionValue('u'), isAdmin);
        if (cl.hasOption('p'))
            pu.setPassword(cl.getOptionValue('p'));
        if (cl.hasOption('P')) {
            pu.setPassword(StringUtil.readSingleLineFromFile(cl.getOptionValue('P')));
        }
        if (cl.hasOption('d'))
            pu.setDebug(true);

        if (cl.hasOption('t'))
            pu.setTimeout(cl.getOptionValue('t'));

        args = cl.getArgs();

        pu.setInteractive(args.length < 1);

        pu.initMailbox();
        if (args.length < 1) {
            InputStream is = null;
            if (cl.hasOption('f')) {
                is = new FileInputStream(cl.getOptionValue('f'));
            } else {
                if (LC.command_line_editing_enabled.booleanValue()) {
                    try {
                        CliUtil.enableCommandLineEditing(LC.zimbra_home.value() + "/.zmmailbox_history");
                    } catch (IOException e) {
                        System.err.println("Command line editing will be disabled: " + e);
                        if (pu.mGlobalVerbose) {
                            e.printStackTrace(System.err);
                        }
                    }
                }
                is = System.in; // This has to happen last because JLine modifies System.in.
            }
            pu.interactive(new BufferedReader(new InputStreamReader(is, "UTF-8")));
        } else {
            pu.execute(args);
        }
    } catch (ServiceException e) {
        Throwable cause = e.getCause();
        stderr.println("ERROR: " + e.getCode() + " (" + e.getMessage() + ")" + (cause == null ? ""
                : " (cause: " + cause.getClass().getName() + " " + cause.getMessage() + ")"));
        if (pu.mGlobalVerbose)
            e.printStackTrace(stderr);
        System.exit(2);
    }
}

From source file:hu.bme.mit.sette.run.Run.java

public static void main(String[] args) {
    LOG.debug("main() called");

    // parse properties
    Properties prop = new Properties();
    InputStream is = null;//w  ww .j  a v a  2  s.c  o  m

    try {
        is = new FileInputStream(SETTE_PROPERTIES);
        prop.load(is);
    } catch (IOException e) {
        System.err.println("Parsing  " + SETTE_PROPERTIES + " has failed");
        e.printStackTrace();
        System.exit(1);
    } finally {
        IOUtils.closeQuietly(is);
    }

    String[] basedirs = StringUtils.split(prop.getProperty("basedir"), '|');
    String snippetDir = prop.getProperty("snippet-dir");
    String snippetProject = prop.getProperty("snippet-project");
    String catgPath = prop.getProperty("catg");
    String catgVersionFile = prop.getProperty("catg-version-file");
    String jPETPath = prop.getProperty("jpet");
    String jPETDefaultBuildXml = prop.getProperty("jpet-default-build.xml");
    String jPETVersionFile = prop.getProperty("jpet-version-file");
    String spfPath = prop.getProperty("spf");
    String spfDefaultBuildXml = prop.getProperty("spf-default-build.xml");
    String spfVersionFile = prop.getProperty("spf-version-file");
    String outputDir = prop.getProperty("output-dir");

    Validate.notEmpty(basedirs, "At least one basedir must be specified in " + SETTE_PROPERTIES);
    Validate.notBlank(snippetDir, "The property snippet-dir must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(snippetProject, "The property snippet-project must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(catgPath, "The property catg must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(jPETPath, "The property jpet must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(spfPath, "The property spf must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(outputDir, "The property output-dir must be set in " + SETTE_PROPERTIES);

    String basedir = null;
    for (String bd : basedirs) {
        bd = StringUtils.trimToEmpty(bd);

        if (bd.startsWith("~")) {
            // Linux home
            bd = System.getProperty("user.home") + bd.substring(1);
        }

        FileValidator v = new FileValidator(new File(bd));
        v.type(FileType.DIRECTORY);

        if (v.isValid()) {
            basedir = bd;
            break;
        }
    }

    if (basedir == null) {
        System.err.println("basedir = " + Arrays.toString(basedirs));
        System.err.println("ERROR: No valid basedir was found, please check " + SETTE_PROPERTIES);
        System.exit(2);
    }

    BASEDIR = new File(basedir);
    SNIPPET_DIR = new File(basedir, snippetDir);
    SNIPPET_PROJECT = snippetProject;
    OUTPUT_DIR = new File(basedir, outputDir);

    try {
        String catgVersion = readToolVersion(new File(BASEDIR, catgVersionFile));
        if (catgVersion != null) {
            new CatgTool(new File(BASEDIR, catgPath), catgVersion);
        }

        String jPetVersion = readToolVersion(new File(BASEDIR, jPETVersionFile));
        if (jPetVersion != null) {
            new JPetTool(new File(BASEDIR, jPETPath), new File(BASEDIR, jPETDefaultBuildXml), jPetVersion);
        }

        String spfVersion = readToolVersion(new File(BASEDIR, spfVersionFile));
        if (spfVersion != null) {
            new SpfTool(new File(BASEDIR, spfPath), new File(BASEDIR, spfDefaultBuildXml), spfVersion);
        }

        // TODO stuff
        stuff(args);
    } catch (Exception e) {
        System.err.println(ExceptionUtils.getStackTrace(e));

        ValidatorException vex = (ValidatorException) e;

        for (ValidationException v : vex.getValidator().getAllExceptions()) {
            v.printStackTrace();
        }

        // System.exit(0);

        e.printStackTrace();
        System.err.println("==========");
        e.printStackTrace();

        if (e instanceof ValidatorException) {
            System.err.println("Details:");
            System.err.println(((ValidatorException) e).getFullMessage());
        } else if (e.getCause() instanceof ValidatorException) {
            System.err.println("Details:");
            System.err.println(((ValidatorException) e.getCause()).getFullMessage());
        }
    }
}

From source file:com.zimbra.cs.account.ProvUtil.java

public static void main(String args[]) throws IOException, ServiceException {
    CliUtil.setCliSoapHttpTransportTimeout();
    ZimbraLog.toolSetupLog4jConsole("INFO", true, false); // send all logs to stderr
    SocketFactories.registerProtocols();

    SoapTransport.setDefaultUserAgent("zmprov", BuildInfo.VERSION);

    ProvUtil pu = new ProvUtil();
    CommandLineParser parser = new PosixParser();
    Options options = new Options();

    options.addOption("h", "help", false, "display usage");
    options.addOption("f", "file", true, "use file as input stream");
    options.addOption("s", "server", true, "host[:port] of server to connect to");
    options.addOption("l", "ldap", false, "provision via LDAP");
    options.addOption("L", "logpropertyfile", true, "log4j property file");
    options.addOption("a", "account", true, "account name (not used with --ldap)");
    options.addOption("p", "password", true, "password for account");
    options.addOption("P", "passfile", true, "filename with password in it");
    options.addOption("z", "zadmin", false,
            "use zimbra admin name/password from localconfig for account/password");
    options.addOption("v", "verbose", false, "verbose mode");
    options.addOption("d", "debug", false, "debug mode (SOAP request and response payload)");
    options.addOption("D", "debughigh", false, "debug mode (SOAP req/resp payload and http headers)");
    options.addOption("m", "master", false, "use LDAP master (has to be used with --ldap)");
    options.addOption("t", "temp", false,
            "write binary values to files in temporary directory specified in localconfig key zmprov_tmp_directory");
    options.addOption("r", "replace", false, "allow replacement of multi-valued attr value");
    options.addOption("fd", "forcedisplay", false, "force display attr value");
    options.addOption(SoapCLI.OPT_AUTHTOKEN);
    options.addOption(SoapCLI.OPT_AUTHTOKENFILE);

    CommandLine cl = null;/*from w w w  .  j av  a  2 s .c  om*/
    boolean err = false;

    try {
        cl = parser.parse(options, args, true);
    } catch (ParseException pe) {
        printError("error: " + pe.getMessage());
        err = true;
    }

    if (err || cl.hasOption('h')) {
        pu.usage();
    }

    if (cl.hasOption('l') && cl.hasOption('s')) {
        printError("error: cannot specify both -l and -s at the same time");
        System.exit(2);
    }

    pu.setVerbose(cl.hasOption('v'));
    if (cl.hasOption('l')) {
        pu.setUseLdap(true, cl.hasOption('m'));
    }

    if (cl.hasOption('L')) {
        if (cl.hasOption('l')) {
            ZimbraLog.toolSetupLog4j("INFO", cl.getOptionValue('L'));
        } else {
            printError("error: cannot specify -L when -l is not specified");
            System.exit(2);
        }
    }

    if (cl.hasOption('z')) {
        pu.setAccount(LC.zimbra_ldap_user.value());
        pu.setPassword(LC.zimbra_ldap_password.value());
    }

    if (cl.hasOption(SoapCLI.O_AUTHTOKEN) && cl.hasOption(SoapCLI.O_AUTHTOKENFILE)) {
        printError("error: cannot specify " + SoapCLI.O_AUTHTOKEN + " when " + SoapCLI.O_AUTHTOKENFILE
                + " is specified");
        System.exit(2);
    }
    if (cl.hasOption(SoapCLI.O_AUTHTOKEN)) {
        ZAuthToken zat = ZAuthToken.fromJSONString(cl.getOptionValue(SoapCLI.O_AUTHTOKEN));
        pu.setAuthToken(zat);
    }
    if (cl.hasOption(SoapCLI.O_AUTHTOKENFILE)) {
        String authToken = StringUtil.readSingleLineFromFile(cl.getOptionValue(SoapCLI.O_AUTHTOKENFILE));
        ZAuthToken zat = ZAuthToken.fromJSONString(authToken);
        pu.setAuthToken(zat);
    }

    if (cl.hasOption('s')) {
        pu.setServer(cl.getOptionValue('s'));
    }
    if (cl.hasOption('a')) {
        pu.setAccount(cl.getOptionValue('a'));
    }
    if (cl.hasOption('p')) {
        pu.setPassword(cl.getOptionValue('p'));
    }
    if (cl.hasOption('P')) {
        pu.setPassword(StringUtil.readSingleLineFromFile(cl.getOptionValue('P')));
    }

    if (cl.hasOption('d') && cl.hasOption('D')) {
        printError("error: cannot specify both -d and -D at the same time");
        System.exit(2);
    }
    if (cl.hasOption('D')) {
        pu.setDebug(SoapDebugLevel.high);
    } else if (cl.hasOption('d')) {
        pu.setDebug(SoapDebugLevel.normal);
    }

    if (!pu.useLdap() && cl.hasOption('m')) {
        printError("error: cannot specify -m when -l is not specified");
        System.exit(2);
    }

    if (cl.hasOption('t')) {
        pu.setOutputBinaryToFile(true);
    }

    if (cl.hasOption('r')) {
        pu.setAllowMultiValuedAttrReplacement(true);
    }

    if (cl.hasOption("fd")) {
        pu.setForceDisplayAttrValue(true);
    }

    args = recombineDecapitatedAttrs(cl.getArgs(), options, args);

    try {
        if (args.length < 1) {
            pu.initProvisioning();
            InputStream is = null;
            if (cl.hasOption('f')) {
                pu.setBatchMode(true);
                is = new FileInputStream(cl.getOptionValue('f'));
            } else {
                if (LC.command_line_editing_enabled.booleanValue()) {
                    try {
                        CliUtil.enableCommandLineEditing(LC.zimbra_home.value() + "/.zmprov_history");
                    } catch (IOException e) {
                        errConsole.println("Command line editing will be disabled: " + e);
                        if (pu.verboseMode) {
                            e.printStackTrace(errConsole);
                        }
                    }
                }

                // This has to happen last because JLine modifies System.in.
                is = System.in;
            }
            pu.interactive(new BufferedReader(new InputStreamReader(is, "UTF-8")));
        } else {
            Command cmd = pu.lookupCommand(args[0]);
            if (cmd == null) {
                pu.usage();
            }
            if (cmd.isDeprecated()) {
                pu.deprecated();
            }
            if (pu.forceLdapButDontRequireUseLdapOption(cmd)) {
                pu.setUseLdap(true, false);
            }

            if (pu.needProvisioningInstance(cmd)) {
                pu.initProvisioning();
            }

            try {
                if (!pu.execute(args)) {
                    pu.usage();
                }
            } catch (ArgException e) {
                pu.usage();
            }
        }
    } catch (ServiceException e) {
        Throwable cause = e.getCause();
        String errText = "ERROR: " + e.getCode() + " (" + e.getMessage() + ")" + (cause == null ? ""
                : " (cause: " + cause.getClass().getName() + " " + cause.getMessage() + ")");

        printError(errText);

        if (pu.verboseMode) {
            e.printStackTrace(errConsole);
        }
        System.exit(2);
    }
}

From source file:liveplugin.toolwindow.addplugin.git.jetbrains.plugins.github.util.GithubSslSupport.java

public static boolean isCertificateException(IOException e) {
    return e.getCause() instanceof ValidatorException;
}

From source file:org.apache.tika.parser.pdf.OCR2XHTML.java

/**
 * Converts the given PDF document (and related metadata) to a stream
 * of XHTML SAX events sent to the given content handler.
 *
 * @param document PDF document/*from   w  ww.  ja  v  a2  s  . co m*/
 * @param handler  SAX content handler
 * @param metadata PDF metadata
 * @throws SAXException  if the content handler fails to process SAX events
 * @throws TikaException if there was an exception outside of per page processing
 */
public static void process(PDDocument document, ContentHandler handler, ParseContext context, Metadata metadata,
        PDFParserConfig config) throws SAXException, TikaException {
    OCR2XHTML ocr2XHTML = null;
    try {
        ocr2XHTML = new OCR2XHTML(document, handler, context, metadata, config);
        ocr2XHTML.writeText(document, new Writer() {
            @Override
            public void write(char[] cbuf, int off, int len) {
            }

            @Override
            public void flush() {
            }

            @Override
            public void close() {
            }
        });
    } catch (IOException e) {
        if (e.getCause() instanceof SAXException) {
            throw (SAXException) e.getCause();
        } else {
            throw new TikaException("Unable to extract PDF content", e);
        }
    }
    if (ocr2XHTML.exceptions.size() > 0) {
        //throw the first
        throw new TikaException("Unable to extract all PDF content", ocr2XHTML.exceptions.get(0));
    }
}

From source file:com.amazonaws.hbase.kinesis.utils.HBaseUtils.java

/**
 * Helper method to insert a list of records
 * /*w  w w .  j  av  a2s . c  o  m*/
 * @param tableName - table to insert
  * @param dnsId - Amazon EMR master node public DNS
 * @param hbaseRestPort -  HBase Rest port
 * @param batch - list of records to insert into HBase
 */
public static void addRecords(String tableName, String dnsId, int hbaseRestPort, List<Put> batch) {
    RemoteHTable table = null;
    try {
        table = new RemoteHTable(new Client(new Cluster().add(dnsId, hbaseRestPort)), tableName);
        table.put(batch);
        LOG.info("inserted " + batch.size() + " records to table " + tableName + " ok.");
        table.flushCommits();
    } catch (IOException e) {
        LOG.error(e, e.getCause());
        if (table != null)
            try {
                table.close();
            } catch (IOException e1) {
                LOG.error(e, e.getCause());
            }
    }
}

From source file:StringUtils.java

/**
 * Decode a string using Base64 encoding.
 *
 * @param str// w ww  .j  a va  2  s . c o  m
 * @return String
 */
public static String decodeString(String str) {
    sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
    try {
        return new String(dec.decodeBuffer(str));
    } catch (IOException io) {
        throw new RuntimeException(io.getMessage(), io.getCause());
    }
}