Example usage for java.nio.file StandardOpenOption WRITE

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

Introduction

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

Prototype

StandardOpenOption WRITE

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

Click Source Link

Document

Open for write access.

Usage

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   w  w  w .  ja  va  2  s . com*/
 *
 * @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:com.rvantwisk.cnctools.controllers.CNCToolsController.java

@FXML
public void onViewGCode(ActionEvent actionEvent) {
    try {// w w  w . j a v  a  2  s. c o m
        if (v_projectList.getSelectionModel().selectedItemProperty().get() != null) {
            final Project p = v_projectList.getSelectionModel().selectedItemProperty().get();

            if (p.postProcessorProperty().get() == null) {
                MonologFX dialog = new MonologFX(MonologFX.Type.QUESTION);
                dialog.setTitleText("No postprocessor");
                dialog.setMessage("No post processor configured, please select a post processor first!");
                dialog.show();
            } else {

                File file = File.createTempFile("cnctools", "gcode");
                final GCodeCollection gCode = p.getGCode(toolDBManager);
                file.createNewFile();
                file.deleteOnExit();
                if (file != null) {
                    try (BufferedWriter br = Files.newBufferedWriter(file.toPath(), Charset.forName("UTF-8"),
                            new OpenOption[] { StandardOpenOption.WRITE })) {
                        br.write(gCode.concate().toString());
                        br.write("\n");
                        br.flush();
                        br.close();

                        Project project = projectModel.projectsProperty()
                                .get(v_projectList.getSelectionModel().getSelectedIndex());
                        showGCodeFromFile(project, file.getAbsolutePath());

                    } catch (IOException ex) {
                        handleException(ex);
                    }
                }
            }

        }
    } catch (Exception e) {
        handleException(e);
    }
}

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  2s.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  w w.j  a  v  a  2s  . co  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);
    }
}

From source file:br.bireme.ngrams.NGrams.java

public static void export(NGIndex index, final NGSchema schema, final String outFile,
        final String outFileEncoding) throws IOException {
    if (index == null) {
        throw new NullPointerException("index");
    }//from  w  w w. ja  v  a  2s .com
    if (schema == null) {
        throw new NullPointerException("schema");
    }
    if (outFile == null) {
        throw new NullPointerException("outFile");
    }
    if (outFileEncoding == null) {
        throw new NullPointerException("outFileEncoding");
    }
    final Parameters parameters = schema.getParameters();
    final TreeMap<Integer, String> fields = new TreeMap<>();
    final IndexReader reader = index.getIndexSearcher().getIndexReader();
    final int maxdoc = reader.maxDoc();
    //final Bits liveDocs = MultiFields.getLiveDocs(reader);
    final Bits liveDocs = MultiBits.getLiveDocs(reader);
    final BufferedWriter writer = Files.newBufferedWriter(Paths.get(outFile), Charset.forName(outFileEncoding),
            StandardOpenOption.CREATE, StandardOpenOption.WRITE);

    boolean first = true;

    for (Map.Entry<Integer, br.bireme.ngrams.Field> entry : parameters.sfields.entrySet()) {
        fields.put(entry.getKey(), entry.getValue().name + NOT_NORMALIZED_FLD);
    }

    for (int docID = 0; docID < maxdoc; docID++) {
        if ((liveDocs != null) && (!liveDocs.get(docID)))
            continue;
        final Document doc = reader.document(docID);

        if (first) {
            first = false;
        } else {
            writer.newLine();
        }
        writer.append(doc2pipe(doc, fields));
    }
    writer.close();
    reader.close();
}

From source file:tv.phantombot.PhantomBot.java

private void init() {
    /* Is the web toggle enabled? */
    if (webEnabled) {
        try {//from w  ww  . j a v a 2 s.  c om
            checkPortAvailabity(basePort);
            checkPortAvailabity(panelSocketPort);

            /* Is the music toggled on? */
            if (musicEnabled) {
                checkPortAvailabity(ytSocketPort);
                if (useHttps) {
                    /* Set the music player server */
                    youtubeSocketSecureServer = new YTWebSocketSecureServer(bindIP, ytSocketPort, youtubeOAuth,
                            youtubeOAuthThro, httpsFileName, httpsPassword, socketServerTasksSize);
                    /* Start this youtube socket server */
                    youtubeSocketSecureServer.start();
                    print("YouTubeSocketSecureServer accepting connections on port: " + ytSocketPort
                            + " (SSL)");
                } else {
                    /* Set the music player server */
                    youtubeSocketServer = new YTWebSocketServer(bindIP, ytSocketPort, youtubeOAuth,
                            youtubeOAuthThro);
                    /* Start this youtube socket server */
                    youtubeSocketServer.start();
                    print("YouTubeSocketServer accepting connections on port: " + ytSocketPort);
                }
            }

            if (useHttps) {
                if (testPanelServer) {
                    newPanelSocketServer = new NewPanelSocketServer(panelSocketPort, webOAuth, webOAuthThro,
                            httpsFileName, httpsPassword);
                    newPanelSocketServer.start();
                    print("TEST PanelSocketSecureServer accepting connections on port: " + panelSocketPort
                            + " (SSL)");
                } else {
                    /* Set up the panel socket server */
                    panelSocketSecureServer = new PanelSocketSecureServer(bindIP, panelSocketPort, webOAuth,
                            webOAuthThro, httpsFileName, httpsPassword, socketServerTasksSize);
                    /* Start the panel socket server */
                    panelSocketSecureServer.start();
                    print("PanelSocketSecureServer accepting connections on port: " + panelSocketPort
                            + " (SSL)");
                }

                /* Set up a new https server */
                httpsServer = new HTTPSServer(bindIP, (basePort), oauth, webOAuth, panelUsername, panelPassword,
                        httpsFileName, httpsPassword);
                print("HTTPS server accepting connection on port: " + basePort + " (SSL)");
            } else {
                if (testPanelServer) {
                    newPanelSocketServer = new NewPanelSocketServer(panelSocketPort, webOAuth, webOAuthThro);
                    newPanelSocketServer.start();
                    print("TEST PanelSocketServer accepting connections on port: " + panelSocketPort);
                } else {
                    /* Set up the panel socket server */
                    panelSocketServer = new PanelSocketServer(bindIP, panelSocketPort, webOAuth, webOAuthThro);
                    /* Set up the NEW panel socket server */
                    /* Start the panel socket server */
                    panelSocketServer.start();
                    print("PanelSocketServer accepting connections on port: " + panelSocketPort);
                }

                /* Set up a new http server */
                httpServer = new HTTPServer(bindIP, (basePort), oauth, webOAuth, panelUsername, panelPassword);
                print("HTTP server accepting connection on port: " + basePort);
            }
        } catch (Exception ex) {
            print("Exception occurred in one of the socket based services, PhantomBot will now exit.");
            System.exit(0);
        }
    }

    /* 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 = " + ytSocketPort + ";\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 Playlist 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 = " + ytSocketPort + ";\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   : " + panelSocketPort + ",\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();

        byte[] bytes = data.getBytes(StandardCharsets.UTF_8);

        /* Write the data to that file */
        Files.write(Paths.get("./web/panel/js/panelConfig.js"), bytes, StandardOpenOption.CREATE,
                StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);

        // If betap write the file in that folder too.
        if (PhantomBot.betap) {
            Files.write(Paths.get("./web/beta-panel/js/utils/panelConfig.js"), bytes, 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   : " + panelSocketPort + ",\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());
    /* Register the console event handler */
    EventBus.instance().register(ConsoleEventHandler.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", TwitchAPIv5.instance(), 0);
    Script.global.defineProperty("botName", botName.toLowerCase(), 0);
    Script.global.defineProperty("channelName", channelName.toLowerCase(), 0);
    Script.global.defineProperty("ownerName", ownerName.toLowerCase(), 0);
    Script.global.defineProperty("ytplayer", (useHttps ? youtubeSocketSecureServer : youtubeSocketServer), 0);
    if (testPanelServer) {
        Script.global.defineProperty("panelsocketserver", newPanelSocketServer, 0);
    } else {
        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("isPrerelease", isPrerelease(), 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);
    Script.global.defineProperty("dataRenderServiceAPI", DataRenderServiceAPIv1.instance(), 0);

    /* open a new thread for when the bot is exiting */
    Thread thread = new Thread(() -> {
        onExit();
    }, "tv.phantombot.PhantomBot::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);
    }

    // Moved this to debug only. People are already asking questions.
    if (PhantomBot.enableDebugging) {
        /* Check for bot verification. */
        print("Bot Verification Status: " + (TwitchAPIv5.instance().getBotVerified(this.botName) ? "" : " NOT ")
                + "Verified.");
    }

    /* 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 partialGetWithBookOverChunkBoundry()
        throws IOException, XmlProcessingException, URISyntaxException {
    final String bucketName = "partialGetOnBook";
    final Path filePath = Files.createTempFile("ds3", "lesmis-copies.txt");
    LOG.info("TempFile for partial get of book: " + filePath.toAbsolutePath().toString());

    try {//  w  w w . jav  a  2s .c  o  m

        HELPERS.ensureBucketExists(bucketName, envDataPolicyId);

        final List<Ds3Object> putObjects = Lists.newArrayList(new Ds3Object("lesmis-copies.txt", 13290604));

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

        putJob.transfer(new ResourceObjectPutter("largeFiles/"));

        final List<Ds3Object> getObjects = Lists.newArrayList();
        getObjects.add(new PartialDs3Object("lesmis-copies.txt", Range.byLength(1048476, 200)));

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

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

        final Path expectedResultPath = Paths.get(Smoke_Test.class.getResource("/largeFiles/output").toURI());

        assertThat(Files.size(filePath), is(200L));
        final String partialFile = new String(Files.readAllBytes(filePath), Charset.forName("UTF-8"));
        final String expectedResult = new String(Files.readAllBytes(expectedResultPath),
                Charset.forName("UTF-8"));
        assertThat(partialFile, is(expectedResult.substring(0, expectedResult.length() - 1))); // need the trim to remove a newline that is added by the os
    } finally {
        deleteAllContents(client, bucketName);
        Files.delete(filePath);
    }
}

From source file:me.gloriouseggroll.quorrabot.Quorrabot.java

@Subscribe
public void onConsoleMessage(ConsoleInputEvent msg) {
    String message = msg.getMsg();
    boolean changed = false;
    if (message == null) {
        return;//  w  w w  .  j  a v  a  2 s  .c om
    }

    if (message.equals("debugon")) {
        Quorrabot.setDebugging(true);
    }

    //used for testing notifications
    if (message.equalsIgnoreCase("subtest")) {
        String randomUser = generateRandomString(10);
        EventBus.instance().post(
                new IrcPrivateMessageEvent(this.session, "twitchnotify", randomUser + " just subscribed!"));

    }
    if (message.equalsIgnoreCase("resubtest")) {
        String randomUser = generateRandomString(10);
        EventBus.instance().post(new IrcPrivateMessageEvent(this.session, "twitchnotify",
                randomUser + " just subscribed for 10 months in a row!"));

    }
    if (message.equalsIgnoreCase("followtest")) {
        String randomUser = generateRandomString(10);
        EventBus.instance().post(new TwitchFollowEvent(randomUser, this.channel));
    }

    if (message.equalsIgnoreCase("hosttest")) {
        String randomUser = generateRandomString(10);
        EventBus.instance().post(new TwitchHostedEvent(randomUser, this.tcechannel));
    }

    if (message.equals("debugoff")) {
        Quorrabot.setDebugging(false);
    }

    if (message.startsWith("inidb.get")) {
        String spl[] = message.split(" ", 4);

        com.gmt2001.Console.out.println(dataStoreObj.GetString(spl[1], spl[2], spl[3]));
    }

    if (message.startsWith("inidb.set")) {
        String spl[] = message.split(" ", 5);

        dataStoreObj.SetString(spl[1], spl[2], spl[3], spl[4]);
        com.gmt2001.Console.out.println(dataStoreObj.GetString(spl[1], spl[2], spl[3]));
    }

    if (message.equals("apioauth")) {
        com.gmt2001.Console.out.print("Please enter the bot owner's api oauth string: ");
        String newoauth = System.console().readLine().trim();

        TwitchAPIv3.instance().SetOAuth(newoauth);
        apioauth = newoauth;

        changed = true;
    }

    if (message.equalsIgnoreCase("mysqlsetup")) {
        try {
            com.gmt2001.Console.out.println("");
            com.gmt2001.Console.out.println("QuorraBot MySQL setup.");
            com.gmt2001.Console.out.println("");

            com.gmt2001.Console.out.print("Please enter your MySQL host name or IP: ");
            String newHost = System.console().readLine().trim();
            mySqlHost = newHost;

            com.gmt2001.Console.out.print("Please enter your MySQL port: ");
            String newPost = System.console().readLine().trim();
            mySqlPort = newPost;

            com.gmt2001.Console.out.print("Please enter your MySQL db name: ");
            String newName = System.console().readLine().trim();
            mySqlName = newName;

            com.gmt2001.Console.out.print("Please enter a username for MySQL: ");
            String newUser = System.console().readLine().trim();
            mySqlUser = newUser;

            com.gmt2001.Console.out.print("Please enter a password for MySQL: ");
            String newPass = System.console().readLine().trim();
            mySqlPass = newPass;

            datastore = "MySQLStore";

            dataStoreObj = MySQLStore.instance();

            if (mySqlPort.isEmpty()) {
                mySqlConn = "jdbc:mariadb://" + mySqlHost + "/" + mySqlName;
            } else {
                mySqlConn = "jdbc:mariadb://" + mySqlHost + ":" + mySqlPort + "/" + mySqlName;
            }
            /**
             * Check to see if we can create a connection
             */
            if (dataStoreObj.CreateConnection(mySqlConn, mySqlUser, mySqlPass) == null) {
                com.gmt2001.Console.out
                        .println("Could not create a connection with MySql. QuorraBot now shutting down...");
                System.exit(0);
            }

            if (IniStore.instance().GetFileList().length > 0) {
                ini2MySql(true);
            } else if (SqliteStore.instance().GetFileList().length > 0) {
                sqlite2MySql();
            }

            com.gmt2001.Console.out.println("QuorraBot MySQL setup done.");

            changed = true;
        } catch (NullPointerException ex) {
            com.gmt2001.Console.err.printStackTrace(ex);
        }
    }

    if (message.equals("clientid")) {
        com.gmt2001.Console.out.print("Please enter the bot api clientid string: ");
        String newclientid = System.console().readLine().trim();

        TwitchAPIv3.instance().SetClientID(newclientid);
        clientid = newclientid;

        changed = true;
    }

    if (message.equals("baseport")) {
        com.gmt2001.Console.out.print("Please enter a new base port: ");
        String newbaseport = System.console().readLine().trim();

        baseport = Integer.parseInt(newbaseport);

        changed = true;
    }

    if (message.equals("ip")) {
        com.gmt2001.Console.out.print("Please enter an IP address to bind to: ");
        String ipstr = System.console().readLine().trim();
        try {
            InetAddress newip = InetAddress.getByName(ipstr);
            ip = newip;
            changed = true;
        } catch (UnknownHostException e) {
            com.gmt2001.Console.out.print("Error binding to IP address, please double check your IP entry.");
            return;
        }
    }
    if (message.equals("youtubekey")) {
        com.gmt2001.Console.out.print("Please enter a new YouTube API key: ");
        String newyoutubekey = System.console().readLine().trim();

        YouTubeAPIv3.instance().SetAPIKey(newyoutubekey);
        youtubekey = newyoutubekey;

        changed = true;
    }

    if (message.equals("twitchalerts")) {
        com.gmt2001.Console.out.print("Please enter a new TwitchAlerts Access Token: ");
        String newtwitchalertstoken = System.console().readLine().trim();

        DonationHandlerAPI.instance().SetAccessToken(newtwitchalertstoken, "twitchalerts");
        twitchalertstoken = newtwitchalertstoken;

        changed = true;
    }
    if (message.equals("lastfm")) {
        com.gmt2001.Console.out.print("Please enter a last.fm username: ");
        String newlastfmuser = System.console().readLine().trim();

        LastFMAPI.instance().SetUsername(newlastfmuser);
        lastfmuser = newlastfmuser;

        changed = true;
    }
    if (message.equals("tipeeestream")) {
        com.gmt2001.Console.out.print("Please enter a new Tipeeestream Access Token: ");
        String newtpetoken = System.console().readLine().trim();

        DonationHandlerAPI.instance().SetAccessToken(newtpetoken, "tpestream");
        tpetoken = newtpetoken;

        changed = true;
    }
    if (message.equals("twitter")) {
        com.gmt2001.Console.out
                .print("Please visit this url to grant QuorraBot twitter access, then enter your pin" + "\n");
        com.gmt2001.Console.out.print(TwitterAPI.instance().getRequestTokenURL() + "\n");
        com.gmt2001.Console.out.print("Twitter PIN:");

        String newtwittertoken = System.console().readLine().trim();

        TwitterAPI.instance().CreateAccessToken(newtwittertoken);
        twittertoken = TwitterAPI.instance().getAccessToken();
        twittertokensecret = TwitterAPI.instance().getAccessTokenSecret();

        changed = true;
    }

    if (message.equals("streamtip")) {
        com.gmt2001.Console.out.print("Please enter a new StreamTip Client ID: ");
        String newstreamtipid = System.console().readLine().trim();

        DonationHandlerAPI.instance().SetClientID(newstreamtipid, "streamtip");
        streamtipid = newstreamtipid;

        com.gmt2001.Console.out.print("Please enter a new StreamTip Access Token: ");
        String newstreamtiptoken = System.console().readLine().trim();

        DonationHandlerAPI.instance().SetAccessToken(newstreamtiptoken, "streamtip");
        streamtiptoken = newstreamtiptoken;

        changed = true;
    }

    if (message.equals("gamewisp")) {
        com.gmt2001.Console.out.print("Please enter a new GameWisp Access Token: ");
        String newgamewispauth = System.console().readLine().trim();
        gamewispauth = newgamewispauth;
        GameWispAPI.instance().SetAccessToken(gamewispauth);
        SingularityAPI.instance().setAccessToken(gamewispauth);

        com.gmt2001.Console.out.print("Please enter a new GameWisp Refresh Token: ");
        String newgamewisprefresh = System.console().readLine().trim();

        gamewisprefresh = newgamewisprefresh;
        GameWispAPI.instance().SetRefreshToken(gamewisprefresh);
        doRefreshGameWispToken();
        changed = true;
    }

    if (message.equals("discord")) {
        com.gmt2001.Console.out.print("Please enter a new Discord Access Token: ");
        String newdiscordtoken = System.console().readLine().trim();
        discordToken = newdiscordtoken;

        com.gmt2001.Console.out.print("Please enter the name of the discord channel for the bot to join: ");
        String newdiscordmainchannel = System.console().readLine().trim();
        discordMainChannel = newdiscordmainchannel;
        changed = true;
    }

    if (message.equals("testgwrefresh")) {
        com.gmt2001.Console.out.println("[CONSOLE] Executing testgwrefresh");
        updateGameWispTokens(GameWispAPI.instance().refreshToken());
        changed = true;
    }

    if (message.equals("testgwsub")) {
        com.gmt2001.Console.out.println("[CONSOLE] Executing testgwsub");
        EventBus.instance().post(new GameWispSubscribeEvent(this.username, 1));
        return;
    }

    if (message.equals("testgwresub")) {
        com.gmt2001.Console.out.println("[CONSOLE] Executing testgwresub");
        EventBus.instance().post(new GameWispAnniversaryEvent(this.username, 2, 3));
        return;
    }

    if (message.equals("webenable")) {
        com.gmt2001.Console.out.print(
                "Please note that the music server will also be disabled if the web server is disabled. The bot will require a restart for this to take effect. Type true or false to enable/disable web server: ");
        String newwebenable = System.console().readLine().trim();
        changed = true;

        if (newwebenable.equalsIgnoreCase("1") || newwebenable.equalsIgnoreCase("true")) {
            webenable = true;
        } else {
            webenable = false;
        }
    }

    if (message.equals("musicenable")) {
        if (!webenable) {
            com.gmt2001.Console.out.println("Web server must be enabled first. ");
        } else {
            com.gmt2001.Console.out.print(
                    "The bot will require a restart for this to take effect. Please type true or false to enable/disable music server: ");
            String newmusicenable = System.console().readLine().trim();
            changed = true;

            if (newmusicenable.equalsIgnoreCase("1") || newmusicenable.equalsIgnoreCase("true")) {
                musicenable = true;
            } else {
                musicenable = false;
            }
        }
    }

    if (changed) {
        try {
            String data = "";
            data += "user=" + username + "\r\n";
            data += "oauth=" + oauth + "\r\n";
            data += "apioauth=" + apioauth + "\r\n";
            data += "clientid=" + clientid + "\r\n";
            data += "webauth=" + webauth + "\r\n";
            data += "webauthro=" + webauthro + "\r\n";
            data += "owner=" + ownerName + "\r\n";
            data += "channel=" + channelName + "\r\n";
            data += "baseport=" + baseport + "\r\n";
            data += "ip=" + ip.getHostAddress() + "\r\n";
            data += "hostname=" + hostname + "\r\n";
            data += "port=" + port + "\r\n";
            data += "msglimit30=" + msglimit30 + "\r\n";
            data += "datastore=" + datastore + "\r\n";
            data += "youtubekey=" + youtubekey + "\r\n";
            data += "twitchalertstoken=" + twitchalertstoken + "\r\n";
            data += "gamewispauth=" + gamewispauth + "\r\n";
            data += "gamewisprefresh=" + gamewisprefresh + "\r\n";
            data += "lastfmuser=" + lastfmuser + "\r\n";
            data += "tpetoken=" + tpetoken + "\r\n";
            data += "twittertoken=" + twittertoken + "\r\n";
            data += "twittertokensecret=" + twittertokensecret + "\r\n";
            data += "streamtiptoken=" + streamtiptoken + "\r\n";
            data += "streamtipid=" + streamtipid + "\r\n";
            data += "webenable=" + webenable + "\r\n";
            data += "musicenable=" + musicenable + "\r\n";
            data += "usehttps=" + usehttps + "\r\n";
            data += "logtimezone=" + timeZone + "\r\n";
            data += "mysqlhost=" + mySqlHost + "\r\n";
            data += "mysqlport=" + mySqlPort + "\r\n";
            data += "mysqlname=" + mySqlName + "\r\n";
            data += "mysqluser=" + mySqlUser + "\r\n";
            data += "mysqlpass=" + mySqlPass + "\r\n";
            data += "keystorepath=" + keystorepath + "\r\n";
            data += "discordtoken=" + discordToken + "\r\n";
            data += "discordmainchannel=" + discordMainChannel + "\r\n";

            Files.write(Paths.get("./botlogin.txt"), data.getBytes(StandardCharsets.UTF_8),
                    StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);

            SingularityAPI.instance().setAccessToken(gamewispauth);

            if (webenable) {
                com.gmt2001.Console.out.println("[SHUTDOWN] Terminating web server...");
                eventsocketserver.dispose();
                if (musicenable) {
                    com.gmt2001.Console.out.println("[SHUTDOWN] Terminating music server...");
                    musicsocketserver.dispose();
                }
                httpserver.dispose();

                startWebServices();
            }
            if (!discordToken.isEmpty()) {
                DiscordAPI.instance().reconnect();
                connectDiscord();
            }

            com.gmt2001.Console.out.println(
                    "Changes have been saved! Some changes may only take place after QuorraBot is restarted.");
        } catch (IOException ex) {
            com.gmt2001.Console.err.printStackTrace(ex);
        }
    }

    if (message.equals("save")) {
        dataStoreObj.SaveAll(true);
    }

    if (message.equals("quicksave")) {
        dataStoreObj.SaveChangedNow();
    }

    if (message.equals("exit")) {
        System.exit(0);
    }
    Map<String, String> tags = new HashMap<>();
    handleCommand(username, message, tags, channel, ownerName);
}

From source file:me.gloriouseggroll.quorrabot.Quorrabot.java

public static void main(String[] args) throws IOException {
    String user = "";
    String oauth = "";
    String apioauth = "";
    String channelName = "";
    String webauth = "";
    String webauthro = "";
    String clientid = "";
    String owner = "";
    String hostname = "";
    int baseport = 25300;
    InetAddress ip = InetAddress.getByName("127.0.0.1");
    int port = 0;
    double msglimit30 = 18.75;
    String datastore = "";
    String datastoreconfig = "";
    String youtubekey = "";
    String gamewispauth = "";
    String gamewisprefresh = "";
    String twitchalertstoken = "";
    String lastfmuser = "";
    String tpetoken = "";
    String twittertoken = "";
    String twittertokensecret = "";
    String streamtiptoken = "";
    String streamtipid = "";
    boolean webenable = true;
    boolean musicenable = true;
    boolean usehttps = false;
    String keystorepath = "";
    String keystorepassword = "";
    String timeZone = "";
    String mySqlConn = "";
    String mySqlHost = "";
    String mySqlPort = "";
    String mySqlName = "";
    String mySqlUser = "";
    String mySqlPass = "";
    FollowersCache followersCache;/*from www .  ja v a 2 s. c o m*/
    ChannelUsersCache channelUsersCache;
    ChannelHostCache hostCache;
    SubscribersCache subscribersCache;
    String discordToken = "";
    String discordMainChannel = "";

    boolean changed = false;

    try {
        if (new File("./botlogin.txt").exists()) {
            String data = FileUtils.readFileToString(new File("./botlogin.txt"));
            String[] lines = data.replaceAll("\\r", "").split("\\n");

            for (String line : lines) {

                if (line.startsWith("logtimezone=") && line.length() >= 15) {
                    timeZone = line.substring(12);
                }
                if (line.startsWith("websocketircab")) {
                    Quorrabot.webSocketIRCAB = true;
                }
                if (line.startsWith("user=") && line.length() > 8) {
                    user = line.substring(5);
                }
                if (line.startsWith("oauth=") && line.length() > 9) {
                    oauth = line.substring(6);
                }
                if (line.startsWith("apioauth=") && line.length() > 12) {
                    apioauth = line.substring(9);
                }
                if (line.startsWith("clientid=") && line.length() > 12) {
                    clientid = line.substring(9);
                }
                if (line.startsWith("channel=") && line.length() > 11) {
                    channelName = line.substring(8);
                }
                if (line.startsWith("owner=") && line.length() > 9) {
                    owner = line.substring(6);
                }
                if (line.startsWith("baseport=") && line.length() > 10) {
                    baseport = Integer.parseInt(line.substring(9));
                }
                if (line.startsWith("ip=") && line.length() > 4) {
                    ip = InetAddress.getByName(line.substring(3));
                }
                if (line.startsWith("hostname=") && line.length() > 10) {
                    hostname = line.substring(9);
                }
                if (line.startsWith("port=") && line.length() > 6) {
                    port = Integer.parseInt(line.substring(5));
                }
                if (line.startsWith("msglimit30=") && line.length() > 12) {
                    msglimit30 = Double.parseDouble(line.substring(11));
                }
                if (line.startsWith("datastore=") && line.length() > 11) {
                    datastore = line.substring(10);
                }
                if (line.startsWith("youtubekey=") && line.length() > 12) {
                    youtubekey = line.substring(11);
                }
                if (line.startsWith("gamewispauth=") && line.length() > 14) {
                    gamewispauth = line.substring(13);
                }
                if (line.startsWith("gamewisprefresh=") && line.length() > 17) {
                    gamewisprefresh = line.substring(16);
                }
                if (line.startsWith("twitchalertstoken=") && line.length() > 19) {
                    twitchalertstoken = line.substring(18);
                }
                if (line.startsWith("lastfmuser=") && line.length() > 12) {
                    lastfmuser = line.substring(11);
                }
                if (line.startsWith("tpetoken=") && line.length() > 10) {
                    tpetoken = line.substring(9);
                }
                if (line.startsWith("twittertoken=") && line.length() > 14) {
                    twittertoken = line.substring(13);
                }
                if (line.startsWith("twittertokensecret=") && line.length() > 20) {
                    twittertokensecret = line.substring(19);
                }
                if (line.startsWith("streamtiptoken=") && line.length() > 16) {
                    streamtiptoken = line.substring(15);
                }
                if (line.startsWith("streamtipid=") && line.length() > 13) {
                    streamtipid = line.substring(12);
                }
                if (line.startsWith("webenable=") && line.length() > 11) {
                    webenable = Boolean.valueOf(line.substring(10));
                }
                if (line.startsWith("musicenable=") && line.length() > 13) {
                    musicenable = Boolean.valueOf(line.substring(12));
                }
                if (line.startsWith("usehttps=") && line.length() > 10) {
                    usehttps = Boolean.valueOf(line.substring(9));
                }
                if (line.startsWith("mysqlhost=") && line.length() > 11) {
                    mySqlHost = line.substring(10);
                }
                if (line.startsWith("mysqlport=") && line.length() > 11) {
                    mySqlPort = line.substring(10);
                }
                if (line.startsWith("mysqlname=") && line.length() > 11) {
                    mySqlName = line.substring(10);
                }
                if (line.startsWith("mysqluser=") && line.length() > 11) {
                    mySqlUser = line.substring(10);
                }
                if (line.startsWith("mysqlpass=") && line.length() > 11) {
                    mySqlPass = line.substring(10);
                }
                if (line.startsWith("keystorepath=") && line.length() > 14) {
                    keystorepath = line.substring(13);
                }
                if (line.startsWith("keystorepassword=") && line.length() > 18) {
                    keystorepassword = line.substring(17);
                }
                if (line.startsWith("webauth=") && line.length() > 9) {
                    webauth = line.substring(8);
                }
                if (line.startsWith("webauthro=") && line.length() > 11) {
                    webauthro = line.substring(10);
                }
                if (line.startsWith("discordtoken=") && line.length() >= 14) {
                    discordToken = line.substring(13);
                }
                if (line.startsWith("discordmainchannel=") && line.length() >= 20) {
                    discordMainChannel = line.substring(19);
                }
            }
        }
    } catch (IOException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    }

    /**
     * Check to see if there's a soundboardauth set
     */
    if (webauth.isEmpty()) {
        webauth = generateWebAuth();
        com.gmt2001.Console.debug.println("New webauth key has been generated for botlogin.txt");
        changed = true;
    }
    /**
     * Check to see if there's a soundboardauthread set
     */
    if (webauthro.isEmpty()) {
        webauthro = generateWebAuth();
        com.gmt2001.Console.debug.println("New webauth read-only key has been generated for botlogin.txt");
        changed = true;
    }

    try {
        if (user.isEmpty()) {
            com.gmt2001.Console.out.print("Please enter the bot's twitch username: ");
            user = System.console().readLine().trim().toLowerCase();
            changed = true;
        }
        if (oauth.isEmpty()) {
            com.gmt2001.Console.out.println(
                    "Visit http://quorrabot.com/pages/twitchapi/ to generate oAuth tokens for both the bot and the channel owner accounts (including 'oauth:') & type it below.");
            com.gmt2001.Console.out
                    .println("IMPORTANT: This MUST be done while logged in as the BOT account!" + "\n");
            com.gmt2001.Console.out.println("Please enter the bot's tmi oauth token: ");
            oauth = System.console().readLine().trim();
            changed = true;
        }
        if (channelName.isEmpty()) {
            com.gmt2001.Console.out.print(
                    "Please enter the name of the twitch channel the bot should join (not the url, just the name): ");
            channelName = System.console().readLine().trim().toLowerCase();
            changed = true;
        }
        if (apioauth.isEmpty()) {
            com.gmt2001.Console.out.println(
                    "Visit http://quorrabot.com/pages/twitchapi/ to generate oAuth tokens for both the bot and the channel owner accounts (including 'oauth:') & type it below.");
            com.gmt2001.Console.out.println(
                    "IMPORTANT: This MUST be done while logged in on the CHANNEL OWNER account!" + "\n");
            com.gmt2001.Console.out.println("Please enter the channel owner's tmi oauth token: ");
            apioauth = System.console().readLine().trim();
            changed = true;
        }
    } catch (NullPointerException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    }

    if (owner.isEmpty()) {
        owner = channelName;

        changed = true;
    }

    if (args.length > 0) {
        for (String arg : args) {
            if (arg.equalsIgnoreCase("printlogin")) {
                com.gmt2001.Console.out.println("user='" + user + "'");
                com.gmt2001.Console.out.println("oauth='" + oauth + "'");
                com.gmt2001.Console.out.println("apioauth='" + apioauth + "'");
                com.gmt2001.Console.out.println("clientid='" + clientid + "'");
                com.gmt2001.Console.out.println("channel='" + channelName + "'");
                com.gmt2001.Console.out.println("owner='" + owner + "'");
                com.gmt2001.Console.out.println("baseport='" + baseport + "'");
                com.gmt2001.Console.out.println("ip='" + ip.getHostAddress() + "'");
                com.gmt2001.Console.out.println("hostname='" + hostname + "'");
                com.gmt2001.Console.out.println("port='" + port + "'");
                com.gmt2001.Console.out.println("msglimit30='" + msglimit30 + "'");
                com.gmt2001.Console.out.println("datastore='" + datastore + "'");
                com.gmt2001.Console.out.println("youtubekey='" + youtubekey + "'");
                com.gmt2001.Console.out.println("gamewispauth=" + gamewispauth + "'");
                com.gmt2001.Console.out.println("gamewisprefresh=" + gamewisprefresh + "'");
                com.gmt2001.Console.out.println("twitchalertstoken='" + twitchalertstoken + "'");
                com.gmt2001.Console.out.println("lastfmuser='" + lastfmuser + "'");
                com.gmt2001.Console.out.println("tpetoken='" + tpetoken + "'");
                com.gmt2001.Console.out.println("twittertoken='" + twittertoken + "'");
                com.gmt2001.Console.out.println("twittertokensecret='" + twittertokensecret + "'");
                com.gmt2001.Console.out.println("streamtiptoken='" + streamtiptoken + "'");
                com.gmt2001.Console.out.println("streamtipid='" + streamtipid + "'");
                com.gmt2001.Console.out.println("webenable=" + webenable);
                com.gmt2001.Console.out.println("musicenable=" + musicenable);
                com.gmt2001.Console.out.println("usehttps=" + usehttps);
                com.gmt2001.Console.out.println("keystorepath='" + keystorepath + "'");
                com.gmt2001.Console.out.println("keystorepassword='" + keystorepassword + "'");
                com.gmt2001.Console.out.println("discordtoken='" + discordToken + "'");
                com.gmt2001.Console.out.println("discordmainchannel='" + discordMainChannel + "'");
            }
            if (arg.equalsIgnoreCase("debugon")) {
                Quorrabot.enableDebugging = true;
            }
            if (arg.equalsIgnoreCase("ini2sqlite")) {
                com.gmt2001.Console.out.println("Converting default IniStore to default SqliteStore...");
                ini2sqlite(false);
                com.gmt2001.Console.out.println("Operation complete. The bot will now exit");
                System.exit(0);
                return;
            }
            if (arg.toLowerCase().startsWith("user=") && arg.length() > 8) {
                if (!user.equals(arg.substring(5))) {
                    user = arg.substring(5).toLowerCase();
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("oauth=") && arg.length() > 9) {
                if (!oauth.equals(arg.substring(6))) {
                    oauth = arg.substring(6);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("apioauth=") && arg.length() > 12) {
                if (!apioauth.equals(arg.substring(9))) {
                    apioauth = arg.substring(9);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("mysqlhost=") && arg.length() > 11) {
                if (!mySqlHost.equals(arg.substring(10))) {
                    mySqlHost = arg.substring(10);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("mysqlport=") && arg.length() > 11) {
                if (!mySqlPort.equals(arg.substring(10))) {
                    mySqlPort = arg.substring(10);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("mysqlname=") && arg.length() > 11) {
                if (!mySqlName.equals(arg.substring(10))) {
                    mySqlName = arg.substring(10);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("mysqluser=") && arg.length() > 11) {
                if (!mySqlUser.equals(arg.substring(14))) {
                    mySqlUser = arg.substring(10);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("mysqlpass=") && arg.length() > 11) {
                if (!mySqlPass.equals(arg.substring(10))) {
                    mySqlPass = arg.substring(10);
                    changed = true;
                }
            }

            if (arg.toLowerCase().startsWith("clientid=") && arg.length() > 12) {
                if (!clientid.equals(arg.substring(9))) {
                    clientid = arg.substring(9);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("channel=") && arg.length() > 11) {
                if (!channelName.equals(arg.substring(8))) {
                    channelName = arg.substring(8).toLowerCase();
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("owner=") && arg.length() > 9) {
                if (!owner.equals(arg.substring(6))) {
                    owner = arg.substring(6).toLowerCase();
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("baseport=") && arg.length() > 10) {
                if (baseport != Integer.parseInt(arg.substring(9))) {
                    baseport = Integer.parseInt(arg.substring(9));
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("ip=") && arg.length() > 4) {
                if (ip != InetAddress.getByName(arg.substring(3))) {
                    ip = InetAddress.getByName(arg.substring(3));
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("hostname=") && arg.length() > 10) {
                if (!hostname.equals(arg.substring(9))) {
                    hostname = arg.substring(9);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("port=") && arg.length() > 6) {
                if (port != Integer.parseInt(arg.substring(5))) {
                    port = Integer.parseInt(arg.substring(5));
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("msglimit30=") && arg.length() > 12) {
                if (msglimit30 != Double.parseDouble(arg.substring(11))) {
                    msglimit30 = Double.parseDouble(arg.substring(11));
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("datastore=") && arg.length() > 11) {
                if (!datastore.equals(arg.substring(10))) {
                    datastore = arg.substring(10);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("datastoreconfig=") && arg.length() > 17) {
                datastoreconfig = arg.substring(16);
            }
            if (arg.toLowerCase().startsWith("youtubekey=") && arg.length() > 12) {
                if (!youtubekey.equals(arg.substring(11))) {
                    youtubekey = arg.substring(11);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("gamewispauth=") && arg.length() > 14) {
                if (!gamewispauth.equals(arg.substring(13))) {
                    gamewispauth = arg.substring(13);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("gamewisprefresh=") && arg.length() > 17) {
                if (!gamewisprefresh.equals(arg.substring(16))) {
                    gamewisprefresh = arg.substring(16);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("twitchalertstoken=") && arg.length() > 19) {
                if (!twitchalertstoken.equals(arg.substring(18))) {
                    twitchalertstoken = arg.substring(18);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("lastfmuser=") && arg.length() > 12) {
                if (!lastfmuser.equals(arg.substring(11))) {
                    lastfmuser = arg.substring(11);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("tpetoken=") && arg.length() > 10) {
                if (!tpetoken.equals(arg.substring(9))) {
                    tpetoken = arg.substring(9);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("twittertoken=") && arg.length() > 14) {
                if (!twittertoken.equals(arg.substring(13))) {
                    twittertoken = arg.substring(13);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("twittertokensecret=") && arg.length() > 20) {
                if (!twittertokensecret.equals(arg.substring(19))) {
                    twittertokensecret = arg.substring(19);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("streamtiptoken=") && arg.length() > 16) {
                if (!streamtiptoken.equals(arg.substring(15))) {
                    streamtiptoken = arg.substring(15);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("streamtipid=") && arg.length() > 13) {
                if (!streamtipid.equals(arg.substring(12))) {
                    streamtipid = arg.substring(12);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("webenable=") && arg.length() > 11) {
                if (webenable != Boolean.valueOf(arg.substring(10))) {
                    webenable = Boolean.valueOf(arg.substring(10));
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("musicenable=") && arg.length() > 13) {
                if (musicenable != Boolean.valueOf(arg.substring(12))) {
                    musicenable = Boolean.valueOf(arg.substring(12));
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("usehttps=") && arg.length() > 10) {
                if (usehttps != Boolean.valueOf(arg.substring(9))) {
                    usehttps = Boolean.valueOf(arg.substring(9));
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("keystorepath=") && arg.length() > 14) {
                if (!keystorepath.equals(arg.substring(13))) {
                    keystorepath = arg.substring(13);
                    changed = true;
                }
            }
            if (arg.toLowerCase().startsWith("keystorepassword=") && arg.length() > 18) {
                if (!keystorepassword.equals(arg.substring(17))) {
                    keystorepassword = arg.substring(17);
                    changed = true;
                }
            }

            if (arg.equalsIgnoreCase("help") || arg.equalsIgnoreCase("--help") || arg.equalsIgnoreCase("-h")
                    || arg.equalsIgnoreCase("-?")) {
                com.gmt2001.Console.out.println(
                        "Usage: java -Dfile.encoding=UTF-8 -jar QuorraBot.jar [printlogin] [user=<bot username>] "
                                + "[oauth=<bot irc oauth>] [apioauth=<editor oauth>] [clientid=<oauth clientid>] [channel=<channel to join>] "
                                + "[owner=<bot owner username>] [baseport=<bot webserver port, music server will be +1>] [ip=<IP address (optional) to bind to>] [hostname=<custom irc server>] "
                                + "[port=<custom irc port>] [msglimit30=<message limit per 30 seconds>] "
                                + "[datastore=<DataStore type, for a list, run java -jar QuorraBot.jar storetypes>] "
                                + "[datastoreconfig=<Optional DataStore config option, different for each DataStore type>] "
                                + "[youtubekey=<youtube api key>] [webenable=<true | false>] [musicenable=<true | false>] "
                                + "[gamewispauth=<gamewisp oauth>] "
                                + "[gamewisprefresh=<gamewisp refresh key>] "
                                + "[twitchalertstoken=<TwitchAlerts access token>] "
                                + "[lastfmuser=<Last.FM username>] " + "[tpetoken=<Tipeeestream access token>] "
                                + "[streamtiptoken=<StreamTip access token>] "
                                + "[streamtipid=<StreamTip Client ID>] "
                                + "[twittertoken=<Twitter access token>] "
                                + "[twittertokensecret=<Twitter access token secret>]");

                return;
            }
            if (arg.equalsIgnoreCase("storetypes")) {
                com.gmt2001.Console.out.println(
                        "DataStore types: IniStore (datastoreconfig parameter is folder name, stores in .ini files), "
                                + "TempStore (Stores in memory, lost on shutdown), "
                                + "SqliteStore (Default, Stores in a SQLite3 database, datastoreconfig parameter is a config file");
                return;
            }
        }
    }

    if (changed) {
        String data = "";
        data += "user=" + user + "\r\n";
        data += "oauth=" + oauth + "\r\n";
        data += "apioauth=" + apioauth + "\r\n";
        data += "clientid=" + clientid + "\r\n";
        data += "webauth=" + webauth + "\r\n";
        data += "webauthro=" + webauthro + "\r\n";
        data += "channel=" + channelName + "\r\n";
        data += "owner=" + owner + "\r\n";
        data += "baseport=" + baseport + "\r\n";
        data += "ip=" + ip.getHostAddress() + "\r\n";
        data += "hostname=" + hostname + "\r\n";
        data += "port=" + port + "\r\n";
        data += "msglimit30=" + msglimit30 + "\r\n";
        data += "datastore=" + datastore + "\r\n";
        data += "youtubekey=" + youtubekey + "\r\n";
        data += "gamewispauth=" + gamewispauth + "\r\n";
        data += "gamewisprefresh=" + gamewisprefresh + "\r\n";
        data += "twitchalertstoken=" + twitchalertstoken + "\r\n";
        data += "lastfmuser=" + lastfmuser + "\r\n";
        data += "tpetoken=" + tpetoken + "\r\n";
        data += "twittertoken=" + twittertoken + "\r\n";
        data += "twittertokensecret=" + twittertokensecret + "\r\n";
        data += "streamtiptoken=" + streamtiptoken + "\r\n";
        data += "streamtipid=" + streamtipid + "\r\n";
        data += "webenable=" + webenable + "\r\n";
        data += "musicenable=" + musicenable + "\r\n";
        data += "usehttps=" + usehttps + "\r\n";
        data += "logtimezone=" + timeZone + "\r\n";
        data += "mysqlhost=" + mySqlHost + "\r\n";
        data += "mysqlport=" + mySqlPort + "\r\n";
        data += "mysqlname=" + mySqlName + "\r\n";
        data += "mysqluser=" + mySqlUser + "\r\n";
        data += "mysqlpass=" + mySqlPass + "\r\n";
        data += "keystorepath=" + keystorepath + "\r\n";
        data += "keystorepassword=" + keystorepassword + "\r\n";
        data += "discordtoken=" + discordToken + "\r\n";
        data += "discordmainchannel=" + discordMainChannel;

        Files.write(Paths.get("./botlogin.txt"), data.getBytes(StandardCharsets.UTF_8),
                StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
    }
    channelUsersCache = ChannelUsersCache.instance(owner);
    followersCache = FollowersCache.instance(owner);
    hostCache = ChannelHostCache.instance(owner);
    subscribersCache = SubscribersCache.instance(owner);

    Quorrabot.instance = new Quorrabot(user, oauth, apioauth, clientid, channelName, owner, baseport, ip,
            hostname, port, msglimit30, datastore, datastoreconfig, youtubekey, gamewispauth, gamewisprefresh,
            twitchalertstoken, lastfmuser, tpetoken, twittertoken, twittertokensecret, streamtiptoken,
            streamtipid, webenable, webauth, webauthro, musicenable, usehttps, timeZone, mySqlHost, mySqlPort,
            mySqlConn, mySqlPass, mySqlUser, mySqlName, keystorepath, followersCache, hostCache,
            channelUsersCache, subscribersCache, discordToken, discordMainChannel);
}

From source file:me.gloriouseggroll.quorrabot.Quorrabot.java

/**
 *
 * @param newTokens//from  w w w.j a  v a 2  s . co  m
 */
public void updateGameWispTokens(String[] newTokens) {
    String data = "";
    data += "user=" + username + "\r\n";
    data += "oauth=" + oauth + "\r\n";
    data += "apioauth=" + apioauth + "\r\n";
    data += "webauth=" + webauth + "\r\n";
    data += "webauthro=" + webauthro + "\r\n";
    data += "clientid=" + clientid + "\r\n";
    data += "channel=" + channelName + "\r\n";
    data += "owner=" + ownerName + "\r\n";
    data += "baseport=" + baseport + "\r\n";
    data += "ip=" + ip.getHostAddress() + "\r\n";
    data += "hostname=" + hostname + "\r\n";
    data += "port=" + port + "\r\n";
    data += "msglimit30=" + msglimit30 + "\r\n";
    data += "datastore=" + datastore + "\r\n";
    data += "youtubekey=" + youtubekey + "\r\n";
    data += "gamewispauth=" + newTokens[0] + "\r\n";
    data += "gamewisprefresh=" + newTokens[1] + "\r\n";
    data += "twitchalertstoken=" + twitchalertstoken + "\r\n";
    data += "lastfmuser=" + lastfmuser + "\r\n";
    data += "tpetoken=" + tpetoken + "\r\n";
    data += "twittertoken=" + twittertoken + "\r\n";
    data += "twittertokensecret=" + twittertokensecret + "\r\n";
    data += "streamtiptoken=" + streamtiptoken + "\r\n";
    data += "streamtipid=" + streamtipid + "\r\n";
    data += "webenable=" + webenable + "\r\n";
    data += "musicenable=" + musicenable + "\r\n";
    data += "usehttps=" + usehttps + "\r\n";
    data += "logtimezone=" + timeZone + "\r\n";
    data += "mysqlhost=" + mySqlHost + "\r\n";
    data += "mysqlport=" + mySqlPort + "\r\n";
    data += "mysqlname=" + mySqlName + "\r\n";
    data += "mysqluser=" + mySqlUser + "\r\n";
    data += "mysqlpass=" + mySqlPass + "\r\n";
    data += "keystorepath=" + keystorepath + "\r\n";
    data += "discordtoken=" + discordToken + "\r\n";
    data += "discordmainchannel=" + discordMainChannel;

    try {
        Files.write(Paths.get("./botlogin.txt"), data.getBytes(StandardCharsets.UTF_8),
                StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
        com.gmt2001.Console.out.println("GameWisp Token has been refreshed.");
    } catch (IOException ex) {
        com.gmt2001.Console.err.println(
                "!!!! CRITICAL !!!! Failed to update GameWisp Refresh Tokens into botlogin.txt! Must manually add!");
        com.gmt2001.Console.err.println(
                "!!!! CRITICAL !!!! gamewispauth = " + newTokens[0] + " gamewisprefresh = " + newTokens[1]);
    }

    SingularityAPI.instance().setAccessToken(gamewispauth);

}