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:org.jahia.modules.external.modules.ModulesDataSource.java

private void saveProperties(ExternalData data) throws RepositoryException {
    OutputStream outputStream = null;
    try {// w ww .jav  a  2s  .c  o m
        ExtendedNodeType propertiesType = NodeTypeRegistry.getInstance()
                .getNodeType(Constants.JAHIAMIX_VIEWPROPERTIES);
        Map<String, ExtendedPropertyDefinition> propertyDefinitionMap = propertiesType
                .getDeclaredPropertyDefinitionsAsMap();
        Properties properties = new SortedProperties();
        for (Map.Entry<String, String[]> property : data.getProperties().entrySet()) {
            if (propertyDefinitionMap.containsKey(property.getKey())) {
                String[] v = property.getValue();
                if (v != null) {
                    String propertyValue = StringUtils.join(v, ",");
                    if (propertyDefinitionMap.get(property.getKey()).getRequiredType() != PropertyType.BOOLEAN
                            || !propertyValue.equals("false")) {
                        properties.put(property.getKey(), propertyValue);
                    }
                }
            }
        }
        FileObject file = getFile(StringUtils.substringBeforeLast(data.getPath(), ".") + PROPERTIES_EXTENSION);
        Properties original = new Properties();
        if (file.exists()) {
            original.load(file.getContent().getInputStream());
            for (String s : propertyDefinitionMap.keySet()) {
                original.remove(s);
            }
        }
        properties.putAll(original);
        if (!properties.isEmpty()) {
            outputStream = file.getContent().getOutputStream();
            properties.store(outputStream, data.getPath());
        } else {
            if (file.exists()) {
                file.delete();
            }
        }
        ResourceBundle.clearCache();
    } catch (FileSystemException e) {
        logger.error(e.getMessage(), e);
        throw new RepositoryException("Failed to write source code", e);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        throw new RepositoryException("Failed to write source code", e);
    } catch (NoSuchNodeTypeException e) {
        logger.error("Unable to find type : " + data.getType() + " for node " + data.getPath(), e);
        throw e;
    } finally {
        IOUtils.closeQuietly(outputStream);
    }
}

From source file:de.fhg.igd.mapviewer.server.file.FileTiler.java

/**
 * Ask the user for an image file for that a tiled map shall be created
 *///from w w w. ja v  a  2s  .c o m
public void run() {
    JFileChooser fileChooser = new JFileChooser();

    // load current dir
    fileChooser.setCurrentDirectory(
            new File(pref.get(PREF_DIR, fileChooser.getCurrentDirectory().getAbsolutePath())));

    // open
    int returnVal = fileChooser.showOpenDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        // save current dir
        pref.put(PREF_DIR, fileChooser.getCurrentDirectory().getAbsolutePath());

        // get file
        File imageFile = fileChooser.getSelectedFile();

        // get image dimension
        Dimension size = getSize(imageFile);
        log.info("Image size: " + size);

        // ask for min tile size
        int minTileSize = 0;
        while (minTileSize <= 0) {
            try {
                minTileSize = Integer.parseInt(
                        JOptionPane.showInputDialog("Minimal tile size", String.valueOf(DEF_MIN_TILE_SIZE)));
            } catch (Exception e) {
                minTileSize = 0;
            }
        }

        // determine min map width
        int width = size.width;

        while (width / 2 > minTileSize && width % 2 == 0) {
            width = width / 2;
        }
        int minMapWidth = width; // min map width

        log.info("Minimal map width: " + minMapWidth);

        // determine min map height
        int height = size.height;

        while (height / 2 > minTileSize && height % 2 == 0) {
            height = height / 2; // min map height
        }
        int minMapHeight = height;

        log.info("Minimal map height: " + minMapHeight);

        // ask for min map size
        int minMapSize = 0;
        while (minMapSize <= 0) {
            try {
                minMapSize = Integer.parseInt(
                        JOptionPane.showInputDialog("Minimal map size", String.valueOf(DEF_MIN_MAP_SIZE)));
            } catch (Exception e) {
                minMapSize = 0;
            }
        }

        // determine zoom levels
        int zoomLevels = 1;

        width = size.width;
        height = size.height;

        while (width % 2 == 0 && height % 2 == 0 && width / 2 >= Math.max(minMapWidth, minMapSize)
                && height / 2 >= Math.max(minMapHeight, minMapSize)) {
            zoomLevels++;
            width = width / 2;
            height = height / 2;
        }

        log.info("Number of zoom levels: " + zoomLevels);

        // determine tile width
        width = minMapWidth;
        int tileWidth = minMapWidth;
        for (int i = 3; i < Math.sqrt(minMapWidth) && width > minTileSize;) {
            tileWidth = width;
            if (width % i == 0) {
                width = width / i;
            } else
                i++;
        }

        // determine tile height
        height = minMapHeight;
        int tileHeight = minMapHeight;
        for (int i = 3; i < Math.sqrt(minMapHeight) && height > minTileSize;) {
            tileHeight = height;
            if (height % i == 0) {
                height = height / i;
            } else
                i++;
        }

        // create tiles for each zoom level
        if (JOptionPane.showConfirmDialog(null,
                "Create tiles (" + tileWidth + "x" + tileHeight + ") for " + zoomLevels + " zoom levels?",
                "Create tiles", JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
            int currentWidth = size.width;
            int currentHeight = size.height;
            File currentImage = imageFile;

            Properties properties = new Properties();
            properties.setProperty(PROP_TILE_WIDTH, String.valueOf(tileWidth));
            properties.setProperty(PROP_TILE_HEIGHT, String.valueOf(tileHeight));
            properties.setProperty(PROP_ZOOM_LEVELS, String.valueOf(zoomLevels));

            List<File> files = new ArrayList<File>();

            for (int i = 0; i < zoomLevels; i++) {
                int mapWidth = currentWidth / tileWidth;
                int mapHeight = currentHeight / tileHeight;

                log.info("Creating tiles for zoom level " + i);
                log.info("Map width: " + currentWidth + " pixels, " + mapWidth + " tiles");
                log.info("Map height: " + currentHeight + " pixels, " + mapHeight + " tiles");

                // create tiles
                tile(currentImage, TILE_FILE_PREFIX + i + TILE_FILE_SEPARATOR + "%d", TILE_FILE_EXTENSION,
                        tileWidth, tileHeight);

                // add files to list
                for (int num = 0; num < mapWidth * mapHeight; num++) {
                    files.add(new File(imageFile.getParentFile().getAbsolutePath() + File.separator
                            + TILE_FILE_PREFIX + i + TILE_FILE_SEPARATOR + num + TILE_FILE_EXTENSION));
                }

                // store map width and height at current zoom
                properties.setProperty(PROP_MAP_WIDTH + i, String.valueOf(mapWidth));
                properties.setProperty(PROP_MAP_HEIGHT + i, String.valueOf(mapHeight));

                // create image for next zoom level
                currentWidth /= 2;
                currentHeight /= 2;
                // create temp image file name
                File nextImage = suffixFile(imageFile, i + 1);
                // resize image
                convert(currentImage, nextImage, currentWidth, currentHeight, 100);
                // delete previous temp file
                if (!currentImage.equals(imageFile)) {
                    if (!currentImage.delete()) {
                        log.warn("Error deleting " + imageFile.getAbsolutePath());
                    }
                }

                currentImage = nextImage;
            }

            // delete previous temp file
            if (!currentImage.equals(imageFile)) {
                if (!currentImage.delete()) {
                    log.warn("Error deleting " + imageFile.getAbsolutePath());
                }
            }

            // write properties file
            File propertiesFile = new File(
                    imageFile.getParentFile().getAbsolutePath() + File.separator + MAP_PROPERTIES_FILE);
            try {
                FileWriter propertiesWriter = new FileWriter(propertiesFile);
                try {
                    properties.store(propertiesWriter, "Map generated from " + imageFile.getName());
                    // add properties file to list
                    files.add(propertiesFile);
                } finally {
                    propertiesWriter.close();
                }
            } catch (IOException e) {
                log.error("Error writing map properties file", e);
            }

            // add a converter properties file
            String convProperties = askForPath(fileChooser, new ExactFileFilter(CONVERTER_PROPERTIES_FILE),
                    "Select a converter properties file");
            File convFile = null;
            if (convProperties != null) {
                convFile = new File(convProperties);
                files.add(convFile);
            }

            // create jar file
            log.info("Creating jar archive...");
            if (createJarArchive(replaceExtension(imageFile, MAP_ARCHIVE_EXTENSION), files)) {
                log.info("Archive successfully created, deleting tiles...");
                // don't delete converter properties
                if (convFile != null)
                    files.remove(files.size() - 1);
                // delete files
                for (File file : files) {
                    if (!file.delete()) {
                        log.warn("Error deleting " + file.getAbsolutePath());
                    }
                }
            }

            log.info("Fin.");
        }
    }
}

From source file:de.ingrid.admin.Config.java

@SuppressWarnings("rawtypes")
public void writePlugdescriptionToProperties(PlugdescriptionCommandObject pd) {
    try {//w  w w.  ja  va  2s. c om

        Resource override = getOverrideConfigResource();
        InputStream is = new FileInputStream(override.getFile().getAbsolutePath());
        Properties props = new Properties() {
            private static final long serialVersionUID = 6956076060462348684L;

            @Override
            public synchronized Enumeration<Object> keys() {
                return Collections.enumeration(new TreeSet<Object>(super.keySet()));
            }
        };
        props.load(is);

        for (Iterator<Object> it = pd.keySet().iterator(); it.hasNext();) {
            String key = (String) it.next();

            // do not write properties from plug description we do not want
            if (IGNORE_LIST.contains(key))
                continue;

            Object valObj = pd.get(key);
            if (valObj instanceof String) {
                props.setProperty("plugdescription." + key, (String) valObj);
            } else if (valObj instanceof List) {
                props.setProperty("plugdescription." + key, convertListToString((List) valObj));
            } else if (valObj instanceof Integer) {
                if ("IPLUG_ADMIN_GUI_PORT".equals(key)) {
                    props.setProperty("jetty.port", String.valueOf(valObj));
                } else {
                    props.setProperty("plugdescription." + key, String.valueOf(valObj));
                }
            } else if (valObj instanceof File) {
                props.setProperty("plugdescription." + key, ((File) valObj).getPath());
            } else {
                if (valObj != null) {
                    props.setProperty("plugdescription." + key, valObj.toString());
                } else {
                    log.warn("value of plugdescription field was NULL: " + key);
                }
            }
        }

        // always write working dir as relative path if it was set as such
        String workDir = pd.getRealWorkingDir();
        if (workDir == null) {
            workDir = pd.getWorkinDirectory() == null ? "." : pd.getWorkinDirectory().getPath();
        }
        props.setProperty("plugdescription.workingDirectory", workDir);

        props.setProperty("plugdescription.queryExtensions",
                convertQueryExtensionsToString(this.queryExtensions));

        props.setProperty("index.searchInTypes", StringUtils.join(this.indexSearchInTypes, ','));

        setDatatypes(props);

        IConfig externalConfig = JettyStarter.getInstance().getExternalConfig();
        if (externalConfig != null) {
            externalConfig.setPropertiesFromPlugdescription(props, pd);
            externalConfig.addPlugdescriptionValues(pd);
        }

        // ---------------------------
        is.close();
        try (OutputStream os = new FileOutputStream(override.getFile().getAbsolutePath())) {
            if (log.isDebugEnabled()) {
                log.debug("writing configuration to: " + override.getFile().getAbsolutePath());
            }
            props.store(os, "Override configuration written by the application");
        }
    } catch (Exception e) {
        log.error("Error writing properties:", e);
    }
}

From source file:de.unibi.cebitec.bibiserv.web.beans.runinthecloud.BashExecutor.java

/**
 * Creates the needed bibigrid.properties file which will configure the
 * bibigrid binaries to start correctly.
 *
 * @param tempDirectoryPath - The resolved unique folder id
 * @param isr - inputstream reader/*from  ww  w. j av a  2 s  .c  o m*/
 * @param out - outputStream
 * @param execScript - filediscriptor of execScript
 * @param sourceProperties - filediscriptor to the now building
 * bibigrid.properties
 */
private void createBiBiGridPropertiesFile(final Path tempDirectoryPath, final InputStreamReader isr,
        final OutputStream out, final File execScript, final Properties sourceProperties) {
    /**
     * Get selected values from wizard.
     */
    final Integer numberOfSlaves = ec2InstanceWizard.getNumberOfSlaves();
    final String masterInstanceType = ec2InstanceWizard.getSelectedEc2MasterInstance().getInstanceName();
    final String slaveInstanceType = ec2InstanceWizard.getSelectedEc2SlaveInstance().getInstanceName();
    final String region = ec2InstanceWizard.getSelectedRegion();

    /**
     * Get identitiyfile from SSH-Keychain Module.
     */
    final File identityfile = new File(tempDirectoryPath.toFile(), user.getId() + "_identityfile.pem");
    final StringBuffer keypairname = new StringBuffer();
    try (PrintWriter id_pw = new PrintWriter(identityfile)) {
        ArrayList<SshKeyPair> foundKeyPairs = new ArrayList(dc.retrieveSshKeyFile(user));
        for (SshKeyPair kp : foundKeyPairs) {
            /**
             * If there is one active keypair we can quit searching and take
             * this keypair. The active keypair can be set in the
             * KeyChainModule.
             */
            if (kp.isActive()) {
                id_pw.println(kp.getIdentityFile());
                keypairname.append(kp.getKeypairName());
                break;
            }
        }
        id_pw.close();

    } catch (FileNotFoundException fnfe) {
        log.error(fnfe.getMessage(), fnfe);
    }
    /**
     * Start new Thread for creating and writing new bibigrid.properties.
     */
    Thread bibiGridPropertiesCreatorThread = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                sourceProperties.load(isr);
                sourceProperties.setProperty("accessKey", ec2InstanceWizard.getAwsbean().getAccessKey());
                sourceProperties.setProperty("secretKey", ec2InstanceWizard.getAwsbean().getSecretKey());
                sourceProperties.setProperty("region", region);
                sourceProperties.setProperty("keypair", keypairname.toString());
                /**
                 * The availability zones are HARD CODED! I've at this point
                 * no idea how to parse the available
                 * endpoints/availability-zones.
                 */
                sourceProperties.setProperty("availability-zone", region + "a");
                sourceProperties.setProperty("master-instance-type", masterInstanceType);
                sourceProperties.setProperty("master-image", ec2InstanceWizard.getIMAGE_ID_HVM_MASTER());
                sourceProperties.setProperty("slave-instance-type", slaveInstanceType);
                sourceProperties.setProperty("slave-instance-min", "1");
                sourceProperties.setProperty("slave-instance-start", String.valueOf(numberOfSlaves));
                sourceProperties.setProperty("slave-instance-max", String.valueOf(numberOfSlaves));
                sourceProperties.setProperty("slave-image", ec2InstanceWizard.getIMAGE_ID_HVM_SLAVE());
                sourceProperties.setProperty("ports", "8080,8081");
                sourceProperties.setProperty("execute-script", execScript.getName());
                sourceProperties.setProperty("use-master-as-compute", "no");
                sourceProperties.setProperty("grid-properties-file", gridPropertiesFile);
                sourceProperties.setProperty("identity-file", identityfile.getName());
                sourceProperties.store(out, null);
            } catch (IOException | NullPointerException e) {
                log.error(e.getMessage(), e);
            } finally {
                try {
                    isr.close();
                    out.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    });
    bibiGridPropertiesCreatorThread.start();
}

From source file:com.izforge.izpack.util.LogUtils.java

public static void loadConfiguration(final Properties configuration) throws IOException {
    if (OVERRIDE) {
        LogManager manager = LogManager.getLogManager();

        // Merge global logging properties
        InputStream baseResourceStream = null;
        try {//  www . j av a  2  s . c  om
            baseResourceStream = LogUtils.class.getResourceAsStream(LOGGING_BASE_CONFIGURATION);
            final Properties baseProps = new Properties();
            baseProps.load(baseResourceStream);
            mergeLoggingConfiguration(configuration, baseProps);
        } finally {
            IOUtils.closeQuietly(baseResourceStream);
        }

        boolean mkdirs = false;
        String pattern = null;
        if (configuration.getProperty("handlers") != null
                && configuration.getProperty("handlers").contains(FILEHANDLER_CLASSNAME)
                && manager.getProperty("handlers").contains(FILEHANDLER_CLASSNAME)) {
            // IzPack maintains just one log file, don't override the existing handler type of it.
            // Special use case: Command line argument -logfile "wins" over the <log-file> tag.
            // Assumption at the moment for optimization: Just FileHandler is used for configurations from install.xml.
            return;
        }
        for (String key : configuration.stringPropertyNames()) {
            if (key.equals(FILEHANDLER_CLASSNAME + ".pattern")) {
                // Workaround for not normalized file paths, for example ${INSTALL_PATH}/../install_log/name.log
                // to get them working before creating ${INSTALL_PATH} in the
                // com.izforge.izpack.installer.unpacker.UnpackerBase.preUnpack phase
                // otherwise the FileHandler will fail when opening files already in constructor and not recover from that.
                pattern = FilenameUtils.normalize(configuration.getProperty(key));
                configuration.setProperty(key, pattern);
            } else if (key.equals(FILEHANDLER_CLASSNAME + ".mkdirs")) {
                // This key goes beyond the capabilities of java.util.logging.FileHandler
                mkdirs = Boolean.parseBoolean(configuration.getProperty(key));
                configuration.remove(key);
            }
        }
        if (mkdirs && pattern != null) {
            FileUtils.forceMkdirParent(new File(pattern));
        }

        // Merge user settings compiled in
        final Properties userProps = new Properties();
        InputStream userPropsStream = LogUtils.class
                .getResourceAsStream(ResourceManager.getInstallLoggingConfigurationResourceName());
        try {
            if (userPropsStream != null) {
                userProps.load(userPropsStream);
                for (String userPropName : userProps.stringPropertyNames()) {
                    if (userPropName.endsWith(".level") && !userPropName.startsWith(FILEHANDLER_CLASSNAME)) {
                        String level = userProps.getProperty(userPropName);
                        if (level != null) {
                            configuration.setProperty(userPropName, level);
                        }
                    }
                }
            }
        } finally {
            IOUtils.closeQuietly(userPropsStream);
        }

        InputStream defaultResourceStream = null;
        try {
            defaultResourceStream = LogUtils.class.getResourceAsStream(LOGGING_CONFIGURATION);
            final Properties defaultProps = new Properties();
            defaultProps.load(defaultResourceStream);
            mergeLoggingConfiguration(configuration, defaultProps);
        } finally {
            IOUtils.closeQuietly(defaultResourceStream);
        }

        if (Debug.isDEBUG()) {
            configuration.setProperty(FILEHANDLER_CLASSNAME + ".level", Level.FINE.toString());
            configuration.setProperty(ConsoleHandler.class.getName() + ".level", Level.FINE.toString());
        }

        // Set general log level which acts as filter in front of all handlers
        String fileLevelName = configuration.getProperty(FILEHANDLER_CLASSNAME + ".level",
                Level.ALL.toString());
        Level fileLevel = Level.ALL;
        if (fileLevelName != null) {
            fileLevel = Level.parse(fileLevelName);
        }

        String consoleLevelName = configuration.getProperty(CONSOLEHANDLER_CLASSNAME + ".level",
                Level.INFO.toString());
        Level consoleLevel = Level.INFO;
        if (consoleLevelName != null) {
            consoleLevel = Level.parse(consoleLevelName);
        }

        configuration.setProperty(".level",
                (fileLevel.intValue() < consoleLevel.intValue()) ? fileLevelName : consoleLevelName);

        final PipedOutputStream out = new PipedOutputStream();
        final PipedInputStream in = new PipedInputStream(out);
        try {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        configuration.store(out, null);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        IOUtils.closeQuietly(out);
                    }
                }
            }).start();

            manager.readConfiguration(in);
        } finally {
            IOUtils.closeQuietly(in);
        }
    }
}

From source file:com.hpe.application.automation.tools.run.RunFromFileBuilder.java

@Override
public void perform(@Nonnull Run<?, ?> build, @Nonnull FilePath workspace, @Nonnull Launcher launcher,
        @Nonnull TaskListener listener)//from  w  ww.  ja  v  a 2  s  .  c  om

        throws InterruptedException, IOException {

    // get the mc server settings
    MCServerSettingsModel mcServerSettingsModel = getMCServerSettingsModel();

    EnvVars env = null;
    try {
        env = build.getEnvironment(listener);

    } catch (IOException | InterruptedException e) {
        listener.error("Failed loading build environment " + e);
    }

    // this is an unproper replacment to the build.getVariableResolver since workflow run won't support the
    // getBuildEnviroment() as written here:
    // https://github.com/jenkinsci/pipeline-plugin/blob/893e3484a25289c59567c6724f7ce19e3d23c6ee/DEVGUIDE.md#variable-substitutions

    JSONObject jobDetails = null;
    String mcServerUrl = "";
    // now merge them into one list
    Properties mergedProperties = new Properties();
    if (mcServerSettingsModel != null) {
        mcServerUrl = mcServerSettingsModel.getProperties().getProperty("MobileHostAddress");
        if (runFromFileModel.getProxySettings() == null) {
            jobDetails = runFromFileModel.getJobDetails(mcServerUrl, null, null, null);
        } else {
            jobDetails = runFromFileModel.getJobDetails(mcServerUrl,
                    runFromFileModel.getProxySettings().getFsProxyAddress(),
                    runFromFileModel.getProxySettings().getFsProxyUserName(),
                    runFromFileModel.getProxySettings().getFsProxyPassword());
        }
        mergedProperties.setProperty("mobileinfo", jobDetails != null ? jobDetails.toJSONString() : "");
        mergedProperties.setProperty("MobileHostAddress", mcServerUrl);
    }

    if (runFromFileModel != null && StringUtils.isNotBlank(runFromFileModel.getFsPassword())) {
        try {
            String encPassword = EncryptionUtils.Encrypt(runFromFileModel.getFsPassword(),
                    EncryptionUtils.getSecretKey());
            mergedProperties.put("MobilePassword", encPassword);
        } catch (Exception e) {
            build.setResult(Result.FAILURE);
            listener.fatalError("problem in mobile center password encryption" + e);
        }
    }

    if (env == null) {
        listener.fatalError("Enviroment not set");
        throw new IOException("Env Null - something went wrong with fetching jenkins build environment");
    }
    if (build instanceof AbstractBuild) {
        VariableResolver<String> varResolver = ((AbstractBuild) build).getBuildVariableResolver();
        mergedProperties.putAll(runFromFileModel.getProperties(env, varResolver));
    } else {
        mergedProperties.putAll(runFromFileModel.getProperties(env));
    }

    int idx = 0;
    for (Iterator<String> iterator = env.keySet().iterator(); iterator.hasNext();) {
        String key = iterator.next();
        idx++;
        mergedProperties.put("JenkinsEnv" + idx, key + ";" + env.get(key));
    }

    Date now = new Date();
    Format formatter = new SimpleDateFormat("ddMMyyyyHHmmssSSS");
    String time = formatter.format(now);

    // get a unique filename for the params file
    ParamFileName = "props" + time + ".txt";
    ResultFilename = "Results" + time + ".xml";

    mergedProperties.put("runType", AlmRunTypes.RunType.FileSystem.toString());
    mergedProperties.put("resultsFilename", ResultFilename);

    //handling mtbx file content :
    // If we have mtbx content - it is located in Test1 property and there is no other test properties (like Test2 etc)
    // We save mtbx content in workspace and replace content of Test1 by reference to saved file
    String firstTestKey = "Test1";
    String firstTestContent = mergedProperties.getProperty(firstTestKey, "");
    if (RunFromFileSystemModel.isMtbxContent(firstTestContent)) {
        try {
            String mtbxFilePath = createMtbxFileInWs(workspace, firstTestContent, time);
            mergedProperties.setProperty(firstTestKey, mtbxFilePath);
        } catch (IOException | InterruptedException e) {
            build.setResult(Result.FAILURE);
            listener.error("Failed to save MTBX file : " + e.getMessage());
        }
    }

    // get properties serialized into a stream
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    try {
        mergedProperties.store(stream, "");
    } catch (IOException e) {
        listener.error("Storing run variable failed: " + e);
        build.setResult(Result.FAILURE);
    }
    String propsSerialization = stream.toString();
    FilePath CmdLineExe;
    try (InputStream propsStream = IOUtils.toInputStream(propsSerialization)) {

        // Get the URL to the Script used to run the test, which is bundled
        // in the plugin
        @SuppressWarnings("squid:S2259")
        URL cmdExeUrl = Jenkins.getInstance().pluginManager.uberClassLoader.getResource(HP_TOOLS_LAUNCHER_EXE);
        if (cmdExeUrl == null) {
            listener.fatalError(HP_TOOLS_LAUNCHER_EXE + " not found in resources");
            return;
        }

        @SuppressWarnings("squid:S2259")
        URL cmdExe2Url = Jenkins.getInstance().pluginManager.uberClassLoader
                .getResource(LRANALYSIS_LAUNCHER_EXE);
        if (cmdExe2Url == null) {
            listener.fatalError(LRANALYSIS_LAUNCHER_EXE + "not found in resources");
            return;
        }

        FilePath propsFileName = workspace.child(ParamFileName);
        CmdLineExe = workspace.child(HP_TOOLS_LAUNCHER_EXE);
        FilePath CmdLineExe2 = workspace.child(LRANALYSIS_LAUNCHER_EXE);

        try {
            // create a file for the properties file, and save the properties
            propsFileName.copyFrom(propsStream);

            // Copy the script to the project workspace
            CmdLineExe.copyFrom(cmdExeUrl);

            CmdLineExe2.copyFrom(cmdExe2Url);

        } catch (IOException | InterruptedException e) {
            build.setResult(Result.FAILURE);
            listener.error("Copying executable files to executing node " + e);
        }
    }

    try {
        // Run the HpToolsLauncher.exe
        AlmToolsUtils.runOnBuildEnv(build, launcher, listener, CmdLineExe, ParamFileName);
        // Has the report been successfully generated?
    } catch (IOException ioe) {
        Util.displayIOException(ioe, listener);
        build.setResult(Result.FAILURE);
        listener.error("Failed running HpToolsLauncher " + ioe);
        return;
    } catch (InterruptedException e) {
        build.setResult(Result.ABORTED);
        PrintStream out = listener.getLogger();
        listener.error("Failed running HpToolsLauncher - build aborted " + e);

        try {
            AlmToolsUtils.runHpToolsAborterOnBuildEnv(build, launcher, listener, ParamFileName, workspace);
        } catch (IOException e1) {
            Util.displayIOException(e1, listener);
            build.setResult(Result.FAILURE);
            return;
        } catch (InterruptedException e1) {
            listener.error("Failed running HpToolsAborter " + e1);
        }
        out.println("Operation Was aborted by user.");
    }
}

From source file:JNLPAppletLauncher.java

private void updateDeploymentPropertiesImpl() {
    String userHome = System.getProperty("user.home");
    File dontAskFile = new File(userHome + File.separator + ".jnlp-applet" + File.separator + DONT_ASK);
    if (dontAskFile.exists())
        return; // User asked us not to prompt again

    int option = 0;

    if (!getBooleanParameter("noddraw.check.silent")) {
        option = JOptionPane.showOptionDialog(null,
                "For best robustness of OpenGL applets on Windows,\n"
                        + "we recommend disabling Java2D's use of DirectDraw.\n"
                        + "This setting will affect all applets, but is unlikely\n"
                        + "to slow other applets down significantly. May we update\n"
                        + "your deployment.properties to turn off DirectDraw for\n"
                        + "applets? You can change this back later if necessary\n"
                        + "using the Java Control Panel, Java tab, under Java\n" + "Applet Runtime Settings.",
                "Update deployment.properties?", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
                null, new Object[] { "Yes", "No", "No, Don't Ask Again" }, "Yes");
    }//from  w  w  w.  j a v  a 2 s. c  o  m

    if (option < 0 || option == 1)
        return; // No

    if (option == 2) {
        try {
            dontAskFile.createNewFile();
        } catch (IOException e) {
        }
        return; // No, Don't Ask Again
    }

    try {
        // Must update deployment.properties
        File propsDir = new File(getDeploymentPropsDir());
        if (!propsDir.exists()) {
            // Don't know what's going on or how to set this permanently
            return;
        }

        File propsFile = new File(propsDir, "deployment.properties");
        if (!propsFile.exists()) {
            // Don't know what's going on or how to set this permanently
            return;
        }

        Properties props = new Properties();
        InputStream input = new BufferedInputStream(new FileInputStream(propsFile));
        props.load(input);
        input.close();
        // Search through the keys looking for JRE versions
        Set/*<String>*/ jreVersions = new HashSet/*<String>*/();
        for (Iterator /*<String>*/ iter = props.keySet().iterator(); iter.hasNext();) {
            String key = (String) iter.next();
            if (key.startsWith(JRE_PREFIX)) {
                int idx = key.lastIndexOf(".");
                if (idx >= 0 && idx > JRE_PREFIX.length()) {
                    String jreVersion = key.substring(JRE_PREFIX.length(), idx);
                    jreVersions.add(jreVersion);
                }
            }
        }

        // Make sure the currently-running JRE shows up in this set to
        // avoid repeated displays of the dialog. It might not in some
        // upgrade scenarios where there was a pre-existing
        // deployment.properties and the new Java Control Panel hasn't
        // been run yet.
        jreVersions.add(System.getProperty("java.version"));

        // OK, now that we know all JRE versions covered by the
        // deployment.properties, check out the args for each and update
        // them
        for (Iterator /*<String>*/ iter = jreVersions.iterator(); iter.hasNext();) {
            String version = (String) iter.next();
            String argKey = JRE_PREFIX + version + ".args";
            String argVal = props.getProperty(argKey);
            if (argVal == null) {
                argVal = NODDRAW_PROP;
            } else if (argVal.indexOf(NODDRAW_PROP) < 0) {
                argVal = argVal + " " + NODDRAW_PROP;
            }
            props.setProperty(argKey, argVal);
        }

        OutputStream output = new BufferedOutputStream(new FileOutputStream(propsFile));
        props.store(output, null);
        output.close();

        if (!getBooleanParameter("noddraw.check.silent")) {
            // Tell user we're done
            JOptionPane.showMessageDialog(null, "For best robustness, we recommend you now exit and\n"
                    + "restart your web browser. (Note: clicking \"OK\" will\n" + "not exit your browser.)",
                    "Browser Restart Recommended", JOptionPane.INFORMATION_MESSAGE);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:io.github.arven.flare.boot.TomcatContainer.java

public void start() throws Exception {
    if (base == null || !base.exists()) {
        setup(configuration);// w  ww.  ja va  2 s  .  co m
    }

    final Properties props = configuration.getProperties();

    if (props != null) {
        StrSubstitutor substitutor = null;
        for (final String s : props.stringPropertyNames()) {
            final String v = props.getProperty(s);
            if (v != null && v.contains("${")) {
                if (substitutor == null) {
                    final Map<String, String> placeHolders = new HashMap<String, String>();
                    placeHolders.put("tomee.embedded.http", Integer.toString(configuration.getHttpPort()));
                    placeHolders.put("tomee.embedded.https", Integer.toString(configuration.getHttpsPort()));
                    placeHolders.put("tomee.embedded.stop", Integer.toString(configuration.getStopPort()));
                    substitutor = new StrSubstitutor(placeHolders);
                }
                props.put(s, substitutor.replace(v));
            }
        }

        // inherit from system props
        final Properties properties = new Properties(System.getProperties());
        properties.putAll(configuration.getProperties());
        Logger.configure(properties);
    } else {
        Logger.configure();
    }

    final File conf = new File(base, "conf");
    final File webapps = new File(base, "webapps");

    final String catalinaBase = base.getAbsolutePath();

    // set the env before calling anoything on tomcat or Catalina!!
    System.setProperty("catalina.base", catalinaBase);
    System.setProperty("openejb.deployments.classpath", "false");
    System.setProperty("catalina.home", catalinaBase);
    System.setProperty("catalina.base", catalinaBase);
    System.setProperty("openejb.home", catalinaBase);
    System.setProperty("openejb.base", catalinaBase);
    System.setProperty("openejb.servicemanager.enabled", "false");

    copyFileTo(conf, "catalina.policy");
    copyTemplateTo(conf, "catalina.properties");
    copyFileTo(conf, "context.xml");
    copyFileTo(conf, "openejb.xml");
    copyFileTo(conf, "tomcat-users.xml");
    copyFileTo(conf, "web.xml");

    final boolean initialized;
    if (configuration.hasServerXml()) {
        final File file = new File(conf, "server.xml");
        final FileOutputStream fos = new FileOutputStream(file);
        try {
            IO.copy(configuration.getServerXmlFile(), fos);
        } finally {
            IO.close(fos);
        }

        // respect config (host/port) of the Configuration
        final QuickServerXmlParser ports = QuickServerXmlParser.parse(file);
        if (configuration.isKeepServerXmlAsThis()) {
            // force ports to be able to stop the server and get @ArquillianResource
            configuration.setHttpPort(Integer.parseInt(ports.http()));
            configuration.setStopPort(Integer.parseInt(ports.stop()));
        } else {
            final Map<String, String> replacements = new HashMap<String, String>();
            replacements.put(ports.http(), String.valueOf(configuration.getHttpPort()));
            replacements.put(ports.https(), String.valueOf(configuration.getHttpsPort()));
            replacements.put(ports.stop(), String.valueOf(configuration.getStopPort()));
            IO.copy(IO.slurp(new ReplaceStringsInputStream(IO.read(file), replacements)).getBytes(), file);
        }

        tomcat.server(createServer(file.getAbsolutePath()));
        initialized = true;
    } else {
        copyFileTo(conf, "server.xml");
        initialized = false;
    }

    if (props != null && !props.isEmpty()) {
        final FileWriter systemProperties = new FileWriter(new File(conf, "system.properties"));
        try {
            props.store(systemProperties, "");
        } finally {
            IO.close(systemProperties);
        }
    }

    // Need to use JULI so log messages from the tests are visible
    // using openejb logging conf in embedded mode
    /* if we use our config (Logger.configure()) don't override it
    copyFileTo(conf, "logging.properties");
    System.setProperty("java.util.logging.manager", "org.apache.juli.ClassLoaderLogManager");
    final File logging = new File(conf, "logging.properties");
    if (logging.exists()) {
    System.setProperty("java.util.logging.config.file", logging.getAbsolutePath());
    }
    */

    // Trigger loading of catalina.properties
    CatalinaProperties.getProperty("foo");

    tomcat.setBaseDir(base.getAbsolutePath());
    tomcat.setHostname(configuration.getHost());
    if (!initialized) {
        tomcat.getHost().setAppBase(webapps.getAbsolutePath());
        tomcat.getEngine().setDefaultHost(configuration.getHost());
        tomcat.setHostname(configuration.getHost());
    }

    if (tomcat.getRawConnector() == null && !configuration.isSkipHttp()) {
        final Connector connector = new Connector(Http11Protocol.class.getName());
        connector.setPort(configuration.getHttpPort());
        connector.setAttribute("connectionTimeout", "3000");
        tomcat.getService().addConnector(connector);
        tomcat.setConnector(connector);
    }

    // create https connector
    if (configuration.isSsl()) {
        final Connector httpsConnector = new Connector(Http11Protocol.class.getName());
        httpsConnector.setPort(configuration.getHttpsPort());
        httpsConnector.setSecure(true);
        httpsConnector.setProperty("SSLEnabled", "true");
        httpsConnector.setProperty("sslProtocol", configuration.getSslProtocol());

        if (configuration.getKeystoreFile() != null) {
            httpsConnector.setAttribute("keystoreFile", configuration.getKeystoreFile());
        }
        if (configuration.getKeystorePass() != null) {
            httpsConnector.setAttribute("keystorePass", configuration.getKeystorePass());
        }
        httpsConnector.setAttribute("keystoreType", configuration.getKeystoreType());
        httpsConnector.setAttribute("clientAuth", configuration.getClientAuth());
        httpsConnector.setAttribute("keyAlias", configuration.getKeyAlias());

        tomcat.getService().addConnector(httpsConnector);

        if (configuration.isSkipHttp()) {
            tomcat.setConnector(httpsConnector);
        }
    }

    // Bootstrap Tomcat
    Logger.getInstance(LogCategory.OPENEJB_STARTUP, TomcatContainer.class)
            .info("Starting TomEE from: " + base.getAbsolutePath()); // create it after Logger is configured

    if (configuration.getUsers() != null) {
        for (final Map.Entry<String, String> user : configuration.getUsers().entrySet()) {
            tomcat.addUser(user.getKey(), user.getValue());
        }
    }
    if (configuration.getRoles() != null) {
        for (final Map.Entry<String, String> user : configuration.getRoles().entrySet()) {
            for (final String role : user.getValue().split(" *, *")) {
                tomcat.addRole(user.getKey(), role);
            }
        }
    }
    if (!initialized) {
        tomcat.init();
    }
    tomcat.start();

    // Bootstrap OpenEJB
    final Properties properties = new Properties();
    properties.setProperty("openejb.deployments.classpath", "false");
    properties.setProperty("openejb.loader", "tomcat-system");
    properties.setProperty("openejb.home", catalinaBase);
    properties.setProperty("openejb.base", catalinaBase);
    properties.setProperty("openejb.servicemanager.enabled", "false");
    if (configuration.getProperties() != null) {
        properties.putAll(configuration.getProperties());
    }
    if (properties.getProperty("openejb.system.apps") == null) { // will make startup faster and it is rarely useful for embedded case
        properties.setProperty("openejb.system.apps", "false");
    }
    if (configuration.isQuickSession()) {
        properties.put("openejb.session.manager", QuickSessionManager.class.getName());
    }

    try {
        final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        final Properties tomcatServerInfo = IO.readProperties(
                classLoader.getResourceAsStream("org/apache/catalina/util/ServerInfo.properties"),
                new Properties());

        String serverNumber = tomcatServerInfo.getProperty("server.number");
        if (serverNumber == null) {
            // Tomcat5 only has server.info
            final String serverInfo = tomcatServerInfo.getProperty("server.info");
            if (serverInfo != null) {
                final int slash = serverInfo.indexOf('/');
                serverNumber = serverInfo.substring(slash + 1);
            }
        }
        if (serverNumber != null) {
            System.setProperty("tomcat.version", serverNumber);
        }

        final String serverBuilt = tomcatServerInfo.getProperty("server.built");
        if (serverBuilt != null) {
            System.setProperty("tomcat.built", serverBuilt);
        }
    } catch (final Throwable e) {
        // no-op
    }

    final TomcatLoader loader = new TomcatLoader();
    loader.initDefaults(properties);

    // need to add properties after having initialized defaults
    // to properties passed to SystemInstance otherwise we loose some of them
    final Properties initProps = new Properties();
    initProps.putAll(System.getProperties());
    initProps.putAll(properties);
    if (SystemInstance.isInitialized()) {
        SystemInstance.get().getProperties().putAll(initProps);
    } else {
        SystemInstance.init(initProps);
    }
    SystemInstance.get().setComponent(StandardServer.class, (StandardServer) tomcat.getServer());
    SystemInstance.get().setComponent(Server.class, tomcat.getServer()); // needed again cause of init()

    loader.initialize(properties);

    assembler = SystemInstance.get().getComponent(Assembler.class);
    configurationFactory = new ConfigurationFactory();
}