@Test public void shouldPrefixStderrOutput() { CommandLine line = CommandLine.createCommandLine("rmdir").withArg("/a/directory/that/does/not/exist"); InMemoryStreamConsumer output = new InMemoryStreamConsumer(); ProcessWrapper processWrapper = line.execute(output, new EnvironmentVariableContext(), null); processWrapper.waitForExit(); assertThat(output.getAllOutput(), containsString("STDERR: ")); }
public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value == null) { setText(getDefaultText()); } else if (value instanceof ProcessWrapper) { ProcessWrapper w = (ProcessWrapper) value; setFont(w.isConnected() ? connectedFont : disconnectedFont); setText(w.getName()); } return this; }
@Test @RunIf( value = EnhancedOSChecker.class, arguments = {DO_NOT_RUN_ON, OSChecker.WINDOWS}) public void shouldBeAbleToSpecifyEncoding() throws IOException { String chrisWasHere = "?????"; CommandLine line = CommandLine.createCommandLine("echo").withArg(chrisWasHere).withEncoding("UTF-8"); InMemoryStreamConsumer output = new InMemoryStreamConsumer(); ProcessWrapper processWrapper = line.execute(output, new EnvironmentVariableContext(), null); processWrapper.waitForExit(); assertThat(output.getAllOutput(), containsString(chrisWasHere)); }
@Override public void detachInputStream() { PMS.get().getFrame().setReadValue(0, ""); if (attachedThread != null) { attachedThread.setReadyToStop(true); } Runnable checkEnd = new Runnable() { @Override public void run() { try { Thread.sleep(CHECK_END_OF_PROCESS); } catch (InterruptedException e) { LOGGER.error(null, e); } if (attachedThread != null && attachedThread.isReadyToStop()) { if (!attachedThread.isDestroyed()) { attachedThread.stopProcess(); } reset(); } } }; new Thread(checkEnd, "Buffered IO End Checker").start(); }
@Test @RunIf(value = OSChecker.class, arguments = OSChecker.WINDOWS) public void shouldLogPasswordsOnOutputAsStarsUnderWindows() throws IOException { CommandLine line = CommandLine.createCommandLine("cmd") .withArg("/c") .withArg("echo") .withArg("My Password is:") .withArg(new PasswordArgument("secret")); InMemoryStreamConsumer output = new InMemoryStreamConsumer(); InMemoryStreamConsumer displayOutputStreamConsumer = InMemoryStreamConsumer.inMemoryConsumer(); ProcessWrapper processWrapper = line.execute(output, new EnvironmentVariableContext(), null); processWrapper.waitForExit(); assertThat(output.getAllOutput(), containsString("secret")); assertThat(displayOutputStreamConsumer.getAllOutput(), not(containsString("secret"))); }
/** Stop and wait for the process to exit. */ public void stop() { try { if (process != null) { process.stop(); process.waitFor(); process = null; } } catch (Exception e) { throw new RuntimeException("Could not stop container", e); } finally { closeConnection(); final ExecutorService exec = executor; if (exec != null) { exec.shutdownNow(); executor = null; } } }
@Override public int read(boolean firstRead, long readCount) { if (readCount > INITIAL_BUFFER_SIZE && readCount < maxMemorySize) { int newMargin = maxMemorySize - MARGIN_MEDIUM; if (bufferOverflowWarning != newMargin) { LOGGER.debug("Setting margin to 2Mb"); } this.bufferOverflowWarning = newMargin; } if (eof && readCount >= writeCount) { return -1; } int c = 0; int minBufferS = firstRead ? minMemorySize : secondread_minsize; while (writeCount - readCount <= minBufferS && !eof && c < 15) { if (c == 0) { LOGGER.trace("Suspend Read: readCount=" + readCount + " / writeCount=" + writeCount); } c++; try { Thread.sleep(CHECK_INTERVAL); } catch (InterruptedException e) { } } if (attachedThread != null) { attachedThread.setReadyToStop(false); } if (c > 0) { LOGGER.trace("Resume Read: readCount=" + readCount + " / writeCount=" + writeCount); } if (buffer == null || !buffered) { return -1; } try { return 0xff & buffer[(int) (readCount % maxMemorySize)]; } catch (ArrayIndexOutOfBoundsException ex) { LOGGER.error("Buffer read ArrayIndexOutOfBoundsException error.", ex); LOGGER.error("buffer.length: " + formatter.format(buffer.length) + " bytes."); LOGGER.error("readCount: \"" + readCount + "\""); LOGGER.error("maxMemorySize: \"" + maxMemorySize + "\""); return -1; } }
@Test @RunIf( value = EnhancedOSChecker.class, arguments = {DO_NOT_RUN_ON, OSChecker.WINDOWS}) public void shouldLogPasswordsOnEnvironemntAsStarsUnderLinux() throws IOException { CommandLine line = CommandLine.createCommandLine("echo") .withArg("My Password is:") .withArg("secret") .withArg(new PasswordArgument("secret")); EnvironmentVariableContext environmentVariableContext = new EnvironmentVariableContext(); environmentVariableContext.setProperty("ENV_PASSWORD", "secret", false); InMemoryStreamConsumer output = new InMemoryStreamConsumer(); InMemoryStreamConsumer forDisplay = InMemoryStreamConsumer.inMemoryConsumer(); ProcessWrapper processWrapper = line.execute(output, environmentVariableContext, null); processWrapper.waitForExit(); assertThat(forDisplay.getAllOutput(), not(containsString("secret"))); assertThat(output.getAllOutput(), containsString("secret")); }
@Override public InputStream getInputStream(long newReadPosition) { if (attachedThread != null) { attachedThread.setReadyToStop(false); } WaitBufferedInputStream atominputStream; if (!configuration.getTrancodeBlocksMultipleConnections() || getCurrentInputStream() == null) { atominputStream = new WaitBufferedInputStream(this); inputStreams.add(atominputStream); } else { if (configuration.getTrancodeKeepFirstConnections()) { LOGGER.debug( "BufferedOutputFile is already attached to an InputStream: " + getCurrentInputStream()); } else { // Ditlew - fixes the above (the above iterator breaks on items getting close, cause they // will remove them self from the arraylist) while (inputStreams.size() > 0) { try { inputStreams.get(0).close(); } catch (IOException e) { LOGGER.error("Error: ", e); } } inputStreams.clear(); atominputStream = new WaitBufferedInputStream(this); inputStreams.add(atominputStream); LOGGER.debug("Reassign inputstream: " + getCurrentInputStream()); } return null; } if (newReadPosition > 0) { LOGGER.debug("Setting InputStream new position to: " + formatter.format(newReadPosition)); atominputStream.setReadCount(newReadPosition); } return atominputStream; }
@Test public void shouldGetIdleTimeForGivenProcess() { processManager = new ProcessManager(); ProcessWrapper processWrapperOne = mock(ProcessWrapper.class); Process processOne = mock(Process.class); ProcessWrapper processWrapperTwo = mock(ProcessWrapper.class); Process processTwo = mock(Process.class); ConcurrentMap<Process, ProcessWrapper> processMap = processManager.getProcessMap(); processMap.put(processOne, processWrapperOne); processMap.put(processTwo, processWrapperTwo); when(processWrapperOne.getProcessTag()).thenReturn("tag1"); when(processWrapperOne.getIdleTime()).thenReturn(200L); when(processWrapperTwo.getProcessTag()).thenReturn("tag2"); when(processWrapperTwo.getIdleTime()).thenReturn(100L); long timeout = processManager.getIdleTimeFor("tag2"); assertThat(timeout, is(100L)); }
public void start() { try { configuration.validate(); final String address = NetworkUtils.formatPossibleIpv6Address( configuration.getHostControllerManagementAddress()); final int port = configuration.getHostControllerManagementPort(); final URI connectionURI = new URI("remote://" + address + ":" + port); // Create the connection - this will try to connect on the first request connection = clientConfiguration.createConnection(connectionURI, getCallbackHandler()); String jbossHomeDir = configuration.getJbossHome(); final String additionalJavaOpts = System.getProperty("jboss.options"); File modulesJar = new File(jbossHomeDir + "/jboss-modules.jar"); if (modulesJar.exists() == false) throw new IllegalStateException("Cannot find: " + modulesJar); String javaHome = configuration.getJavaHome(); String java = (javaHome != null) ? javaHome + "/bin/java" : "java"; File domainDir = configuration.getDomainDirectory() != null ? new File(configuration.getDomainDirectory()) : new File(new File(jbossHomeDir), "domain"); String domainPath = domainDir.getAbsolutePath(); final String modulePath; if (configuration.getModulePath() != null && !configuration.getModulePath().isEmpty()) { modulePath = configuration.getModulePath(); } else { modulePath = jbossHomeDir + "/modules"; } // No point backing up the file in a test scenario, just write what we need. File usersFile = new File(domainPath + "/configuration/mgmt-users.properties"); FileOutputStream fos = new FileOutputStream(usersFile); PrintWriter pw = new PrintWriter(fos); pw.println( "slave=" + new UsernamePasswordHashUtil() .generateHashedHexURP( "slave", "ManagementRealm", "slave_user_password".toCharArray())); pw.close(); fos.close(); List<String> cmd = new ArrayList<String>(); cmd.add(java); if (additionalJavaOpts != null) { for (String opt : additionalJavaOpts.split("\\s+")) { cmd.add(opt); } } TestSuiteEnvironment.getIpv6Args(cmd); cmd.add("-Djboss.home.dir=" + jbossHomeDir); cmd.add("-Dorg.jboss.boot.log.file=" + domainPath + "/log/process-controller.log"); cmd.add( "-Dlogging.configuration=file:" + jbossHomeDir + "/domain/configuration/logging.properties"); cmd.add("-jar"); cmd.add(modulesJar.getAbsolutePath()); cmd.add("-mp"); cmd.add(modulePath); // cmd.add("-jaxpmodule"); // cmd.add("javax.xml.jaxp-provider"); cmd.add("org.jboss.as.process-controller"); cmd.add("-jboss-home"); cmd.add(jbossHomeDir); cmd.add("-jvm"); cmd.add(java); cmd.add("--"); cmd.add("-Dorg.jboss.boot.log.file=" + domainPath + "/log/host-controller.log"); cmd.add( "-Dlogging.configuration=file:" + jbossHomeDir + "/domain/configuration/logging.properties"); TestSuiteEnvironment.getIpv6Args(cmd); if (additionalJavaOpts != null) { for (String opt : additionalJavaOpts.split("\\s+")) { cmd.add(opt); } } cmd.add("--"); cmd.add("-default-jvm"); cmd.add(java); if (configuration.getHostCommandLineProperties() != null) { for (String opt : configuration.getHostCommandLineProperties().split("\\s+")) { cmd.add(opt); } } String domainDirectory = configuration.getDomainDirectory(); if (domainDirectory != null) { cmd.add("-Djboss.domain.base.dir=" + domainDirectory); } else { domainDirectory = domainPath; } if (configuration.getDomainConfigFile() != null) { String name = copyConfigFile( new File(configuration.getDomainConfigFile()), new File(domainDirectory, "configuration")); cmd.add("-domain-config"); cmd.add(name); } if (configuration.getHostConfigFile() != null) { String name = copyConfigFile( new File(configuration.getHostConfigFile()), new File(domainDirectory, "configuration")); cmd.add("-host-config"); cmd.add(name); } if (configuration.getHostControllerManagementAddress() != null) { cmd.add("--interprocess-hc-address"); cmd.add(configuration.getHostControllerManagementAddress()); cmd.add("--pc-address"); cmd.add(configuration.getHostControllerManagementAddress()); } // the process working dir final String workingDir = configuration.getDomainDirectory(); // Start the process final ProcessWrapper wrapper = new ProcessWrapper( configuration.getHostName(), cmd, Collections.<String, String>emptyMap(), workingDir); wrapper.start(); process = wrapper; // Wait for the servers to be started boolean serversAvailable = false; long start = System.currentTimeMillis(); long deadline = start + configuration.getStartupTimeoutInSeconds() * 1000; // Wait a while before starting to check for the servers TimeUnit.SECONDS.sleep(2); while (serversAvailable == false) { long remaining = deadline - System.currentTimeMillis(); if (remaining <= 0) { break; } if (!serversAvailable) { TimeUnit.MILLISECONDS.sleep(250); } serversAvailable = areServersStarted(); } if (!serversAvailable) { throw new TimeoutException( String.format( "Managed servers were not started within [%d] seconds", configuration.getStartupTimeoutInSeconds())); } log.info("All servers started in " + (System.currentTimeMillis() - start) + " ms"); } catch (Exception e) { throw new RuntimeException("Could not start container", e); } }
@Override public int read(boolean firstRead, long readCount, byte buf[], int off, int len) { if (readCount > INITIAL_BUFFER_SIZE && readCount < maxMemorySize) { int newMargin = maxMemorySize - MARGIN_MEDIUM; if (bufferOverflowWarning != newMargin) { LOGGER.debug("Setting margin to 2Mb"); } this.bufferOverflowWarning = newMargin; } if (eof && readCount >= writeCount) { return -1; } int c = 0; int minBufferS = firstRead ? minMemorySize : secondread_minsize; while (writeCount - readCount <= minBufferS && !eof && c < 15) { if (c == 0) { LOGGER.trace("Suspend Read: readCount=" + readCount + " / writeCount=" + writeCount); } c++; try { Thread.sleep(CHECK_INTERVAL); } catch (InterruptedException e) { } } if (attachedThread != null) { attachedThread.setReadyToStop(false); } if (c > 0) { LOGGER.trace("Resume Read: readCount=" + readCount + " / writeCount=" + writeCount); } if (buffer == null || !buffered) { return -1; } int mb = (int) (readCount % maxMemorySize); int endOF = buffer.length; int cut = 0; if (eof && (writeCount - readCount) < len) { cut = (int) (len - (writeCount - readCount)); } if (mb >= endOF - len) { try { System.arraycopy(buffer, mb, buf, off, endOF - mb - cut); } catch (ArrayIndexOutOfBoundsException ex) { LOGGER.error("Something went wrong with the buffer.", ex); LOGGER.error("buffer.length: " + formatter.format(buffer.length) + " bytes."); LOGGER.error("mb: " + mb); LOGGER.error("buf.length: " + formatter.format(buf.length) + " bytes."); LOGGER.error("off: " + off); LOGGER.error("endOF - mb - cut: " + (endOF - mb - cut)); } return endOF - mb; } else { System.arraycopy(buffer, mb, buf, off, len - cut); return len; } }