下面列出了怎么用org.apache.commons.io.output.WriterOutputStream的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
@Issue("SECURITY-1458")
public void shouldNotExportPassword() throws Exception {
ConfigurationAsCode casc = ConfigurationAsCode.get();
final String passwordText = "Hello, world!";
BatchCloud cloud = new BatchCloud("testBatchCloud", "whatever",
"sge", 5, "sge.acmecorp.com", 8080,
"username", passwordText);
j.jenkins.clouds.add(cloud);
StringWriter writer = new StringWriter();
casc.export(new WriterOutputStream(writer, StandardCharsets.UTF_8));
String exported = writer.toString();
assertThat("Password should not have been exported",
exported, not(containsString(passwordText)));
}
private static List<String> getPublicKeys() throws Exception {
return new JschConfigSessionFactory() {
@Override
protected void configure(OpenSshConfig.Host hc, Session session) {
}
List<String> getPublicKeys() throws Exception {
JSch jSch = createDefaultJSch(FS.DETECTED);
List<String> keys = new ArrayList<>();
for (Object o : jSch.getIdentityRepository().getIdentities()) {
Identity i = (Identity) o;
KeyPair keyPair = KeyPair.load(jSch, i.getName(), null);
StringBuilder sb = new StringBuilder();
try (StringBuilderWriter sbw = new StringBuilderWriter(sb);
OutputStream os = new WriterOutputStream(sbw, "UTF-8")) {
keyPair.writePublicKey(os, keyPair.getPublicKeyComment());
} finally {
keyPair.dispose();
}
keys.add(sb.toString().trim());
}
return keys;
}
}.getPublicKeys();
}
protected String messageContextToText(org.apache.axis2.context.MessageContext msgCtx) throws IOException {
OMOutputFormat format = BaseUtils.getOMOutputFormat(msgCtx);
MessageFormatter messageFormatter = MessageProcessorSelector.getMessageFormatter(msgCtx);
StringWriter sw = new StringWriter();
OutputStream out = new WriterOutputStream(sw, format.getCharSetEncoding());
messageFormatter.writeTo(msgCtx, format, out, true);
out.close();
return sw.toString();
}
public static String toString(ExpressionNode node) {
StringWriter writer = new StringWriter();
try (PrintStream os = new PrintStream(new WriterOutputStream(writer, StandardCharsets.UTF_8))) {
print(node, os);
}
return writer.toString();
}
public static String toString(ExpressionNode node) {
StringWriter writer = new StringWriter();
try (PrintStream os = new PrintStream(new WriterOutputStream(writer, StandardCharsets.UTF_8))) {
print(node, os);
}
return writer.toString();
}
@Override
public void launch() throws IOException, InterruptedException {
if (launchCommand == null) {
commandField.setText("This launcher does not support launch in test mode.");
showAndWait();
return;
}
launchCommand.copyOutputTo(new WriterOutputStream(new TextAreaWriter(outputArea), Charset.defaultCharset()));
launchCommand.setMessageArea(new WriterOutputStream(new TextAreaWriter(errorArea), Charset.defaultCharset()));
if (launchCommand.start() == ITestLauncher.OK_OPTION) {
commandField.setText(launchCommand.toString());
showAndWait();
}
}
default String asString() throws IOException {
final StringWriter strData = new StringWriter();
try (final WriterOutputStream wos = new WriterOutputStream(strData, Charset.defaultCharset())) {
writeTo(wos);
}
return strData.toString();
}
@Test
public void test() throws Exception {
String config;
try(StringWriter sw = new StringWriter();
OutputStream osw = new WriterOutputStream(sw, StandardCharsets.UTF_8)) {
service.write(MimeTypeUtils.APPLICATION_JSON_VALUE, osw);
config = sw.toString();
}
System.out.println(config);
try (StringReader sr = new StringReader(config);
InputStream is = new ReaderInputStream(sr, StandardCharsets.UTF_8)) {
service.read(MimeTypeUtils.APPLICATION_JSON_VALUE, is);
}
sampleBean.check();
}
private Future<CommandResult> executeCommand(String command, File executionDirectory, boolean silent)
throws IOException {
StringWriter writer = new StringWriter();
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
try (WriterOutputStream outputStream = new WriterOutputStream(writer)) {
String outerCommand = "/bin/bash -lc";
CommandLine outer = CommandLine.parse(outerCommand);
outer.addArgument(command, false);
DefaultExecutor executor = new DefaultExecutor();
executor.setWorkingDirectory(executionDirectory);
executor.setStreamHandler(new PumpStreamHandler(silent ? outputStream : System.out, null));
executor.execute(outer, ENVIRONMENT, resultHandler);
resultHandler.waitFor();
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
return new AsyncResult<CommandResult>(
new CommandResult(resultHandler.getExitValue(), writer.toString(), resultHandler.getException()));
}
/**
* Writes out a given name / value pair.
* This is similar to {@link XMLWriter#writeVal(String, Object)}.
* This is needed because that similar method is not extensible and cannot be overriden
* (it is called recursively by other methods).
*
* @param name the name of the attribute.
* @param value the value of the attribute.
* @param data the complete set of response values.
* @throws IOException in case of I/O failure.
*/
public void writeValue(final String name, final Object value, final NamedList<?> data) throws IOException {
if (value == null) {
writeNull(name);
} else if (value instanceof ResultSet) {
final int start = req.getParams().getInt(CommonParams.START, 0);
final int rows = req.getParams().getInt(CommonParams.ROWS, 10);
writeStartDocumentList("response", start, rows, (Integer) data.remove(Names.NUM_FOUND), 1.0f);
final XMLOutput outputter = new XMLOutput(false);
outputter.format(new WriterOutputStream(writer), (ResultSet)value);
writeEndDocumentList();
} else if (value instanceof String || value instanceof Query) {
writeStr(name, value.toString(), false);
} else if (value instanceof Number) {
if (value instanceof Integer || value instanceof Short || value instanceof Byte) {
writeInt(name, value.toString());
} else if (value instanceof Long) {
writeLong(name, value.toString());
} else if (value instanceof Float) {
writeFloat(name, ((Float) value).floatValue());
} else if (value instanceof Double) {
writeDouble(name, ((Double) value).doubleValue());
}
} else if (value instanceof Boolean) {
writeBool(name, value.toString());
} else if (value instanceof Date) {
writeDate(name, (Date) value);
} else if (value instanceof Map) {
writeMap(name, (Map<?,?>) value, false, true);
} else if (value instanceof NamedList) {
writeNamedList(name, (NamedList<?>) value);
} else if (value instanceof Iterable) {
writeArray(name, ((Iterable<?>) value).iterator());
} else if (value instanceof Object[]) {
writeArray(name, (Object[]) value);
} else if (value instanceof Iterator) {
writeArray(name, (Iterator<?>) value);
}
}
public OutputStream asStream() throws StreamingException {
if (requestStream instanceof OutputStream) {
if (log.isDebugEnabled()) log.debug(getLogPrefix() + "returning OutputStream as OutputStream");
return (OutputStream) requestStream;
}
if (requestStream instanceof Writer) {
if (log.isDebugEnabled()) log.debug(getLogPrefix() + "returning Writer as OutputStream");
return new WriterOutputStream((Writer) requestStream, StreamUtil.DEFAULT_INPUT_STREAM_ENCODING);
}
if (requestStream instanceof ContentHandler) {
if (log.isDebugEnabled()) log.debug(getLogPrefix() + "returning ContentHandler as OutputStream");
return new ContentHandlerOutputStream((ContentHandler) requestStream, threadConnector);
}
return null;
}
/**
* Tests configuring the server w/o xml but configuring the JAXB objects directly.
*/
@SuppressWarnings("java:S2699") //sonar wants assertions, but this test is not run in CI
@Test
public void embeddedServerProgrammatic() throws Exception {
File homeDir = util.createTempDir("orientdb-home").getCanonicalFile();
System.setProperty("orient.home", homeDir.getPath());
System.setProperty(Orient.ORIENTDB_HOME, homeDir.getPath());
OServer server = new OServer();
OServerConfiguration config = new OServerConfiguration();
// Unsure what this is used for, its apparently assigned to xml location, but forcing it here
config.location = "DYNAMIC-CONFIGURATION";
File databaseDir = new File(homeDir, "db");
config.properties = new OServerEntryConfiguration[] {
new OServerEntryConfiguration("server.database.path", databaseDir.getPath())
};
config.handlers = Lists.newArrayList();
config.hooks = Lists.newArrayList();
config.network = new OServerNetworkConfiguration();
config.network.protocols = Lists.newArrayList(
new OServerNetworkProtocolConfiguration("binary", ONetworkProtocolBinary.class.getName())
);
OServerNetworkListenerConfiguration binaryListener = new OServerNetworkListenerConfiguration();
binaryListener.ipAddress = "0.0.0.0";
binaryListener.portRange = "2424-2430";
binaryListener.protocol = "binary";
binaryListener.socket = "default";
config.network.listeners = Lists.newArrayList(
binaryListener
);
config.storages = new OServerStorageConfiguration[] {};
config.users = new OServerUserConfiguration[] {
new OServerUserConfiguration("admin", "admin", "*")
};
config.security = new OServerSecurityConfiguration();
config.security.users = Lists.newArrayList();
config.security.resources = Lists.newArrayList();
server.startup(config);
// Dump config to log stream
StringWriter buff = new StringWriter();
OGlobalConfiguration.dumpConfiguration(new PrintStream(new WriterOutputStream(buff), true));
log("Global configuration:\n{}", buff);
server.activate();
server.shutdown();
}
@Override
public Object eval(String userExecutableClassName, ScriptContext context) throws ScriptException {
try {
JavaExecutable javaExecutable = getExecutable(userExecutableClassName);
JavaStandaloneExecutableInitializer execInitializer = new JavaStandaloneExecutableInitializer();
PrintStream output = new PrintStream(new WriterOutputStream(context.getWriter()), true);
execInitializer.setOutputSink(output);
PrintStream error = new PrintStream(new WriterOutputStream(context.getErrorWriter()), true);
execInitializer.setErrorSink(error);
Map<String, byte[]> propagatedVariables = null;
if (context.getAttribute(SchedulerConstants.VARIABLES_BINDING_NAME) != null) {
propagatedVariables = SerializationUtil.serializeVariableMap(((VariablesMap) context.getAttribute(SchedulerConstants.VARIABLES_BINDING_NAME)).getPropagatedVariables());
execInitializer.setPropagatedVariables(propagatedVariables);
} else {
execInitializer.setPropagatedVariables(Collections.<String, byte[]> emptyMap());
}
if (context.getAttribute(Script.ARGUMENTS_NAME) != null) {
execInitializer.setSerializedArguments((Map<String, byte[]>) ((Serializable[]) context.getAttribute(Script.ARGUMENTS_NAME))[0]);
} else {
execInitializer.setSerializedArguments(Collections.<String, byte[]> emptyMap());
}
if (context.getAttribute(SchedulerConstants.CREDENTIALS_VARIABLE) != null) {
execInitializer.setThirdPartyCredentials((Map<String, String>) context.getAttribute(SchedulerConstants.CREDENTIALS_VARIABLE));
} else {
execInitializer.setThirdPartyCredentials(Collections.<String, String> emptyMap());
}
if (context.getAttribute(SchedulerConstants.MULTI_NODE_TASK_NODESURL_BINDING_NAME) != null) {
List<String> nodesURLs = (List<String>) context.getAttribute(SchedulerConstants.MULTI_NODE_TASK_NODESURL_BINDING_NAME);
execInitializer.setNodesURL(nodesURLs);
} else {
execInitializer.setNodesURL(Collections.<String> emptyList());
}
javaExecutable.internalInit(execInitializer, context);
Serializable execute = javaExecutable.execute((TaskResult[]) context.getAttribute(SchedulerConstants.RESULTS_VARIABLE));
if (propagatedVariables != null) {
((Map<String, Serializable>) context.getAttribute(SchedulerConstants.VARIABLES_BINDING_NAME)).putAll(javaExecutable.getVariables());
}
output.close();
error.close();
return execute;
} catch (Throwable e) {
throw new ScriptException(new TaskException(getStackTraceAsString(e), e));
}
}
@Override
public void writeTo(Writer writer, Syntax syntax) throws IOException,
ModelRuntimeException, SyntaxNotSupportedException {
WriterOutputStream stream = new WriterOutputStream(writer, StandardCharsets.UTF_8);
writeTo(stream, syntax);
}
public Client(Settings settings) {
_additionalBatfishOptions = new HashMap<>();
_bfq = new TreeMap<>();
_settings = settings;
switch (_settings.getRunMode()) {
case batch:
if (_settings.getBatchCommandFile() == null) {
System.err.println(
"org.batfish.client: Command file not specified while running in batch mode.");
System.err.printf(
"Use '-%s <cmdfile>' if you want batch mode, or '-%s interactive' if you want "
+ "interactive mode\n",
Settings.ARG_COMMAND_FILE, Settings.ARG_RUN_MODE);
System.exit(1);
}
_logger = new BatfishLogger(_settings.getLogLevel(), false, _settings.getLogFile());
break;
case interactive:
System.err.println(
"This is not a supported client for Batfish. Please use pybatfish following the "
+ "instructions in the README: https://github.com/batfish/batfish/#how-do-i-get-started");
try {
_reader =
LineReaderBuilder.builder()
.terminal(TerminalBuilder.builder().build())
.completer(new ArgumentCompleter(new CommandCompleter(), new NullCompleter()))
.build();
Path historyPath = Paths.get(System.getenv(ENV_HOME), HISTORY_FILE);
historyPath.toFile().createNewFile();
_reader.setVariable(LineReader.HISTORY_FILE, historyPath.toAbsolutePath().toString());
_reader.unsetOpt(Option.INSERT_TAB); // supports completion with nothing entered
@SuppressWarnings("PMD.CloseResource") // PMD does not understand things closed later.
PrintWriter pWriter = new PrintWriter(_reader.getTerminal().output(), true);
@SuppressWarnings("PMD.CloseResource") // PMD does not understand things closed later.
OutputStream os = new WriterOutputStream(pWriter, StandardCharsets.UTF_8);
@SuppressWarnings("PMD.CloseResource") // PMD does not understand things closed later.
PrintStream ps = new PrintStream(os, true);
_logger = new BatfishLogger(_settings.getLogLevel(), false, ps);
} catch (Exception e) {
System.err.printf("Could not initialize client: %s\n", e.getMessage());
e.printStackTrace();
}
break;
default:
System.err.println("org.batfish.client: Unknown run mode.");
System.exit(1);
}
}
/**
* Creates a new {@link PropertiesTextWriter} that will write to the supplied
* {@link Writer}.
*
* @param writer
* The {@link Writer} to write the {@link Properties} document
* to.
*/
public PropertiesTextWriter(final Writer writer) {
this.os = new WriterOutputStream(writer,
PropertiesFormat.TEXT.getCharset());
}
/**
* Creates a new {@link PropertiesXMLWriter} that will write to the supplied
* {@link Writer}.
*
* @param writer
* The {@link Writer} to write the {@link Properties} document
* to.
*/
public PropertiesXMLWriter(final Writer writer) {
this.os = new WriterOutputStream(writer,
PropertiesFormat.XML.getCharset());
}