Example usage for java.nio.file StandardOpenOption CREATE

List of usage examples for java.nio.file StandardOpenOption CREATE

Introduction

In this page you can find the example usage for java.nio.file StandardOpenOption CREATE.

Prototype

StandardOpenOption CREATE

To view the source code for java.nio.file StandardOpenOption CREATE.

Click Source Link

Document

Create a new file if it does not exist.

Usage

From source file:com.spectralogic.ds3client.integration.Smoke_Test.java

@Test
public void testRecoverReadJob()
        throws IOException, XmlProcessingException, JobRecoveryException, URISyntaxException {
    final String bucketName = "test_recover_read_job_bucket";
    final String book1 = "beowulf.txt";
    final String book2 = "ulysses.txt";
    final Path objPath1 = ResourceUtils.loadFileResource(RESOURCE_BASE_NAME + book1);
    final Path objPath2 = ResourceUtils.loadFileResource(RESOURCE_BASE_NAME + book2);
    final Ds3Object obj1 = new Ds3Object(book1, Files.size(objPath1));
    final Ds3Object obj2 = new Ds3Object(book2, Files.size(objPath2));

    final Path dirPath = FileSystems.getDefault().getPath("output");
    if (!Files.exists(dirPath)) {
        Files.createDirectory(dirPath);
    }/*from  w w w . jav  a  2s  .c o m*/

    try {
        HELPERS.ensureBucketExists(bucketName, envDataPolicyId);

        final Ds3ClientHelpers.Job putJob = HELPERS.startWriteJob(bucketName, Lists.newArrayList(obj1, obj2));
        putJob.transfer(new ResourceObjectPutter(RESOURCE_BASE_NAME));

        final FileChannel channel1 = FileChannel.open(dirPath.resolve(book1), StandardOpenOption.WRITE,
                StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);

        final Ds3ClientHelpers.Job readJob = HELPERS.startReadJob(bucketName, Lists.newArrayList(obj1, obj2));
        final GetObjectResponse readResponse1 = client
                .getObject(new GetObjectRequest(bucketName, book1, channel1, readJob.getJobId().toString(), 0));

        assertThat(readResponse1, is(notNullValue()));
        assertThat(readResponse1.getStatusCode(), is(equalTo(200)));

        // Interruption...
        final Ds3ClientHelpers.Job recoverJob = HELPERS.recoverReadJob(readJob.getJobId());

        final FileChannel channel2 = FileChannel.open(dirPath.resolve(book2), StandardOpenOption.WRITE,
                StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
        final GetObjectResponse readResponse2 = client.getObject(
                new GetObjectRequest(bucketName, book2, channel2, recoverJob.getJobId().toString(), 0));
        assertThat(readResponse2, is(notNullValue()));
        assertThat(readResponse2.getStatusCode(), is(equalTo(200)));

    } finally {
        deleteAllContents(client, bucketName);
        for (final Path tempFile : Files.newDirectoryStream(dirPath)) {
            Files.delete(tempFile);
        }
        Files.delete(dirPath);
    }
}

From source file:de.decoit.visa.rdf.RDFManager.java

/**
 * Write the RDF model to a RDF/XML file. The output file will be created at
 * the specified location.//from www.  ja  va2 s . c  om
 *
 * @param pFile File object with path and file name of the output file
 * @throws IOException
 */
public void writeRDF(Path pFile) throws IOException {
    OutputStream os = Files.newOutputStream(pFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE,
            StandardOpenOption.TRUNCATE_EXISTING);

    writeRDF(os);

    Set<PosixFilePermission> attrSet = PosixFilePermissions.fromString("rwxrwxrwx");
    Files.setPosixFilePermissions(pFile, attrSet);
}

From source file:ca.osmcanada.osvuploadr.JPMain.java

private void Process(String dir, String accessToken) {
    File dir_photos = new File(dir);
    //filter only .jpgs
    FilenameFilter fileNameFilter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            if (name.lastIndexOf('.') > 0) {
                int lastIndex = name.lastIndexOf('.');
                String str = name.substring(lastIndex);
                if (str.toLowerCase().equals(".jpg")) {
                    return true;
                }/*ww  w .  j ava2 s  . c o m*/
            }
            return false;
        }
    };
    File[] file_list = dir_photos.listFiles(fileNameFilter);
    System.out.println("Pictures found:" + String.valueOf(file_list.length));

    System.out.println("Sorting files");
    //sort by modified time
    Arrays.sort(file_list, new Comparator<File>() {
        public int compare(File f1, File f2) {
            return Long.valueOf(Helper.getFileTime(f1)).compareTo(Helper.getFileTime(f2));
        }
    });
    System.out.println("End sorting");
    File f_sequence = new File(dir + "/sequence_file.txt");
    Boolean need_seq = true;
    long sequence_id = -1;
    System.out.println("Checking " + f_sequence.getPath() + " for sequence_file");
    if (f_sequence.exists()) {
        try {
            System.out.println("Found file, reading sequence id");
            List<String> id = Files.readAllLines(Paths.get(f_sequence.getPath()));
            if (id.size() > 0) {
                sequence_id = Long.parseLong(id.get(0));
                need_seq = false;
            }
        } catch (Exception ex) {
            need_seq = true;
        }
    } else {
        System.out.println("Sequence file not found, will need to request new id");
        need_seq = true;
    }
    //TODO: Load count from file
    System.out.println("Looking for count file");
    int cnt = 0;
    File f_cnt = new File(dir + "/count_file.txt");
    if (f_cnt.exists()) {
        System.out.println("Found count file:" + f_cnt.toString());
        try {
            List<String> id = Files.readAllLines(Paths.get(f_cnt.getPath()));
            if (id.size() > 0) {
                cnt = Integer.parseInt(id.get(0));
            }
        } catch (Exception ex) {
            cnt = 0;
        }
    } else {
        try {
            System.out.println("Creating new count file:" + f_cnt.getPath());
            f_cnt.createNewFile();
        } catch (Exception ex) {
            Logger.getLogger(JPMain.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    System.out.println("Current count at:" + String.valueOf(cnt));
    if (cnt > 0) {
        if (file_list.length > cnt) {
            File[] tmp = new File[file_list.length - cnt];
            int local_cnt = 0;
            for (int i = cnt; i < file_list.length; i++) {
                tmp[local_cnt] = file_list[i];
                local_cnt++;
            }
            file_list = tmp;
        }
    }

    System.out.println("Processing photos...");
    //Read file info
    for (File f : file_list) {
        try {
            System.out.println("Processing:" + f.getPath());
            ImageProperties imp = Helper.getImageProperties(f);
            System.out.println("Image Properties:");
            System.out.println("Lat:" + String.valueOf(imp.getLatitude()) + " Long:"
                    + String.valueOf(imp.getLongitude()) + "Created:" + String.valueOf(Helper.getFileTime(f)));
            //TODO: Check that file has GPS coordinates
            //TODO: Remove invalid photos
            if (need_seq) {
                System.out.println("Requesting sequence ID");
                sequence_id = getSequence(imp, accessToken);
                System.out.println("Obtained:" + sequence_id);
                byte[] bytes = Long.toString(sequence_id).getBytes(StandardCharsets.UTF_8);
                Files.write(Paths.get(f_sequence.getPath()), bytes, StandardOpenOption.CREATE);
                need_seq = false;
            }
            imp.setSequenceNumber(cnt);
            cnt++; //TODO: Write count to file
            System.out.println("Uploading image:" + f.getPath());
            Upload_Image(imp, accessToken, sequence_id);
            System.out.println("Uploaded");
            String out = String.valueOf(cnt);
            Files.write(Paths.get(f_cnt.getPath()), out.getBytes("UTF-8"),
                    StandardOpenOption.TRUNCATE_EXISTING);

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR);
        }

    }
    System.out.println("Sending finish for sequence:" + sequence_id);
    SendFinished(sequence_id, accessToken);
}

From source file:org.wildfly.security.tool.FileSystemRealmCommand.java

/**
 * Creates the script/commands the user must run for Elytron to recognize
 * and use the new filesystem-realm/*from   w  ww . j  ava 2 s.  c  om*/
 */
private void createWildFlyScript() throws Exception {
    for (Descriptor descriptor : descriptors) {
        String usersFile = descriptor.getUsersFile();
        if (descriptor.getUsersFile() == null || descriptor.getRolesFile() == null
                || descriptor.getOutputLocation() == null) {
            continue;
        }
        String fileSystemRealmName = descriptor.getFileSystemRealmName();
        if (fileSystemRealmName == null || fileSystemRealmName.isEmpty()) {
            warningHandler(String.format(
                    "No name provided for filesystem-realm, using default filesystem-realm name for %s.",
                    usersFile));
            descriptor.setFileSystemRealmName(DEFAULT_FILESYSTEM_REALM_NAME);
            fileSystemRealmName = DEFAULT_FILESYSTEM_REALM_NAME;
        }
        String outputLocation = descriptor.getOutputLocation();
        String securityDomainName = descriptor.getSecurityDomainName();

        String createScriptCheck = "";
        if (Paths.get(String.format("%s.sh", fileSystemRealmName)).toFile().exists()) {
            createScriptCheck = prompt(false, null, false, ElytronToolMessages.msg
                    .shouldFileBeOverwritten(String.format("%s.sh", fileSystemRealmName)));
        }
        String fullOutputPath;
        if (outputLocation.startsWith(".")) {
            fullOutputPath = Paths.get(outputLocation.substring(2, outputLocation.length())).toAbsolutePath()
                    .toString();
        } else {
            fullOutputPath = Paths.get(outputLocation).toAbsolutePath().toString();
        }

        if (summaryMode) {
            summaryString.append(String.format("Configured script for WildFly named %s.sh at %s.",
                    fileSystemRealmName, fullOutputPath));
            summaryString.append(System.getProperty("line.separator"));
            summaryString.append("The script is using the following names:");
            summaryString.append(System.getProperty("line.separator"));
            summaryString.append(String.format("Name of filesystem-realm: %s", fileSystemRealmName));
            summaryString.append(System.getProperty("line.separator"));
        }

        if (securityDomainName != null && !securityDomainName.isEmpty()) {
            if (summaryMode) {
                summaryString.append(String.format("Name of security-domain: %s", securityDomainName));
                summaryString.append(System.getProperty("line.separator"));
            }
        } else {
            warningHandler(String.format(
                    "No name provided for security-domain, using default security-domain name for %s.",
                    usersFile));
            securityDomainName = DEFAULT_SECURITY_DOMAIN_NAME;
        }

        List<String> scriptLines = Arrays.asList(
                String.format("/subsystem=elytron/filesystem-realm=%s:add(path=%s)", fileSystemRealmName,
                        fullOutputPath),
                String.format(
                        "/subsystem=elytron/security-domain=%1$s:add(realms=[{realm=%2$s}],default-realm=%2$s,permission-mapper=default-permission-mapper)",
                        securityDomainName, fileSystemRealmName));

        if (!createScriptCheck.equals("y") && !createScriptCheck.equals("yes")) {
            Files.write(Paths.get(String.format("%s/%s.sh", outputLocation, fileSystemRealmName)), scriptLines,
                    StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
        } else {
            Files.write(Paths.get(String.format("%s/%s.sh", outputLocation, fileSystemRealmName)), scriptLines,
                    StandardOpenOption.APPEND);
        }
    }
}

From source file:org.codice.ddf.configuration.migration.ConfigurationMigrationManagerTest.java

private void createBrandingFile(String branding) throws IOException {
    final File brandingFile = new File(ddfHome.resolve("Branding.txt").toString());

    brandingFile.createNewFile();//w  ww  .  jav a 2s .com
    Files.write(brandingFile.toPath(), branding.getBytes(), StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING);
}

From source file:org.codice.ddf.configuration.migration.ConfigurationMigrationManagerTest.java

private void createVersionFile(String version) throws IOException {
    File versionFile = new File(ddfHome.resolve("Version.txt").toString());
    versionFile.createNewFile();//from   ww w  . ja va2s  . c o m
    Files.write(versionFile.toPath(), version.getBytes(), StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING);
}

From source file:org.codice.ddf.configuration.migration.ConfigurationMigrationManagerTest.java

private void createMigrationPropsFile(String contents) throws IOException {
    Path migrationPropsPath = ddfHome.resolve(Paths.get("etc", "migration.properties"));
    Files.createDirectories(migrationPropsPath.getParent());
    Files.createFile(migrationPropsPath);
    Files.write(migrationPropsPath, contents.getBytes(), StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING);
}

From source file:vn.edu.vnu.uet.nlp.smt.ibm.IBMModel3.java

@Override
public void save(String folder) throws IOException {
    super.save(folder);

    File fol = new File(folder);
    if (!fol.isDirectory()) {
        System.err.println(folder + " is not a folder! Cannot save model!");
        return;//from   ww  w  . j  ava2 s .  c om
    }

    if (!folder.endsWith("/")) {
        folder = folder + "/";
    }

    // Save distortion
    String dFileName = folder + IConstants.distortionModelName;
    Utils.saveArray(d, maxLe, maxLf, maxLe, maxLf, dFileName, iStart);

    // Save fertility
    String nFileName = folder + IConstants.fertilityModelName;
    Utils.saveObject(n, nFileName);

    // Save null insertion
    String nullInsertionFileName = folder + IConstants.nullInsertionModelName;

    BufferedWriter bw = Files.newBufferedWriter(Paths.get(nullInsertionFileName), StandardOpenOption.CREATE);
    bw.write("p0 = " + p0);
    bw.flush();
    bw.close();

}

From source file:me.mast3rplan.phantombot.PhantomBot.java

private void init() {
    /* Is the web toggle enabled? */
    if (webEnabled) {
        if (legacyServers) {
            /* open a normal non ssl server */
            httpServer = new HTTPServer(basePort, oauth);
            /* Start this http server  */
            httpServer.start();/*from   ww w .  j  a  v a  2 s  .c om*/
        }

        /* Is the music toggled on? */
        if (musicEnabled) {
            /* Set the music player server */
            youtubeSocketServer = new YTWebSocketServer((basePort + 3), youtubeOAuth, youtubeOAuthThro);
            /* Start this youtube socket server */
            youtubeSocketServer.start();
            print("YouTubeSocketServer accepting connections on port: " + (basePort + 3));
        }

        /* Checks if the user wants the legacy servers, this is off by default. */
        if (legacyServers) {
            /* Create a event server to get all the events. */
            eventWebSocketServer = new EventWebSocketServer((basePort + 2));
            /* Start this event server */
            eventWebSocketServer.start();
            print("EventSocketServer accepting connections on port: " + (basePort + 2));
            /* make the event bus register this event server */
            EventBus.instance().register(eventWebSocketServer);
        }

        if (useHttps) {
            /* Set up the panel socket server */
            panelSocketSecureServer = new PanelSocketSecureServer((basePort + 4), webOAuth, webOAuthThro,
                    httpsFileName, httpsPassword);
            /* Start the panel socket server */
            panelSocketSecureServer.start();
            print("PanelSocketSecureServer accepting connections on port: " + (basePort + 4) + " (SSL)");

            /* Set up a new https server */
            newHttpsServer = new NEWHTTPSServer((basePort + 5), oauth, webOAuth, panelUsername, panelPassword,
                    httpsFileName, httpsPassword);
            print("New HTTPS server accepting connection on port: " + (basePort + 5) + " (SSL)");
        } else {
            /* Set up the panel socket server */
            panelSocketServer = new PanelSocketServer((basePort + 4), webOAuth, webOAuthThro);
            /* Start the panel socket server */
            panelSocketServer.start();
            print("PanelSocketServer accepting connections on port: " + (basePort + 4));

            /* Set up a new http server */
            newHttpServer = new NEWHTTPServer((basePort + 5), oauth, webOAuth, panelUsername, panelPassword);
            print("New HTTP server accepting connection on port: " + (basePort + 5));
        }
    }

    /* Enable GameWisp if the oAuth is set */
    if (!gameWispOAuth.isEmpty() && checkModuleEnabled("./handlers/gameWispHandler.js")) {
        /* Set the oAuths */
        GameWispAPIv1.instance().SetAccessToken(gameWispOAuth);
        GameWispAPIv1.instance().SetRefreshToken(gameWispRefresh);
        SingularityAPI.instance().setAccessToken(gameWispOAuth);
        SingularityAPI.instance().StartService();
        /* get a fresh token */
        doRefreshGameWispToken();
    }

    /* Connect to Discord if the data is present. */
    if (!discordToken.isEmpty()) {
        DiscordAPI.instance().connect(discordToken);
    }

    /* Set Streamlabs currency code, if possible */
    if (dataStore.HasKey("donations", "", "currencycode")) {
        TwitchAlertsAPIv1.instance().SetCurrencyCode(dataStore.GetString("donations", "", "currencycode"));
    }

    /* Check to see if all the Twitter info needed is there */
    if (!twitterUsername.isEmpty() && !twitterAccessToken.isEmpty() && !twitterConsumerToken.isEmpty()
            && !twitterConsumerSecret.isEmpty() && !twitterSecretToken.isEmpty()) {
        /* Set the Twitter tokens */
        TwitterAPI.instance().setUsername(twitterUsername);
        TwitterAPI.instance().setAccessToken(twitterAccessToken);
        TwitterAPI.instance().setSecretToken(twitterSecretToken);
        TwitterAPI.instance().setConsumerKey(twitterConsumerToken);
        TwitterAPI.instance().setConsumerSecret(twitterConsumerSecret);
        /* Check to see if the tokens worked */
        this.twitterAuthenticated = TwitterAPI.instance().authenticate();
    }

    /* print a extra line in the console. */
    print("");

    /* Create configuration for YTPlayer v2.0 for the WS port. */
    String data = "";
    String http = (useHttps ? "https://" : "http://");

    try {
        data += "//Configuration for YTPlayer\r\n";
        data += "//Automatically Generated by PhantomBot at Startup\r\n";
        data += "//Do NOT Modify! Overwritten when PhantomBot is restarted!\r\n";
        data += "var playerPort = " + (basePort + 3) + ";\r\n";
        data += "var channelName = \"" + channelName + "\";\r\n";
        data += "var auth=\"" + youtubeOAuth + "\";\r\n";
        data += "var http=\"" + http + "\";\r\n";
        data += "function getPlayerPort() { return playerPort; }\r\n";
        data += "function getChannelName() { return channelName; }\r\n";
        data += "function getAuth() { return auth; }\r\n";
        data += "function getProtocol() { return http; }\r\n";

        /* Create a new file if it does not exist */
        if (!new File("./web/ytplayer/").exists())
            new File("./web/ytplayer/").mkdirs();
        if (!new File("./web/ytplayer/js").exists())
            new File("./web/ytplayer/js").mkdirs();

        /* Write the data to that file */
        Files.write(Paths.get("./web/ytplayer/js/playerConfig.js"), data.getBytes(StandardCharsets.UTF_8),
                StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
    } catch (IOException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    }

    /* Create configuration for YTPlayer v2.0 for the WS port. */
    data = "";
    try {
        data += "//Configuration for YTPlayer\r\n";
        data += "//Automatically Generated by PhantomBot at Startup\r\n";
        data += "//Do NOT Modify! Overwritten when PhantomBot is restarted!\r\n";
        data += "var playerPort = " + (basePort + 3) + ";\r\n";
        data += "var channelName = \"" + channelName + "\";\r\n";
        data += "var auth=\"" + youtubeOAuthThro + "\";\r\n";
        data += "var http=\"" + http + "\";\r\n";
        data += "function getPlayerPort() { return playerPort; }\r\n";
        data += "function getChannelName() { return channelName; }\r\n";
        data += "function getAuth() { return auth; }\r\n";
        data += "function getProtocol() { return http; }\r\n";

        /* Create a new file if it does not exist */
        if (!new File("./web/playlist/").exists())
            new File("./web/playlist/").mkdirs();
        if (!new File("./web/playlist/js").exists())
            new File("./web/playlist/js").mkdirs();

        /* Write the data to that file */
        Files.write(Paths.get("./web/playlist/js/playerConfig.js"), data.getBytes(StandardCharsets.UTF_8),
                StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
    } catch (IOException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    }

    /* Create configuration for WebPanel for the WS port. */
    data = "";
    try {
        data += "//Configuration for Control Panel\r\n";
        data += "//Automatically Generated by PhantomBot at Startup\r\n";
        data += "//Do NOT Modify! Overwritten when PhantomBot is restarted!\r\n";
        data += "var panelSettings = {\r\n";
        data += "    panelPort   : " + (basePort + 4) + ",\r\n";
        data += "    channelName : \"" + channelName + "\",\r\n";
        data += "    auth        : \"" + webOAuth + "\",\r\n";
        data += "    http        : \"" + http + "\"\r\n";
        data += "};\r\n\r\n";
        data += "function getPanelPort() { return panelSettings.panelPort; }\r\n";
        data += "function getChannelName() { return panelSettings.channelName; }\r\n";
        data += "function getAuth() { return panelSettings.auth; }\r\n";
        data += "function getProtocol() { return panelSettings.http; }\r\n";

        /* Create a new file if it does not exist */
        if (!new File("./web/panel/").exists())
            new File("./web/panel/").mkdirs();
        if (!new File("./web/panel/js").exists())
            new File("./web/panel/js").mkdirs();

        /* Write the data to that file */
        Files.write(Paths.get("./web/panel/js/panelConfig.js"), data.getBytes(StandardCharsets.UTF_8),
                StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
    } catch (IOException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    }

    /* Create configuration for Read-Only Access to WS port. */
    data = "";
    try {
        data += "//Configuration for Control Panel\r\n";
        data += "//Automatically Generated by PhantomBot at Startup\r\n";
        data += "//Do NOT Modify! Overwritten when PhantomBot is restarted!\r\n";
        data += "var panelSettings = {\r\n";
        data += "    panelPort   : " + (basePort + 4) + ",\r\n";
        data += "    channelName : \"" + channelName + "\",\r\n";
        data += "    auth        : \"" + webOAuthThro + "\",\r\n";
        data += "    http        : \"" + http + "\"\r\n";
        data += "};\r\n\r\n";
        data += "function getPanelPort() { return panelSettings.panelPort; }\r\n";
        data += "function getChannelName() { return panelSettings.channelName; }\r\n";
        data += "function getAuth() { return panelSettings.auth; }\r\n";
        data += "function getProtocol() { return panelSettings.http; }\r\n";

        /* Create a new file if it does not exist */
        if (!new File("./web/common/").exists())
            new File("./web/common/").mkdirs();
        if (!new File("./web/common/js").exists())
            new File("./web/common/js").mkdirs();

        /* Write the data to that file */
        Files.write(Paths.get("./web/common/js/wsConfig.js"), data.getBytes(StandardCharsets.UTF_8),
                StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
    } catch (IOException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    }

    /* check if the console is interactive */
    if (interactive) {
        ConsoleInputListener consoleIL = new ConsoleInputListener();
        /* Start the Console Input Listener */
        consoleIL.start();
    }

    /* Register PhantomBot (this) with the event bus. */
    EventBus.instance().register(this);
    /* Register the script manager with the event bus. */
    EventBus.instance().register(ScriptEventManager.instance());

    /* Load the datastore config */
    dataStore.LoadConfig(dataStoreConfig);

    /* Export all these to the $. api in the scripts. */
    Script.global.defineProperty("inidb", dataStore, 0);
    Script.global.defineProperty("username", UsernameCache.instance(), 0);
    Script.global.defineProperty("twitch", TwitchAPIv3.instance(), 0);
    Script.global.defineProperty("botName", botName, 0);
    Script.global.defineProperty("channelName", channelName, 0);
    Script.global.defineProperty("channels", channels, 0);
    Script.global.defineProperty("ownerName", ownerName, 0);
    Script.global.defineProperty("ytplayer", youtubeSocketServer, 0);
    Script.global.defineProperty("panelsocketserver", (useHttps ? panelSocketSecureServer : panelSocketServer),
            0);
    Script.global.defineProperty("random", random, 0);
    Script.global.defineProperty("youtube", YouTubeAPIv3.instance(), 0);
    Script.global.defineProperty("shortenURL", GoogleURLShortenerAPIv1.instance(), 0);
    Script.global.defineProperty("gamewisp", GameWispAPIv1.instance(), 0);
    Script.global.defineProperty("twitter", TwitterAPI.instance(), 0);
    Script.global.defineProperty("twitchCacheReady", PhantomBot.twitchCacheReady, 0);
    Script.global.defineProperty("isNightly", isNightly(), 0);
    Script.global.defineProperty("version", botVersion(), 0);
    Script.global.defineProperty("changed", newSetup, 0);
    Script.global.defineProperty("discordAPI", DiscordAPI.instance(), 0);
    Script.global.defineProperty("hasDiscordToken", hasDiscordToken(), 0);
    Script.global.defineProperty("customAPI", CustomAPI.instance(), 0);

    /* open a new thread for when the bot is exiting */
    Thread thread = new Thread(() -> {
        onExit();
    });

    /* Get the un time for that new thread we just created */
    Runtime.getRuntime().addShutdownHook(thread);

    /* And finally try to load init, that will then load the scripts */
    try {
        ScriptManager.loadScript(new File("./scripts/init.js"));
    } catch (IOException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    }

    /* Check for a update with PhantomBot */
    doCheckPhantomBotUpdate();

    /* Perform SQLite datbase backups. */
    if (this.backupSQLiteAuto) {
        doBackupSQLiteDB();
    }
}

From source file:com.spectralogic.ds3client.integration.Smoke_Test.java

@Test
public void partialObjectGetOverChunkBoundry() throws IOException, XmlProcessingException {
    final String bucketName = "partialGetOverBoundry";
    final String testFile = "testObject.txt";
    final Path filePath = Files.createTempFile("ds3", testFile);
    final int seed = 12345;
    LOG.info("Test file: " + filePath.toAbsolutePath());
    try {/*from  w ww. j  av  a 2s.  c  o  m*/
        HELPERS.ensureBucketExists(bucketName, envDataPolicyId);

        final int objectSize = PutBulkJobSpectraS3Request.MIN_UPLOAD_SIZE_IN_BYTES * 2;

        final List<Ds3Object> objs = Lists.newArrayList(new Ds3Object(testFile, objectSize));

        final Ds3ClientHelpers.Job putJob = HELPERS.startWriteJob(bucketName, objs, WriteJobOptions.create()
                .withMaxUploadSize(PutBulkJobSpectraS3Request.MIN_UPLOAD_SIZE_IN_BYTES));

        putJob.transfer(new Ds3ClientHelpers.ObjectChannelBuilder() {
            @Override
            public SeekableByteChannel buildChannel(final String key) throws IOException {
                final byte[] randomData = IOUtils.toByteArray(new RandomDataInputStream(seed, objectSize));
                final ByteBuffer randomBuffer = ByteBuffer.wrap(randomData);

                final ByteArraySeekableByteChannel channel = new ByteArraySeekableByteChannel(objectSize);
                channel.write(randomBuffer);

                return channel;

            }
        });

        final List<Ds3Object> partialObjectGet = Lists.newArrayList();
        partialObjectGet.add(new PartialDs3Object(testFile,
                Range.byPosition(PutBulkJobSpectraS3Request.MIN_UPLOAD_SIZE_IN_BYTES - 100,
                        PutBulkJobSpectraS3Request.MIN_UPLOAD_SIZE_IN_BYTES + 99)));

        final Ds3ClientHelpers.Job getJob = HELPERS.startReadJob(bucketName, partialObjectGet);

        getJob.transfer(new Ds3ClientHelpers.ObjectChannelBuilder() {
            @Override
            public SeekableByteChannel buildChannel(final String key) throws IOException {
                return Files.newByteChannel(filePath, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
            }
        });

        assertThat(Files.size(filePath), is(200L));

    } finally {
        Files.delete(filePath);
        deleteAllContents(client, bucketName);
    }
}