Example usage for org.apache.commons.lang3.mutable MutableObject setValue

List of usage examples for org.apache.commons.lang3.mutable MutableObject setValue

Introduction

In this page you can find the example usage for org.apache.commons.lang3.mutable MutableObject setValue.

Prototype

@Override
public void setValue(final T value) 

Source Link

Document

Sets the value.

Usage

From source file:com.examples.with.different.packagename.ClassHierarchyIncludingInterfaces.java

public static Iterable<Class<?>> hierarchy(final Class<?> type, final Interfaces interfacesBehavior) {
    final Iterable<Class<?>> classes = new Iterable<Class<?>>() {

        @Override/*from ww w. j a v  a  2 s .co m*/
        public Iterator<Class<?>> iterator() {
            final MutableObject<Class<?>> next = new MutableObject<Class<?>>(type);
            return new Iterator<Class<?>>() {

                @Override
                public boolean hasNext() {
                    return next.getValue() != null;
                }

                @Override
                public Class<?> next() {
                    final Class<?> result = next.getValue();
                    next.setValue(result.getSuperclass());
                    return result;
                }

                @Override
                public void remove() {
                    throw new UnsupportedOperationException();
                }

            };
        }

    };
    if (interfacesBehavior != Interfaces.INCLUDE) {
        return classes;
    }
    return new Iterable<Class<?>>() {

        @Override
        public Iterator<Class<?>> iterator() {
            final Set<Class<?>> seenInterfaces = new HashSet<Class<?>>();
            final Iterator<Class<?>> wrapped = classes.iterator();

            return new Iterator<Class<?>>() {
                Iterator<Class<?>> interfaces = Collections.<Class<?>>emptySet().iterator();

                @Override
                public boolean hasNext() {
                    return interfaces.hasNext() || wrapped.hasNext();
                }

                @Override
                public Class<?> next() {
                    if (interfaces.hasNext()) {
                        final Class<?> nextInterface = interfaces.next();
                        seenInterfaces.add(nextInterface);
                        return nextInterface;
                    }
                    final Class<?> nextSuperclass = wrapped.next();
                    final Set<Class<?>> currentInterfaces = new LinkedHashSet<Class<?>>();
                    walkInterfaces(currentInterfaces, nextSuperclass);
                    interfaces = currentInterfaces.iterator();
                    return nextSuperclass;
                }

                private void walkInterfaces(final Set<Class<?>> addTo, final Class<?> c) {
                    for (final Class<?> iface : c.getInterfaces()) {
                        if (!seenInterfaces.contains(iface)) {
                            addTo.add(iface);
                        }
                        walkInterfaces(addTo, iface);
                    }
                }

                @Override
                public void remove() {
                    throw new UnsupportedOperationException();
                }

            };
        }
    };
}

From source file:com.jayway.restassured.module.mockmvc.ResultHandlerTest.java

private ResultHandler customResultHandler(final MutableObject<Boolean> mutableObject) {
    return new ResultHandler() {
        public void handle(MvcResult result) throws Exception {
            mutableObject.setValue(true);
        }/*from  ww  w  .  j  a va  2s  .  c  o m*/
    };
}

From source file:com.romeikat.datamessie.core.base.util.publishedDates.loading.parallel.CountPublishedDateParallelLoadingStrategy.java

@Override
protected void mergeResults(final MutableObject<Long> previousResult, final MutableObject<Long> nextResult) {
    final long previousValue = previousResult.getValue();
    final long nextValue = nextResult.getValue();
    final long mergedValue = previousValue + nextValue;

    previousResult.setValue(mergedValue);
}

From source file:com.flipkart.flux.client.runtime.LocalContextTest.java

@Test
public void shouldAllowSameMethodRegistrationFromDifferentThreads() throws Exception {

    final MutableObject<StateMachineDefinition> definitionOne = new MutableObject<>(null);
    final MutableObject<StateMachineDefinition> definitionTwo = new MutableObject<>(null);

    final Thread thread1 = new Thread(() -> {
        localContext.registerNew("fooBar", 1, "someDescription", "someContext");
        definitionOne.setValue(tlStateMachineDef.get());
    });/*  w  ww  .  j a  v  a  2s.c  o m*/
    final Thread thread2 = new Thread(() -> {
        localContext.registerNew("fooBar", 1, "someDescription", "someContext");
        definitionTwo.setValue(tlStateMachineDef.get());
    });
    thread1.start();
    thread2.start();

    thread1.join();
    thread2.join();

    assertThat(definitionOne.getValue()).isNotNull().isEqualTo(definitionTwo.getValue())
            .isEqualTo(new StateMachineDefinition("someDescription", "fooBar", 1l, new HashSet<>(),
                    new HashSet<>(), "someContext"));
}

From source file:com.jayway.restassured.itest.java.AcceptHeaderITest.java

@Test
public void accept_headers_are_overwritten_from_request_spec_by_default() {
    RequestSpecification spec = new RequestSpecBuilder().setAccept(JSON).build();

    final MutableObject<List<String>> headers = new MutableObject<List<String>>();

    given().accept("text/jux").spec(spec).body("{ \"message\" : \"hello world\"}").filter(new Filter() {
        public Response filter(FilterableRequestSpecification requestSpec,
                FilterableResponseSpecification responseSpec, FilterContext ctx) {
            headers.setValue(requestSpec.getHeaders().getValues("Accept"));
            return ctx.next(requestSpec, responseSpec);
        }/*from  w w  w  . j  ava  2  s .c o m*/
    }).when().post("/jsonBodyAcceptHeader").then().body(equalTo("hello world"));

    assertThat(headers.getValue(), contains("application/json, application/javascript, text/javascript"));
}

From source file:io.restassured.itest.java.AcceptHeaderITest.java

@Test
public void accept_headers_are_overwritten_from_request_spec_by_default() {
    RequestSpecification spec = new RequestSpecBuilder().setAccept(ContentType.JSON).build();

    final MutableObject<List<String>> headers = new MutableObject<List<String>>();

    RestAssured.given().accept("text/jux").spec(spec).body("{ \"message\" : \"hello world\"}")
            .filter(new Filter() {
                public Response filter(FilterableRequestSpecification requestSpec,
                        FilterableResponseSpecification responseSpec, FilterContext ctx) {
                    headers.setValue(requestSpec.getHeaders().getValues("Accept"));
                    return ctx.next(requestSpec, responseSpec);
                }/*from  ww  w  .jav a  2 s.c om*/
            }).when().post("/jsonBodyAcceptHeader").then().body(equalTo("hello world"));

    assertThat(headers.getValue(), contains("application/json, application/javascript, text/javascript"));
}

From source file:com.wolvereness.renumerated.Renumerated.java

private void process() throws Throwable {
    validateInput();/*from w  w  w  .  j ava2s . c o  m*/

    final MultiProcessor executor = MultiProcessor.newMultiProcessor(cores - 1,
            new ThreadFactoryBuilder().setDaemon(true)
                    .setNameFormat(Renumerated.class.getName() + "-processor-%d")
                    .setUncaughtExceptionHandler(this).build());
    final Future<?> fileCopy = executor.submit(new Callable<Object>() {
        @Override
        public Object call() throws Exception {
            if (original != null) {
                if (original.exists()) {
                    original.delete();
                }
                Files.copy(input, original);
            }
            return null;
        }
    });

    final List<Pair<ZipEntry, Future<byte[]>>> fileEntries = newArrayList();
    final List<Pair<MutableObject<ZipEntry>, Future<byte[]>>> classEntries = newArrayList();
    {
        final ZipFile input = new ZipFile(this.input);
        final Enumeration<? extends ZipEntry> inputEntries = input.entries();
        while (inputEntries.hasMoreElements()) {
            final ZipEntry entry = inputEntries.nextElement();
            final Future<byte[]> future = executor.submit(new Callable<byte[]>() {
                @Override
                public byte[] call() throws Exception {
                    return ByteStreams.toByteArray(input.getInputStream(entry));
                }
            });
            if (entry.getName().endsWith(".class")) {
                classEntries.add(new MutablePair<MutableObject<ZipEntry>, Future<byte[]>>(
                        new MutableObject<ZipEntry>(entry), future));
            } else {
                fileEntries.add(new ImmutablePair<ZipEntry, Future<byte[]>>(entry, future));
            }
        }

        for (final Pair<MutableObject<ZipEntry>, Future<byte[]>> pair : classEntries) {
            final byte[] data = pair.getRight().get();
            pair.setValue(executor.submit(new Callable<byte[]>() {
                String className;
                List<String> fields;

                @Override
                public byte[] call() throws Exception {
                    try {
                        return method();
                    } catch (final Exception ex) {
                        throw new Exception(pair.getLeft().getValue().getName(), ex);
                    }
                }

                private byte[] method() throws Exception {
                    final ClassReader clazz = new ClassReader(data);
                    clazz.accept(new ClassVisitor(ASM4) {
                        @Override
                        public void visit(final int version, final int access, final String name,
                                final String signature, final String superName, final String[] interfaces) {
                            if (superName.equals("java/lang/Enum")) {
                                className = name;
                            }
                        }

                        @Override
                        public FieldVisitor visitField(final int access, final String name, final String desc,
                                final String signature, final Object value) {
                            if (className != null && (access & 0x4000) != 0) {
                                List<String> fieldNames = fields;
                                if (fieldNames == null) {
                                    fieldNames = fields = newArrayList();
                                }
                                fieldNames.add(name);
                            }
                            return null;
                        }
                    }, ClassReader.SKIP_CODE);

                    if (className == null)
                        return data;

                    final String classDescriptor = Type.getObjectType(className).getDescriptor();

                    final ClassWriter writer = new ClassWriter(0);
                    clazz.accept(new ClassVisitor(ASM4, writer) {
                        @Override
                        public MethodVisitor visitMethod(final int access, final String name, final String desc,
                                final String signature, final String[] exceptions) {
                            final MethodVisitor methodVisitor = super.visitMethod(access, name, desc, signature,
                                    exceptions);
                            if (!name.equals("<clinit>")) {
                                return methodVisitor;
                            }
                            return new MethodVisitor(ASM4, methodVisitor) {
                                final Iterator<String> it = fields.iterator();
                                boolean active;
                                String lastName;

                                @Override
                                public void visitTypeInsn(final int opcode, final String type) {
                                    if (!active && it.hasNext()) {
                                        // Initiate state machine
                                        if (opcode != NEW)
                                            throw new AssertionError("Unprepared for " + opcode + " on " + type
                                                    + " in " + className);
                                        active = true;
                                    }
                                    super.visitTypeInsn(opcode, type);
                                }

                                @Override
                                public void visitLdcInsn(final Object cst) {
                                    if (active && lastName == null) {
                                        if (!(cst instanceof String))
                                            throw new AssertionError(
                                                    "Unprepared for " + cst + " in " + className);
                                        // Switch the first constant in the Enum constructor
                                        super.visitLdcInsn(lastName = it.next());
                                    } else {
                                        super.visitLdcInsn(cst);
                                    }
                                }

                                @Override
                                public void visitFieldInsn(final int opcode, final String owner,
                                        final String name, final String desc) {
                                    if (opcode == PUTSTATIC && active && lastName != null
                                            && owner.equals(className) && desc.equals(classDescriptor)
                                            && name.equals(lastName)) {
                                        // Finish the current state machine
                                        active = false;
                                        lastName = null;
                                    }
                                    super.visitFieldInsn(opcode, owner, name, desc);
                                }
                            };
                        }
                    }, ClassReader.EXPAND_FRAMES);

                    final MutableObject<ZipEntry> key = pair.getLeft();
                    key.setValue(new ZipEntry(key.getValue().getName()));
                    return writer.toByteArray();
                }
            }));
        }

        for (final Pair<ZipEntry, Future<byte[]>> pair : fileEntries) {
            pair.getRight().get();
        }

        input.close();
    }

    fileCopy.get();

    FileOutputStream fileOut = null;
    JarOutputStream jar = null;
    try {
        jar = new JarOutputStream(fileOut = new FileOutputStream(output));
        for (final Pair<ZipEntry, Future<byte[]>> fileEntry : fileEntries) {
            jar.putNextEntry(fileEntry.getLeft());
            jar.write(fileEntry.getRight().get());
        }
        for (final Pair<MutableObject<ZipEntry>, Future<byte[]>> classEntry : classEntries) {
            final byte[] data = classEntry.getRight().get();
            final ZipEntry entry = classEntry.getLeft().getValue();
            entry.setSize(data.length);
            jar.putNextEntry(entry);
            jar.write(data);
        }
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (final IOException ex) {
            }
        }
        if (fileOut != null) {
            try {
                fileOut.close();
            } catch (final IOException ex) {
            }
        }
    }

    final Pair<Thread, Throwable> uncaught = this.uncaught;
    if (uncaught != null)
        throw new MojoExecutionException(String.format("Uncaught exception in %s", uncaught.getLeft()),
                uncaught.getRight());
}

From source file:gov.va.isaac.workflow.engine.RemoteSynchronizer.java

/**
 * Request a remote synchronization. This call blocks until the operation is complete,
 * or the thread is interrupted./*from  w  w w. jav a 2  s  . c om*/
 * 
 * @throws InterruptedException
 */
public SynchronizeResult blockingSynchronize() throws InterruptedException {
    log.info("Queuing a blocking sync request");
    final MutableObject<SynchronizeResult> result = new MutableObject<SynchronizeResult>();
    final CountDownLatch cdl = new CountDownLatch(1);
    Consumer<SynchronizeResult> callback = new Consumer<SynchronizeResult>() {
        @Override
        public void accept(SynchronizeResult t) {
            result.setValue(t);
            cdl.countDown();
        }
    };

    synchronize(callback);
    cdl.await();
    return result.getValue();
}

From source file:fr.duminy.components.swing.form.JFormPane.java

/**
 * Display this form in a dialog./*  ww w .j a va 2s  . com*/
 *
 * @param parentComponent The parent component of the dialog.
 * @return The final value entered by the user in the dialog, or null if it was cancelled.
 */
public B showDialog(Component parentComponent) {
    Window parentWindow;
    if (parentComponent == null) {
        parentWindow = JOptionPane.getRootFrame();
    } else if (parentComponent instanceof Window) {
        parentWindow = (Window) parentComponent;
    } else {
        parentWindow = SwingUtilities.getWindowAncestor(parentComponent);
    }
    final JDialog dialog = new JDialog(parentWindow, title, Dialog.ModalityType.APPLICATION_MODAL);
    dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    dialog.setContentPane(this);
    dialog.setResizable(false);
    setBorder(null);
    final MutableObject<Boolean> validated = new MutableObject<>(false);
    FormListener<B> listener = new FormListener<B>() {
        @Override
        public void formValidated(Form<B> form) {
            validated.setValue(true);
            dialog.dispose();
        }

        @Override
        public void formCancelled(Form<B> form) {
            dialog.dispose();
        }
    };

    try {
        addFormListener(listener);
        dialog.pack();
        dialog.setVisible(true);
        return validated.getValue() ? getValue() : null;
    } finally {
        removeFormListener(listener);
    }
}

From source file:com.jayway.restassured.itest.java.AcceptHeaderITest.java

@Test
public void accept_headers_are_merged_from_request_spec_and_request_when_configured_to() {
    RequestSpecification spec = new RequestSpecBuilder().setAccept("text/jux").build();

    final MutableObject<List<String>> headers = new MutableObject<List<String>>();

    given().config(RestAssuredConfig.config().headerConfig(headerConfig().mergeHeadersWithName("Accept")))
            .accept(JSON).spec(spec).body("{ \"message\" : \"hello world\"}").filter(new Filter() {
                public Response filter(FilterableRequestSpecification requestSpec,
                        FilterableResponseSpecification responseSpec, FilterContext ctx) {
                    headers.setValue(requestSpec.getHeaders().getValues("Accept"));
                    return ctx.next(requestSpec, responseSpec);
                }//from w ww.  j ava 2 s .co m
            }).when().post("/jsonBodyAcceptHeader").then().body(equalTo("hello world"));

    assertThat(headers.getValue(),
            contains("application/json, application/javascript, text/javascript", "text/jux"));
}