Example usage for java.nio.channels Channels newOutputStream

List of usage examples for java.nio.channels Channels newOutputStream

Introduction

In this page you can find the example usage for java.nio.channels Channels newOutputStream.

Prototype

public static OutputStream newOutputStream(AsynchronousByteChannel ch) 

Source Link

Document

Constructs a stream that writes bytes to the given channel.

Usage

From source file:org.blue.star.plugins.check_ftp.java

public boolean execute_check() {
    /* Declare variables */
    FTPClient ftp = new FTPClient();
    File filename = null;/* w  w  w.  j  av  a  2  s .c o m*/
    FileChannel channel;
    InputStream is;
    OutputStream os;
    int reply;

    if (super.verbose > 0)
        verbose = true;

    /* Configure client to meet our requirements */
    ftp.setDefaultPort(port);
    ftp.setDefaultTimeout(timeout);

    if (verbose) {
        System.out.println("Using FTP Server: " + hostname);
        System.out.println("Using FTP Port: " + port);
        System.out.println("Using Timeout of: " + timeout);
    }

    if (passive) {
        ftp.enterLocalPassiveMode();
        if (verbose)
            System.out.println("Using Passive Mode");
    }

    try {
        filename = new File(file);
        channel = new RandomAccessFile(filename, "rw").getChannel();

        if (verbose)
            System.out.println("Attempting FTP Connection to " + hostname);
        ftp.connect(hostname);
        reply = ftp.getReplyCode();

        /* Test to see if we actually managed to connect */
        if (!FTPReply.isPositiveCompletion(reply)) {
            if (verbose)
                System.out.println("FTP Connection to " + hostname + " failed");
            check_state = common_h.STATE_CRITICAL;
            check_message = ftp.getReplyString();
            filename.delete();
            ftp.disconnect();
            return true;
        }

        /* Try and login if we're using username/password */
        if (username != null && password != null) {
            if (verbose)
                System.out.println("Attempting to log in into FTP Server " + hostname);

            if (!ftp.login(username, password)) {
                if (verbose)
                    System.out.println("Unable to log in to FTP Server " + hostname);
                check_state = common_h.STATE_CRITICAL;
                check_message = ftp.getReplyString();
                ftp.disconnect();
                filename.delete();
                return true;
            }
        }

        if (verbose)
            System.out.println("Attempting to change to required directory");
        /* Try and change to the given directory */
        if (!ftp.changeWorkingDirectory(directory)) {
            if (verbose)
                System.out.println("Required directory cannot be found!");
            check_state = common_h.STATE_WARNING;
            check_message = ftp.getReplyString();
            ftp.disconnect();
            filename.delete();
            return true;
        }

        if (verbose)
            System.out.println("Attempting to retrieve specified file!");
        /* Try to get Stream on Remote File! */
        is = ftp.retrieveFileStream(file);

        if (is == null) {
            if (verbose)
                System.out.println("Unable to locate required file.");
            check_state = common_h.STATE_WARNING;
            check_message = ftp.getReplyString();
            ftp.disconnect();
            filename.delete();
            return true;
        }

        /* OutputStream */
        os = Channels.newOutputStream(channel);

        /* Create the buffer */
        byte[] buf = new byte[4096];

        if (verbose)
            System.out.println("Beginning File transfer...");
        for (int len = -1; (len = is.read(buf)) != -1;)
            os.write(buf, 0, len);

        if (verbose) {
            System.out.println("...transfer complete.");
            System.out.println("Attempting to finalise Command");
        }

        /* Finalise the transfer details */
        if (!ftp.completePendingCommand()) {
            if (verbose)
                System.out.println("Unable to finalise command");
            check_state = common_h.STATE_WARNING;
            check_message = ftp.getReplyString();
            ftp.disconnect();
            filename.delete();
            return true;
        }

        /* Clean up */
        if (verbose)
            System.out.println("Check Completed.");
        check_state = common_h.STATE_OK;
        check_message = ftp.getReplyString();

        /* Close out things */
        is.close();
        os.close();
        channel.close();
        filename.delete();

    } catch (IOException e) {
        check_state = common_h.STATE_CRITICAL;
        check_message = e.getMessage();
        if (filename != null)
            filename.delete();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.logout();
                ftp.disconnect();

            } catch (Exception e) {
            }
        }
    }

    return true;
}

From source file:org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin.java

private void startConnection() throws IOException {
    Launcher<JavaLanguageClient> launcher;
    ExecutorService executorService = Executors.newCachedThreadPool();
    protocol = new JDTLanguageServer(projectsManager, preferenceManager);
    if (JDTEnvironmentUtils.inSocketStreamDebugMode()) {
        String host = JDTEnvironmentUtils.getClientHost();
        Integer port = JDTEnvironmentUtils.getClientPort();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(host, port);
        AsynchronousServerSocketChannel serverSocket = AsynchronousServerSocketChannel.open()
                .bind(inetSocketAddress);
        try {//from  w ww  .  j a v  a  2 s  .c  o  m
            AsynchronousSocketChannel socketChannel = serverSocket.accept().get();
            InputStream in = Channels.newInputStream(socketChannel);
            OutputStream out = Channels.newOutputStream(socketChannel);
            Function<MessageConsumer, MessageConsumer> messageConsumer = it -> it;
            launcher = Launcher.createIoLauncher(protocol, JavaLanguageClient.class, in, out, executorService,
                    messageConsumer);
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException("Error when opening a socket channel at " + host + ":" + port + ".", e);
        }
    } else {
        ConnectionStreamFactory connectionFactory = new ConnectionStreamFactory();
        InputStream in = connectionFactory.getInputStream();
        OutputStream out = connectionFactory.getOutputStream();
        Function<MessageConsumer, MessageConsumer> wrapper;
        if ("false".equals(System.getProperty("watchParentProcess"))) {
            wrapper = it -> it;
        } else {
            wrapper = new ParentProcessWatcher(this.languageServer);
        }
        launcher = Launcher.createLauncher(protocol, JavaLanguageClient.class, in, out, executorService,
                wrapper);
    }
    protocol.connectClient(launcher.getRemoteProxy());
    launcher.startListening();
}

From source file:org.lockss.repository.TestRepositoryNodeImpl.java

void findMaxDirPathNio(File root) {
    int maxName = findMaxDirname(root) - 10;
    String one = mkstr("onedir", maxName) + "/";
    for (int rpt = 1; rpt < 1000; rpt++) {
        String path = StringUtils.repeat(one, rpt);
        File dir = new File(root, path);
        String dirstr = dir.getPath();
        boolean res = dir.mkdirs();
        if (!res) {
            log.info("mkdirs failed at " + dirstr.length() + " chars");
            break;
        }/*from  w w w .j ava  2s .  c o  m*/
        log.info("mkdirs ok: " + dirstr.length());
        File f = new File(dir, "foobbb");
        try {
            Path npath = Paths.get(f.getPath());
            Files.createFile(npath);
            FileChannel ochan = FileChannel.open(npath, StandardOpenOption.WRITE);
            OutputStream os = Channels.newOutputStream(ochan);
            os.write((byte) 44);
            os.close();

            FileChannel ichan = FileChannel.open(npath, StandardOpenOption.READ);
            InputStream is = Channels.newInputStream(ichan);
            int bb = is.read();
            is.close();
            assertEquals(44, bb);
            log.info("file ok at " + npath.toString().length() + " chars");
        } catch (FileNotFoundException fnfe) {
            log.error("FNF: " + f.getPath().length(), fnfe);
        } catch (IOException ioe) {
            log.error("IOE: " + f.getPath().length() + ", " + ioe.getMessage());
        }
    }
}

From source file:org.pentaho.googlecloudstorage.vfs.GoogleCloudStorageFileObject.java

@Override
protected OutputStream doGetOutputStream(boolean bAppend) throws FileSystemException {
    BlobInfo blobInfo = BlobInfo.newBuilder(getBucketName(), getPath()).build();
    Blob blob = storage.create(blobInfo);
    return Channels.newOutputStream(blob.writer());
}

From source file:org.springframework.cloud.gcp.storage.GoogleStorageResource.java

/**
 * Returns the output stream for a Google Cloud Storage file.
 * @return the object's output stream or {@code null} if the object doesn't exist and cannot be
 * created/*from   ww  w  . j a  v a 2  s  . c  o  m*/
 * @throws IOException if an issue occurs getting the OutputStream
 */
@Override
public OutputStream getOutputStream() throws IOException {
    if (isBucket()) {
        throw new IllegalStateException("Cannot open an output stream to a bucket: '" + getURI() + "'");
    } else {
        Blob blob = getBlob();

        if (blob == null || !blob.exists()) {
            if (!this.autoCreateFiles) {
                throw new FileNotFoundException("The blob was not found: " + getURI());
            }

            blob = createBlob();
        }

        return Channels.newOutputStream(blob.writer());
    }
}