Example usage for java.util Properties store

List of usage examples for java.util Properties store

Introduction

In this page you can find the example usage for java.util Properties store.

Prototype

public void store(OutputStream out, String comments) throws IOException 

Source Link

Document

Writes this property list (key and element pairs) in this Properties table to the output stream in a format suitable for loading into a Properties table using the #load(InputStream) load(InputStream) method.

Usage

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

@Subscribe
public void consoleInput(ConsoleInputEvent event) {
    String message = event.getMsg();
    Boolean changed = false;/*from w ww. j a  v a 2  s  .  c om*/
    Boolean reset = false;
    String arguments;
    String[] argument = null;

    /* Check to see if the message is null or has nothing in it */
    if (message == null || message.isEmpty()) {
        return;
    }

    /* Check for arguments */
    if (message.contains(" ")) {
        String messageString = message;
        message = messageString.substring(0, messageString.indexOf(" "));
        arguments = messageString.substring(messageString.indexOf(" ") + 1);
        argument = arguments.split(" ");
    }

    if (message.equalsIgnoreCase("ankhtophantombot")) {
        print("Not all of AnkhBot's data will be compatible with PhantomBot.");
        print("This process will take a long time.");
        print("Are you sure you want to convert AnkhBot's data to PhantomBot? [y/n]");
        String check = System.console().readLine().trim();
        if (check.equals("y")) {
            AnkhConverter.instance();
        } else {
            print("No changes were made.");
            return;
        }
    }

    if (message.equalsIgnoreCase("backupdb")) {
        SimpleDateFormat datefmt = new SimpleDateFormat("ddMMyyyy.hhmmss");
        datefmt.setTimeZone(TimeZone.getTimeZone(timeZone));
        String timestamp = datefmt.format(new Date());

        dataStore.backupSQLite3("phantombot.manual.backup." + timestamp + ".db");
        return;
    }

    /* Update the followed (followers) table. */
    if (message.equalsIgnoreCase("fixfollowedtable")) {
        TwitchAPIv3.instance().FixFollowedTable(channelName, dataStore, false);
        return;
    }

    /* Update the followed (followers) table - forced. */
    if (message.equalsIgnoreCase("fixfollowedtable-force")) {
        TwitchAPIv3.instance().FixFollowedTable(channelName, dataStore, true);
        return;
    }

    if (message.equalsIgnoreCase("jointest")) {
        for (int i = 0; i < 30; i++) {
            EventBus.instance()
                    .postAsync(new IrcChannelJoinEvent(this.session, this.channel, generateRandomString(8)));
        }
    }

    /* tests a follow event */
    if (message.equalsIgnoreCase("followertest")) {
        String randomUser = generateRandomString(10);
        print("[CONSOLE] Executing followertest (User: " + randomUser + ")");
        EventBus.instance()
                .postAsync(new TwitchFollowEvent(randomUser, PhantomBot.getChannel(this.channelName)));
        return;
    }

    /* tests multiple follows */
    if (message.equalsIgnoreCase("followerstest")) {
        String randomUser = generateRandomString(10);
        int followCount = 5;

        if (argument != null) {
            followCount = Integer.parseInt(argument[0]);
        }

        print("[CONSOLE] Executing followerstest (Count: " + followCount + ", User: " + randomUser + ")");
        for (int i = 0; i < followCount; i++) {
            EventBus.instance().postAsync(
                    new TwitchFollowEvent(randomUser + "_" + i, PhantomBot.getChannel(this.channelName)));
        }
        return;
    }

    /* Test a subscriber event */
    if (message.equalsIgnoreCase("subscribertest")) {
        String randomUser = generateRandomString(10);
        print("[CONSOLE] Executing subscribertest (User: " + randomUser + ")");
        EventBus.instance().postAsync(new NewSubscriberEvent(PhantomBot.getSession(this.channelName),
                PhantomBot.getChannel(this.channelName), randomUser));
        return;
    }

    /* Test a prime subscriber event */
    if (message.equalsIgnoreCase("primesubscribertest")) {
        String randomUser = generateRandomString(10);
        print("[CONSOLE] Executing primesubscribertest (User: " + randomUser + ")");
        EventBus.instance().postAsync(new NewPrimeSubscriberEvent(PhantomBot.getSession(this.channelName),
                PhantomBot.getChannel(this.channelName), randomUser));
        return;
    }

    /* Test a resubscriber event */
    if (message.equalsIgnoreCase("resubscribertest")) {
        String randomUser = generateRandomString(10);
        print("[CONSOLE] Executing resubscribertest (User: " + randomUser + ")");
        EventBus.instance().postAsync(new NewReSubscriberEvent(PhantomBot.getSession(this.channelName),
                PhantomBot.getChannel(this.channelName), randomUser, "10"));
        return;
    }

    /* Test the online event */
    if (message.equalsIgnoreCase("onlinetest")) {
        print("[CONSOLE] Executing onlinetest");
        EventBus.instance().postAsync(new TwitchOnlineEvent(PhantomBot.getChannel(this.channelName)));
        return;
    }

    /* Test the offline event */
    if (message.equalsIgnoreCase("offlinetest")) {
        print("[CONSOLE] Executing offlinetest");
        EventBus.instance().postAsync(new TwitchOfflineEvent(PhantomBot.getChannel(this.channelName)));
        return;
    }

    /* Test the host event */
    if (message.equalsIgnoreCase("hosttest")) {
        print("[CONSOLE] Executing hosttest");
        EventBus.instance()
                .postAsync(new TwitchHostedEvent(this.botName, PhantomBot.getChannel(this.channelName)));
        return;
    }

    /* test the gamewisp subscriber event */
    if (message.equalsIgnoreCase("gamewispsubscribertest")) {
        print("[CONSOLE] Executing gamewispsubscribertest");
        EventBus.instance().postAsync(new GameWispSubscribeEvent(this.botName, 1));
        return;
    }

    /* test the gamewisp resubscriber event */
    if (message.equalsIgnoreCase("gamewispresubscribertest")) {
        print("[CONSOLE] Executing gamewispresubscribertest");
        EventBus.instance().postAsync(new GameWispAnniversaryEvent(this.botName, 2));
        return;
    }

    /* test the bits event */
    if (message.equalsIgnoreCase("bitstest")) {
        print("[CONSOLE] Executing bitstest");
        EventBus.instance().postAsync(new BitsEvent(PhantomBot.getSession(this.channelName),
                PhantomBot.getChannel(this.channelName), this.botName, "100"));
        return;
    }

    /* enables debug mode */
    if (message.equalsIgnoreCase("debugon")) {
        print("[CONSOLE] Executing debugon: Enable Debug Mode");
        PhantomBot.setDebugging(true);
        return;
    }

    /* disables debug mode - note that setDebuggingLogOnly() completely disables all debugging */
    if (message.equalsIgnoreCase("debugoff")) {
        print("[CONSOLE] Executing debugoff: Disable Debug Mode");
        PhantomBot.setDebuggingLogOnly(false);
        return;
    }

    /* enables debug mode - log only */
    if (message.equalsIgnoreCase("debuglog")) {
        print("[CONSOLE] Executing debuglog: Enable Debug Mode - Log Only");
        PhantomBot.setDebuggingLogOnly(true);
        return;
    }

    /* Reset the bot login */
    if (message.equalsIgnoreCase("reset")) {
        print("Are you sure you want to reset the bot login? [y/n]");
        String check = System.console().readLine().trim();
        if (check.equals("y")) {
            reset = true;
            changed = true;
        } else {
            print("No changes were made.");
            return;
        }
    }

    /* Change the apiOAuth token */
    if (message.equalsIgnoreCase("apioauth")) {
        System.out.print(
                "Please enter you're oauth token that you generated from https://phantombot.tv/oauth while logged as the caster: ");
        apiOAuth = System.console().readLine().trim();
        pbProperties.setProperty("apioauth", apiOAuth);
        changed = true;
    }

    /* Setup for MySql */
    if (message.equalsIgnoreCase("mysqlsetup")) {
        try {
            print("");
            print("PhantomBot MySQL setup.");
            print("");

            com.gmt2001.Console.out.print("Please enter your MySQL host name: ");
            mySqlHost = System.console().readLine().trim();
            pbProperties.setProperty("mysqlhost", mySqlHost);

            com.gmt2001.Console.out.print("Please enter your MySQL port: ");
            mySqlPort = System.console().readLine().trim();
            pbProperties.setProperty("mysqlport", mySqlPort);

            com.gmt2001.Console.out.print("Please enter your MySQL db name: ");
            mySqlName = System.console().readLine().trim();
            pbProperties.setProperty("mysqlname", mySqlName);

            com.gmt2001.Console.out.print("Please enter a username for MySQL: ");
            mySqlUser = System.console().readLine().trim();
            pbProperties.setProperty("mysqluser", mySqlUser);

            com.gmt2001.Console.out.print("Please enter a password for MySQL: ");
            mySqlPass = System.console().readLine().trim();
            pbProperties.setProperty("mysqlpass", mySqlPass);

            dataStoreType = "MySQLStore";
            pbProperties.setProperty("datastore", dataStoreType);

            print("PhantomBot MySQL setup done, PhantomBot will exit.");
            changed = true;
        } catch (NullPointerException ex) {
            com.gmt2001.Console.err.printStackTrace(ex);
        }
    }

    /* Setup for GameWisp */
    if (message.equalsIgnoreCase("gamewispsetup")) {
        try {
            print("");
            print("PhantomBot GameWisp setup.");
            print("");

            com.gmt2001.Console.out.print("Please enter your GameWisp OAuth key: ");
            gameWispOAuth = System.console().readLine().trim();
            pbProperties.setProperty("gamewispauth", gameWispOAuth);

            com.gmt2001.Console.out.print("Please enter your GameWisp refresh key: ");
            gameWispRefresh = System.console().readLine().trim();
            pbProperties.setProperty("gamewisprefresh", gameWispRefresh);

            print("PhantomBot GameWisp setup done, PhantomBot will exit.");
            changed = true;
        } catch (NullPointerException ex) {
            com.gmt2001.Console.err.printStackTrace(ex);
        }
    }

    /* Setup for StreamLabs (TwitchAlerts) */
    if (message.equalsIgnoreCase("streamlabssetup")) {
        try {
            print("");
            print("PhantomBot StreamLabs setup.");
            print("");

            com.gmt2001.Console.out.print("Please enter your StreamLabs OAuth key: ");
            twitchAlertsKey = System.console().readLine().trim();
            pbProperties.setProperty("twitchalertskey", twitchAlertsKey);

            print("PhantomBot StreamLabs setup done, PhantomBot will exit.");
            changed = true;
        } catch (NullPointerException ex) {
            com.gmt2001.Console.err.printStackTrace(ex);
        }
    }

    /* Setup for StreamTip */
    if (message.equalsIgnoreCase("streamtipsetup")) {
        try {
            print("");
            print("PhantomBot StreamTip setup.");
            print("");

            com.gmt2001.Console.out.print("Please enter your StreamTip Api OAuth: ");
            streamTipOAuth = System.console().readLine().trim();
            pbProperties.setProperty("streamtipkey", streamTipOAuth);

            com.gmt2001.Console.out.print("Please enter your StreamTip Client Id: ");
            streamTipClientId = System.console().readLine().trim();
            pbProperties.setProperty("streamtipid", streamTipClientId);

            print("PhantomBot StreamTip setup done, PhantomBot will exit.");
            changed = true;
        } catch (NullPointerException ex) {
            com.gmt2001.Console.err.printStackTrace(ex);
        }
    }

    /* Setup for TipeeeStream */
    if (message.equalsIgnoreCase("tipeeestreamsetup")) {
        try {
            print("");
            print("PhantomBot TipeeeStream setup.");
            print("");

            com.gmt2001.Console.out.print("Please enter your TipeeeStream Api OAuth: ");
            tipeeeStreamOAuth = System.console().readLine().trim();
            pbProperties.setProperty("tipeeestreamkey", tipeeeStreamOAuth);

            print("PhantomBot TipeeeStream setup done, PhantomBot will exit.");
            changed = true;
        } catch (NullPointerException ex) {
            com.gmt2001.Console.err.printStackTrace(ex);
        }
    }

    /* Setup the web panel login info */
    if (message.equalsIgnoreCase("panelsetup")) {
        try {
            print("");
            print("PhantomBot Web Panel setup.");
            print("Note: Do not use any ascii characters in your username of password.");
            print("");

            com.gmt2001.Console.out.print("Please enter a username of your choice: ");
            panelUsername = System.console().readLine().trim();
            pbProperties.setProperty("paneluser", panelUsername);

            com.gmt2001.Console.out.print("Please enter a password of your choice: ");
            panelPassword = System.console().readLine().trim();
            pbProperties.setProperty("panelpassword", panelPassword);

            print("PhantomBot Web Panel setup done, PhantomBot will exit.");
            changed = true;
        } catch (NullPointerException ex) {
            com.gmt2001.Console.err.printStackTrace(ex);
        }
    }

    /* Setup for Twitter */
    if (message.equalsIgnoreCase("twittersetup")) {
        try {
            print("");
            print("PhantomBot Twitter setup.");
            print("");

            com.gmt2001.Console.out.print("Please enter your Twitter username: ");
            twitterUsername = System.console().readLine().trim();
            pbProperties.setProperty("twitterUser", twitterUsername);

            com.gmt2001.Console.out.print("Please enter your consumer key: ");
            twitterConsumerToken = System.console().readLine().trim();
            pbProperties.setProperty("twitter_consumer_key", twitterConsumerToken);

            com.gmt2001.Console.out.print("Please enter your consumer secret: ");
            twitterConsumerSecret = System.console().readLine().trim();
            pbProperties.setProperty("twitter_consumer_secret", twitterConsumerSecret);

            com.gmt2001.Console.out.print("Please enter your access token: ");
            twitterAccessToken = System.console().readLine().trim();
            pbProperties.setProperty("twitter_access_token", twitterAccessToken);

            com.gmt2001.Console.out.print("Please enter your access token secret: ");
            twitterSecretToken = System.console().readLine().trim();
            pbProperties.setProperty("twitter_secret_token", twitterSecretToken);

            /* Delete the old Twitter file if it exists */
            try {
                File f = new File("./twitter.txt");
                f.delete();
            } catch (NullPointerException ex) {
                com.gmt2001.Console.debug.println(ex);
            }

            print("PhantomBot Twitter setup done, PhantomBot will exit.");
            changed = true;
        } catch (NullPointerException ex) {
            com.gmt2001.Console.err.printStackTrace(ex);
        }
    }

    /* Check to see if any settings have been changed */
    if (changed && !reset) {
        Properties outputProperties = new Properties() {
            @Override
            public synchronized Enumeration<Object> keys() {
                return Collections.enumeration(new TreeSet<>(super.keySet()));
            }
        };

        try {
            try (FileOutputStream outputStream = new FileOutputStream("botlogin.txt")) {
                outputProperties.putAll(pbProperties);
                outputProperties.store(outputStream, "PhantomBot Configuration File");
            }

            dataStore.SaveAll(true);

            print("");
            print("Changes have been saved, now exiting PhantomBot.");
            print("");
            System.exit(0);
        } catch (IOException ex) {
            com.gmt2001.Console.err.printStackTrace(ex);
        }
        return;
    }

    /* Save everything */
    if (message.equalsIgnoreCase("save")) {
        print("[CONSOLE] Executing save");
        dataStore.SaveAll(true);
        return;
    }

    /* Exit phantombot */
    if (message.equalsIgnoreCase("exit")) {
        print("[CONSOLE] Executing exit");
        System.exit(0);
        return;
    }

    /* handle any other commands */
    handleCommand(botName, event.getMsg(), PhantomBot.getChannel(this.channelName));
    // Need to support channel here. command (channel) argument[1]

    /* Handle dev commands */
    if (event.getMsg().startsWith("!debug !dev")) {
        devDebugCommands(event.getMsg(), "no_id", botName, true);
    }
}

From source file:com.jiangyifen.ec2.ui.mgr.system.tabsheet.SystemLicence.java

/**
 * added by chb 20140520//  w  ww .  ja  v a2 s .co m
 * @return
 */
private VerticalLayout updateLicenseComponent() {
    VerticalLayout licenseUpdateLayout = new VerticalLayout();
    final VerticalLayout textAreaPlaceHolder = new VerticalLayout();
    final HorizontalLayout buttonPlaceHolder = new HorizontalLayout();
    buttonPlaceHolder.setSpacing(true);

    //
    final Button updateButton = new Button("License");
    updateButton.setData("show");

    //
    final Button cancelButton = new Button("?");

    //
    final TextArea licenseTextArea = new TextArea();
    licenseTextArea.setColumns(30);
    licenseTextArea.setRows(5);
    licenseTextArea.setWordwrap(true);
    licenseTextArea.setInputPrompt("??");

    //Layout
    buttonPlaceHolder.addComponent(updateButton);
    licenseUpdateLayout.addComponent(textAreaPlaceHolder);
    licenseUpdateLayout.addComponent(buttonPlaceHolder);

    //
    cancelButton.addListener(new Button.ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {
            textAreaPlaceHolder.removeAllComponents();
            buttonPlaceHolder.removeComponent(cancelButton);
            updateButton.setData("show");
            updateButton.setCaption("License");
        }
    });

    updateButton.addListener(new Button.ClickListener() {

        @Override
        public void buttonClick(ClickEvent event) {
            if (((String) event.getButton().getData()).equals("show")) {
                textAreaPlaceHolder.removeAllComponents();
                textAreaPlaceHolder.addComponent(licenseTextArea);
                buttonPlaceHolder.addComponent(cancelButton);
                event.getButton().setData("updateAndHide");
                event.getButton().setCaption("??");
            } else if (((String) event.getButton().getData()).equals("updateAndHide")) {
                StringReader stringReader = new StringReader(
                        StringUtils.trimToEmpty((String) licenseTextArea.getValue()));
                Properties props = new Properties();
                try {
                    props.load(stringReader);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                stringReader.close();
                //               Boolean isValidvalidateLicense(licenseTextArea.getValue());
                String license_date = props.getProperty(LicenseManager.LICENSE_DATE);
                String license_count = props.getProperty(LicenseManager.LICENSE_COUNT);
                String license_localmd5 = props.getProperty(LicenseManager.LICENSE_LOCALMD5);
                //
                Boolean isMatch = regexMatchCheck(license_date, license_count, license_localmd5);
                if (isMatch) {

                    Map<String, String> licenseMap = new HashMap<String, String>();
                    //??
                    //                  String license_count = (String)props.get(LicenseManager.LICENSE_COUNT);
                    license_count = license_count == null ? "" : license_count;
                    licenseMap.put(LicenseManager.LICENSE_COUNT, license_count);

                    //?
                    //                  String license_date = (String)props.get(LicenseManager.LICENSE_DATE);
                    license_date = license_date == null ? "" : license_date;
                    licenseMap.put(LicenseManager.LICENSE_DATE, license_date);

                    //???
                    //                  String license_localmd5 = (String)props.get(LicenseManager.LICENSE_LOCALMD5);
                    license_localmd5 = license_localmd5 == null ? "" : license_localmd5;
                    licenseMap.put(LicenseManager.LICENSE_LOCALMD5, license_localmd5);

                    //?License
                    Map<String, String> resultMap = LicenseManager.licenseValidate(licenseMap);

                    String validateResult = resultMap.get(LicenseManager.LICENSE_VALIDATE_RESULT);
                    if (LicenseManager.LICENSE_VALID.equals(validateResult)) {
                        //continue
                    } else {
                        NotificationUtil.showWarningNotification(SystemLicence.this,
                                "License ?License");
                        return;
                    }

                    try {
                        URL resourceurl = SystemLicence.class.getResource(LicenseManager.LICENSE_FILE);
                        //System.err.println("chb: SystemLicense"+resourceurl.getPath());
                        OutputStream fos = new FileOutputStream(resourceurl.getPath());
                        props.store(fos, "license");
                    } catch (Exception e) {
                        e.printStackTrace();
                        NotificationUtil.showWarningNotification(SystemLicence.this, "License ");
                        return;
                    }
                    textAreaPlaceHolder.removeAllComponents();
                    buttonPlaceHolder.removeComponent(cancelButton);
                    updateButton.setData("show");
                    updateButton.setCaption("License");
                    LicenseManager.loadLicenseFile(LicenseManager.LICENSE_FILE.substring(1));
                    //                  LicenseManager.loadLicenseFile(licenseFilename)
                    refreshLicenseInfo();
                    NotificationUtil.showWarningNotification(SystemLicence.this,
                            "License ?,?");
                } else {
                    NotificationUtil.showWarningNotification(SystemLicence.this,
                            "License ??");
                }
            }
        }

        /**
         * license ?
         * @param license_date
         * @param license_count
         * @param license_localmd5
         * @return
         */
        private Boolean regexMatchCheck(String license_date, String license_count, String license_localmd5) {
            if (StringUtils.isEmpty(license_date) || StringUtils.isEmpty(license_count)
                    || StringUtils.isEmpty(license_localmd5)) {
                return false;
            }
            String date_regex = "^\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}$"; //?
            String count_regex = "^\\d+$"; //?
            String md5_32_regex = "^\\w{32}$"; //?
            return license_localmd5.matches(md5_32_regex) && license_date.matches(date_regex)
                    && license_count.matches(count_regex);
        }
    });

    return licenseUpdateLayout;
}

From source file:de.tudarmstadt.ukp.clarin.webanno.api.dao.RepositoryServiceDbData.java

@Override
public <T> void saveUserSettings(String aUsername, Project aProject, Mode aSubject, T aConfigurationObject)
        throws IOException {
    BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(aConfigurationObject);
    Properties property = new Properties();
    for (PropertyDescriptor value : wrapper.getPropertyDescriptors()) {
        if (wrapper.getPropertyValue(value.getName()) == null) {
            continue;
        }//w  w  w. jav a 2  s . co m
        property.setProperty(aSubject + "." + value.getName(),
                wrapper.getPropertyValue(value.getName()).toString());
    }
    String propertiesPath = dir.getAbsolutePath() + PROJECT + aProject.getId() + SETTINGS + aUsername;
    // append existing preferences for the other mode
    if (new File(propertiesPath, annotationPreferencePropertiesFileName).exists()) {
        // aSubject = aSubject.equals(Mode.ANNOTATION) ? Mode.CURATION :
        // Mode.ANNOTATION;
        for (Entry<Object, Object> entry : loadUserSettings(aUsername, aProject).entrySet()) {
            String key = entry.getKey().toString();
            // Maintain other Modes of annotations confs than this one
            if (!key.substring(0, key.indexOf(".")).equals(aSubject.toString())) {
                property.put(entry.getKey(), entry.getValue());
            }
        }
    }
    FileUtils.forceDeleteOnExit(new File(propertiesPath, annotationPreferencePropertiesFileName));
    FileUtils.forceMkdir(new File(propertiesPath));
    property.store(new FileOutputStream(new File(propertiesPath, annotationPreferencePropertiesFileName)),
            null);

    createLog(aProject).info(" Saved preferences file [" + annotationPreferencePropertiesFileName
            + "] for project [" + aProject.getName() + "] with ID [" + aProject.getId() + "] to location: ["
            + propertiesPath + "]");
    createLog(aProject).removeAllAppenders();

}

From source file:com.photon.phresco.framework.rest.api.CIService.java

/**
 * @return//from   ww w.j  av a2s  .co m
 * @throws PhrescoException
 */
@POST
@Path("/global")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response setGlobalConfiguration(GlobalSettings globalInfo,
        @QueryParam(REST_QUERY_EMAIL_ADDRESS) String emailAddress,
        @QueryParam(REST_QUERY_EMAIL_PASSWORD) String emailPassword, @QueryParam(REST_QUERY_URL) String url,
        @QueryParam(REST_QUERY_USER_NAME) String username, @QueryParam(REST_QUERY_PASSWORD) String password,
        @QueryParam(REST_QUERY_TFS_URL) String tfsUrl, @QueryParam(REST_QUERY_TYPE) String ciType)
        throws PhrescoException {
    ResponseInfo responseData = new ResponseInfo();
    ResponseInfo finalOutput = null;
    boolean setGlobalConfiguration = false;
    if (ciType.equalsIgnoreCase(BAMBOO)) {
        try {
            InputStream in = this.getClass().getClassLoader().getResourceAsStream(FRAMEWORK_CONFIG);
            Properties frameworkConfig = new Properties();
            frameworkConfig.load(in);
            in.close();

            frameworkConfig.setProperty(BAMBOO_URL, url);

            frameworkConfig.setProperty(BAMBOO_USERNAME, username);
            String encryptedPassword = com.photon.phresco.framework.commons.FrameworkUtil
                    .encryptString(password);

            frameworkConfig.setProperty(BAMBOO_PASSWORD, encryptedPassword);
            URL resource = this.getClass().getClassLoader().getResource("framework.config");
            String filePath = resource.getPath();
            File configFile = new File(filePath);
            if (configFile.exists()) {
                OutputStream out = new FileOutputStream(configFile);
                frameworkConfig.store(out, "");
                setGlobalConfiguration = true;
            }
        } catch (IOException e) {
            finalOutput = responseDataEvaluation(responseData, e, setGlobalConfiguration, RESPONSE_STATUS_ERROR,
                    PHR810034);
            return Response.status(Status.OK).entity(finalOutput)
                    .header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER).build();
        }
    } else {
        try {
            File pomFile = new File(FrameworkUtil.getJenkinsPOMFilePath());
            PomProcessor pom = new PomProcessor(pomFile);
            if (StringUtils.isNotEmpty(url)) {
                pom.setProperty(URL, url);
                pom.setProperty(USER_NAME, username);
                pom.setProperty(FrameworkConstants.PASSWORD, password);
            } else {
                pom.removeProperty(URL);
                pom.removeProperty(USER_NAME);
                pom.removeProperty(FrameworkConstants.PASSWORD);
            }
            pom.save();
            CIManager ciManager = PhrescoFrameworkFactory.getCIManager();
            String jenkinsUrl = FrameworkUtil.getLocaJenkinsUrl();
            //To enable remote global configuration changing
            //         String jenkinsUrl = FrameworkUtil.getJenkinsUrl();
            String submitUrl = jenkinsUrl + FrameworkConstants.FORWARD_SLASH + CONFIG_SUBMIT;
            org.json.JSONArray JSONarray = new org.json.JSONArray();
            List<RepoDetail> repoDetails = globalInfo.getRepoDetails();
            if (CollectionUtils.isNotEmpty(repoDetails)) {
                for (RepoDetail repodetail : repoDetails) {
                    org.json.JSONObject confluenceObj = new org.json.JSONObject();
                    confluenceObj.put(CONFLUENCE_SITE_URL, repodetail.getRepoUrl());
                    confluenceObj.put(CONFLUENCE_USERNAME, repodetail.getUserName());
                    confluenceObj.put(FrameworkConstants.PASSWORD, repodetail.getPassword());
                    JSONarray.put(confluenceObj);
                }
            }
            org.json.JSONArray testFlightJSONarray = new org.json.JSONArray();
            List<TestFlight> testFlightConfigs = globalInfo.getTestFlight();
            if (CollectionUtils.isNotEmpty(testFlightConfigs)) {
                for (TestFlight testFlight : testFlightConfigs) {
                    org.json.JSONObject testFlightObj = new org.json.JSONObject();
                    testFlightObj.put(TESTFLIGHT_TOKEN_NAME, testFlight.getTokenPairName());
                    testFlightObj.put(API_TOKEN, testFlight.getApiToken());
                    testFlightObj.put(TEAM_TOKEN, testFlight.getTeamToken());
                    testFlightJSONarray.put(testFlightObj);
                }
            }

            org.json.JSONArray keyChainJSONarray = new org.json.JSONArray();
            List<Keychain> keyChainConfigs = globalInfo.getKeychains();
            if (CollectionUtils.isNotEmpty(keyChainConfigs)) {
                for (Keychain keyChain : keyChainConfigs) {
                    org.json.JSONObject keyChainObj = new org.json.JSONObject();
                    keyChainObj.put("keychainName", keyChain.getKeychainName());
                    keyChainObj.put("keychainPath", keyChain.getKeychainPath());
                    keyChainObj.put("keychainPassword", keyChain.getKeychainPassword());
                    keyChainObj.put("inSearchPath", true);
                    keyChainJSONarray.put(keyChainObj);
                }
            }
            setGlobalConfiguration = ciManager.setGlobalConfiguration(jenkinsUrl, submitUrl, JSONarray,
                    emailAddress, emailPassword, testFlightJSONarray, keyChainJSONarray, tfsUrl);
        } catch (PhrescoException e) {
            finalOutput = responseDataEvaluation(responseData, e, setGlobalConfiguration, RESPONSE_STATUS_ERROR,
                    PHR810034);
            return Response.status(Status.OK).entity(finalOutput)
                    .header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER).build();
        } catch (org.json.JSONException e) {
            finalOutput = responseDataEvaluation(responseData, e, setGlobalConfiguration, RESPONSE_STATUS_ERROR,
                    PHR810034);
            return Response.status(Status.OK).entity(finalOutput)
                    .header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER).build();
        } catch (PhrescoPomException e) {
            finalOutput = responseDataEvaluation(responseData, null, setGlobalConfiguration,
                    RESPONSE_STATUS_SUCCESS, PHR800022);
            return Response.status(Status.OK).entity(finalOutput)
                    .header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER).build();
        }
    }
    finalOutput = responseDataEvaluation(responseData, null, setGlobalConfiguration, RESPONSE_STATUS_SUCCESS,
            PHR800022);
    return Response.status(Status.OK).entity(finalOutput).header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER)
            .build();
}

From source file:com.streamsets.datacollector.cluster.BaseClusterProvider.java

@VisibleForTesting
void rewriteProperties(File sdcPropertiesFile, List<File> additionalPropFiles, File etcStagingDir,
        Map<String, String> sourceConfigs, Map<String, String> sourceInfo, String clusterToken,
        Optional<String> mesosURL) throws IOException {
    InputStream sdcInStream = null;
    OutputStream sdcOutStream = null;
    Properties sdcProperties = new Properties();
    try {//  w  w  w  . j av a2  s. c  om
        sdcInStream = new FileInputStream(sdcPropertiesFile);
        sdcProperties.load(sdcInStream);

        for (File propFiles : additionalPropFiles) {
            sdcInStream = new FileInputStream(propFiles);
            sdcProperties.load(sdcInStream);
        }
        copyDpmTokenIfRequired(sdcProperties, etcStagingDir);
        sdcProperties.setProperty(RuntimeModule.PIPELINE_EXECUTION_MODE_KEY, ExecutionMode.SLAVE.name());
        sdcProperties.setProperty(WebServerTask.REALM_FILE_PERMISSION_CHECK, "false");

        // Remove always problematical properties
        for (String property : SDC_CONFIGS_TO_ALWAYS_REMOVE) {
            sdcProperties.remove(property);
        }

        // Remove additional properties that user might need to
        String propertiesToRemove = sdcProperties.getProperty(CONFIG_ADDITIONAL_CONFIGS_TO_REMOVE);
        if (propertiesToRemove != null) {
            for (String property : propertiesToRemove.split(",")) {
                sdcProperties.remove(property);
            }
        }

        if (runtimeInfo != null) {
            if (runtimeInfo.getSSLContext() != null) {
                sdcProperties.setProperty(WebServerTask.HTTP_PORT_KEY, "-1");
                sdcProperties.setProperty(WebServerTask.HTTPS_PORT_KEY, "0");
            } else {
                sdcProperties.setProperty(WebServerTask.HTTP_PORT_KEY, "0");
                sdcProperties.setProperty(WebServerTask.HTTPS_PORT_KEY, "-1");
            }
            String id = String.valueOf(runtimeInfo.getId());
            sdcProperties.setProperty(Constants.SDC_ID, id);
            sdcProperties.setProperty(Constants.PIPELINE_CLUSTER_TOKEN_KEY, clusterToken);
            sdcProperties.setProperty(Constants.CALLBACK_SERVER_URL_KEY, runtimeInfo.getClusterCallbackURL());
        }

        if (mesosURL.isPresent()) {
            sdcProperties.setProperty(Constants.MESOS_JAR_URL, mesosURL.get());
        }
        addClusterConfigs(sourceConfigs, sdcProperties);
        addClusterConfigs(sourceInfo, sdcProperties);

        sdcOutStream = new FileOutputStream(sdcPropertiesFile);
        sdcProperties.store(sdcOutStream, null);
        getLog().debug("sourceConfigs = {}", sourceConfigs);
        getLog().debug("sourceInfo = {}", sourceInfo);
        getLog().debug("sdcProperties = {}", sdcProperties);
        sdcOutStream.flush();
        sdcOutStream.close();
    } finally {
        if (sdcInStream != null) {
            IOUtils.closeQuietly(sdcInStream);
        }
        if (sdcOutStream != null) {
            IOUtils.closeQuietly(sdcOutStream);
        }
    }
}

From source file:org.testeditor.fixture.swt.SwtBotFixture.java

/**
 * copies the original config.ini of the SWT-app-under-test in the
 * temporary-directory of the os and adds a reference to the SWTBotAgent.
 * This is necessary to start the application with the SWTBotAgent.
 * /*  w ww. jav  a2  s .  c  om*/
 * 
 * @param applicationPath
 *            the path of the application.
 * @param swtBotAgentBundlePath
 *            Directory to the TestEditor bundle directory.
 * @return the absolutPath to the directory of the config.ini of the
 *         application.
 * @throws IOException
 *             on creating the property file.
 */
private String createAUTConfiguration(String applicationPath, String swtBotAgentBundlePath) throws IOException {
    FileInputStream fileInputStreamConfig = null;
    FileOutputStream fileOutputStream = null;
    Properties properties = new Properties();
    String result = null;
    fileInputStreamConfig = new FileInputStream(lookUpConfigIni(applicationPath));
    properties.load(fileInputStreamConfig);
    fileInputStreamConfig.close();
    String bundles = properties.getProperty("osgi.bundles");
    LOGGER.info("Bundle: " + swtBotAgentBundlePath);
    // begin; This part is just for considering the testing of an swt
    // application with the test-editor started from IDE
    if (new File(swtBotAgentBundlePath).isDirectory()) {
        LOGGER.info("Directory found for bundle: " + swtBotAgentBundlePath);
        File srcBundleDir = new File(swtBotAgentBundlePath + File.separator + "target");
        LOGGER.info("Directory found for source bundle: " + srcBundleDir + " -> " + srcBundleDir.exists());
        File jarBundle = srcBundleDir.listFiles(getSWTBotAgentFilter())[0];
        swtBotAgentBundlePath = jarBundle.getAbsolutePath();
    }
    // end;
    LOGGER.info("Found Path to Agent Bundle: " + swtBotAgentBundlePath);
    properties.setProperty("osgi.bundles", bundles + ",reference:file:" + swtBotAgentBundlePath);
    File file = new File(System.getProperty("java.io.tmpdir") + File.separator + "configuration");
    if (!file.exists()) {
        if (!file.mkdir()) {
            return "";
        }
    }
    result = file.getAbsolutePath() + File.separator + "config.ini";
    fileOutputStream = new FileOutputStream(result);
    properties.store(fileOutputStream, "Changed for TestEditor run.");
    fileOutputStream.close();
    LOGGER.info("New congfig.ini: " + result);
    return new File(result).getParentFile().getAbsolutePath();
}

From source file:org.jahia.modules.external.modules.ModulesDataSource.java

private void saveCndResourceBundle(ExternalData data, String key) throws RepositoryException {
    String resourceBundleName = module.getResourceBundleName();
    if (resourceBundleName == null) {
        resourceBundleName = "resources." + module.getId();
    }/*from  w ww  . j a  v  a2 s .  c om*/
    String rbBasePath = "/src/main/resources/resources/"
            + StringUtils.substringAfterLast(resourceBundleName, ".");
    Map<String, Map<String, String[]>> i18nProperties = data.getI18nProperties();
    if (i18nProperties != null) {
        List<File> newFiles = new ArrayList<File>();
        for (Map.Entry<String, Map<String, String[]>> entry : i18nProperties.entrySet()) {
            String lang = entry.getKey();
            Map<String, String[]> properties = entry.getValue();

            String[] values = properties.get(Constants.JCR_TITLE);
            String title = ArrayUtils.isEmpty(values) ? null : values[0];

            values = properties.get(Constants.JCR_DESCRIPTION);
            String description = ArrayUtils.isEmpty(values) ? null : values[0];

            String rbPath = rbBasePath + "_" + lang + PROPERTIES_EXTENSION;
            InputStream is = null;
            InputStreamReader isr = null;
            OutputStream os = null;
            OutputStreamWriter osw = null;
            try {
                FileObject file = getFile(rbPath);
                FileContent content = file.getContent();
                Properties p = new SortedProperties();
                if (file.exists()) {
                    is = content.getInputStream();
                    isr = new InputStreamReader(is, Charsets.ISO_8859_1);
                    p.load(isr);
                    isr.close();
                    is.close();
                } else if (StringUtils.isBlank(title) && StringUtils.isBlank(description)) {
                    continue;
                } else {
                    newFiles.add(new File(file.getName().getPath()));
                }
                if (!StringUtils.isEmpty(title)) {
                    p.setProperty(key, title);
                }
                if (!StringUtils.isEmpty(description)) {
                    p.setProperty(key + "_description", description);
                }
                os = content.getOutputStream();
                osw = new OutputStreamWriter(os, Charsets.ISO_8859_1);
                p.store(osw, rbPath);
                ResourceBundle.clearCache();
            } catch (FileSystemException e) {
                logger.error("Failed to save resourceBundle", e);
                throw new RepositoryException("Failed to save resourceBundle", e);
            } catch (IOException e) {
                logger.error("Failed to save resourceBundle", e);
                throw new RepositoryException("Failed to save resourceBundle", e);
            } finally {
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(isr);
                IOUtils.closeQuietly(os);
                IOUtils.closeQuietly(osw);
            }
        }
        SourceControlManagement sourceControl = module.getSourceControl();
        if (sourceControl != null) {
            try {
                sourceControl.add(newFiles);
            } catch (IOException e) {
                logger.error("Failed to add files to source control", e);
                throw new RepositoryException("Failed to add new files to source control: " + newFiles, e);
            }
        }
    }
}

From source file:com.virtusa.isq.rft.runtime.RFTCommandBase.java

/**
 * Stores a given key-value pair of given type <br>
 * Overwrites any existing value of same key <br>
 * <br>//  w  w  w.  j  ava 2s  .co m
 * <b>Fails</b> if, <li>data store file cannot be created</li> <li>data
 * cannot be written to file</li> <li>type of the value to be stored
 * mismatches the type specified</li> <br>
 * <br>
 * .
 * 
 * @param key
 *            : key for the value to be stored
 * @param type
 *            : type of value to be stored
 * @param value
 *            the value
 */
@Override
public final void store(final String key, final String type, final String value) {
    String projectPropertiesLocation = "project_data.properties";
    Properties prop = new Properties();
    FileInputStream fis = null;
    FileOutputStream fos = null;
    File file = new File(projectPropertiesLocation);
    try {
        if (!file.exists() && !file.createNewFile()) {

            System.err.println(
                    "Cannot create a new file in the intended location. " + "" + file.getAbsolutePath());
        }
        fis = new FileInputStream(file.getAbsoluteFile());
        prop.load(fis);
        prop.setProperty(key + "_Val", value);
        prop.setProperty(key + "_Type", type);

        checkStoreValueType(type, value);

        fos = new FileOutputStream(projectPropertiesLocation);
        prop.store(fos, "project settings");
        reportResults(ReportLogger.ReportLevel.SUCCESS, "Store", "Success",
                "Store value passed. Input value : " + value);

    } catch (IOException e) {
        reportResults(true, ReportLogger.ReportLevel.FAILURE, "Store", "Error", "Cannot Store the value. ::: "
                + value + " : " + type + " : " + key + "Actual Error : " + e.getMessage());

    } catch (NumberFormatException e) {
        reportResults(true, ReportLogger.ReportLevel.FAILURE, "Store", "Error", "Cannot Store the value. ::: "
                + value + " : " + type + " : " + key + "Actual Error : " + e.getMessage());
    } catch (IllegalArgumentException e) {

        reportResults(true, ReportLogger.ReportLevel.FAILURE, "Store", "Error",
                "Cannot parse value to the expected format. ::: Actual Error : " + e.getMessage());

    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:pl.project13.maven.git.GitCommitIdMojo.java

void maybeGeneratePropertiesFile(@NotNull Properties localProperties, File base, String propertiesFilename)
        throws GitCommitIdExecutionException {
    try {/*from   w w w  .j  a va  2  s  .  co m*/
        final File gitPropsFile = craftPropertiesOutputFile(base, propertiesFilename);
        final boolean isJsonFormat = "json".equalsIgnoreCase(format);

        boolean shouldGenerate = true;

        if (gitPropsFile.exists()) {
            final Properties persistedProperties;

            try {
                if (isJsonFormat) {
                    log.info("Reading existing json file [{}] (for module {})...",
                            gitPropsFile.getAbsolutePath(), project.getName());

                    persistedProperties = readJsonProperties(gitPropsFile);
                } else {
                    log.info("Reading existing properties file [{}] (for module {})...",
                            gitPropsFile.getAbsolutePath(), project.getName());

                    persistedProperties = readProperties(gitPropsFile);
                }

                final Properties propertiesCopy = (Properties) localProperties.clone();

                final String buildTimeProperty = prefixDot + BUILD_TIME;

                propertiesCopy.remove(buildTimeProperty);
                persistedProperties.remove(buildTimeProperty);

                shouldGenerate = !propertiesCopy.equals(persistedProperties);
            } catch (CannotReadFileException ex) {
                // Read has failed, regenerate file
                log.info("Cannot read properties file [{}] (for module {})...", gitPropsFile.getAbsolutePath(),
                        project.getName());
                shouldGenerate = true;
            }
        }

        if (shouldGenerate) {
            Files.createParentDirs(gitPropsFile);
            Writer outputWriter = null;
            boolean threw = true;

            try {
                outputWriter = new OutputStreamWriter(new FileOutputStream(gitPropsFile), sourceCharset);
                if (isJsonFormat) {
                    log.info("Writing json file to [{}] (for module {})...", gitPropsFile.getAbsolutePath(),
                            project.getName());
                    ObjectMapper mapper = new ObjectMapper();
                    mapper.writerWithDefaultPrettyPrinter().writeValue(outputWriter, localProperties);
                } else {
                    log.info("Writing properties file to [{}] (for module {})...",
                            gitPropsFile.getAbsolutePath(), project.getName());
                    localProperties.store(outputWriter, "Generated by Git-Commit-Id-Plugin");
                }
                threw = false;
            } catch (final IOException ex) {
                throw new RuntimeException("Cannot create custom git properties file: " + gitPropsFile, ex);
            } finally {
                Closeables.close(outputWriter, threw);
            }
        } else {
            log.info("Properties file [{}] is up-to-date (for module {})...", gitPropsFile.getAbsolutePath(),
                    project.getName());
        }
    } catch (IOException e) {
        throw new GitCommitIdExecutionException(e);
    }
}

From source file:edu.ku.brc.specify.Specify.java

/**
 * /* w  ww . j  a  v a 2  s.co m*/
 */
protected void exportPrefs() {
    AppPreferences remotePrefs = AppPreferences.getRemote();
    Properties props = remotePrefs.getProperties();
    try {
        JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        String title = getResourceString("Specify.SELECT_FILE_OR_DIR");//$NON-NLS-1$
        if (chooser.showDialog(null, title) != JFileChooser.CANCEL_OPTION) {
            File destFile = chooser.getSelectedFile();
            props.store(new FileOutputStream(destFile), "User Prefs"); //$NON-NLS-1$
        } else {
            throw new NoSuchElementException("The External File Repository needs a valid directory."); //$NON-NLS-1$
        }

    } catch (Exception ex) {
        log.error(ex); // XXX Error Dialog
    }
}