Example usage for org.apache.commons.lang3.mutable MutableBoolean getValue

List of usage examples for org.apache.commons.lang3.mutable MutableBoolean getValue

Introduction

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

Prototype

@Override
public Boolean getValue() 

Source Link

Document

Gets the value as a Boolean instance.

Usage

From source file:fr.duminy.components.swing.listpanel.SimpleItemManagerTest.java

@Test
public void testCreateItemCallsInitItem() {
    final SimpleItemManager.FormDisplayer displayer = mock(SimpleItemManager.FormDisplayer.class);
    final FormBuilder<Bean> builder = new DefaultFormBuilder<>(Bean.class);
    final MutableBoolean called = new MutableBoolean(false);

    GuiActionRunner.execute(new GuiQuery<Void>() {
        protected Void executeInEDT() {
            final SimpleItemManager manager = new SimpleItemManager<Bean>(Bean.class, builder, new JLabel(""),
                    title, displayer) {/*from  ww  w  . j a v a 2 s.  co  m*/
                @Override
                protected void initItem(Bean item) {
                    called.setValue(true);
                }
            };

            manager.createItem();
            return null;
        }
    });

    assertThat(called.getValue()).as("initItem called").isTrue();
}

From source file:com.ibm.jaggr.core.impl.modulebuilder.javascript.RequireExpansionCompilerPassTest.java

@Test
public void testRequireExpansion() throws Exception {
    List<ModuleDeps> expanded = new ArrayList<ModuleDeps>();
    MutableBoolean hasExpandableRequires = new MutableBoolean(false);
    RequireExpansionCompilerPass pass = new RequireExpansionCompilerPass(mockAggregator, new Features(), null,
            expanded, hasExpandableRequires, true, null, false, null);

    String code, output;//  w w w  .  j a va 2  s . com

    // Ensure require list is modified
    code = "require([\"foo\"],function(foo){});";
    output = runPass(pass, code);
    System.out.println(output);
    Assert.assertTrue(output.contains("[\"foo\",\"" + placeHolder0 + "\"]"));
    Assert.assertEquals(1, expanded.size());
    Assert.assertEquals(new LinkedHashSet<String>(Arrays.asList(new String[] { "bar", "a/b" })),
            expanded.get(0).getModuleIds());
    Assert.assertTrue(hasExpandableRequires.getValue());

    // Ensure require list is modified
    hasExpandableRequires.setValue(false);
    code = "require([\"foo\"]);";
    output = runPass(pass, code);
    System.out.println(output);
    Assert.assertTrue(output.contains("[\"foo\",\"" + placeHolder0 + "\"]"));
    Assert.assertEquals(1, expanded.size());
    Assert.assertEquals(new LinkedHashSet<String>(Arrays.asList(new String[] { "bar", "a/b" })),
            expanded.get(0).getModuleIds());
    Assert.assertTrue(hasExpandableRequires.getValue());

    // Ensure require list is NOT modified
    hasExpandableRequires.setValue(false);
    pass = new RequireExpansionCompilerPass(mockAggregator, new Features(), null, expanded,
            hasExpandableRequires, false, null, false, null);
    code = "require([\"foo\"]);";
    output = runPass(pass, code);
    System.out.println(output);
    Assert.assertEquals(code, output);
    Assert.assertEquals(0, expanded.size());
    Assert.assertTrue(hasExpandableRequires.getValue());

    // Ensure hasExpandableRequires is false
    hasExpandableRequires.setValue(false);
    pass = new RequireExpansionCompilerPass(mockAggregator, new Features(), null, expanded,
            hasExpandableRequires, false, null, false, null);
    code = "define([\"foo\"], function(foo) {});";
    Assert.assertFalse(hasExpandableRequires.getValue());

    // Ensure only array literals are expanded
    pass = new RequireExpansionCompilerPass(mockAggregator, new Features(), null, expanded,
            new MutableBoolean(false), true, null, false, null);
    code = "require(\"foo\");";
    output = runPass(pass, code);
    System.out.println(output);
    Assert.assertEquals(code, output);

    // Ensure variables are not modified
    code = "require([\"foo\", jsvar])";
    output = runPass(pass, code);
    System.out.println(output);
    Assert.assertTrue(output.contains("[\"foo\",jsvar,\"" + placeHolder0 + "\"]"));
    Assert.assertEquals(1, expanded.size());
    Assert.assertEquals(new LinkedHashSet<String>(Arrays.asList(new String[] { "bar", "a/b" })),
            expanded.get(0).getModuleIds());

    // test with compound strings
    code = "require([\"foo\" + jsvar])";
    output = runPass(pass, code);
    System.out.println(output);
    Assert.assertTrue(output.contains("[\"foo\"+jsvar]"));

    code = "require([\"foo\" + \"bar\"])";
    output = runPass(pass, code);
    System.out.println(output);
    Assert.assertTrue(output.contains("[\"foo\"+\"bar\"]"));

    code = "require([\"foo\", \"a\"+\"b\", \"x/y\"])";
    output = runPass(pass, code);
    System.out.println(output);
    Assert.assertTrue(output.contains("[\"foo\",\"a\"+\"b\",\"x/y\",\"" + placeHolder0 + "\"]"));
    Assert.assertEquals(1, expanded.size());
    System.out.println(expanded.get(0).keySet());
    Assert.assertEquals(new LinkedHashSet<String>(Arrays.asList(new String[] { "bar", "a/b", "x/y/z" })),
            expanded.get(0).getModuleIds());

    // Ensure relative paths are resolved based on module name
    moduleName = "a/a";
    code = "require([\"foo\",\"./c\"]);";
    output = runPass(pass, code);
    System.out.println(output);
    Assert.assertTrue(output.contains("[\"foo\",\"./c\",\"" + placeHolder0 + "\"]"));
    Assert.assertEquals(1, expanded.size());
    Assert.assertEquals(new LinkedHashSet<String>(Arrays.asList(new String[] { "bar", "a/b", "c/d" })),
            expanded.get(0).getModuleIds());
    moduleName = "test";

    // Ensure enclosing dependencies not expanded
    code = "define([\"bar\"],function(bar){require([\"foo\",\"a/b\"])});";
    moduleName = "dependsOnBar";
    output = runPass(pass, code);
    System.out.println(output);
    Assert.assertEquals(code, output);

    // No encloding dependencies
    moduleName = "dependsOnModule";
    code = "define([\"module\"],function(bar){require([\"foo\"]);});";
    output = runPass(pass, code);
    System.out.println(output);
    Assert.assertTrue(output.contains("[\"foo\",\"" + placeHolder0 + "\"]"));
    Assert.assertEquals(1, expanded.size());
    Assert.assertEquals(new LinkedHashSet<String>(Arrays.asList(new String[] { "bar", "a/b" })),
            expanded.get(0).getModuleIds());

    // multiple require calls
    code = "define([\"module\"],function(bar){require([\"foo\"]); var abc = 123; require([\"x/y\"]);});";
    output = runPass(pass, code);
    System.out.println(output);
    Assert.assertTrue(output.contains("[\"foo\",\"" + placeHolder0 + "\"]"));
    Assert.assertTrue(output.contains("[\"x/y\",\"" + placeHolder1 + "\"]"));
    Assert.assertEquals(2, expanded.size());
    Assert.assertEquals(new LinkedHashSet<String>(Arrays.asList(new String[] { "bar", "a/b" })),
            expanded.get(0).getModuleIds());
    Assert.assertEquals(new LinkedHashSet<String>(Arrays.asList(new String[] { "foo", "bar", "a/b", "x/y/z" })),
            expanded.get(1).getModuleIds());

    // Enable development mode and make sure a RuntimeDependencyVerificationException
    // is thrown if the dependency list specified in the code does not match
    // the dependency list returned by IDependencies.getDeclaredDependencies()
    // for the module.

    // First, enable development mode
    mockAggregator.getOptions().setOption(IOptions.DEVELOPMENT_MODE, true);
    mockAggregator.getOptions().setOption(IOptions.VERIFY_DEPS, true);

    // this test should not throw because the code matches the dependencies
    code = "define([\"module\"],function(bar){require([\"foo\"]);});";
    output = runPass(pass, code);
    System.out.println(output);
    Assert.assertTrue(output.contains("[\"foo\",\"" + placeHolder0 + "\"]"));

    // This test should throw because the code doesn't match the dependencies
    boolean exceptionThrown = false;
    code = "define([\"module\",\"another\"],function(bar){require([\"foo\"]);});";
    try {
        output = runPass(pass, code);
        System.out.println(output);
    } catch (RuntimeDependencyVerificationException e) {
        exceptionThrown = true;
    }
    Assert.assertTrue("RuntimeDependencyVerificationException not thrown", exceptionThrown);

    // This test verifies that relative dependency paths are resolved correctly
    // Will throw RuntimeDependencyVerificationException if relative modules
    // specified in define are not normalized and resolved to the absolute paths
    // specified in the dependency map for module x/y.
    moduleName = "x/y";
    code = "define([\"./y/z\",\"../foo\"],function(bar){require([\"foo\"]);});";
    output = runPass(pass, code);
    System.out.println(output);

    moduleName = "dependsOnModule";
    code = "define([\"module\",\"another\"],function(bar){require([\"foo\"]);});";

    // Assert that both development mode and verify deps need to be enabled
    // for an exception to be thrown
    mockAggregator.getOptions().setOption(IOptions.DEVELOPMENT_MODE, true);
    mockAggregator.getOptions().setOption(IOptions.VERIFY_DEPS, false);
    output = runPass(pass, code);
    mockAggregator.getOptions().setOption(IOptions.DEVELOPMENT_MODE, false);
    mockAggregator.getOptions().setOption(IOptions.VERIFY_DEPS, true);
    output = runPass(pass, code);
    mockAggregator.getOptions().setOption(IOptions.DEVELOPMENT_MODE, false);
    mockAggregator.getOptions().setOption(IOptions.VERIFY_DEPS, false);
    output = runPass(pass, code);

}

From source file:com.mirth.connect.plugins.datapruner.DataPrunerPanel.java

public void doStart() {
    final MutableBoolean saveChanges = new MutableBoolean(false);

    if (isSaveEnabled()) {
        if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this,
                "Settings changes must be saved first, would you like to save the settings and prune now?",
                "Select an Option", JOptionPane.OK_CANCEL_OPTION)) {
            if (!validateFields()) {
                return;
            }/*from   w ww. j  a  v a  2 s  .c o  m*/

            saveChanges.setValue(true);
        } else {
            return;
        }
    }

    setStartTaskVisible(false);
    final String workingId = parent.startWorking("Starting the data pruner...");

    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        @Override
        protected Void doInBackground() {
            if (saveChanges.getValue()) {
                try {
                    plugin.setPropertiesToServer(getProperties());
                } catch (Exception e) {
                    getFrame().alertThrowable(getFrame(), e);
                    return null;
                }
            }

            try {
                parent.mirthClient.getServlet(DataPrunerServletInterface.class).start();
            } catch (Exception e) {
                parent.alertThrowable(parent, e,
                        "An error occurred while attempting to start the data pruner.");
                return null;
            }

            return null;
        }

        @Override
        public void done() {
            if (saveChanges.getValue()) {
                setSaveEnabled(false);
            }

            parent.stopWorking(workingId);
            updateStatus();
        }
    };

    worker.execute();
}

From source file:com.ibm.jaggr.core.impl.modulebuilder.javascript.RequireExpansionCompilerPassTest.java

@Test
public void testLogging() throws Exception {

    MutableBoolean hasExpandableRequires = new MutableBoolean(false);
    RequireExpansionCompilerPass pass = new RequireExpansionCompilerPass(mockAggregator, new Features(), null,
            new ArrayList<ModuleDeps>(), hasExpandableRequires, true, null, true, null);

    String code, output;/*w  ww. j  a  v  a  2 s. c o m*/
    code = "require([\"foo\"],function(){});";
    output = runPass(pass, code);
    System.out.println(output);
    Assert.assertTrue("Expected pattern not found.",
            Pattern.compile("console\\.log\\(\\\"[^)\"]*Expanding requires list").matcher(output).find());
    Assert.assertTrue("Output does not contain expected value.", output.contains(
            "foo (" + MessageFormat.format(com.ibm.jaggr.core.util.Messages.DependencyList_5, "test") + ")"));
    Assert.assertTrue("Output does not contain expected value.", output.contains(
            "bar (" + MessageFormat.format(com.ibm.jaggr.core.util.Messages.DependencyList_4, "foo") + ")"));
    Assert.assertTrue("Output does not contain expected value.", output.contains(
            "a/b (" + MessageFormat.format(com.ibm.jaggr.core.util.Messages.DependencyList_4, "bar") + ")"));
    Assert.assertTrue(hasExpandableRequires.getValue());

}

From source file:com.ibm.jaggr.core.impl.modulebuilder.javascript.JavaScriptModuleBuilder.java

@Override
public ModuleBuild build(String mid, IResource resource, HttpServletRequest request,
        List<ICacheKeyGenerator> keyGens) throws Exception {
    final IAggregator aggr = (IAggregator) request.getAttribute(IAggregator.AGGREGATOR_REQATTRNAME);
    // Get the parameters from the request
    CompilationLevel level = getCompilationLevel(request);
    boolean createNewKeyGen = (keyGens == null);
    boolean isHasFiltering = RequestUtil.isHasFiltering(request);
    // If the source doesn't exist, throw an exception.
    if (!resource.exists()) {
        if (log.isLoggable(Level.WARNING)) {
            log.warning(MessageFormat.format(Messages.JavaScriptModuleBuilder_0,
                    new Object[] { resource.getURI().toString() }));
        }/*from w w w .  ja v  a 2s  .co  m*/
        throw new NotFoundException(resource.getURI().toString());
    }

    List<JSSourceFile> sources = this.getJSSource(mid, resource, request, keyGens);

    JSSource source = null;
    if (level == null) {
        // If optimization level is none, then we need to modify the source code
        // when expanding require lists and exporting module names because the
        // parsed AST produced by closure does not preserve whitespace and comments.
        StringBuffer code = new StringBuffer();
        for (JSSourceFile sf : sources) {
            code.append(sf.getCode());
        }
        source = new JSSource(code.toString(), mid);
    }
    boolean coerceUndefinedToFalse = aggr.getConfig().isCoerceUndefinedToFalse();
    Features features = (Features) request.getAttribute(IHttpTransport.FEATUREMAP_REQATTRNAME);
    if (features == null || level == null || !RequestUtil.isHasFiltering(request)) {
        // If no features specified or we're only processing features to
        // get the dependency list for the cache key generator, then use
        // an empty feature set.
        features = Features.emptyFeatures;
        coerceUndefinedToFalse = false;
    }

    Set<String> discoveredHasConditionals = new LinkedHashSet<String>();
    Set<String> hasFiltDiscoveredHasConditionals = new HashSet<String>();
    String output = null;

    Compiler compiler = new Compiler();
    CompilerOptions compiler_options = CompilerUtil.getDefaultOptions();
    compiler_options.customPasses = HashMultimap.create();
    if (isHasFiltering && (level != null || keyGens == null)) {
        // Run has filtering compiler pass if we are doing has filtering, or if this
        // is the first build for this module (keyGens == null) so that we can get
        // the dependent features for the module to include in the cache key generator.
        HasFilteringCompilerPass hfcp = new HasFilteringCompilerPass(features,
                keyGens == null ? hasFiltDiscoveredHasConditionals : null, coerceUndefinedToFalse);
        compiler_options.customPasses.put(CustomPassExecutionTime.BEFORE_CHECKS, hfcp);
    }

    boolean isReqExpLogging = RequestUtil.isRequireExpLogging(request);
    boolean isExpandRequires = RequestUtil.isExplodeRequires(request);
    List<ModuleDeps> expandedDepsList = null;
    MutableBoolean hasExpandableRequires = new MutableBoolean(false);
    if (isExpandRequires || createNewKeyGen) {
        expandedDepsList = new ArrayList<ModuleDeps>();
        /*
         * Register the RequireExpansionCompilerPass if we're exploding
         * require lists to include nested dependencies
         */
        RequireExpansionCompilerPass recp = new RequireExpansionCompilerPass(aggr, features,
                discoveredHasConditionals, expandedDepsList, hasExpandableRequires, isExpandRequires,
                (String) request.getAttribute(IHttpTransport.CONFIGVARNAME_REQATTRNAME), isReqExpLogging,
                source);

        compiler_options.customPasses.put(CustomPassExecutionTime.BEFORE_CHECKS, recp);

        // Call IRequestedModuleNames.getBaseLayerDeps() in case it throws an exception so that
        // we propagate it here instead of in layerBeginEndNotifier where we can't propagate
        // the exception.
        IRequestedModuleNames reqNames = (IRequestedModuleNames) request
                .getAttribute(IHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME);
        if (reqNames != null) {
            reqNames.getRequireExpansionExcludes();
        }
    }
    if (RequestUtil.isExportModuleName(request)) {
        compiler_options.customPasses.put(CustomPassExecutionTime.BEFORE_CHECKS,
                new ExportModuleNameCompilerPass(source));
    }

    if (level != null && level != CompilationLevel.WHITESPACE_ONLY) {
        level.setOptionsForCompilationLevel(compiler_options);
    } else {
        // If CompilationLevel is WHITESPACE_ONLY, then don't call
        // setOptionsForCompilationLevel because it disables custom
        // compiler passes and we want them to run.

        // Allows annotations that are not standard.
        compiler_options.setWarningLevel(DiagnosticGroups.NON_STANDARD_JSDOC, CheckLevel.OFF);
    }

    // we do our own threading, so disable compiler threads.
    compiler.disableThreads();

    // compile the module
    Result result = compiler.compile(externs, sources, compiler_options);
    if (result.success) {
        if (aggr.getOptions().isDevelopmentMode() && aggr.getOptions().isVerifyDeps()) {
            // Validate dependencies for this module by comparing the
            // discovered has conditionals against the dependent features
            // that were discovered when building the dependency graph
            List<String> dependentFeatures = aggr.getDependencies().getDependentFeatures(mid);
            if (dependentFeatures != null) {
                if (!new HashSet<String>(dependentFeatures).containsAll(hasFiltDiscoveredHasConditionals)) {
                    throw new DependencyVerificationException(mid);
                }
            }
        }
        discoveredHasConditionals.addAll(hasFiltDiscoveredHasConditionals);
        if (keyGens != null) {
            // Determine if we need to update the cache key generator.  Updating may be
            // necessary due to require list expansion as a result of different
            // dependency path traversals resulting from the specification of different
            // feature sets in the request.
            CacheKeyGenerator keyGen = (CacheKeyGenerator) keyGens.get(1);
            if (keyGen.featureKeyGen == null || keyGen.featureKeyGen.getFeatureSet() == null
                    || !keyGen.featureKeyGen.getFeatureSet().containsAll(discoveredHasConditionals)) {
                discoveredHasConditionals.addAll(keyGen.featureKeyGen.getFeatureSet());
                createNewKeyGen = true;
            }
        }
        if (level == null) {
            output = source.toString() + "\r\n"; //$NON-NLS-1$
        } else {
            // Get the compiler output and set the data in the ModuleBuild
            output = compiler.toSource();
        }
    } else {
        // Got a compiler error.  Output a warning message to the browser console
        StringBuffer sb = new StringBuffer(MessageFormat.format(Messages.JavaScriptModuleBuilder_1,
                new Object[] { resource.getURI().toString() }));
        for (JSError error : result.errors) {
            sb.append("\r\n\t").append(error.description) //$NON-NLS-1$
                    .append(" (").append(error.lineNumber).append(")."); //$NON-NLS-1$ //$NON-NLS-2$
        }
        if (aggr.getOptions().isDevelopmentMode() || aggr.getOptions().isDebugMode()) {
            // In development mode, return the error message
            // together with the uncompressed source.
            String errorMsg = StringUtil.escapeForJavaScript(sb.toString());
            StringBuffer code = new StringBuffer();
            for (JSSourceFile sf : sources) {
                code.append(sf.getCode());
            }
            return new ModuleBuild(code.toString(), null, errorMsg);
        } else {
            throw new Exception(sb.toString());
        }
    }
    return new ModuleBuild(
            expandedDepsList == null || expandedDepsList.size() == 0 ? output
                    : new JavaScriptBuildRenderer(mid, output, expandedDepsList, isReqExpLogging),
            createNewKeyGen ? getCacheKeyGenerators(discoveredHasConditionals, hasExpandableRequires.getValue())
                    : keyGens,
            null);
}

From source file:org.objectweb.proactive.core.remoteobject.RemoteObjectSet.java

/**
 * Select the best suited RemoteRemoteObject (protocol related), and send it the Request
 * Fallback to default (according to the PA_COMMUNICATION_PROTOCOL property) if necessary
 *//*from   w ww  .j  ava 2s .co  m*/
public Reply receiveMessage(Request message)
        throws ProActiveException, RenegotiateSessionException, IOException {
    if (forcedProtocol != null) {
        return forcedProtocol.receiveMessage(message);
    }
    RemoteRemoteObject rro = null;
    // the order is cloned to allow asynchronous updates by the benchmark threads
    ReentrantReadWriteLock.ReadLock rl = rwlock.readLock();

    rl.lock();
    ArrayList<URI> cloned = (ArrayList<URI>) sortedrros.clone();
    rl.unlock();
    // For each protocol already selected and sorted

    Throwable defaultProtocolException = null;

    MutableBoolean anyException = new MutableBoolean(false);

    Reply reply = null;
    for (URI uri : cloned) {
        rro = rros.get(uri);
        if (LOGGER_RO.isDebugEnabled()) {
            LOGGER_RO.debug("[ROAdapter] Sending message " + message + " to " + uri);
        }
        try {
            reply = rro.receiveMessage(message);
            // These Exceptions happened on client side
            // RMI doesn't act as others protocols and Exceptions aren't
            // encapsulated, so they are caught here.
        } catch (ProtocolException pae) {
            defaultProtocolException = handleProtocolException(pae, uri, cloned.size() > 1, anyException);
        } catch (IOException io) {
            defaultProtocolException = handleProtocolException(io, uri, cloned.size() > 1, anyException);
        } catch (RenegotiateSessionException rse) {
            defaultProtocolException = handleProtocolException(rse, uri, cloned.size() > 1, anyException);
        }

        if (reply != null) {
            // The Exception is thrown on server side
            // So it is encapsulated to be delivered on client side
            Throwable t = reply.getResult().getException();
            if (t != null && (t instanceof ProtocolException || t instanceof IOException
                    || t instanceof RenegotiateSessionException)) {
                defaultProtocolException = handleProtocolException(t, uri, cloned.size() > 1, anyException);
                continue;
            }
            break;
        }
    }

    // if we arrive to this point either a reply has been received or all protocols sent exceptions

    // if there has been any exception we sort the uri list before sending back the result
    if (anyException.getValue()) {
        sortProtocolsInternal();
    }

    // In case all protocols led to Exception, simply throw the Exception sent by the default protocol
    if (reply == null && defaultProtocolException != null) {
        if (defaultProtocolException instanceof ProtocolException) {
            throw (ProtocolException) defaultProtocolException;
        } else if (defaultProtocolException instanceof IOException) {
            throw (IOException) defaultProtocolException;
        } else if (defaultProtocolException instanceof RenegotiateSessionException) {
            throw (RenegotiateSessionException) defaultProtocolException;
        }
    }
    // otherwise, we received a reply
    return reply;
}

From source file:org.pircbotx.ConfigurationTest.java

@Test(dataProvider = "fieldNamesDataProvider", dependsOnMethods = "containSameFieldsTest", description = "Make sure every getter in builder gets called when creating Configuration")
@SuppressWarnings("unchecked")
public void copyConstructorTest(Class containerClass, Class copiedClass, Object copiedOpject, String getterName)
        throws Exception {
    //Get the method that is going to be called
    final Method methodToCall = copiedClass.getDeclaredMethod(getterName);

    //Trip if method gets called
    final MutableBoolean isMethodCalled = new MutableBoolean(false);
    Object copiedObjectSpied = mock(copiedClass,
            withSettings().spiedInstance(copiedOpject).defaultAnswer(new Answer() {
                public Object answer(InvocationOnMock invocation) throws Throwable {
                    if (invocation.getMethod().equals(methodToCall))
                        isMethodCalled.setValue(true);
                    return invocation.callRealMethod();
                }//from   w w  w. j  a v  a 2  s.c  o m
            }));

    //Call and test
    containerClass.getDeclaredConstructor(copiedClass).newInstance(copiedObjectSpied);
    assertTrue(isMethodCalled.getValue(), "Getter " + getterName
            + " on Builder not called in constructor in class " + containerClass.getCanonicalName());
}