Example usage for java.io File toPath

List of usage examples for java.io File toPath

Introduction

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

Prototype

public Path toPath() 

Source Link

Document

Returns a Path java.nio.file.Path object constructed from this abstract path.

Usage

From source file:at.nonblocking.cliwix.cli.CliwixCliClient.java

private static void doExport(String cliwixServerUrl, Options options) {
    waitForServerReady(cliwixServerUrl, options);

    String exportFolder = options.getExportFolder();
    if (exportFolder == null) {
        console.printlnError("Error: Property export.folder is required.");
        console.exit(EXIT_STATUS_FAIL);//from   www. j a va  2 s .  co m
        return;
    }

    File outputDir = null;
    try {
        outputDir = new File(exportFolder);
        outputDir.mkdirs();
    } catch (Exception e) {
        console.printlnError("Error: Invalid export folder: " + exportFolder);
        console.exit(EXIT_STATUS_FAIL);
        return;
    }

    JSONObject exportSettings = options.getExportSettings();

    JSONObject json = postJson(cliwixServerUrl, "/services/exports", exportSettings);
    JSONObject exportResult = (JSONObject) json.get("exportResult");
    String exportId = (String) exportResult.get("exportId");

    console.println("Export started. Id: " + exportId);

    boolean success = waitForImportExport(true, exportId, cliwixServerUrl, options);

    if (success) {
        console.println("Export succeeded.");

        String path = "/services/exports/" + exportId + "/zip";
        if (debug)
            console.println("Sending GET request: " + path);
        Response zipResponse = getHandler.get(cliwixServerUrl, path, cookieManager);
        handleError(zipResponse);

        File tempFile = null;
        try {
            tempFile = File.createTempFile("export", ".zip");
        } catch (IOException e) {
            if (debug)
                console.printStacktrace(e);
            console.printlnError("Error: Unable to create temporary zip file");
            console.exit(EXIT_STATUS_FAIL);
            return;
        }
        long fileLength = zipResponse.getContentLength();
        ProgressCallback progressCallback = new ProgressCallbackConsoleImpl(console);

        try (InputStream inputStream = zipResponse.getResponseStream();
                OutputStream outputStream = new FileOutputStream(tempFile)) {

            byte[] buffer = new byte[BaseHttpHandler.CHUNK_SIZE];
            long transferred = 0;
            int len = -1;
            while ((len = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, len);
                transferred = transferred + len;
                progressCallback.bytesTransferred(transferred, fileLength);
            }

            progressCallback.bytesTransferred(fileLength, fileLength);

        } catch (IOException e) {
            if (debug)
                console.printStacktrace(e);
            console.printlnError("Error: " + e.getMessage());
            console.exit(EXIT_STATUS_FAIL);
        } finally {
            zipResponse.disconnect();
        }

        if (options.isExtractZip()) {
            try {
                ZipFile zip = new ZipFile(tempFile);
                zip.extractAll(outputDir.getAbsolutePath());
            } catch (ZipException e) {
                if (debug)
                    console.printStacktrace(e);
                console.printlnError("Error: Corrupt ZIP file");
                console.exit(EXIT_STATUS_FAIL);
            } finally {
                tempFile.delete();
            }
        } else {
            File targetFile = new File(outputDir, "export_" + exportId + ".zip");
            try (FileInputStream fis = new FileInputStream(tempFile)) {
                Files.copy(fis, targetFile.toPath());
            } catch (IOException e) {
                if (debug)
                    console.printStacktrace(e);
                console.printlnError("Error: " + e.getMessage());
                console.exit(EXIT_STATUS_FAIL);
            } finally {
                tempFile.delete();
            }
        }

        console.println("Export data written to: " + outputDir.getAbsolutePath());

    } else {
        console.printlnError("Export failed!");

        String path = "/services/exports/" + exportId + "/report";
        if (debug)
            console.println("Sending GET request: " + path);
        Response reportResponse = getHandler.get(cliwixServerUrl, path, cookieManager);
        handleError(reportResponse);

        File reportFile = new File(outputDir, "export-report.html");

        try (OutputStream outputStream = new FileOutputStream(reportFile)) {
            outputStream.write(reportResponse.getResponseAsString().getBytes("UTF-8"));
            console.println("Error report written to: " + reportFile.getAbsolutePath());

        } catch (IOException e) {
            if (debug)
                console.printStacktrace(e);
            console.printlnError("Error: No report found");
        } finally {
            reportResponse.disconnect();
        }
    }

    if (options.isExportDeleteOnServerAfterTransfer()) {
        Response deleteResponse = deleteHandler.delete(cliwixServerUrl, "/services/exports/" + exportId,
                cookieManager);
        if (deleteResponse.getStatusCode() == 200) {
            console.println("Successfully deleted export folder on server.");
        } else {
            console.printlnError("Failed to delete export folder on server!");
        }
    }

    if (!success) {
        console.exit(EXIT_STATUS_FAIL);
    }
}

From source file:com.googlecode.fascinator.storage.jclouds.BlobStoreClient.java

/**
 * Establish a connection to the BlobStore, then return the instantiated
 * BlobStore client used to connect.//from   w w  w  .j  av  a 2 s  . co m
 *
 * @return BlobStore: The client used to connect to the API
 * @throws StorageException
 *             if there was an error
 */
private static BlobStore blobStoreConnect() throws StorageException {
    if (blobStore != null && connectCount < 100) {
        return blobStore;
    }
    connectCount = 0;
    ContextBuilder contextBuilder = ContextBuilder.newBuilder(provider);
    // If we're using filesystem, set local directory to write objects to
    if ("filesystem".equals(provider)) {
        if (supportsUserMetadataSetting != null) {
            supportsUserMetadata = supportsUserMetadataSetting;
        } else {
            File storageDir = new File(fileSystemLocation);
            if (!storageDir.exists()) {
                try {
                    FileUtils.forceMkdir(storageDir);
                    // Java doesn't support extended attributes in some file
                    // systems like FAT32 and HFS. As JClouds use them to
                    // store
                    // user metadata we'll need to store them differently on
                    // these file systems.
                    if (!Files.getFileStore(storageDir.toPath())
                            .supportsFileAttributeView(UserDefinedFileAttributeView.class)) {
                        supportsUserMetadata = false;
                    }
                } catch (IOException e) {
                    throw new StorageException("Failed to create storage directory", e);
                }
            }
        }
        Properties properties = new Properties();
        properties.setProperty(FilesystemConstants.PROPERTY_BASEDIR, fileSystemLocation);
        contextBuilder.overrides(properties);
    } else if ("gridfs".equals(provider)) {
        Properties properties = new Properties();
        properties.setProperty(Constants.PROPERTY_ENDPOINT, gridFsConnectionString);
        contextBuilder.overrides(properties);

    }
    context = contextBuilder.credentials(identity, credential)
            .endpoint("https://keystone.rc.nectar.org.au:5000/v2.0").buildView(BlobStoreContext.class);

    blobStore = context.getBlobStore();

    Location loc = null;
    if (StringUtils.isNotEmpty(location)) {
        for (Location assignableLoc : blobStore.listAssignableLocations()) {
            if (assignableLoc.getId().equalsIgnoreCase(location)) {
                loc = assignableLoc;
                break;
            }

        }
        if (loc == null) {
            throw new StorageException(location + " location not found in Blobstore");
        }
    }
    blobStore.createContainerInLocation(loc, containerName);

    return blobStore;
}

From source file:nextflow.fs.dx.DxFileSystemProvider.java

/**
 * Find out the default DnaNexus project id in the specified configuration file
 *
 * @return The string value//from w w  w. j a  va  2s. c om
 */
static String getContextIdByConfig(File config) {

    StringBuilder buffer = new StringBuilder();
    try {
        BufferedReader reader = Files.newBufferedReader(config.toPath(), Charset.defaultCharset());
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line).append('\n');
        }

        JsonNode object = DxJson.parseJson(buffer.toString());
        return object.get("DX_PROJECT_CONTEXT_ID").textValue();
    } catch (FileNotFoundException e) {
        throw new IllegalStateException(String.format(
                "Unable to load DnaNexus configuration file: %s -- cannot configure file system", config), e);
    } catch (IOException e) {
        throw new IllegalStateException("Unable to configure DnaNexus file system", e);
    }
}

From source file:com.streamsets.pipeline.stage.BaseHiveIT.java

/**
 * Start all required mini clusters.//w w w.j ava 2 s. c o  m
 */
@BeforeClass
public static void setUpClass() throws Exception {
    // Conf dir
    new File(confDir).mkdirs();

    // HDFS
    File minidfsDir = new File("target/minidfs").getAbsoluteFile();
    if (!minidfsDir.exists()) {
        Assert.assertTrue(minidfsDir.mkdirs());
    }
    Set<PosixFilePermission> set = new HashSet<>();
    set.add(PosixFilePermission.OWNER_EXECUTE);
    set.add(PosixFilePermission.OWNER_READ);
    set.add(PosixFilePermission.OWNER_WRITE);
    set.add(PosixFilePermission.OTHERS_READ);
    java.nio.file.Files.setPosixFilePermissions(minidfsDir.toPath(), set);
    System.setProperty(MiniDFSCluster.PROP_TEST_BUILD_DATA, minidfsDir.getPath());
    final Configuration conf = new HdfsConfiguration();
    conf.set("hadoop.proxyuser." + System.getProperty("user.name") + ".hosts", "*");
    conf.set("hadoop.proxyuser." + System.getProperty("user.name") + ".groups", "*");
    miniDFS = new MiniDFSCluster.Builder(conf).build();
    miniDFS.getFileSystem().setPermission(new Path("/"), FsPermission.createImmutable((short) 0777));
    writeConfiguration(miniDFS.getConfiguration(0), confDir + "/core-site.xml");
    writeConfiguration(miniDFS.getConfiguration(0), confDir + "/hdfs-site.xml");
    writeConfiguration(miniDFS.getConfiguration(0), confDir + "/mapred-site.xml");
    writeConfiguration(miniDFS.getConfiguration(0), confDir + "/yarn-site.xml");

    // Configuration for both HMS and HS2
    final HiveConf hiveConf = new HiveConf(miniDFS.getConfiguration(0), HiveConf.class);
    hiveConf.set(HiveConf.ConfVars.METASTORECONNECTURLKEY.varname,
            "jdbc:derby:;databaseName=target/metastore_db;create=true");
    hiveConf.set(HiveConf.ConfVars.METASTOREURIS.varname,
            Utils.format("thrift://{}:{}", HOSTNAME, METASTORE_PORT));
    hiveConf.set(HiveConf.ConfVars.HIVE_SERVER2_THRIFT_BIND_HOST.varname, "localhost");
    hiveConf.setInt(HiveConf.ConfVars.HIVE_SERVER2_THRIFT_PORT.varname, HIVE_SERVER_PORT);

    // Hive metastore
    Callable<Void> metastoreService = new Callable<Void>() {
        public Void call() throws Exception {
            try {
                HiveMetaStore.startMetaStore(METASTORE_PORT, ShimLoader.getHadoopThriftAuthBridge(), hiveConf);
                while (true)
                    ;
            } catch (Throwable e) {
                throw new Exception("Error starting metastore", e);
            }
        }
    };
    hiveMetastoreExecutor.submit(metastoreService);
    NetworkUtils.waitForStartUp(HOSTNAME, METASTORE_PORT, MINICLUSTER_BOOT_RETRY, MINICLUSTER_BOOT_SLEEP);

    // HiveServer 2
    hiveServer2 = new HiveServer2();
    hiveServer2.init(hiveConf);
    hiveServer2.start();
    writeConfiguration(hiveServer2.getHiveConf(), confDir + "/hive-site.xml");
    NetworkUtils.waitForStartUp(HOSTNAME, HIVE_SERVER_PORT, MINICLUSTER_BOOT_RETRY, MINICLUSTER_BOOT_SLEEP);

    // JDBC Connection to Hive
    Class.forName(HIVE_JDBC_DRIVER);
    hiveConnection = HiveMetastoreUtil.getHiveConnection(getHiveJdbcUrl(),
            HadoopSecurityUtil.getLoginUser(conf));
    hiveQueryExecutor = new HiveQueryExecutor(hiveConnection);
}

From source file:io.werval.cli.DamnSmallDevShell.java

private static void newCommand(String name, CommandLine cmd) throws IOException {
    File baseDir = new File(name);
    File ctrlDir = new File(baseDir,
            "src" + separator + "main" + separator + "java" + separator + "controllers");
    File rsrcDir = new File(baseDir, "src" + separator + "main" + separator + "resources");
    Files.createDirectories(ctrlDir.toPath());
    Files.createDirectories(rsrcDir.toPath());

    // Generate secret
    String conf = "\napp.secret = " + CryptoInstance.newRandomSecret256BitsHex() + "\n";
    Files.write(new File(rsrcDir, "application.conf").toPath(), conf.getBytes(UTF_8));

    // Generate controller
    String controller = "package controllers;\n\n" + "import io.werval.api.outcomes.Outcome;\n\n"
            + "public class Application {\n\n" + "    public Outcome index() {\n"
            + "        return new io.werval.controllers.Welcome().welcome();\n" + "    }\n\n" + "}\n";
    Files.write(new File(ctrlDir, "Application.java").toPath(), controller.getBytes(UTF_8));

    // Generate routes
    String routes = "\nGET / controllers.Application.index\n";
    Files.write(new File(rsrcDir, "routes.conf").toPath(), routes.getBytes(UTF_8));

    // Generate Gradle build file
    String gradle = "buildscript {\n" + "  repositories { jcenter() }\n"
            + "    dependencies { classpath 'io.werval:io.werval.gradle:" + VERSION + "' }\n" + "}\n"
            + "apply plugin: 'io.werval.application'\n" + "\n" + "dependencies {\n" + "\n"
            + "    // Add application compile dependencies here\n" + "\n"
            + "    runtime 'ch.qos.logback:logback-classic:1.1.2'\n"
            + "    // Add application runtime dependencies here\n" + "\n"
            + "    // Add application test dependencies here\n" + "\n" + "}\n" + "";
    Files.write(new File(baseDir, "build.gradle.example").toPath(), gradle.getBytes(UTF_8));

    // Generate Maven POM file
    String pom = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            + "<project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n"
            + "         xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
            + "         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n"
            + "    <modelVersion>4.0.0</modelVersion>\n" + "\n" + "    <groupId>" + name + "</groupId>\n"
            + "    <artifactId>" + name + "</artifactId>\n" + "    <version>" + VERSION + "</version>\n" + "\n"
            + "    <properties>\n"
            + "        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n"
            + "        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n"
            + "    </properties>\n" + "\n" + "    <repositories>\n" + "        <repository>\n"
            + "            <id>jcenter</id>\n" + "            <url>https://jcenter.bintray.com/</url>\n"
            + "        </repository>\n" + "    </repositories>\n" + "\n" + "    <dependencies>\n" + "\n"
            + "        <dependency>\n" + "            <groupId>io.werval</groupId>\n"
            + "            <artifactId>io.werval.api</artifactId>\n" + "            <version>" + VERSION
            + "</version>\n" + "        </dependency>\n"
            + "        <!-- Add application compile dependencies here -->\n" + "\n" + "        <dependency>\n"
            + "            <groupId>io.werval</groupId>\n"
            + "            <artifactId>io.werval.server.bootstrap</artifactId>\n" + "            <version>"
            + VERSION + "</version>\n" + "            <scope>runtime</scope>\n" + "        </dependency>\n"
            + "        <dependency>\n" + "            <groupId>ch.qos.logback</groupId>\n"
            + "            <artifactId>logback-classic</artifactId>\n"
            + "            <version>1.1.2</version>\n" + "            <scope>runtime</scope>\n"
            + "        </dependency>\n" + "        <!-- Add application runtime dependencies here -->\n" + "\n"
            + "        <dependency>\n" + "            <groupId>io.werval</groupId>\n"
            + "            <artifactId>io.werval.test</artifactId>\n" + "            <version>" + VERSION
            + "</version>\n" + "            <scope>test</scope>\n" + "        </dependency>\n"
            + "        <!-- Add application test dependencies here -->\n" + "\n" + "    </dependencies>\n"
            + "\n" + "    <pluginRepositories>\n" + "        <pluginRepository>\n"
            + "            <id>jcenter</id>\n" + "            <url>https://jcenter.bintray.com/</url>\n"
            + "        </pluginRepository>\n" + "    </pluginRepositories>\n" + "\n" + "    <build>\n"
            + "        <plugins>\n" + "            <plugin>\n"
            + "                <artifactId>maven-compiler-plugin</artifactId>\n"
            + "                <version>3.1</version>\n" + "                <configuration>\n"
            + "                    <source>1.8</source>\n" + "                    <target>1.8</target>\n"
            + "                </configuration>\n" + "            </plugin>\n" + "            <plugin>\n"
            + "                <groupId>io.werval</groupId>\n"
            + "                <artifactId>io.werval.maven</artifactId>\n" + "                <version>"
            + VERSION + "</version>\n" + "            </plugin>\n" + "            <plugin>\n"
            + "                <groupId>org.codehaus.mojo</groupId>\n"
            + "                <artifactId>appassembler-maven-plugin</artifactId>\n"
            + "                <version>1.8</version>\n" + "                <executions>\n"
            + "                    <execution>\n" + "                        <id>app-assembly</id>\n"
            + "                        <!-- Sample Packaging -->\n"
            + "                        <phase>package</phase>\n"
            + "                        <goals><goal>assemble</goal></goals>\n"
            + "                        <configuration>\n"
            + "                            <repositoryName>lib</repositoryName>\n"
            + "                            <repositoryLayout>flat</repositoryLayout>\n"
            + "                            <programs>\n" + "                                <program>\n"
            + "                                    <id>werval-sample-maven</id>\n"
            + "                                    <mainClass>io.werval.server.bootstrap.Main</mainClass>\n"
            + "                                </program>\n" + "                            </programs>\n"
            + "                        </configuration>\n" + "                    </execution>\n"
            + "                </executions>\n" + "            </plugin>\n" + "        </plugins>\n"
            + "    </build>\n" + "\n" + "</project>\n";
    Files.write(new File(baseDir, "pom.xml.example").toPath(), pom.getBytes(UTF_8));

    // Generate .gitignore
    String gitignore = "target\nbuild\n.devshell.lock\nbuild.gradle.example\npom.xml.example\n.gradle\n";
    Files.write(new File(baseDir, ".gitignore").toPath(), gitignore.getBytes(UTF_8));

    // Inform user
    System.out.println("New Werval Application generated in '" + baseDir.getAbsolutePath() + "'.");
}

From source file:com.ebixio.virtmus.stats.StatsLogger.java

/**
 * Check for new versions of VirtMus./*from w ww.j a  v a 2s.c  om*/
 * @param installId The random ID identifying this install.
 * @param prevVersion The previous version of VirtMus installed.
 * @param statsEnabled Set to true if the user is participating in stats collection.
 */
private static void checkForNewVersion(long installId, String prevVersion, UploadStats statsEnabled) {
    final String urlStr = pref.get(Options.OptCheckVersionUrl, CHECK_VERSION);

    // Catch redirects.
    HttpRedirectStrategy httpRedirect = new HttpRedirectStrategy() {
        @Override
        public void handlePermanentRedirect(HttpRequest request, HttpResponse response,
                HttpUriRequest redirect) {
            if (!Utils.isNullOrEmpty(newUrl) && !newUrl.equals(urlStr)) {
                pref.put(Options.OptCheckVersionUrl, newUrl);
            }
        }
    };

    // TODO: Use http://wiki.fasterxml.com/JacksonHome to avoid warnings?
    String postData = new JSONStringer().object().key("version").value(MainApp.VERSION)
            /* installId MUST be sent as string since JS on the server
            side only has 64-bit float values and can't represent
            all long int values, leading to truncation of some digits
            since the JS float mantisa has only 53 bits (not 64).
            See: http://www.2ality.com/2012/07/large-integers.html
            */
            .key("installId").value(String.valueOf(installId)).key("prevVersion").value(prevVersion)
            .key("statsEnabled").value(statsEnabled.name()).endObject().toString();

    try {
        CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(httpRedirect).build();

        HttpPost post = new HttpPost(urlStr);
        addHttpHeaders(post);
        StringEntity entity = new StringEntity(postData, ContentType.APPLICATION_JSON);
        post.setEntity(entity);
        HttpResponse response = client.execute(post);

        int status = response.getStatusLine().getStatusCode();
        if (status == HttpStatus.SC_OK) { // 200
            if (statsEnabled == UploadStats.No) {
                // If the user doesn't want to participate, he probably doesn't
                // want to be checking for new releases either, so disable it.
                pref.putBoolean(Options.OptCheckVersion, false);
            }

            // This is used to notify the user that a newer version is available
            HttpEntity rspEntity = response.getEntity();
            if (rspEntity != null && statsEnabled != UploadStats.No) {
                File f = File.createTempFile("VersionPost", "html");
                f.deleteOnExit();
                Files.copy(rspEntity.getContent(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);
                if (f.length() > 0) {
                    URL rspUrl = Utilities.toURI(f).toURL();
                    HtmlBrowser.URLDisplayer.getDefault().showURL(rspUrl);
                }
            }
        } else {
            Log.log(Level.INFO, "CheckVersion result: {0}", status);
        }

    } catch (MalformedURLException ex) {
        Log.log(ex);
    } catch (IOException ex) {
        Log.log(ex);
    }
}

From source file:it.uniud.ailab.dcore.launchers.Launcher.java

/**
 * Load the document trying different charsets. The charset tried, are, in
 * order:/*from   w w w  .  jav  a2  s .c  o  m*/
 * <ul>
 * <li>UTF-16;</li>
 * <li>UTF-8;</li>
 * <li>US-ASCII.</li>
 * </ul>
 *
 * @param filePath the path of the document
 * @return the text of the document
 * @throws IOException if the charset is not supported
 */
private static String loadDocument(File filePath) throws IOException {

    String document = "";

    IOException exception = null;
    // try different charsets. if none is recognized, throw the
    // exception detected when reading.
    try {
        document = String.join(" ", Files.readAllLines(filePath.toPath(), StandardCharsets.UTF_8));

    } catch (java.nio.charset.MalformedInputException e) {
        exception = e;
    }

    if (exception != null) {
        try {
            exception = null;
            document = String.join(" ", Files.readAllLines(filePath.toPath(), StandardCharsets.UTF_16));

        } catch (java.nio.charset.MalformedInputException e) {
            exception = e;
        }
    }

    if (exception != null) {
        try {
            exception = null;
            document = String.join(" ", Files.readAllLines(filePath.toPath(), StandardCharsets.US_ASCII));

        } catch (java.nio.charset.MalformedInputException e) {
            exception = e;
        }
    }

    // no charset has been recognized
    if (exception != null) {
        throw exception;
    }
    return document;
}

From source file:com.streamsets.pipeline.stage.destination.hdfs.metadataexecutor.HdfsMetadataExecutorIT.java

@BeforeClass
public static void setUpClass() throws Exception {
    // Conf dir//from w ww .  j  av a2s  .  co m
    new File(confDir).mkdirs();

    //setting some dummy kerberos settings to be able to test a mis-setting
    System.setProperty("java.security.krb5.realm", "foo");
    System.setProperty("java.security.krb5.kdc", "localhost:0");

    File minidfsDir = new File(baseDir, "minidfs").getAbsoluteFile();
    if (!minidfsDir.exists()) {
        Assert.assertTrue(minidfsDir.mkdirs());
    }
    Set<PosixFilePermission> set = new HashSet<>();
    set.add(PosixFilePermission.OWNER_EXECUTE);
    set.add(PosixFilePermission.OWNER_READ);
    set.add(PosixFilePermission.OWNER_WRITE);
    set.add(PosixFilePermission.OTHERS_READ);
    java.nio.file.Files.setPosixFilePermissions(minidfsDir.toPath(), set);
    System.setProperty(MiniDFSCluster.PROP_TEST_BUILD_DATA, minidfsDir.getPath());
    Configuration conf = new HdfsConfiguration();
    conf.set("hadoop.proxyuser." + System.getProperty("user.name") + ".hosts", "*");
    conf.set("hadoop.proxyuser." + System.getProperty("user.name") + ".groups", "*");
    conf.set("dfs.namenode.acls.enabled", "true");
    fooUgi = UserGroupInformation.createUserForTesting("foo", new String[] { "all" });
    EditLogFileOutputStream.setShouldSkipFsyncForTesting(true);
    FileSystem.closeAll();
    miniDFS = new MiniDFSCluster.Builder(conf).build();
    miniDFS.getFileSystem().setPermission(new Path("/"), FsPermission.createImmutable((short) 0777));
    fs = miniDFS.getFileSystem();
    writeConfiguration(miniDFS.getConfiguration(0), confDir + "core-site.xml");
    writeConfiguration(miniDFS.getConfiguration(0), confDir + "hdfs-site.xml");
}

From source file:com.att.aro.core.util.Util.java

/**
 * <pre>/*from  w w w  . j a  va  2  s . c  om*/
 * makes a folder in the targetLibFolder location.
 * Mac {home}/AROLibrary
 * Win
 *
 * if it fails it will create AROLibrary the current application execution folder
 *
 * @param filename
 * @param currentRelativePath
 * @param targetLibFolder
 * @return
 */
public static String makeLibFolder(String filename, File libFolder) {
    String targetLibFolder = libFolder.toPath().toString();
    Path currentRelativePath = Paths.get("");
    try {
        Files.createDirectories(libFolder.toPath());
    } catch (IOException ioe1) {
        // if no write access rights to the path folder then extract the lib to a default local folder
        targetLibFolder = currentRelativePath.toAbsolutePath().toString() + File.separator + "AROLibrary";
        try {
            Files.createDirectories(libFolder.toPath());
        } catch (IOException ioe2) {
            return null;
        }
    }
    return targetLibFolder;
}

From source file:codes.thischwa.c5c.UserObjectProxy.java

/**
 * Instantiates all user-objects.//from  w  w w.j a  v  a2  s.  c o m
 *
 * @param servletContext
 *            the servlet context
 * @throws RuntimeException
 *             is thrown, if one of the required user-objects couldn't be instantiated
 */
static void init(ServletContext servletContext) throws RuntimeException {
    UserObjectProxy.servletContext = servletContext;

    // try to instantiate to FileCapacity
    String className = PropertiesLoader.getFileCapabilityImpl();
    if (StringUtils.isNullOrEmpty(className))
        throw new RuntimeException(
                "Empty FilemanagerCapability implementation class name! Depending property must be set!");
    try {
        Class<?> clazz = Class.forName(className);
        fileCapability = (FilemanagerCapability) clazz.newInstance();
        logger.info("FilemanagerCapability initialized to {}", className);
    } catch (Throwable e) {
        String msg = String.format("FilemanagerCapability implementation [%s] couldn't be instantiated.",
                className);
        logger.error(msg);
        throw new RuntimeException(msg, e);
    }

    // try to initialize the MessageResolver
    className = PropertiesLoader.getMessageResolverImpl();
    if (StringUtils.isNullOrEmpty(className))
        throw new RuntimeException(
                "Empty MessageResolver implementation class name! Depending property must be set!");
    try {
        Class<?> clazz = Class.forName(className);
        messageHolder = (MessageResolver) clazz.newInstance();
        messageHolder.setServletContext(servletContext);
        logger.info("MessageResolver initialized to {}", className);
    } catch (Throwable e) {
        String msg = String.format("MessageResolver implementation [%s] couldn't be instantiated.", className);
        logger.error(msg);
        throw new RuntimeException(msg, e);
    }

    // try to initialize the BackendPathBuilder
    className = PropertiesLoader.getUserPathBuilderImpl();
    if (StringUtils.isNullOrEmpty(className))
        throw new RuntimeException(
                "Empty BackendPathBuilder implementation class name! Depending property must be set!");
    try {
        Class<?> clazz = Class.forName(className);
        userPathBuilder = (BackendPathBuilder) clazz.newInstance();
        logger.info("BackendPathBuilder initialized to {}", className);
    } catch (Throwable e) {
        String msg = "BackendPathBuilder couldn't be initialized.";
        logger.error(msg);
        throw new RuntimeException(msg, e);
    }

    // try to initialize the FilemanagerConfigBuilder
    className = PropertiesLoader.getFilemanagerConfigImpl();
    if (StringUtils.isNullOrEmpty(className))
        throw new RuntimeException(
                "Empty FilemanagerConfigBuilder implementation class name! Depending property must be set!");
    try {
        Class<?> clazz = Class.forName(className);
        configBuilder = (FilemanagerConfigBuilder) clazz.newInstance();
        logger.info("FilemanagerConfigBuilder initialized to {}", className);
    } catch (Throwable e) {
        String msg = "FilemanagerConfigBuilder couldn't be initialized.";
        logger.error(msg);
        throw new RuntimeException(msg, e);
    }

    // try to instantiate the IconResolver object
    className = PropertiesLoader.getIconResolverImpl();
    if (StringUtils.isNullOrEmptyOrBlank(className))
        throw new RuntimeException(
                "Empty IconResolver implementation class name! Depending property must be set!");
    try {
        Class<?> clazz = Class.forName(className);
        iconResolver = (IconResolver) clazz.newInstance();
        iconResolver.initContext(servletContext);
        logger.info("IconResolver initialized to {}", className);
    } catch (Throwable e) {
        String msg = String.format("IconResolver implementation [%s] couldn't be instantiated.", className);
        logger.error(msg);
        throw new RuntimeException(msg, e);
    }

    // try to instantiate the DimensionProvider object
    className = PropertiesLoader.getDimensionProviderImpl();
    if (StringUtils.isNullOrEmptyOrBlank(className))
        throw new RuntimeException(
                "Empty DimensionProvider implementation class name! Depending property must be set!");
    try {
        Class<?> clazz = Class.forName(className);
        imageDimensionProvider = (IDimensionProvider) clazz.newInstance();
        logger.info("DimensionProvider initialized to {}", className);
    } catch (Throwable e) {
        String msg = String.format("DimensionProvider implementation [%s] couldn't be instantiated.",
                className);
        logger.error(msg);
        throw new RuntimeException(msg, e);
    }

    // try to instantiate the ExifRemover object
    className = PropertiesLoader.getExifRemoverImpl();
    if (StringUtils.isNullOrEmptyOrBlank(className)) {
        logger.warn("Empty ExifRemover implementation class name! EXIF data won't be removed.");
        exifRemover = null;
    } else {
        try {
            Class<?> clazz = Class.forName(className);
            exifRemover = (ExifRemover) clazz.newInstance();
            logger.info("ExifRemover initialized to {}", className);
        } catch (Throwable e) {
            String msg = String.format("ExifRemover implementation [%s] couldn't be instantiated.", className);
            logger.error(msg);
            throw new RuntimeException(msg, e);
        }
    }

    // try to read the dimension for thumbnails
    Matcher dimMatcher = dimensionPattern.matcher(PropertiesLoader.getThumbnailDimension());
    if (dimMatcher.matches()) {
        thumbnailDimension = new Dimension(Integer.valueOf(dimMatcher.group(1)),
                Integer.valueOf(dimMatcher.group(2)));
    }

    // try to read the dimension for preview
    dimMatcher = dimensionPattern.matcher(PropertiesLoader.getPreviewDimension());
    if (dimMatcher.matches()) {
        previewDimension = new Dimension(Integer.valueOf(dimMatcher.group(1)),
                Integer.valueOf(dimMatcher.group(2)));
    }

    // fetch the temporary directory
    File tempDir = (File) UserObjectProxy.servletContext.getAttribute(ServletContext.TEMPDIR);
    if (tempDir == null) {
        String msg = "No temporary directory according to the Servlet spec SRV.3.7.1 found!";
        logger.error(msg);
        throw new RuntimeException(msg);
    }
    tempDirectory = tempDir.toPath();

    // try to instantiate the DefaultConfigResolver object and fetches the default configuration
    className = PropertiesLoader.getDefaultConfigResolverImpl();
    if (StringUtils.isNullOrEmptyOrBlank(className))
        throw new RuntimeException(
                "Empty DefaultConfigResolver implementation class name! Depending property must be set!");
    try {
        Class<?> clazz = Class.forName(className);
        DefaultConfigResolver configResolver = (DefaultConfigResolver) clazz.newInstance();
        configResolver.initContext(servletContext);
        filemanagerDefaultConfig = configResolver.read();
        logger.info("Default configuration of the filemanager successful fetched from {}", className);
    } catch (Throwable e) {
        String msg = String.format("DefaultConfigResolver implementation [%s] couldn't be instantiated.",
                className);
        logger.error(msg);
        if (e instanceof RuntimeException)
            throw (RuntimeException) e;
        throw new RuntimeException(msg, e);
    }

    // build regex pattern
    String folderExcludePatternStr = PropertiesLoader.getRegexToExcludeFolders();
    if (StringUtils.isNullOrEmptyOrBlank(folderExcludePatternStr)) {
        logger.warn("Property 'connector.regex.exclude.folders' isn't set.");
        excludeFoldersPattern = null;
    } else {
        try {
            excludeFoldersPattern = Pattern.compile(folderExcludePatternStr);
        } catch (PatternSyntaxException e) {
            throw new RuntimeException("Exclude pattern for folders couldn't be compiled!");
        }
    }

    String fileExcludePatternStr = PropertiesLoader.getRegexToExcludeFiles();
    if (StringUtils.isNullOrEmptyOrBlank(fileExcludePatternStr)) {
        logger.warn("Property 'connector.regex.exclude.files' isn't set.");
        excludeFilesPattern = null;
    } else {
        try {
            excludeFilesPattern = Pattern.compile(fileExcludePatternStr);
        } catch (PatternSyntaxException e) {
            throw new RuntimeException("Exclude pattern for files couldn't be compiled!");
        }
    }
}