Java Code Examples for org.wildfly.security.manager.WildFlySecurityManager#getPropertyPrivileged()

The following examples show how to use org.wildfly.security.manager.WildFlySecurityManager#getPropertyPrivileged() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CliBootOperationsTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
void build() throws Exception {
    Files.createDirectories(markerDirectory.toPath());
    sb.append(" -D" + AdditionalBootCliScriptInvoker.MARKER_DIRECTORY_PROPERTY + "=" + markerDirectory.getAbsolutePath());

    File cliFile = new File(markerDirectory, "commands.cli");
    Files.createFile(cliFile.toPath());
    try (BufferedWriter writer = new BufferedWriter(new FileWriter(cliFile))) {
        writer.write(commands == null ? "" : commands);
        writer.write("\n\n");
    }
    sb.append(" -D" + AdditionalBootCliScriptInvoker.CLI_SCRIPT_PROPERTY + "=" + cliFile.getAbsolutePath());

    if (skipReload) {
        sb.append(" -D" + AdditionalBootCliScriptInvoker.SKIP_RELOAD_PROPERTY + "=true");
    }

    // Propagate this property since it has the maven repository information which is needed on CI
    if (WildFlySecurityManager.getPropertyPrivileged("cli.jvm.args", null) != null) {
        sb.append(" " + WildFlySecurityManager.getPropertyPrivileged("cli.jvm.args", null));
    }

    WildFlySecurityManager.setPropertyPrivileged("jvm.args", sb.toString());
}
 
Example 2
Source File: AbstractControllerService.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static int getBootStackSize() {
    String prop = WildFlySecurityManager.getPropertyPrivileged(BOOT_STACK_SIZE_PROPERTY, null);
    if (prop == null) {
        return  DEFAULT_BOOT_STACK_SIZE;
    } else {
        int base = 1;
        String multiple = prop;
        int lastIdx = prop.length() - 1;
        if (lastIdx > 0) {
            char last = prop.charAt(lastIdx);
            if ('k' == last || 'K' == last) {
                multiple = prop.substring(0, lastIdx);
                base = 1024;
            } else if ('m' == last || 'M' == last) {
                multiple = prop.substring(0, lastIdx);
                base = 1024 * 1024;
            }
        }
        try {
            return Integer.parseInt(multiple) * base;
        } catch (NumberFormatException e) {
            ROOT_LOGGER.invalidSystemPropertyValue(prop, BOOT_STACK_SIZE_PROPERTY, DEFAULT_BOOT_STACK_SIZE);
            return DEFAULT_BOOT_STACK_SIZE;
        }
    }
}
 
Example 3
Source File: BlockingTimeoutImpl.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static int resolveDefaultTimeout() {
    String propValue = WildFlySecurityManager.getPropertyPrivileged(SYSTEM_PROPERTY, DEFAULT_TIMEOUT_STRING);
    if (sysPropLocalValue == null || !sysPropLocalValue.equals(propValue)) {
        // First call or the system property changed
        sysPropLocalValue = propValue;
        int number = -1;
        try {
            number = Integer.valueOf(sysPropLocalValue);
        } catch (NumberFormatException nfe) {
            // ignored
        }

        if (number > 0) {
            defaultLocalValue = number * 1000; // seconds to ms
        } else {
            ControllerLogger.MGMT_OP_LOGGER.invalidDefaultBlockingTimeout(sysPropLocalValue, SYSTEM_PROPERTY, DEFAULT_TIMEOUT);
            defaultLocalValue = DEFAULT_TIMEOUT * 1000; // seconds to ms
        }
    }
    return defaultLocalValue;
}
 
Example 4
Source File: CliBootOperationsTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Before
public void setup() throws Exception {
    originalJvmArgs = WildFlySecurityManager.getPropertyPrivileged("jvm.args", null);
    timestamp = String.valueOf(System.currentTimeMillis());
    File target = new File("target").getAbsoluteFile();
    if (!Files.exists(target.toPath())) {
        throw new IllegalStateException("No target/ directory");
    }

    File parent = new File(target, "cli-boot-ops");
    if (!Files.exists(parent.toPath())) {
        Files.createDirectories(parent.toPath());
    }

    markerDirectory = new File(parent, timestamp);
    if (Files.exists(markerDirectory.toPath())) {
        throw new IllegalStateException(markerDirectory.getAbsolutePath() + " already exists");
    }

}
 
Example 5
Source File: BlockingTimeoutImpl.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/** Allows testsuites to shorten the domain timeout adder */
private static int resolveDomainTimeoutAdder() {
    String propValue = WildFlySecurityManager.getPropertyPrivileged(DOMAIN_TEST_SYSTEM_PROPERTY, DEFAULT_DOMAIN_TIMEOUT_STRING);
    if (sysPropDomainValue == null || !sysPropDomainValue.equals(propValue)) {
        // First call or the system property changed
        sysPropDomainValue = propValue;
        int number = -1;
        try {
            number = Integer.valueOf(sysPropDomainValue);
        } catch (NumberFormatException nfe) {
            // ignored
        }

        if (number > 0) {
            defaultDomainValue = number; // this one is in ms
        } else {
            ControllerLogger.MGMT_OP_LOGGER.invalidDefaultBlockingTimeout(sysPropDomainValue, DOMAIN_TEST_SYSTEM_PROPERTY, DEFAULT_DOMAIN_TIMEOUT_ADDER);
            defaultDomainValue = DEFAULT_DOMAIN_TIMEOUT_ADDER;
        }
    }
    return defaultDomainValue;
}
 
Example 6
Source File: SystemPropertyValueWriteAttributeHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName,
                                       ModelNode resolvedValue, ModelNode currentValue, HandbackHolder<SysPropValue> handbackHolder) throws OperationFailedException {

    final String name = PathAddress.pathAddress(operation.get(OP_ADDR)).getLastElement().getValue();
    String setValue = resolvedValue.isDefined() ? resolvedValue.asString() : null;
    // This method will only be called if systemPropertyUpdater != null (see requiresRuntime())
    final boolean applyToRuntime = systemPropertyUpdater.isRuntimeSystemPropertyUpdateAllowed(name, setValue, context.isBooting());

    if (applyToRuntime) {
        final String oldValue = WildFlySecurityManager.getPropertyPrivileged(name, null);
        if (setValue != null) {
            WildFlySecurityManager.setPropertyPrivileged(name, setValue);
        } else {
            WildFlySecurityManager.clearPropertyPrivileged(name);
        }
        systemPropertyUpdater.systemPropertyUpdated(name, setValue);

        handbackHolder.setHandback(new SysPropValue(name, oldValue));
    }

    return !applyToRuntime;
}
 
Example 7
Source File: WildFlyAcmeClient.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void cleanupAfterChallenge(AcmeAccount account, AcmeChallenge challenge) throws AcmeException {
    Assert.checkNotNullParam("account", account);
    Assert.checkNotNullParam("challenge", challenge);
    // ensure the token is valid before proceeding
    String token = challenge.getToken();
    if (! token.matches(TOKEN_REGEX)) {
        throw ROOT_LOGGER.invalidCertificateAuthorityChallenge();
    }

    // delete the file that was created to prove identifier control
    String responseFilePath = WildFlySecurityManager.getPropertyPrivileged("jboss.home.dir", ".") + ACME_CHALLENGE_PREFIX + token;
    File responseFile = new File(responseFilePath);
    if (responseFile.exists()) {
        responseFile.delete();
    }
}
 
Example 8
Source File: BootScriptInvoker.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void handleProperties(File propertiesFile) {
    try ( InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(propertiesFile), StandardCharsets.UTF_8)) {
        props.load(inputStreamReader);
        for (String key : props.stringPropertyNames()) {
            String original = WildFlySecurityManager.getPropertyPrivileged(key, null);
            if (original != null) {
                existingProps.put(key, original);
            }
            WildFlySecurityManager.setPropertyPrivileged(key, props.getProperty(key));
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 9
Source File: LongOutputTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Before
public void setup() throws Exception {
    readThreadActive = new AtomicBoolean(true);
    threads = new ArrayList<>();
    queue = new ArrayBlockingQueue<>(1);
    consoleInput = new PipedInputStream(bufferSize);
    consoleWriter = new PrintWriter(new PipedOutputStream(consoleInput));
    consoleOutput = new PipedOutputStream();
    consoleInputStream = new PipedInputStream(consoleOutput, bufferSize);
    consoleReader = new InputStreamReader(consoleInputStream);
    sb = new StringBuilder();
    // tests can  manipulate with jboss.cli.config system property thus we need  keep have original value so
    // it can be restored in @After phase
    originalCliConfig = WildFlySecurityManager.getPropertyPrivileged("jboss.cli.config", "");
}
 
Example 10
Source File: CLIEmbedServerTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void testPathDir(final String propName, final String value) throws IOException, InterruptedException {
    String currBaseDir = null;
    final String newStandalone = "CLIEmbedServerTestCaseStandaloneTmp";
    assertFalse(cli.isConnected());
    try {
        // save the current value
        currBaseDir = WildFlySecurityManager.getPropertyPrivileged(JBOSS_SERVER_BASE_DIR, null);
        // The current directory isn't set until the embedded server is started, just use the root directory if the
        // property was not previously set.
        if (currBaseDir == null) {
            currBaseDir = ROOT + File.separator + "standalone";
        }
        CLIEmbedUtil.copyServerBaseDir(ROOT, "standalone", newStandalone, true);
        String newBaseDir = ROOT + File.separator + newStandalone;
        WildFlySecurityManager.setPropertyPrivileged(propName, newBaseDir + File.separator + value);
        String line = "embed-server --std-out=echo " + JBOSS_HOME;
        cli.sendLine(line);
        assertTrue(cli.isConnected());

        for(String prop : SERVER_PROPS) {
            if (prop.equals(propName)) {
                assertPath(propName, ROOT + File.separator + newStandalone + File.separator + value);
            } else {
                // just make sure the unchanged property has the default basedir
                assertTrue(WildFlySecurityManager.getPropertyPrivileged(prop, "").contains(currBaseDir));
            }
        }
    } finally {
        // stop the server
        cli.sendLine("stop-embedded-server");
        // restore the original
        setProperties(currBaseDir);
        FileUtils.deleteDirectory(new File(ROOT + File.separator + newStandalone));
    }
}
 
Example 11
Source File: FilterTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static void createModule() {
    final String jbossHome = WildFlySecurityManager.getPropertyPrivileged("jboss.home", ".");
    final Path modulesDir = Paths.get(jbossHome, "modules");
    Assert.assertTrue("Could not find modules directory: " + modulesDir, Files.exists(modulesDir));
    // Create an archive for the module
    final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "logging-test.jar")
            .addClasses(TestFilter.class);

    final Path testModule = Paths.get(modulesDir.toString(), "org", "jboss", "as", "logging", "test", "main");
    try {
        Files.createDirectories(testModule);
        try (
                BufferedInputStream in = new BufferedInputStream(AbstractLoggingTestCase.class.getResourceAsStream("module.xml"));
                BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(testModule.resolve("module.xml")))
        ) {
            final byte[] buffer = new byte[512];
            int len;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        }

        // Copy the JAR
        try (OutputStream out = Files.newOutputStream(testModule.resolve("logging-test.jar"), StandardOpenOption.CREATE_NEW)) {
            jar.as(ZipExporter.class).exportTo(out);
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 12
Source File: CliConfigImpl.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static String resolveString(String str) throws XMLStreamException {
    if(str == null) {
        return null;
    }
    if(str.startsWith("${") && str.endsWith("}")) {
        str = str.substring(2, str.length() - 1);
        final String resolved = WildFlySecurityManager.getPropertyPrivileged(str, null);
        if(resolved == null) {
            throw new XMLStreamException("Failed to resolve '" + str + "' to a non-null value.");
        }
        str = resolved;
    }
    return str;
}
 
Example 13
Source File: LoggingExtension.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static boolean getBooleanProperty(final String property, final boolean dft) {
    final String value = WildFlySecurityManager.getPropertyPrivileged(property, null);
    if (value == null) {
        return dft;
    }
    return value.isEmpty() || Boolean.parseBoolean(value);
}
 
Example 14
Source File: LoggingSubsystemTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testLegacyConfigurations() throws Exception {
    // Get a list of all the logging_x_x.xml files
    final Pattern pattern = Pattern.compile("(logging|expressions)_\\d+_\\d+\\.xml");
    // Using the CP as that's the standardSubsystemTest will use to find the config file
    final String cp = WildFlySecurityManager.getPropertyPrivileged("java.class.path", ".");
    final String[] entries = cp.split(Pattern.quote(File.pathSeparator));
    final List<String> configs = new ArrayList<>();
    for (String entry : entries) {
        final Path path = Paths.get(entry);
        if (Files.isDirectory(path)) {
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
                    final String name = file.getFileName().toString();
                    if (pattern.matcher(name).matches()) {
                        configs.add("/" + name);
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        }
    }

    // The paths shouldn't be empty
    Assert.assertFalse("No configs were found", configs.isEmpty());

    for (String configId : configs) {
        // Run the standard subsystem test, but don't compare the XML as it should never match
        standardSubsystemTest(configId, false);
    }
}
 
Example 15
Source File: LoggingTestEnvironment.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static Path getDirectory(final String propName, final String... paths) {
    final String value = WildFlySecurityManager.getPropertyPrivileged(propName, null);
    final Path dir;
    if (value == null) {
        dir = Paths.get(".", paths);
    } else {
        dir = Paths.get(value);
    }
    try {
        Files.createDirectories(dir);
    } catch (IOException e) {
        throw new RuntimeException("Failed to create directory: " + propName, e);
    }
    return dir;
}
 
Example 16
Source File: EnvironmentRestorer.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
EnvironmentRestorer(final String... propertyKeys) {
    this.propertiesToReset = new HashMap<>();
    for (String key : propertyKeys) {
        final String value = WildFlySecurityManager.getPropertyPrivileged(key, null);
        propertiesToReset.put(key, value);
    }
    propertiesToReset.put("jboss.home.dir", WildFlySecurityManager.getPropertyPrivileged("jboss.home.dir", null));
    propertiesToReset.put("org.jboss.boot.log.file", WildFlySecurityManager.getPropertyPrivileged("org.jboss.boot.log.file", null));
}
 
Example 17
Source File: CliConfigImpl.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private CliConfigImpl() {
    defaultControllerProtocol = "remote+http";

    historyEnabled = true;
    historyFileName = ".jboss-cli-history";
    historyFileDir = WildFlySecurityManager.getPropertyPrivileged("user.home", null);
    historyMaxSize = 500;

    connectionTimeout = 5000;
}
 
Example 18
Source File: ConfigurationFile.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private int getInteger(final String name, final int defaultValue) {
    final String val = WildFlySecurityManager.getPropertyPrivileged(name, null);
    try {
        return val == null ? defaultValue : Integer.parseInt(val);
    } catch (NumberFormatException ignored) {
        return defaultValue;
    }
}
 
Example 19
Source File: CLIEmbedHostControllerTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Test
public void testBaseDir() throws IOException, InterruptedException {
    String currBaseDir = null;
    final String newDomain = "CLIEmbedServerTestCaseHostControllerTmp";

    assertFalse(cli.isConnected());

    try {
        // save the current value, if it has one
        currBaseDir = WildFlySecurityManager.getPropertyPrivileged(JBOSS_DOMAIN_BASE_DIR, null);

        CLIEmbedUtil.copyServerBaseDir(ROOT, "domain", newDomain, true);
        CLIEmbedUtil.copyConfig(ROOT, newDomain, "logging.properties.backup", "logging.properties", false);

        String newBaseDir = ROOT + File.separator + newDomain;

        setProperties(newBaseDir);
        final String line = "embed-host-controller --host-config=host-cli.xml --domain-config=domain-cli.xml --std-out=echo " + JBOSS_HOME;
        cli.sendLine(line);
        assertTrue(cli.isConnected());
        cli.sendLine("/system-property=" + newDomain + ":add(value=" + newDomain +")");
        assertProperty(newDomain, newDomain, false);
        // verify we've logged to the right spot at least, and directories were created
        // WFCORE-1187
        //File f = new File(ROOT + File.separator + newDomain + File.separator + "log" + File.separator + "host-controller.log");
        //assertTrue(f.exists());
        //assertTrue(f.length() > 0);

        // stop the hc, and restart it with default properties
        cli.sendLine("stop-embedded-host-controller");

        setProperties(null);
        cli.sendLine(line);
        assertTrue(cli.isConnected());
        // shouldn't be set
        assertProperty(newDomain, null, true);
        cli.sendLine("stop-embedded-host-controller");

        setProperties(newBaseDir);
        cli.sendLine(line);
        assertTrue(cli.isConnected());
        // shouldn't be set
        assertProperty(newDomain, newDomain, false);
    } finally {
        cli.sendLine("stop-embedded-host-controller");
        // clean up copy
        FileUtils.deleteDirectory(ROOT + File.separator + newDomain);
        // restore the originals
        setProperties(currBaseDir);
    }
}
 
Example 20
Source File: JvmType.java    From wildfly-core with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * Create a {@code JvmType} based on the location of the root dir of the JRE/JDK installation, as specified
 * by the system property {@code java.home}.
 * @param forLaunch {@code true} if the created object will be used for launching servers; {@code false}
 *                              if it is simply a data holder. A value of {@code true} will disable
 *                              some validity checks and may disable determining if the JVM is modular
 * @return the {@code JvmType}. Will not return {@code null}
 */
public static JvmType createFromSystemProperty(boolean forLaunch) {
    final String javaHome = WildFlySecurityManager.getPropertyPrivileged(JAVA_HOME_SYS_PROP, null);
    return createFromJavaHome(javaHome, forLaunch);
}