Example usage for java.nio.channels Channels newInputStream

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

Introduction

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

Prototype

public static InputStream newInputStream(AsynchronousByteChannel ch) 

Source Link

Document

Constructs a stream that reads bytes from the given channel.

Usage

From source file:net.transmutator4j.RunTransmutator4j.java

@Override
public void run() {

    long startTime = System.currentTimeMillis();
    InetAddress localhost;/*from w  w  w.  j  a va2 s  . c o m*/
    try {
        localhost = InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
        throw new IllegalStateException("can not resolve local host", e);
    }
    //socket get dynamically generated port
    SocketAddress socket = new InetSocketAddress(localhost, 0);
    AsynchronousChannelGroup group;
    try {
        group = AsynchronousChannelGroup.withFixedThreadPool(10, Executors.defaultThreadFactory());
    } catch (IOException e1) {
        throw new IllegalStateException("can not create channel group", e1);
    }

    try (

            AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open(group).bind(socket,
                    1);

    ) {

        int numTotalTests = runUnmutatedTests();
        long unmutatedTimeEnd = System.currentTimeMillis();
        long unmutatedElapsedTime = unmutatedTimeEnd - startTime;
        listener.testInfo(numTotalTests, unmutatedElapsedTime);
        System.out.println("unmutated tests took " + unmutatedElapsedTime + " ms");
        long timeOut = computeTimeoutTime(unmutatedElapsedTime);
        InetSocketAddress inetSocketAddress = (InetSocketAddress) server.getLocalAddress();
        int port = inetSocketAddress.getPort();
        server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
            @Override
            public void completed(AsynchronousSocketChannel resultChannel, Object attachment) {
                try {
                    ObjectInputStream in = new ObjectInputStream(Channels.newInputStream(resultChannel));
                    MutationTestResult testResult = (MutationTestResult) in.readObject();

                    in.close();

                    listener.mutationResult(testResult);
                    boolean stillPassed = testResult.testsStillPassed();
                    System.out.print(stillPassed ? "P" : ".");
                    System.out.flush();
                    numberOfMutationsMade++;

                    if (stillPassed) {
                        numberOfMutationsThatStillPassedTests++;
                    }
                } catch (IOException | ClassNotFoundException e) {
                    e.printStackTrace();
                    throw new RuntimeException("error getting test result ", e);
                }
                //accept a new connection
                server.accept(null, this);

            }

            @Override
            public void failed(Throwable e, Object attachment) {
                //   System.err.println(attachment + " failed with:" + e.getClass().getName());
                //    e.printStackTrace();
            }
        });

        OUTER: for (String classToMutate : new ClassPathClassRepository()) {
            boolean shouldMutate = shouldMutate(classToMutate);
            if (shouldMutate) {
                System.out.printf("mutating %s%n", classToMutate);
                boolean done = false;
                int mutationCount = 0;
                while (!done) {
                    JavaProcessBuilder builder = new JavaProcessBuilder(

                            "net.transmutator4j.Transmutator4j", classToMutate, nameOfTestSuite,
                            Integer.toString(mutationCount), Integer.toString(port));

                    try {
                        TimedProcess timedProcess = new TimedProcess(builder.getBuilder(), timeOut);
                        int exitValue = timedProcess.call();

                        TransmutatorUtil.EXIT_STATES exitState = TransmutatorUtil.EXIT_STATES
                                .getValueFor(exitValue);
                        if (exitState == TransmutatorUtil.EXIT_STATES.NO_MUTATIONS_MADE) {
                            done = true;
                            System.out.println();
                        } else if (exitState == TransmutatorUtil.EXIT_STATES.TIMED_OUT) {
                            numberOfMutationsThatTimedOut++;

                        }

                    } catch (InterruptedException e) {
                        System.err.println("detected cancellation...halting");
                        //stop iterating through all the classes
                        //by breaking out of outer for loop
                        break OUTER;
                    }

                    mutationCount++;

                }

            }
        }
        //kill any waiting connections this will cause the completionHandler's fail to get called
        group.shutdownNow();
        //group.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);

        long endTime = System.currentTimeMillis();
        System.out.printf("took %d ms to run %d mutations of which %d caused timeouts and %d still passed%n",
                (endTime - startTime), numberOfMutationsMade, numberOfMutationsThatTimedOut,
                numberOfMutationsThatStillPassedTests);

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (listener != null) {
            try {
                listener.close();
            } catch (IOException ignored) {
                //ignore
            }
        }
        group.shutdown();
    }
}

From source file:org.apache.axis2.transport.nhttp.ServerHandler.java

/**
 * Process a new incoming request/*from   ww w.  ja  v  a  2 s .  c  om*/
 * @param conn the connection
 */
public void requestReceived(final NHttpServerConnection conn) {

    HttpContext context = conn.getContext();
    HttpRequest request = conn.getHttpRequest();
    context.setAttribute(HttpContext.HTTP_REQUEST, request);

    // allocate temporary buffers to process this request
    context.setAttribute(REQUEST_BUFFER, ByteBuffer.allocate(2048));
    context.setAttribute(RESPONSE_BUFFER, ByteBuffer.allocate(2048));

    try {
        Pipe requestPipe = Pipe.open(); // the pipe used to process the request
        Pipe responsePipe = Pipe.open(); // the pipe used to process the response
        context.setAttribute(REQUEST_SINK_CHANNEL, requestPipe.sink());
        context.setAttribute(RESPONSE_SOURCE_CHANNEL, responsePipe.source());

        // create the default response to this request
        HttpVersion httpVersion = request.getRequestLine().getHttpVersion();
        HttpResponse response = responseFactory.newHttpResponse(httpVersion, HttpStatus.SC_OK, context);
        response.setParams(this.params);

        // create a basic HttpEntity using the source channel of the response pipe
        BasicHttpEntity entity = new BasicHttpEntity();
        entity.setContent(Channels.newInputStream(responsePipe.source()));
        if (httpVersion.greaterEquals(HttpVersion.HTTP_1_1)) {
            entity.setChunked(true);
        }
        response.setEntity(entity);

        // hand off processing of the request to a thread off the pool
        workerPool.execute(
                new ServerWorker(cfgCtx, conn, this, request, Channels.newInputStream(requestPipe.source()),
                        response, Channels.newOutputStream(responsePipe.sink())));

    } catch (IOException e) {
        handleException("Error processing request received for : " + request.getRequestLine().getUri(), e,
                conn);
    }
}

From source file:com.rogiel.httpchannel.service.impl.HotFileServiceTest.java

@Test
public void testDownloader() throws IOException {
    final URI downloadUrl = URI
            .create("http://hotfile.com/dl/129251605/9b4faf2/simulado_2010_1_res_all.zip.htm");

    final DownloadService<?> service = Services.matchURI(downloadUrl);

    final DownloadChannel channel = service.getDownloader(downloadUrl).openChannel(null, 0);
    final ByteArrayOutputStream bout = new ByteArrayOutputStream();
    IOUtils.copy(Channels.newInputStream(channel), bout);
    System.out.println(bout.size());
}

From source file:org.fastcatsearch.ir.document.DocumentWriter.java

public Document readDocument(int docNo) throws IOException, IRException {
    long prevPosPos = positionOutput.position();
    long docPos = -1;
    try {/*  ww  w . ja v a2 s  . c  o m*/
        long positionOffset = ((long) docNo) * IOUtil.SIZE_OF_LONG;
        positionOutput.seek(positionOffset);
        docPos = IOUtil.readLong(positionOutput.getRaf());
    } finally {
        positionOutput.seek(prevPosPos);
    }

    // find a document block
    long prevDocPos = docOutput.position();
    try {
        docOutput.seek(docPos);
        RandomAccessFile raf = docOutput.getRaf();
        int len = IOUtil.readInt(raf);
        long n = raf.getFilePointer();
        InputStream docInput = Channels.newInputStream(docOutput.getRaf().getChannel().position(n));
        //2014-11-26 ?  working ?   ? ? GC ?? OOM ? ?.
        // Stream  .
        InflaterInputStream decompressInputStream = null;
        inflaterOutput.reset();
        int count = -1;
        try {
            BoundedInputStream boundedInputStream = new BoundedInputStream(docInput, len);
            boundedInputStream.setPropagateClose(false);// docInput  .
            decompressInputStream = new InflaterInputStream(boundedInputStream, new Inflater(), 512);
            while ((count = decompressInputStream.read(workingBuffer)) != -1) {
                inflaterOutput.write(workingBuffer, 0, count);
            }
        } finally {
            decompressInputStream.close();
        }
    } finally {
        docOutput.seek(prevDocPos);
    }

    BytesRef bytesRef = inflaterOutput.getBytesRef();
    DataInput bai = new BytesDataInput(bytesRef.bytes, 0, bytesRef.length);

    Document document = new Document(fields.size());
    for (int i = 0; i < fields.size(); i++) {
        FieldSetting fs = fields.get(i);
        Field f = null;
        boolean hasValue = bai.readBoolean();
        if (hasValue) {
            f = fs.createEmptyField();
            f.readRawFrom(bai);
        } else {
            f = fs.createEmptyField();
        }
        if (f != null) {
            String multiValueDelimiter = fs.getMultiValueDelimiter();
            try {
                f.parseIndexable(multiValueDelimiter);
            } catch (FieldDataParseException e) {
                throw new IOException(e);
            }
        }
        document.add(f);
    }
    document.setDocId(docNo);
    return document;
}

From source file:com.rogiel.httpchannel.service.impl.MegaUploadServiceTest.java

@Test
public void testFreeDownloader() throws IOException {
    final DownloadChannel channel = service.getDownloader(URI.create("http://www.megaupload.com/?d=CVQKJ1KM"))
            .openChannel(new DownloadListener() {
                @Override// ww  w.j a  v a  2  s .  c  o m
                public boolean timer(long time) {
                    System.out.println("Waiting " + time);
                    // if (reason == TimerWaitReason.DOWNLOAD_TIMER)
                    // return true;
                    return true;
                }
            }, 0);
    final ByteArrayOutputStream bout = new ByteArrayOutputStream();
    IOUtils.copy(Channels.newInputStream(channel), bout);
    System.out.println(bout.size());
}

From source file:org.springframework.cloud.gcp.storage.integration.GcsSession.java

@Override
public InputStream readRaw(String source) throws IOException {
    String[] tokens = getBucketAndObjectFromPath(source);
    Assert.state(tokens.length == 2, "Can only write to files, not buckets.");
    return Channels.newInputStream(this.gcs.reader(tokens[0], tokens[1]));
}

From source file:com.almende.eve.state.file.ConcurrentJsonFileState.java

/**
 * Open file.//w  w  w .j a v  a  2s .  c o  m
 * 
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@SuppressWarnings("resource")
protected void openFile() throws IOException {
    Lock llock = null;
    synchronized (LOCKED) {
        llock = LOCKED.get(filename);
        if (llock == null) {
            llock = new Lock();
            LOCKED.put(filename, llock);
        }
    }
    synchronized (llock) {
        while (llock.locked) {
            try {
                llock.wait();
            } catch (final InterruptedException e) {
            }
        }
        llock.locked = true;

        final File file = new File(filename);
        if (!file.exists()) {
            llock.locked = false;
            llock.notifyAll();
            throw new IllegalStateException("Warning: File doesn't exist (anymore):'" + filename + "'");
        }

        channel = new RandomAccessFile(file, "rw").getChannel();
        try {
            // TODO: add support for shared locks, allowing parallel reading
            // operations.
            lock = channel.lock();

        } catch (final Exception e) {
            channel.close();
            channel = null;
            lock = null;
            llock.locked = false;
            llock.notifyAll();
            throw new IllegalStateException("error, couldn't obtain file lock on:" + filename, e);
        }
        fis = new BufferedInputStream(Channels.newInputStream(channel));
        fos = new BufferedOutputStream(Channels.newOutputStream(channel));
    }
}

From source file:com.aliyun.odps.volume.VolumeFSInputStream.java

private synchronized InputStream getInputStream() throws IOException {
    if (seekOptimization) {
        long index = pos / blockSize;
        if (!isPreLoaded) {
            isPreLoaded = true;//from w  ww. jav a 2s  .  c  om
            seekOptimization();
        }
        if (in != null && index == curIndex && isCache && isSeeked) {
            in = Channels.newInputStream(raf.getChannel().position(pos - curIndex * blockSize));
            return in;
        } else {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(raf);
            if (cache.get(index) != STATUS_DOWNLOADED) {
                curIndex = index;
                return getRemoteInputStream();
            } else {
                File blockFile = new File(buffer_block_dir, getBlockFileName(index));
                if (!blockFile.exists()) {
                    cache.remove(index);
                    curIndex = index;
                    return getRemoteInputStream();
                }
                return getLocalInputStream(index);
            }
        }
    } else {
        IOUtils.closeQuietly(in);
        return getRemoteInputStream();
    }

}

From source file:com.rogiel.httpchannel.service.impl.HotFileServiceTest.java

@Test
public void testLoggedInDownloader() throws IOException {
    service.getAuthenticator(new Credential(VALID_USERNAME, VALID_PASSWORD)).login();

    final DownloadChannel channel = service
            .getDownloader(//from  w  ww  . j a  va2  s . c  o  m
                    URI.create("http://hotfile.com/dl/129251605/9b4faf2/simulado_2010_1_res_all.zip.html"))
            .openChannel(null, 0);

    final ByteArrayOutputStream bout = new ByteArrayOutputStream();
    IOUtils.copy(Channels.newInputStream(channel), bout);
    System.out.println(bout.size());
}

From source file:com.chicm.cmraft.rpc.PacketUtils.java

public static RpcCall parseRpcResponseFromChannel(AsynchronousSocketChannel channel, BlockingService service)
        throws InterruptedException, ExecutionException, IOException {
    RpcCall call = null;//  w  w  w.ja v  a  2 s .  c  o  m
    long t = System.currentTimeMillis();
    InputStream in = Channels.newInputStream(channel);
    byte[] datasize = new byte[MESSAGE_LENGHT_FIELD_SIZE];
    in.read(datasize);
    int nDataSize = bytes2Int(datasize);

    LOG.debug("message size: " + nDataSize);

    int len = 0;
    ByteBuffer buf = ByteBuffer.allocateDirect(nDataSize);
    for (; len < nDataSize;) {
        len += channel.read(buf).get();
    }
    if (len < nDataSize) {
        LOG.error("SOCKET READ FAILED, len:" + len);
        return call;
    }
    byte[] data = new byte[nDataSize];
    buf.flip();
    buf.get(data);
    int offset = 0;
    CodedInputStream cis = CodedInputStream.newInstance(data, offset, nDataSize - offset);
    int headerSize = cis.readRawVarint32();
    offset += cis.getTotalBytesRead();
    ResponseHeader header = ResponseHeader.newBuilder().mergeFrom(data, offset, headerSize).build();

    offset += headerSize;
    cis.skipRawBytes(headerSize);
    cis.resetSizeCounter();
    int bodySize = cis.readRawVarint32();
    offset += cis.getTotalBytesRead();

    MethodDescriptor md = service.getDescriptorForType().findMethodByName(header.getResponseName());
    Builder builder = service.getResponsePrototype(md).newBuilderForType();
    Message body = null;
    if (builder != null) {
        body = builder.mergeFrom(data, offset, bodySize).build();
    }
    call = new RpcCall(header.getId(), header, body, md);
    if (LOG.isTraceEnabled()) {
        LOG.trace("Parse Rpc response from socket: " + call.getCallId() + ", takes"
                + (System.currentTimeMillis() - t) + " ms");
    }

    return call;
}