use of java.nio.channels.Channel in project jdk8u_jdk by JetBrains.
the class PipeWriter method main.
/**
* Main program to start the activation system. <br>
* The usage is as follows: rmid [-port num] [-log dir].
*/
public static void main(String[] args) {
boolean stop = false;
// already.
if (System.getSecurityManager() == null) {
System.setSecurityManager(new SecurityManager());
}
try {
int port = ActivationSystem.SYSTEM_PORT;
RMIServerSocketFactory ssf = null;
/*
* If rmid has an inherited channel (meaning that it was
* launched from inetd), set the server socket factory to
* return the inherited server socket.
**/
Channel inheritedChannel = AccessController.doPrivileged(new PrivilegedExceptionAction<Channel>() {
public Channel run() throws IOException {
return System.inheritedChannel();
}
});
if (inheritedChannel != null && inheritedChannel instanceof ServerSocketChannel) {
/*
* Redirect System.err output to a file.
*/
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
public Void run() throws IOException {
File file = Files.createTempFile("rmid-err", null).toFile();
PrintStream errStream = new PrintStream(new FileOutputStream(file));
System.setErr(errStream);
return null;
}
});
ServerSocket serverSocket = ((ServerSocketChannel) inheritedChannel).socket();
port = serverSocket.getLocalPort();
ssf = new ActivationServerSocketFactory(serverSocket);
System.err.println(new Date());
System.err.println(getTextResource("rmid.inherited.channel.info") + ": " + inheritedChannel);
}
String log = null;
List<String> childArgs = new ArrayList<>();
/*
* Parse arguments
*/
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-port")) {
if (ssf != null) {
bomb(getTextResource("rmid.syntax.port.badarg"));
}
if ((i + 1) < args.length) {
try {
port = Integer.parseInt(args[++i]);
} catch (NumberFormatException nfe) {
bomb(getTextResource("rmid.syntax.port.badnumber"));
}
} else {
bomb(getTextResource("rmid.syntax.port.missing"));
}
} else if (args[i].equals("-log")) {
if ((i + 1) < args.length) {
log = args[++i];
} else {
bomb(getTextResource("rmid.syntax.log.missing"));
}
} else if (args[i].equals("-stop")) {
stop = true;
} else if (args[i].startsWith("-C")) {
childArgs.add(args[i].substring(2));
} else {
bomb(MessageFormat.format(getTextResource("rmid.syntax.illegal.option"), args[i]));
}
}
if (log == null) {
if (ssf != null) {
bomb(getTextResource("rmid.syntax.log.required"));
} else {
log = "log";
}
}
debugExec = AccessController.doPrivileged(new GetBooleanAction("sun.rmi.server.activation.debugExec"));
/**
* Determine class name for activation exec policy (if any).
*/
String execPolicyClassName = AccessController.doPrivileged(new GetPropertyAction("sun.rmi.activation.execPolicy", null));
if (execPolicyClassName == null) {
if (!stop) {
DefaultExecPolicy.checkConfiguration();
}
execPolicyClassName = "default";
}
/**
* Initialize method for activation exec policy.
*/
if (!execPolicyClassName.equals("none")) {
if (execPolicyClassName.equals("") || execPolicyClassName.equals("default")) {
execPolicyClassName = DefaultExecPolicy.class.getName();
}
try {
Class<?> execPolicyClass = getRMIClass(execPolicyClassName);
execPolicy = execPolicyClass.newInstance();
execPolicyMethod = execPolicyClass.getMethod("checkExecCommand", ActivationGroupDesc.class, String[].class);
} catch (Exception e) {
if (debugExec) {
System.err.println(getTextResource("rmid.exec.policy.exception"));
e.printStackTrace();
}
bomb(getTextResource("rmid.exec.policy.invalid"));
}
}
if (stop == true) {
final int finalPort = port;
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
System.setProperty("java.rmi.activation.port", Integer.toString(finalPort));
return null;
}
});
ActivationSystem system = ActivationGroup.getSystem();
system.shutdown();
System.exit(0);
}
/*
* Fix for 4173960: Create and initialize activation using
* a static method, startActivation, which will build the
* Activation state in two ways: if when rmid is run, no
* log file is found, the ActLogHandler.recover(...)
* method will create a new Activation instance.
* Alternatively, if a logfile is available, a serialized
* instance of activation will be read from the log's
* snapshot file. Log updates will be applied to this
* Activation object until rmid's state has been fully
* recovered. In either case, only one instance of
* Activation is created.
*/
startActivation(port, ssf, log, childArgs.toArray(new String[childArgs.size()]));
// prevent activator from exiting
while (true) {
try {
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException e) {
}
}
} catch (Exception e) {
System.err.println(MessageFormat.format(getTextResource("rmid.unexpected.exception"), e));
e.printStackTrace();
}
System.exit(1);
}
use of java.nio.channels.Channel in project jdk8u_jdk by JetBrains.
the class NullTest method main.
public static void main(String[] args) {
// test the assertion that SelectorProvider.inheritedChannel()
// and System.inheritedChannel return null when standard input
// is not connected to a socket
Channel c1, c2;
try {
c1 = SelectorProvider.provider().inheritedChannel();
c2 = System.inheritedChannel();
} catch (IOException ioe) {
throw new RuntimeException("Unexpected IOException: " + ioe);
}
if (c1 != null || c2 != null) {
throw new RuntimeException("Channel returned - unexpected");
}
}
use of java.nio.channels.Channel in project jdk8u_jdk by JetBrains.
the class InheritedChannel method createChannel.
/*
* If standard inherited channel is connected to a socket then return a Channel
* of the appropriate type based standard input.
*/
private static Channel createChannel() throws IOException {
// dup the file descriptor - we do this so that for two reasons :-
// 1. Avoids any timing issues with FileDescriptor.in being closed
// or redirected while we create the channel.
// 2. Allows streams based on file descriptor 0 to co-exist with
// the channel (closing one doesn't impact the other)
int fdVal = dup(0);
// Examine the file descriptor - if it's not a socket then we don't
// create a channel so we release the file descriptor.
int st;
st = soType0(fdVal);
if (st != SOCK_STREAM && st != SOCK_DGRAM) {
close0(fdVal);
return null;
}
// Next we create a FileDescriptor for the dup'ed file descriptor
// Have to use reflection and also make assumption on how FD
// is implemented.
Class[] paramTypes = { int.class };
Constructor<?> ctr = Reflect.lookupConstructor("java.io.FileDescriptor", paramTypes);
Object[] args = { new Integer(fdVal) };
FileDescriptor fd = (FileDescriptor) Reflect.invoke(ctr, args);
// Now create the channel. If the socket is a streams socket then
// we see if tthere is a peer (ie: connected). If so, then we
// create a SocketChannel, otherwise a ServerSocketChannel.
// If the socket is a datagram socket then create a DatagramChannel
SelectorProvider provider = SelectorProvider.provider();
assert provider instanceof sun.nio.ch.SelectorProviderImpl;
Channel c;
if (st == SOCK_STREAM) {
InetAddress ia = peerAddress0(fdVal);
if (ia == null) {
c = new InheritedServerSocketChannelImpl(provider, fd);
} else {
int port = peerPort0(fdVal);
assert port > 0;
InetSocketAddress isa = new InetSocketAddress(ia, port);
c = new InheritedSocketChannelImpl(provider, fd, isa);
}
} else {
c = new InheritedDatagramChannelImpl(provider, fd);
}
return c;
}
use of java.nio.channels.Channel in project felix by apache.
the class Pipe method doCall.
private Result doCall() {
// The errChannel will be used to print errors to the error stream
// Before the command is actually executed (i.e. during the initialization,
// including the redirection processing), it will be the original error stream.
// This value may be modified by redirections and the redirected error stream
// will be effective just before actually running the command.
WritableByteChannel errChannel = (WritableByteChannel) streams[2];
ThreadIO threadIo = closure.session().threadIO();
try {
List<Token> tokens = statement.redirections();
for (int i = 0; i < tokens.size(); i++) {
Token t = tokens.get(i);
Matcher m;
if ((m = Pattern.compile("(?:([0-9])?|(&)?)>(>)?").matcher(t)).matches()) {
int fd;
if (m.group(1) != null) {
fd = Integer.parseInt(m.group(1));
} else if (m.group(2) != null) {
// both 1 and 2
fd = -1;
} else {
fd = 1;
}
boolean append = m.group(3) != null;
Set<StandardOpenOption> options = new HashSet<>();
options.add(StandardOpenOption.WRITE);
options.add(StandardOpenOption.CREATE);
options.add(append ? StandardOpenOption.APPEND : StandardOpenOption.TRUNCATE_EXISTING);
Token tok = tokens.get(++i);
Object val = Expander.expand(tok, closure);
for (Path p : toPaths(val)) {
p = closure.session().redirect(p, WRITE);
Channel ch = Files.newByteChannel(p, options);
if (fd >= 0) {
setStream(ch, fd, WRITE);
} else {
setStream(ch, 1, WRITE);
setStream(ch, 2, WRITE);
}
}
} else if ((m = Pattern.compile("([0-9])?>&([0-9])").matcher(t)).matches()) {
int fd0 = 1;
if (m.group(1) != null) {
fd0 = Integer.parseInt(m.group(1));
}
int fd1 = Integer.parseInt(m.group(2));
if (streams[fd0] != null && toclose[fd0]) {
streams[fd0].close();
}
// If the stream has to be closed, close it when both streams are closed
if (toclose[fd1]) {
Channel channel = streams[fd1];
AtomicInteger references = new AtomicInteger();
streams[fd0] = new RefByteChannel(channel, references);
streams[fd1] = new RefByteChannel(channel, references);
toclose[fd0] = true;
} else {
streams[fd0] = streams[fd1];
toclose[fd0] = false;
}
} else if ((m = Pattern.compile("([0-9])?<(>)?").matcher(t)).matches()) {
int fd = 0;
if (m.group(1) != null) {
fd = Integer.parseInt(m.group(1));
}
boolean output = m.group(2) != null;
Set<StandardOpenOption> options = new HashSet<>();
options.add(StandardOpenOption.READ);
if (output) {
options.add(StandardOpenOption.WRITE);
options.add(StandardOpenOption.CREATE);
}
Token tok = tokens.get(++i);
Object val = Expander.expand(tok, closure);
for (Path p : toPaths(val)) {
p = closure.session().redirect(p, READ + (output ? WRITE : 0));
Channel ch = Files.newByteChannel(p, options);
setStream(ch, fd, READ + (output ? WRITE : 0));
}
} else if ((m = Pattern.compile("<<-?").matcher(t)).matches()) {
final Token hereDoc = tokens.get(++i);
final boolean stripLeadingTabs = t.charAt(t.length() - 1) == '-';
InputStream doc = new InputStream() {
final byte[] bytes = hereDoc.toString().getBytes();
int index = 0;
boolean nl = true;
@Override
public int read() throws IOException {
if (nl && stripLeadingTabs) {
while (index < bytes.length && bytes[index] == '\t') {
index++;
}
}
if (index < bytes.length) {
int ch = bytes[index++];
nl = ch == '\n';
return ch;
}
return -1;
}
};
Channel ch = Channels.newChannel(doc);
setStream(ch, 0, READ);
} else if (Token.eq("<<<", t)) {
Token word = tokens.get(++i);
Object val = Expander.expand("\"" + word + "\"", closure);
String str = val != null ? String.valueOf(val) : "";
Channel ch = Channels.newChannel(new ByteArrayInputStream(str.getBytes()));
setStream(ch, 0, READ);
}
}
for (int i = 0; i < streams.length; i++) {
streams[i] = wrap(streams[i]);
}
// Create streams
in = Channels.newInputStream((ReadableByteChannel) streams[0]);
out = new PrintStream(Channels.newOutputStream((WritableByteChannel) streams[1]), true);
err = new PrintStream(Channels.newOutputStream((WritableByteChannel) streams[2]), true);
// Change the error stream to the redirected one, now that
// the command is about to be executed.
errChannel = (WritableByteChannel) streams[2];
if (threadIo != null) {
threadIo.setStreams(in, out, err);
}
Pipe previous = setCurrentPipe(this);
try {
Object result;
// Very special case for empty statements with redirection
if (statement.tokens().isEmpty() && toclose[0]) {
ByteBuffer bb = ByteBuffer.allocate(1024);
while (((ReadableByteChannel) streams[0]).read(bb) >= 0 || bb.position() != 0) {
bb.flip();
((WritableByteChannel) streams[1]).write(bb);
bb.compact();
}
result = null;
} else {
result = closure.execute(statement);
}
// If an error has been set
if (error != 0) {
return new Result(error);
}
// We don't print the result if we're at the end of the pipe
if (result != null && !endOfPipe && !Boolean.FALSE.equals(closure.session().get(".FormatPipe"))) {
out.println(closure.session().format(result, Converter.INSPECT));
}
return new Result(result);
} finally {
setCurrentPipe(previous);
}
} catch (Exception e) {
if (!endOfPipe) {
String msg = "gogo: " + e.getClass().getSimpleName() + ": " + e.getMessage() + "\n";
try {
errChannel.write(ByteBuffer.wrap(msg.getBytes()));
} catch (IOException ioe) {
e.addSuppressed(ioe);
}
}
return new Result(e);
} finally {
if (out != null) {
out.flush();
}
if (err != null) {
err.flush();
}
if (threadIo != null) {
threadIo.close();
}
try {
for (int i = 0; i < 10; i++) {
if (toclose[i] && streams[i] != null) {
streams[i].close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
use of java.nio.channels.Channel in project dataverse by IQSS.
the class ExportService method cacheExport.
// This method runs the selected metadata exporter, caching the output
// in a file in the dataset directory / container based on its DOI:
private void cacheExport(DatasetVersion version, String format, JsonObject datasetAsJson, Exporter exporter) throws ExportException {
try {
// With some storage drivers, we can open a WritableChannel, or OutputStream
// to directly write the generated metadata export that we want to cache;
// Some drivers (like Swift) do not support that, and will give us an
// "operation not supported" exception. If that's the case, we'll have
// to save the output into a temp file, and then copy it over to the
// permanent storage using the IO "save" command:
boolean tempFileRequired = false;
File tempFile = null;
OutputStream outputStream = null;
Dataset dataset = version.getDataset();
StorageIO<Dataset> storageIO = null;
try {
storageIO = DataAccess.createNewStorageIO(dataset, "placeholder");
Channel outputChannel = storageIO.openAuxChannel("export_" + format + ".cached", DataAccessOption.WRITE_ACCESS);
outputStream = Channels.newOutputStream((WritableByteChannel) outputChannel);
} catch (IOException ioex) {
tempFileRequired = true;
tempFile = File.createTempFile("tempFileToExport", ".tmp");
outputStream = new FileOutputStream(tempFile);
}
try {
Path cachedMetadataFilePath = Paths.get(version.getDataset().getFileSystemDirectory().toString(), "export_" + format + ".cached");
if (!tempFileRequired) {
FileOutputStream cachedExportOutputStream = new FileOutputStream(cachedMetadataFilePath.toFile());
exporter.exportDataset(version, datasetAsJson, cachedExportOutputStream);
cachedExportOutputStream.flush();
cachedExportOutputStream.close();
} else {
// this method copies a local filesystem Path into this DataAccess Auxiliary location:
exporter.exportDataset(version, datasetAsJson, outputStream);
outputStream.flush();
outputStream.close();
logger.fine("Saving path as aux for temp file in: " + Paths.get(tempFile.getAbsolutePath()));
storageIO.savePathAsAux(Paths.get(tempFile.getAbsolutePath()), "export_" + format + ".cached");
boolean tempFileDeleted = tempFile.delete();
logger.fine("tempFileDeleted: " + tempFileDeleted);
}
} catch (IOException ioex) {
throw new ExportException("IO Exception thrown exporting as " + "export_" + format + ".cached");
}
} catch (IOException ioex) {
throw new ExportException("IO Exception thrown exporting as " + "export_" + format + ".cached");
}
}
Aggregations