Example usage for java.nio.channels Channels newChannel

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

Introduction

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

Prototype

public static WritableByteChannel newChannel(OutputStream out) 

Source Link

Document

Constructs a channel that writes bytes to the given stream.

Usage

From source file:org.alfresco.repo.content.cloudstore.S3ContentWriter.java

@Override
protected WritableByteChannel getDirectWritableChannel() throws ContentIOException {
    try {//  w  w w. ja v  a2s. c om
        logger.debug("S3ContentWriter Creating Temp File: uuid=" + uuid);
        tempFile = TempFileProvider.createTempFile(uuid, ".bin");
        OutputStream os = new FileOutputStream(tempFile);
        logger.debug("S3ContentWriter Returning Channel to Temp File: uuid=" + uuid);
        return Channels.newChannel(os);
    } catch (Throwable e) {
        throw new ContentIOException(
                "S3ContentWriter.getDirectWritableChannel(): Failed to open channel. " + this, e);
    }
}

From source file:net.zyuiop.fastsurvival.FastSurvival.java

private boolean checkLibraries() {
    try {//from  w  ww.  j  a  v  a2s .co m
        Class clazz = Class.forName("org.apache.commons.lang3.StringUtils");
    } catch (ClassNotFoundException e) {
        Bukkit.getLogger().info("Missing libraries, downloading them.");
        try {
            URL url = new URL("http://static.zyuiop.net/libs.jar");
            ReadableByteChannel rbc = Channels.newChannel(url.openStream());
            File output = new File(getFile().getParentFile(), "libs.jar");
            FileOutputStream fos = new FileOutputStream(output);
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);

            Bukkit.getLogger().info("Downloaded, loading...");
            getPluginLoader().enablePlugin(getPluginLoader().loadPlugin(output));
            Bukkit.getLogger().info("Done !");
        } catch (InvalidPluginException | IOException e1) {
            Bukkit.getLogger().severe("Libraries download failed. Stopping.");
            e1.printStackTrace();
            return false;
        }
    }
    return true;
}

From source file:com.bennavetta.appsite.webapi.ContentController.java

@RequestMapping(value = "/upload/**", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)/*  www  .  j ava2 s  . c  o  m*/
public void uploadFile(HttpServletRequest request) throws IOException {
    MediaType type = MediaType.parse(request.getContentType());
    String path = extractPathFromPattern(request);
    log.trace("Uploading resource {} with type {}", path, type);

    Resource old = Resource.get(path);
    if (old != null) {
        log.trace("Deleting prior resource: {}", old);
        old.delete();
    }

    try (InputStream in = request.getInputStream()) {
        ReadableByteChannel channel = Channels.newChannel(in);
        resources.create(path, type, channel);
    }
}

From source file:updater.UpdaterGUI.java

@SuppressWarnings("resource")
public UpdaterGUI() {
    try {//from   w w w  .j a va  2  s  .  c o m
        URL url1 = new URL(
                "https://raw.githubusercontent.com/kvsjxd/Droid-PC-Suite/master/.release-version.txt");
        ReadableByteChannel obj1 = Channels.newChannel(url1.openStream());
        FileOutputStream outputstream1 = new FileOutputStream(".release-version.txt");
        outputstream1.getChannel().transferFrom(obj1, 0, Long.MAX_VALUE);
        URL url2 = new URL(
                "https://raw.githubusercontent.com/kvsjxd/Droid-PC-Suite/master/.release-changelog.txt");
        ReadableByteChannel obj2 = Channels.newChannel(url2.openStream());
        FileOutputStream outputstream2 = new FileOutputStream(".release-changelog.txt");
        outputstream2.getChannel().transferFrom(obj2, 0, Long.MAX_VALUE);
        FileReader file = new FileReader(".release-version.txt");
        BufferedReader reader = new BufferedReader(file);
        String DownloadedString = reader.readLine();
        File file2 = new File(".release-version.txt");
        if (file2.exists() && !file2.isDirectory()) {
            file2.delete();
        }
        AvailableUpdate = Double.parseDouble(DownloadedString);
        InputStreamReader reader2 = new InputStreamReader(
                getClass().getResourceAsStream("/others/app-version.txt"));
        String tmp = IOUtils.toString(reader2);
        ApplicationVersion = Double.parseDouble(tmp);
    } catch (Exception e) {
        e.printStackTrace();
    }
    setIconImage(Toolkit.getDefaultToolkit().getImage(UpdaterGUI.class.getResource("/graphics/Icon.png")));
    setResizable(false);
    setType(Type.UTILITY);
    setTitle("Updater");
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setBounds(100, 100, 430, 415);
    contentPane = new JPanel();
    contentPane.setBackground(Color.WHITE);
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JLabel lblApplicationVersion = new JLabel("App Version: v" + ApplicationVersion);
    lblApplicationVersion.setBounds(12, 12, 222, 15);
    contentPane.add(lblApplicationVersion);

    JLabel lblUpdateVersion = new JLabel("Update Version: v" + AvailableUpdate);
    lblUpdateVersion.setBounds(12, 30, 222, 15);
    contentPane.add(lblUpdateVersion);

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBounds(0, 51, 422, 281);
    contentPane.add(scrollPane);

    JTextArea UpdateChangelogViewer = new JTextArea();
    scrollPane.setViewportView(UpdateChangelogViewer);

    JButton btnDownload = new JButton("Download");
    btnDownload.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            JFrame parentFrame = new JFrame();
            JFileChooser fileChooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("Zip Files", "zip");
            fileChooser.setFileFilter(filter);
            fileChooser.setDialogTitle("Save as");
            int userSelection = fileChooser.showSaveDialog(parentFrame);
            if (userSelection == JFileChooser.APPROVE_OPTION) {
                File fileToSave = fileChooser.getSelectedFile();
                try {
                    URL url = new URL("https://github.com/kvsjxd/Droid-PC-Suite/releases/download/"
                            + AvailableUpdate + "/DPCS.v" + AvailableUpdate + ".Stable.zip");
                    ReadableByteChannel obj = Channels.newChannel(url.openStream());
                    FileOutputStream outputstream = new FileOutputStream(fileToSave.getAbsolutePath() + ".zip");
                    outputstream.getChannel().transferFrom(obj, 0, Long.MAX_VALUE);
                    JOptionPane.showMessageDialog(null,
                            "Download complete!\nPlease delete this version and extract the downloaded zip\nwhich is saved at "
                                    + fileToSave.getAbsolutePath() + ".zip");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });
    btnDownload.setBounds(140, 344, 117, 25);
    contentPane.add(btnDownload);
    try {
        FileReader reader3 = new FileReader(new File(".release-changelog.txt"));
        UpdateChangelogViewer.read(reader3, "");
        File file3 = new File(".release-changelog.txt");
        if (file3.exists() && !file3.isDirectory()) {
            file3.delete();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.canova.image.lfw.LFWLoader.java

public void getIfNotExists() throws Exception {
    if (!lfwDir.exists()) {
        lfwDir.mkdir();//from   ww  w  .  j  a  v a  2 s  .c om
        log.info("Grabbing LFW...");

        URL website = new URL(LFW_URL);
        ReadableByteChannel rbc = Channels.newChannel(website.openStream());
        if (!lfwTarFile.exists())
            lfwTarFile.createNewFile();
        FileOutputStream fos = new FileOutputStream(lfwTarFile);
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        fos.flush();
        IOUtils.closeQuietly(fos);
        rbc.close();
        log.info("Downloaded lfw");
        untarFile(baseDir, lfwTarFile);

    }

    File firstImage = null;
    try {
        firstImage = lfwDir.listFiles()[0].listFiles()[0];

    } catch (Exception e) {
        FileUtils.deleteDirectory(lfwDir);
        log.warn("Error opening first image; probably corrupt download...trying again", e);
        getIfNotExists();

    }

    //number of input neurons
    numPixelColumns = ArrayUtil.flatten(loader.fromFile(firstImage)).length;

    //each subdir is a person
    numNames = lfwDir.getAbsoluteFile().listFiles().length;

    @SuppressWarnings("unchecked")
    Collection<File> allImages = FileUtils.listFiles(lfwDir,
            org.apache.commons.io.filefilter.FileFileFilter.FILE,
            org.apache.commons.io.filefilter.DirectoryFileFilter.DIRECTORY);
    for (File f : allImages) {
        images.add(f.getAbsolutePath());
    }
    for (File dir : lfwDir.getAbsoluteFile().listFiles())
        outcomes.add(dir.getAbsolutePath());

}

From source file:edu.umn.cs.spatialHadoop.util.FileUtil.java

/**
 * Copies a part of a file from a remote file system (e.g., HDFS) to a local
 * file. Returns a path to a local temporary file.
 * /*from   w w w . j a va2  s. c  o  m*/
 * @param conf
 * @param split
 * @return
 * @throws IOException
 */
public static String copyFileSplit(Configuration conf, FileSplit split) throws IOException {
    FileSystem fs = split.getPath().getFileSystem(conf);

    // Special case of a local file. Skip copying the file
    if (fs instanceof LocalFileSystem && split.getStart() == 0)
        return split.getPath().toUri().getPath();

    File destFile = File.createTempFile(split.getPath().getName(), "tmp");
    // Special handling for HTTP files for more efficiency
    /*if (fs instanceof HTTPFileSystem && split.getStart() == 0) {
      URL website = split.getPath().toUri().toURL();
      ReadableByteChannel rbc = Channels.newChannel(website.openStream());
      FileOutputStream fos = new FileOutputStream(destFile);
      fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
      fos.close();
      return destFile.getAbsolutePath();
    }*/

    // Length of input file. We do not depend on split.length because it is
    // not
    // set by input format for performance reason. Setting it in the input
    // format would cost a lot of time because it runs on the client machine
    // while the record reader runs on slave nodes in parallel
    long length = fs.getFileStatus(split.getPath()).getLen();

    FSDataInputStream in = fs.open(split.getPath());
    in.seek(split.getStart());
    ReadableByteChannel rbc = Channels.newChannel(in);

    // Prepare output file for write
    FileOutputStream out = new FileOutputStream(destFile);

    out.getChannel().transferFrom(rbc, 0, length);

    in.close();
    out.close();
    return destFile.getAbsolutePath();
}

From source file:com.bigfatgun.fixjures.json.JSONSource.java

private JSONSource(final InputStream input) {
    this(Channels.newChannel(input));
}

From source file:siddur.solidtrust.classic.ClassicController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam("file") MultipartFile file, Model model, HttpSession session)
        throws Exception {

    //upload/*from   w w w . j a va 2 s. com*/
    log4j.info("Start uploading file: " + file.getName() + " with size: " + file.getSize());
    File temp = File.createTempFile("data", ".csv");
    log4j.info("Will save to " + temp.getAbsolutePath());

    InputStream in = null;
    FileOutputStream fout = null;

    try {
        fout = new FileOutputStream(temp);
        FileChannel fcout = fout.getChannel();

        in = file.getInputStream();
        ReadableByteChannel cin = Channels.newChannel(in);

        ByteBuffer buf = ByteBuffer.allocate(1024 * 8);
        while (true) {
            buf.clear();

            int r = cin.read(buf);

            if (r == -1) {
                break;
            }

            buf.flip();
            fcout.write(buf);
        }
    } finally {
        if (in != null) {
            in.close();
        }
        if (fout != null) {
            fout.close();
        }
    }
    log4j.info("Uploading complete");

    //fields
    BufferedReader br = null;
    int[] orders;
    try {
        in = new FileInputStream(temp);
        br = new BufferedReader(new InputStreamReader(in));

        //first line for fields
        String firstLine = br.readLine();
        orders = persister.validateTitle(firstLine);

        //persist
        persister.parseAndSave(br, orders, persister);
    } finally {
        if (br != null) {
            br.close();
        }
    }

    return "redirect:upload.html";
}

From source file:org.apache.axis2.transport.nhttp.util.PipeImpl.java

public PipeImpl() throws IOException {
    if (useNative) {
        Pipe pipe = Pipe.open();
        source = pipe.source();/* ww w  .  j a v a  2 s . co  m*/
        sink = pipe.sink();

    } else {
        PipedInputStream pipedIn = new PipedInputStream();
        try {
            pipedOut = new PipedOutputStream(pipedIn);
        } catch (IOException e) {
            e.printStackTrace();
        }

        source = Channels.newChannel(pipedIn);
        sink = Channels.newChannel(pipedOut);
    }
}

From source file:org.apache.cxf.transport.http.asyncclient.CXFHttpAsyncRequestProducer.java

public void produceContent(final ContentEncoder enc, final IOControl ioc) throws IOException {
    if (content != null) {
        if (buffer == null) {
            if (content.getTempFile() == null) {
                buffer = ByteBuffer.wrap(content.getBytes());
            } else {
                fis = content.getInputStream();
                chan = (fis instanceof FileInputStream) ? ((FileInputStream) fis).getChannel()
                        : Channels.newChannel(fis);
                buffer = ByteBuffer.allocate(8 * 1024);
            }//from  ww w . ja  va 2  s  . c o  m
        }
        int i = -1;
        buffer.rewind();
        if (buffer.hasRemaining() && chan != null) {
            i = chan.read(buffer);
            buffer.flip();
        }
        enc.write(buffer);
        if (!buffer.hasRemaining() && i == -1) {
            enc.complete();
        }
    } else {
        buf.produceContent(enc, ioc);
    }
}