Package net.jcores.jre

Examples of net.jcores.jre.CommonCore


     * @return The same core file object (<code>this</code>).
     */
    public CoreFile append(Object object, final Option... options) {
        if (object == null) return this;

        final CommonCore cc = this.commonCore;
        final String string = object.toString();

        map(new F1<File, Object>() {
            public Object f(File x) {
                try {
View Full Code Here


            this.commonCore.report(MessageType.MISUSE, "Destination null for copy().");
            return this;
        }

        final File dest = new File(destination);
        final CommonCore cc = this.commonCore;

        return new CoreFile(this.commonCore, map(new F1<File, File[]>() {
            @Override
            public File[] f(File x) {
                return Files.copy(cc, x, dest);
View Full Code Here

     * <br/>
     *
     * @return A CoreByteBuffer with binary content.
     */
    public CoreByteBuffer data() {
        final CommonCore cc = this.commonCore;
        return new CoreByteBuffer(this.commonCore, map(new F1<File, ByteBuffer>() {
            public ByteBuffer f(File x) {
                try {
                    final FileChannel channel = new FileInputStream(x).getChannel();
                    final long size = channel.size();

                    final ByteBuffer buffer = ByteBuffer.allocate((int) size);
                    int read = channel.read(buffer);

                    if (read != size) {
                        cc.report(MessageType.EXCEPTION, "Error reading data() from " + x + ". Size mismatch (" + read + " != " + size + ")");
                        return null;
                    }

                    channel.close();
                    return buffer;
                } catch (FileNotFoundException e) {
                    cc.report(MessageType.EXCEPTION, "Error reading data() from " + x + ". File not found!");
                    return null;
                } catch (IOException e) {
                    cc.report(MessageType.EXCEPTION, "Error reading data() from " + x + ". IOException!");
                    return null;
                }
            }
        }).array(ByteBuffer.class));
    }
View Full Code Here

     * <br/>
     *
     * @return The same core file object (<code>this</code>).
     */
    public CoreFile delete() {
        final CommonCore cc = this.commonCore;
        map(new F1<File, Void>() {
            public Void f(File x) {
                int lastSize = Integer.MAX_VALUE;
                List<File> list = CoreKeeper.$(x).dir(ListDirectories.DO).list();

                while (list.size() < lastSize) {
                    lastSize = list.size();

                    for (File file : list) {
                        file.delete();
                    }

                    list = CoreKeeper.$(x).dir(ListDirectories.DO).list();
                }

                // Try to delete the entry
                if (!x.delete()) {
                    cc.report(MessageType.EXCEPTION, "Unable to delete " + x);
                }

                return null;
            }
        });
View Full Code Here

     * <br/>
     *
     * @return A CoreBufferedImage with the loaded images.
     */
    public CoreBufferedImage image() {
        final CommonCore cc = this.commonCore;
        return new CoreBufferedImage(this.commonCore, map(new F1<File, BufferedImage>() {
            public BufferedImage f(File x) {
                try {
                    return ImageIO.read(x);
                } catch (IOException e) {
                    cc.report(MessageType.EXCEPTION, "Error loading image " + x);
                }
                return null;
            }
        }).array(BufferedImage.class));
    }
View Full Code Here

     * <br/>
     *
     * @return A CoreString object containing the files' contents.
     */
    public CoreString text() {
        final CommonCore cc = this.commonCore;
        return new CoreString(this.commonCore, map(new F1<File, String>() {
            public String f(final File x) {
                return Files.readText(cc, x);
            }
        }).array(String.class));
View Full Code Here

     * @param options Relevant options: <code>OptionMapType</code>.
     */
    @SuppressWarnings("rawtypes")
    protected void map(final Mapper mapper, final Option... options) {
        final int size = mapper.core().size();
        final CommonCore cc = this.commonCore;

        // Quick pass for the probably most common events
        if (size <= 0) return;
        if (size == 1) {
            mapper.handle(0);
            return;
        }
       
        // Compute the later step size and the number of threads.
        final ProfileInformation profileInfo = cc.profileInformation();
        final int STEP_SIZE = Math.max(size() / 10, 1);
        final AtomicInteger index = new AtomicInteger();
       
        // Test-convert the first item and measure time. If time and size are above
        // a certain threshold, parallelize, otherwise map sequentially. However, in here we
        // only test the first one
        long delta = 0;

        final ListIterator iterator = mapper.core().iterator();
        while(iterator.hasNext()) {
            final int i = iterator.nextIndex();
            final Object o = iterator.next();
           
            // Skipp all null elements
            if(o == null) continue;
           
            // Set the base count to the next position we should consider (in case we break the look)
            index.set(i + 1);

            // Now map the given value
            final long start = System.nanoTime();
            mapper.handle(i);
            delta = System.nanoTime() - start;
           
            break;
        }
       
        // Next, we check if have a speed gain when we move parallel. In general, we do not
        // have a speed gain when the time it takes to spawn threads takes longer than it would
        // take to finish the loop single-threaded
        final int toGo = size - index.get();
        final long estTime = delta * toGo;

        // Request a CPU for each element we have (in case we have many, we only receive maxCPU, in case we have
        // very few, we don't block all CPUs.
        final int NUM_THREADS = Math.min(toGo, this.commonCore.profileInformation().numCPUs); // cc.requestCPUs(toGo);
       
        // We use a safetey factor of 2 for the fork time (FIXME: Should investigate what's the best factor),
        // also, we only spawn something if there is more than one element still to go.
        if((estTime < 2 * profileInfo.forkTime && toGo > 1) || NUM_THREADS < 2) {
            // Instantly release all CPUs when we go singlethreaded
            // this.commonCore.releaseCPUs(NUM_THREADS);
           
            // In this case, we go single threaded
            while(iterator.hasNext()) {
                final int i = iterator.nextIndex();
                iterator.next(); // We need to get the next() that the nextIndex increases.
                mapper.handle(i);
            }
           
            return;
        }


        // TODO: Get proper value for step size (same problem, see below)
        // TODO: Check size, if small, don't do all this setup in here ...
        // NAH, even for two objects we can have a speed gain if the calls
        // are very slow ...

       
        // Okay, in this case the loop was broken and we decided to go parallel. In that case
        // setup the barrier and spawn threads for all our processors so that we process the array.
        final CyclicBarrier barrier = new CyclicBarrier(NUM_THREADS + 1);
        final AtomicInteger baseCount = new AtomicInteger();

        final Runnable runner = new Runnable() {
            public void run() {
                int bc = baseCount.getAndIncrement() * STEP_SIZE;
                int lower = Math.max(index.get(), bc);
               

                // Get new basecount for every pass ...
                while (lower < size) {
                    final int max = Math.min(Math.min(lower + STEP_SIZE, size), bc + STEP_SIZE);

                    // Pass over all elements
                    for (int i = lower; i < max; i++) {
                        mapper.handle(i);
                    }

                    bc = baseCount.getAndIncrement() * STEP_SIZE;
                    lower = bc;
                }

                // Signal finish
                try {
                    barrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        };

        // Execute all our runnables.
        for(int i=0; i<NUM_THREADS; i++) {
            cc.executor().getExecutor().execute(runner);
        }

        // Wait for all threads to finish ...
        try {
            barrier.await();
View Full Code Here

     */
    @SuppressWarnings("null")
    public CoreObject<Object> call(final String string, final Object... params) {
        final int len = params == null ? 0 : params.length;
        final Class<?>[] types = new Class[len];
        final CommonCore cc = this.commonCore;

        // Convert classes.
        for (int i = 0; i < len; i++) {
            types[i] = params[i].getClass();
        }

        final boolean methodcall = string.endsWith("()");
        final String call = methodcall ? string.substring(0, string.length() - 2) : string;

        // If this is a method call ...
        if (methodcall) { return map(new F1<T, Object>() {
            public Object f(T x) {
                try {
                    final Method method = x.getClass().getDeclaredMethod(call, types);
                    method.setAccessible(true);
                    return method.invoke(x, params);
                } catch (SecurityException e) {
                    cc.report(MessageType.EXCEPTION, "SecurityException for " + x + " (method was " + string + ")");
                } catch (NoSuchMethodException e) {
                    cc.report(MessageType.EXCEPTION, "NoSuchMethodException for " + x + " (method was " + string + ")");
                } catch (IllegalArgumentException e) {
                    cc.report(MessageType.EXCEPTION, "IllegalArgumentException for " + x + " (method was " + string + ")");
                } catch (IllegalAccessException e) {
                    cc.report(MessageType.EXCEPTION, "IllegalAccessException for " + x + " (method was " + string + ")");
                } catch (InvocationTargetException e) {
                    cc.report(MessageType.EXCEPTION, "InvocationTargetException for " + x + " (method was " + string + ")");
                }

                return null;
            }
        }); }

        // Or a field access
        return map(new F1<T, Object>() {
            public Object f(T x) {
                try {
                    final Field field = x.getClass().getDeclaredField(call);
                    field.setAccessible(true);
                    return field.get(x);
                } catch (SecurityException e) {
                    cc.report(MessageType.EXCEPTION, "SecurityException for " + x + " (method was " + string + ")");
                } catch (IllegalArgumentException e) {
                    cc.report(MessageType.EXCEPTION, "IllegalArgumentException for " + x + " (method was " + string + ")");
                } catch (IllegalAccessException e) {
                    cc.report(MessageType.EXCEPTION, "IllegalAccessException for " + x + " (method was " + string + ")");
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
                return null;
            }
View Full Code Here

     *
     * @param options Zero or more {@link DefaultOption} objects.
     * @return A CoreByteBuffer wrapping the classes' bytecode
     */
    public CoreByteBuffer bytecode(final Option... options) {
        final CommonCore cc = this.commonCore;

        return new CoreByteBuffer(this.commonCore, map(new F1<Class<T>, ByteBuffer>() {
            @Override
            public ByteBuffer f(Class<T> x) {
                final String classname = x.getCanonicalName().replaceAll("\\.", "/") + ".class";
View Full Code Here

     * @return The core containing the spawned objects.
     */
    @SuppressWarnings("unchecked")
    public CoreObject<T> spawn(final Option... options) {
        // Process each element we might have enclosed.
        final CommonCore cc = this.commonCore;
        final Options options$ = Options.$(this.commonCore, options);
        final Object[] args = options$.args();

        return map(new F1<Class<T>, T>() {
            @Override
View Full Code Here

TOP

Related Classes of net.jcores.jre.CommonCore

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.