Example usage for java.io IOException IOException

List of usage examples for java.io IOException IOException

Introduction

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

Prototype

public IOException(Throwable cause) 

Source Link

Document

Constructs an IOException with the specified cause and a detail message of (cause==null ?

Usage

From source file:Main.java

public static void valiFileCanRead(File file) throws IOException {
    if (!file.canRead()) {
        throw new IOException("For file '" + file.getName() + "' not read access!");
    }//from   w  w  w.  j  a  va 2 s.  c o m
}

From source file:Main.java

/**
 * Make directories. If directory exists, do nothing.
 *
 * @param context/*from  w w w  .  j  ava2s  .c o  m*/
 * @param path
 *          directory path to create.
 * @throws java.io.IOException
 *           if directory doesn't exist and fail to create.
 */
public static void mkdirs(Context context, String path) throws IOException {
    Resources res = context.getResources();
    File pathFile = new File(path);
    if (!pathFile.exists()) {
        if (!pathFile.mkdirs()) {
            throw new IOException(String.format(FAIL_CREATE_DIRECTORY, pathFile.getAbsolutePath()));
        }
    }
}

From source file:Main.java

private static byte[] encryptHMAC(String data, String secret) throws IOException {
    byte[] bytes = null;
    try {/* ww  w  . jav a2 s  .  c om*/
        SecretKey secretKey = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacMD5");
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        mac.init(secretKey);
        bytes = mac.doFinal(data.getBytes("UTF-8"));
    } catch (GeneralSecurityException gse) {
        String msg = getStringFromException(gse);
        throw new IOException(msg);
    }
    return bytes;
}

From source file:com.cws.esolutions.security.main.PasswordUtility.java

public static void main(final String[] args) {
    final String methodName = PasswordUtility.CNAME + "#main(final String[] args)";

    if (DEBUG) {//  ww w.  j a  v a  2  s . co  m
        DEBUGGER.debug("Value: {}", methodName);
    }

    if (args.length == 0) {
        HelpFormatter usage = new HelpFormatter();
        usage.printHelp(PasswordUtility.CNAME, options, true);

        System.exit(1);
    }

    BufferedReader bReader = null;
    BufferedWriter bWriter = null;

    try {
        // load service config first !!
        SecurityServiceInitializer.initializeService(PasswordUtility.SEC_CONFIG, PasswordUtility.LOG_CONFIG,
                false);

        if (DEBUG) {
            DEBUGGER.debug("Options options: {}", options);

            for (String arg : args) {
                DEBUGGER.debug("Value: {}", arg);
            }
        }

        CommandLineParser parser = new PosixParser();
        CommandLine commandLine = parser.parse(options, args);

        if (DEBUG) {
            DEBUGGER.debug("CommandLineParser parser: {}", parser);
            DEBUGGER.debug("CommandLine commandLine: {}", commandLine);
            DEBUGGER.debug("CommandLine commandLine.getOptions(): {}", (Object[]) commandLine.getOptions());
            DEBUGGER.debug("CommandLine commandLine.getArgList(): {}", commandLine.getArgList());
        }

        final SecurityConfigurationData secConfigData = PasswordUtility.svcBean.getConfigData();
        final SecurityConfig secConfig = secConfigData.getSecurityConfig();
        final PasswordRepositoryConfig repoConfig = secConfigData.getPasswordRepo();
        final SystemConfig systemConfig = secConfigData.getSystemConfig();

        if (DEBUG) {
            DEBUGGER.debug("SecurityConfigurationData secConfig: {}", secConfigData);
            DEBUGGER.debug("SecurityConfig secConfig: {}", secConfig);
            DEBUGGER.debug("RepositoryConfig secConfig: {}", repoConfig);
            DEBUGGER.debug("SystemConfig systemConfig: {}", systemConfig);
        }

        if (commandLine.hasOption("encrypt")) {
            if ((StringUtils.isBlank(repoConfig.getPasswordFile()))
                    || (StringUtils.isBlank(repoConfig.getSaltFile()))) {
                System.err.println("The password/salt files are not configured. Entries will not be stored!");
            }

            File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile());
            File saltFile = FileUtils.getFile(repoConfig.getSaltFile());

            if (DEBUG) {
                DEBUGGER.debug("File passwordFile: {}", passwordFile);
                DEBUGGER.debug("File saltFile: {}", saltFile);
            }

            final String entryName = commandLine.getOptionValue("entry");
            final String username = commandLine.getOptionValue("username");
            final String password = commandLine.getOptionValue("password");
            final String salt = RandomStringUtils.randomAlphanumeric(secConfig.getSaltLength());

            if (DEBUG) {
                DEBUGGER.debug("String entryName: {}", entryName);
                DEBUGGER.debug("String username: {}", username);
                DEBUGGER.debug("String password: {}", password);
                DEBUGGER.debug("String salt: {}", salt);
            }

            final String encodedSalt = PasswordUtils.base64Encode(salt);
            final String encodedUserName = PasswordUtils.base64Encode(username);
            final String encryptedPassword = PasswordUtils.encryptText(password, salt,
                    secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                    secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                    systemConfig.getEncoding());
            final String encodedPassword = PasswordUtils.base64Encode(encryptedPassword);

            if (DEBUG) {
                DEBUGGER.debug("String encodedSalt: {}", encodedSalt);
                DEBUGGER.debug("String encodedUserName: {}", encodedUserName);
                DEBUGGER.debug("String encodedPassword: {}", encodedPassword);
            }

            if (commandLine.hasOption("store")) {
                try {
                    new File(passwordFile.getParent()).mkdirs();
                    new File(saltFile.getParent()).mkdirs();

                    boolean saltFileExists = (saltFile.exists()) ? true : saltFile.createNewFile();

                    if (DEBUG) {
                        DEBUGGER.debug("saltFileExists: {}", saltFileExists);
                    }

                    // write the salt out first
                    if (!(saltFileExists)) {
                        throw new IOException("Unable to create salt file");
                    }

                    boolean passwordFileExists = (passwordFile.exists()) ? true : passwordFile.createNewFile();

                    if (!(passwordFileExists)) {
                        throw new IOException("Unable to create password file");
                    }

                    if (commandLine.hasOption("replace")) {
                        File[] files = new File[] { saltFile, passwordFile };

                        if (DEBUG) {
                            DEBUGGER.debug("File[] files: {}", (Object) files);
                        }

                        for (File file : files) {
                            if (DEBUG) {
                                DEBUGGER.debug("File: {}", file);
                            }

                            String currentLine = null;
                            File tmpFile = new File(FileUtils.getTempDirectory() + "/" + "tmpFile");

                            if (DEBUG) {
                                DEBUGGER.debug("File tmpFile: {}", tmpFile);
                            }

                            bReader = new BufferedReader(new FileReader(file));
                            bWriter = new BufferedWriter(new FileWriter(tmpFile));

                            while ((currentLine = bReader.readLine()) != null) {
                                if (!(StringUtils.equals(currentLine.trim().split(",")[0], entryName))) {
                                    bWriter.write(currentLine + System.getProperty("line.separator"));
                                    bWriter.flush();
                                }
                            }

                            bWriter.close();

                            FileUtils.deleteQuietly(file);
                            FileUtils.copyFile(tmpFile, file);
                            FileUtils.deleteQuietly(tmpFile);
                        }
                    }

                    FileUtils.writeStringToFile(saltFile, entryName + "," + encodedUserName + "," + encodedSalt
                            + System.getProperty("line.separator"), true);
                    FileUtils.writeStringToFile(passwordFile, entryName + "," + encodedUserName + ","
                            + encodedPassword + System.getProperty("line.separator"), true);
                } catch (IOException iox) {
                    ERROR_RECORDER.error(iox.getMessage(), iox);
                }
            }

            System.out.println("Entry Name " + entryName + " stored.");
        }

        if (commandLine.hasOption("decrypt")) {
            String saltEntryName = null;
            String saltEntryValue = null;
            String decryptedPassword = null;
            String passwordEntryName = null;

            if ((StringUtils.isEmpty(commandLine.getOptionValue("entry"))
                    && (StringUtils.isEmpty(commandLine.getOptionValue("username"))))) {
                throw new ParseException("No entry or username was provided to decrypt.");
            }

            if (StringUtils.isEmpty(commandLine.getOptionValue("username"))) {
                throw new ParseException("no entry provided to decrypt");
            }

            String entryName = commandLine.getOptionValue("entry");
            String username = commandLine.getOptionValue("username");

            if (DEBUG) {
                DEBUGGER.debug("String entryName: {}", entryName);
                DEBUGGER.debug("String username: {}", username);
            }

            File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile());
            File saltFile = FileUtils.getFile(repoConfig.getSaltFile());

            if (DEBUG) {
                DEBUGGER.debug("File passwordFile: {}", passwordFile);
                DEBUGGER.debug("File saltFile: {}", saltFile);
            }

            if ((!(saltFile.canRead())) || (!(passwordFile.canRead()))) {
                throw new IOException(
                        "Unable to read configured password/salt file. Please check configuration and/or permissions.");
            }

            for (String lineEntry : FileUtils.readLines(saltFile, systemConfig.getEncoding())) {
                saltEntryName = lineEntry.split(",")[0];

                if (DEBUG) {
                    DEBUGGER.debug("String saltEntryName: {}", saltEntryName);
                }

                if (StringUtils.equals(saltEntryName, entryName)) {
                    saltEntryValue = PasswordUtils.base64Decode(lineEntry.split(",")[2]);

                    break;
                }
            }

            if (StringUtils.isEmpty(saltEntryValue)) {
                throw new SecurityException("No entries were found that matched the provided information");
            }

            for (String lineEntry : FileUtils.readLines(passwordFile, systemConfig.getEncoding())) {
                passwordEntryName = lineEntry.split(",")[0];

                if (DEBUG) {
                    DEBUGGER.debug("String passwordEntryName: {}", passwordEntryName);
                }

                if (StringUtils.equals(passwordEntryName, saltEntryName)) {
                    String decodedPassword = PasswordUtils.base64Decode(lineEntry.split(",")[2]);

                    decryptedPassword = PasswordUtils.decryptText(decodedPassword, saltEntryValue,
                            secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                            secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                            systemConfig.getEncoding());

                    break;
                }
            }

            if (StringUtils.isEmpty(decryptedPassword)) {
                throw new SecurityException("No entries were found that matched the provided information");
            }

            System.out.println(decryptedPassword);
        } else if (commandLine.hasOption("encode")) {
            System.out.println(PasswordUtils.base64Encode((String) commandLine.getArgList().get(0)));
        } else if (commandLine.hasOption("decode")) {
            System.out.println(PasswordUtils.base64Decode((String) commandLine.getArgList().get(0)));
        }
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        System.err.println("An error occurred during processing: " + iox.getMessage());
        System.exit(1);
    } catch (ParseException px) {
        ERROR_RECORDER.error(px.getMessage(), px);

        System.err.println("An error occurred during processing: " + px.getMessage());
        System.exit(1);
    } catch (SecurityException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        System.err.println("An error occurred during processing: " + sx.getMessage());
        System.exit(1);
    } catch (SecurityServiceException ssx) {
        ERROR_RECORDER.error(ssx.getMessage(), ssx);
        System.exit(1);
    } finally {
        try {
            if (bReader != null) {
                bReader.close();
            }

            if (bWriter != null) {
                bReader.close();
            }
        } catch (IOException iox) {
        }
    }

    System.exit(0);
}

From source file:Main.java

/**
 * This will parse an XML stream and create a DOM document.
 *
 * @param is The stream to get the XML from.
 * @return The DOM document.//from w w w .ja  va  2s.co  m
 * @throws IOException It there is an error creating the dom.
 */
public static Document parse(InputStream is) throws IOException {
    try {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        return builder.parse(is);
    } catch (Exception e) {
        IOException thrown = new IOException(e.getMessage());
        throw thrown;
    }
}

From source file:Main.java

public static void mkdirs(File file) throws IOException {
    if (file.isDirectory()) {
        return;/*  ww  w . j  av  a2 s  .co  m*/
    }
    if (!file.mkdirs()) {
        if (file.exists()) {
            throw new IOException("failed to create " + file + " file exists and not a directory");
        }
        throw new IOException();
    }
}

From source file:Main.java

public static Document parse(InputStream input) throws IOException {
    try {/*from   www  .  ja  v  a 2  s .  c o m*/
        return createDocumentBuilder().parse(input);
    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:Main.java

/**
 * Creates a new and empty directory in the default temp directory using the
 * given prefix. This methods uses {@link File#createTempFile} to create a
 * new tmp file, deletes it and creates a directory for it instead.
 * //w ww .  j a v  a2s . c o m
 * @param prefix The prefix string to be used in generating the diretory's
 * name; must be at least three characters long.
 * @return A newly-created empty directory.
 * @throws IOException If no directory could be created.
 */
public static File createTempDir(String prefix) throws IOException {
    String tmpDirStr = System.getProperty("java.io.tmpdir");
    if (tmpDirStr == null) {
        throw new IOException("System property 'java.io.tmpdir' does not specify a tmp dir");
    }

    File tmpDir = new File(tmpDirStr);
    if (!tmpDir.exists()) {
        boolean created = tmpDir.mkdirs();
        if (!created) {
            throw new IOException("Unable to create tmp dir " + tmpDir);
        }
    }

    File resultDir = null;
    int suffix = (int) System.currentTimeMillis();
    int failureCount = 0;
    do {
        resultDir = new File(tmpDir, prefix + suffix % 10000);
        suffix++;
        failureCount++;
    } while (resultDir.exists() && failureCount < 50);

    if (resultDir.exists()) {
        throw new IOException(
                failureCount + " attempts to generate a non-existent directory name failed, giving up");
    }
    boolean created = resultDir.mkdir();
    if (!created) {
        throw new IOException("Failed to create tmp directory");
    }

    return resultDir;
}

From source file:com.admc.jcreole.JCreole.java

/**
 * Run this method with no parameters to see syntax requirements and the
 * available parameters./*ww w  .  ja  v  a 2  s .  co  m*/
 *
 * N.b. do not call this method from a persistent program, because it
 * may call System.exit!
 * <p>
 * Any long-running program should use the lower-level methods in this
 * class instead (or directly use CreoleParser and CreoleScanner
 * instances).
 * </p> <p>
 * This method executes with all JCreole privileges.
 * </p> <p>
 * This method sets up the following htmlExpander mappings (therefore you
 * can reference these in both Creole and boilerplate text).<p>
 * <ul>
 *   <li>sys|*: mappings for Java system properties
 *   <li>isoDateTime
 *   <li>isoDate
 *   <li>pageTitle: Value derived from the specified Creole file name.
 * </ul>
 *
 * @throws IOException for any I/O problem that makes it impossible to
 *         satisfy the request.
 * @throws CreoleParseException
 *         if can not generate output, or if the run generates 0 output.
 *         If the problem is due to input formatting, in most cases you
 *         will get a CreoleParseException, which is a RuntimException, and
 *         CreoleParseException has getters for locations in the source
 *         data (though they will be offset for \r's in the provided
 *         Creole source, if any).
 */
public static void main(String[] sa) throws IOException {
    String bpResPath = null;
    String bpFsPath = null;
    String outPath = null;
    String inPath = null;
    boolean debugs = false;
    boolean troubleshoot = false;
    boolean noBp = false;
    int param = -1;
    try {
        while (++param < sa.length) {
            if (sa[param].equals("-d")) {
                debugs = true;
                continue;
            }
            if (sa[param].equals("-t")) {
                troubleshoot = true;
                continue;
            }
            if (sa[param].equals("-r") && param + 1 < sa.length) {
                if (bpFsPath != null || bpResPath != null || noBp)
                    throw new IllegalArgumentException();
                bpResPath = sa[++param];
                continue;
            }
            if (sa[param].equals("-f") && param + 1 < sa.length) {
                if (bpResPath != null || bpFsPath != null || noBp)
                    throw new IllegalArgumentException();
                bpFsPath = sa[++param];
                continue;
            }
            if (sa[param].equals("-")) {
                if (noBp || bpFsPath != null || bpResPath != null)
                    throw new IllegalArgumentException();
                noBp = true;
                continue;
            }
            if (sa[param].equals("-o") && param + 1 < sa.length) {
                if (outPath != null)
                    throw new IllegalArgumentException();
                outPath = sa[++param];
                continue;
            }
            if (inPath != null)
                throw new IllegalArgumentException();
            inPath = sa[param];
        }
        if (inPath == null)
            throw new IllegalArgumentException();
    } catch (IllegalArgumentException iae) {
        System.err.println(SYNTAX_MSG);
        System.exit(1);
    }
    if (!noBp && bpResPath == null && bpFsPath == null)
        bpResPath = DEFAULT_BP_RES_PATH;
    String rawBoilerPlate = null;
    if (bpResPath != null) {
        if (bpResPath.length() > 0 && bpResPath.charAt(0) == '/')
            // Classloader lookups are ALWAYS relative to CLASSPATH roots,
            // and will abort if you specify a beginning "/".
            bpResPath = bpResPath.substring(1);
        InputStream iStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(bpResPath);
        if (iStream == null)
            throw new IOException("Boilerplate inaccessible: " + bpResPath);
        rawBoilerPlate = IOUtil.toString(iStream);
    } else if (bpFsPath != null) {
        rawBoilerPlate = IOUtil.toString(new File(bpFsPath));
    }
    String creoleResPath = (inPath.length() > 0 && inPath.charAt(0) == '/') ? inPath.substring(1) : inPath;
    // Classloader lookups are ALWAYS relative to CLASSPATH roots,
    // and will abort if you specify a beginning "/".
    InputStream creoleStream = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream(creoleResPath);
    File inFile = (creoleStream == null) ? new File(inPath) : null;
    JCreole jCreole = (rawBoilerPlate == null) ? (new JCreole()) : (new JCreole(rawBoilerPlate));
    if (debugs) {
        jCreole.setInterWikiMapper(new InterWikiMapper() {
            // This InterWikiMapper is just for prototyping.
            // Use wiki name of "nil" to force lookup failure for path.
            // Use wiki page of "nil" to force lookup failure for label.
            public String toPath(String wikiName, String wikiPage) {
                if (wikiName != null && wikiName.equals("nil"))
                    return null;
                return "{WIKI-LINK to: " + wikiName + '|' + wikiPage + '}';
            }

            public String toLabel(String wikiName, String wikiPage) {
                if (wikiPage == null)
                    throw new RuntimeException("Null page name sent to InterWikiMapper");
                if (wikiPage.equals("nil"))
                    return null;
                return "{LABEL for: " + wikiName + '|' + wikiPage + '}';
            }
        });
        Expander creoleExpander = new Expander(Expander.PairedDelims.RECTANGULAR);
        creoleExpander.put("testMacro",
                "\n\n<<prettyPrint>>\n{{{\n" + "!/bin/bash -p\n\ncp /etc/inittab /tmp\n}}}\n");
        jCreole.setCreoleExpander(creoleExpander);
    }
    jCreole.setPrivileges(EnumSet.allOf(JCreolePrivilege.class));
    Expander exp = jCreole.getHtmlExpander();
    Date now = new Date();
    exp.putAll("sys", System.getProperties(), false);
    exp.put("isoDateTime", isoDateTimeFormatter.format(now), false);
    exp.put("isoDate", isoDateFormatter.format(now), false);
    exp.put("pageTitle",
            (inFile == null) ? creoleResPath.replaceFirst("[.][^.]*$", "").replaceFirst(".*[/\\\\.]", "")
                    : inFile.getName().replaceFirst("[.][^.]*$", ""));
    if (troubleshoot) {
        // We don't write any HMTL output here.
        // Goal is just to output diagnostics.
        StringBuilder builder = (creoleStream == null) ? IOUtil.toStringBuilder(inFile)
                : IOUtil.toStringBuilder(creoleStream);
        int newlineCount = 0;
        int lastOffset = -1;
        int offset = builder.indexOf("\n");
        for (; offset >= 0; offset = builder.indexOf("\n", offset + 1)) {
            lastOffset = offset;
            newlineCount++;
        }
        // Accommodate input files with no terminating newline:
        if (builder.length() > lastOffset + 1)
            newlineCount++;
        System.out.println("Input lines:  " + newlineCount);
        Exception lastException = null;
        while (true) {
            try {
                jCreole.parseCreole(builder);
                break;
            } catch (Exception e) {
                lastException = e;
            }
            if (builder.charAt(builder.length() - 1) == '\n')
                builder.setLength(builder.length() - 1);
            offset = builder.lastIndexOf("\n");
            if (offset < 1)
                break;
            newlineCount--;
            builder.setLength(builder.lastIndexOf("\n"));
        }
        System.out.println((lastException == null) ? "Input validates"
                : String.format("Error around input line %d:  %s", newlineCount, lastException.getMessage()));
        return;
    }
    String generatedHtml = (creoleStream == null) ? jCreole.parseCreole(inFile)
            : jCreole.parseCreole(IOUtil.toStringBuilder(creoleStream));
    String html = jCreole.postProcess(generatedHtml, SystemUtils.LINE_SEPARATOR);
    if (outPath == null) {
        System.out.print(html);
    } else {
        FileUtils.writeStringToFile(new File(outPath), html, "UTF-8");
    }
}

From source file:Main.java

/**
 * Saves a given XML document to the given output stream.
 *///from w w w .ja v  a2 s  . c  o m
public static void writeXML(Document document, OutputStream os) throws IOException {
    DOMSource src = new DOMSource(document);
    StreamResult res = new StreamResult(os);
    TransformerFactory tf = TransformerFactory.newInstance();
    try {
        Transformer t = tf.newTransformer();
        t.transform(src, res);
    } catch (TransformerException e) {
        throw new IOException(e.getMessage());
    }
}