Java Code Examples for java.util.concurrent.atomic.AtomicReference.set()

The following are Jave code examples for showing how to use set() of the java.util.concurrent.atomic.AtomicReference class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: NiuBi   File: HttpRequestTest.java   Source Code and License Vote up 6 votes
/**
 * Verify HEAD with escaped query parameters
 *
 * @throws Exception
 */
@Test
public void headWithEscapedMappedQueryParams() throws Exception {
  Map<String, String> inputParams = new HashMap<String, String>();
  inputParams.put("name", "us er");
  inputParams.put("number", "100");
  final Map<String, String> outputParams = new HashMap<String, String>();
  final AtomicReference<String> method = new AtomicReference<String>();
  handler = new RequestHandler() {

    @Override
    public void handle(Request request, HttpServletResponse response) {
      method.set(request.getMethod());
      outputParams.put("name", request.getParameter("name"));
      outputParams.put("number", request.getParameter("number"));
      response.setStatus(HTTP_OK);
    }
  };
  HttpRequest request = head(url, inputParams, true);
  assertTrue(request.ok());
  assertEquals("HEAD", method.get());
  assertEquals("us er", outputParams.get("name"));
  assertEquals("100", outputParams.get("number"));
}
 
Example 2
Project: NiuBi   File: HttpRequestTest.java   Source Code and License Vote up 6 votes
/**
 * Verify progress callback when sending a file
 *
 * @throws Exception
 */
@Test
public void uploadProgressSend() throws Exception {
  final AtomicReference<String> body = new AtomicReference<String>();
  handler = new RequestHandler() {

    @Override
    public void handle(Request request, HttpServletResponse response) {
      body.set(new String(read()));
      response.setStatus(HTTP_OK);
    }
  };
  final File file = File.createTempFile("post", ".txt");
  new FileWriter(file).append("hello").close();

  final AtomicLong tx = new AtomicLong(0);
  UploadProgress progress = new UploadProgress() {
    public void onUpload(long transferred, long total) {
      assertEquals(file.length(), total);
      assertEquals(tx.incrementAndGet(), transferred);
    }
  };
  post(url).bufferSize(1).progress(progress).send(file).code();
  assertEquals(file.length(), tx.get());
}
 
Example 3
Project: future   File: NoFutureTest.java   Source Code and License Vote up 6 votes
@Test
public void getInterrupted() throws CheckedFutureException, InterruptedException {
  AtomicReference<Throwable> cause = new AtomicReference<>();
  Thread t = new Thread() {
    @Override
    public void run() {
      try {
        noFuture.get(Duration.ofMinutes(1));
      } catch (CheckedFutureException e) {
        cause.set(e.getCause());
      }
    }
  };
  t.start();
  t.interrupt();
  t.join();
  assertTrue(cause.get() instanceof InterruptedException);
}
 
Example 4
Project: RxJava3-preview   File: SafeSubscriberTest.java   Source Code and License Vote up 6 votes
private static Subscriber<String> OBSERVER_SUCCESS(final AtomicReference<Throwable> onError) {
    return new DefaultSubscriber<String>() {

        @Override
        public void onComplete() {

        }

        @Override
        public void onError(Throwable e) {
            onError.set(e);
        }

        @Override
        public void onNext(String args) {

        }
    };

}
 
Example 5
Project: NiuBi   File: HttpRequestTest.java   Source Code and License Vote up 6 votes
/**
 * Verify GET with query parameters
 *
 * @throws Exception
 */
@Test
public void getWithMappedQueryParams() throws Exception {
  Map<String, String> inputParams = new HashMap<String, String>();
  inputParams.put("name", "user");
  inputParams.put("number", "100");
  final Map<String, String> outputParams = new HashMap<String, String>();
  final AtomicReference<String> method = new AtomicReference<String>();
  handler = new RequestHandler() {

    @Override
    public void handle(Request request, HttpServletResponse response) {
      method.set(request.getMethod());
      outputParams.put("name", request.getParameter("name"));
      outputParams.put("number", request.getParameter("number"));
      response.setStatus(HTTP_OK);
    }
  };
  HttpRequest request = get(url, inputParams, false);
  assertTrue(request.ok());
  assertEquals("GET", method.get());
  assertEquals("user", outputParams.get("name"));
  assertEquals("100", outputParams.get("number"));
}
 
Example 6
Project: guava-mock   File: AbstractServiceTest.java   Source Code and License Vote up 6 votes
public void testAwaitTerminated_FailedService() throws Exception {
  final ManualSwitchedService service = new ManualSwitchedService();
  final AtomicReference<Throwable> exception = Atomics.newReference();
  Thread waiter = new Thread() {
    @Override public void run() {
      try {
        service.awaitTerminated();
        fail("Expected an IllegalStateException");
      } catch (Throwable t) {
        exception.set(t);
      }
    }
  };
  waiter.start();
  service.startAsync();
  service.notifyStarted();
  assertEquals(State.RUNNING, service.state());
  service.notifyFailed(EXCEPTION);
  assertEquals(State.FAILED, service.state());
  waiter.join(LONG_TIMEOUT_MILLIS);
  assertFalse(waiter.isAlive());
  assertThat(exception.get()).isInstanceOf(IllegalStateException.class);
  assertEquals(EXCEPTION, exception.get().getCause());
}
 
Example 7
Project: NiuBi   File: HttpRequestTest.java   Source Code and License Vote up 6 votes
/**
 * Verify HEAD with query parameters
 *
 * @throws Exception
 */
@Test
public void headWithMappedQueryParams() throws Exception {
  Map<String, String> inputParams = new HashMap<String, String>();
  inputParams.put("name", "user");
  inputParams.put("number", "100");
  final Map<String, String> outputParams = new HashMap<String, String>();
  final AtomicReference<String> method = new AtomicReference<String>();
  handler = new RequestHandler() {

    @Override
    public void handle(Request request, HttpServletResponse response) {
      method.set(request.getMethod());
      outputParams.put("name", request.getParameter("name"));
      outputParams.put("number", request.getParameter("number"));
      response.setStatus(HTTP_OK);
    }
  };
  HttpRequest request = head(url, inputParams, false);
  assertTrue(request.ok());
  assertEquals("HEAD", method.get());
  assertEquals("user", outputParams.get("name"));
  assertEquals("100", outputParams.get("number"));
}
 
Example 8
Project: NiuBi   File: HttpRequestTest.java   Source Code and License Vote up 6 votes
/**
 * Verify GET with query parameters
 *
 * @throws Exception
 */
@Test
public void getWithVarargsQueryParams() throws Exception {
  final Map<String, String> outputParams = new HashMap<String, String>();
  final AtomicReference<String> method = new AtomicReference<String>();
  handler = new RequestHandler() {

    @Override
    public void handle(Request request, HttpServletResponse response) {
      method.set(request.getMethod());
      outputParams.put("name", request.getParameter("name"));
      outputParams.put("number", request.getParameter("number"));
      response.setStatus(HTTP_OK);
    }
  };
  HttpRequest request = get(url, false, "name", "user", "number", "100");
  assertTrue(request.ok());
  assertEquals("GET", method.get());
  assertEquals("user", outputParams.get("name"));
  assertEquals("100", outputParams.get("number"));
}
 
Example 9
Project: NiuBi   File: HttpRequestTest.java   Source Code and License Vote up 6 votes
/**
 * Verify PUT with query parameters
 *
 * @throws Exception
 */
@Test
public void putWithMappedQueryParams() throws Exception {
  Map<String, String> inputParams = new HashMap<String, String>();
  inputParams.put("name", "user");
  inputParams.put("number", "100");
  final Map<String, String> outputParams = new HashMap<String, String>();
  final AtomicReference<String> method = new AtomicReference<String>();
  handler = new RequestHandler() {

    @Override
    public void handle(Request request, HttpServletResponse response) {
      method.set(request.getMethod());
      outputParams.put("name", request.getParameter("name"));
      outputParams.put("number", request.getParameter("number"));
      response.setStatus(HTTP_OK);
    }
  };
  HttpRequest request = put(url, inputParams, false);
  assertTrue(request.ok());
  assertEquals("PUT", method.get());
  assertEquals("user", outputParams.get("name"));
  assertEquals("100", outputParams.get("number"));
}
 
Example 10
Project: elasticsearch_my   File: ExpandSearchPhaseTests.java   Source Code and License Vote up 5 votes
public void testSkipPhase() throws IOException {
    MockSearchPhaseContext mockSearchPhaseContext = new MockSearchPhaseContext(1);
    mockSearchPhaseContext.searchTransport = new SearchTransportService(
        Settings.builder().put("search.remote.connect", false).build(), null, null) {

        @Override
        void sendExecuteMultiSearch(MultiSearchRequest request, SearchTask task, ActionListener<MultiSearchResponse> listener) {
          fail("no collapsing here");
        }
    };

    SearchHits hits = new SearchHits(new SearchHit[]{new SearchHit(1, "ID", new Text("type"),
        Collections.singletonMap("someField", new SearchHitField("someField", Collections.singletonList(null)))),
        new SearchHit(2, "ID2", new Text("type"),
            Collections.singletonMap("someField", new SearchHitField("someField", Collections.singletonList(null))))}, 1, 1.0F);
    InternalSearchResponse internalSearchResponse = new InternalSearchResponse(hits, null, null, null, false, null, 1);
    SearchResponse response = mockSearchPhaseContext.buildSearchResponse(internalSearchResponse, null);
    AtomicReference<SearchResponse> reference = new AtomicReference<>();
    ExpandSearchPhase phase = new ExpandSearchPhase(mockSearchPhaseContext, response, r ->
        new SearchPhase("test") {
            @Override
            public void run() throws IOException {
                reference.set(r);
            }
        }
    );
    phase.run();
    mockSearchPhaseContext.assertNoFailure();
    assertNotNull(reference.get());
    assertEquals(1, mockSearchPhaseContext.phasesExecuted.get());
}
 
Example 11
Project: incubator-netbeans   File: NetBeansClusterCreator.java   Source Code and License Vote up 5 votes
private static File findConf(AtomicReference<File> parent, List<? super File> clusters) {
    String nbdirs = System.getProperty("netbeans.dirs");
    if (nbdirs != null) {
    StringTokenizer tok = new StringTokenizer(nbdirs, File.pathSeparator); // NOI18N
    while (tok.hasMoreElements()) {
        File cluster = new File(tok.nextToken());
        clusters.add(cluster);
        if (!cluster.exists()) {
            continue;
        }
        
        
        
        if (parent.get() == null) {
            parent.set(cluster.getParentFile());
        }
        
        if (!parent.get().equals(cluster.getParentFile())) {
            // we can handle only case when all clusters are in
            // the same directory these days
            return null;
        }
    }
    }
    
    return new File(new File(parent.get(), "etc"), "netbeans.clusters");
}
 
Example 12
Project: RxJava3-preview   File: FlowableErrorHandlingTests.java   Source Code and License Vote up 5 votes
/**
 * Test that an error from a user provided Observer.onNext is handled and emitted to the onError
 * even when done across thread boundaries with observeOn
 * @throws InterruptedException if the test is interrupted
 */
@Test
public void testOnNextErrorAcrossThread() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> caughtError = new AtomicReference<Throwable>();
    Flowable<Long> o = Flowable.interval(50, TimeUnit.MILLISECONDS);
    Subscriber<Long> observer = new DefaultSubscriber<Long>() {

        @Override
        public void onComplete() {
            System.out.println("completed");
            latch.countDown();
        }

        @Override
        public void onError(Throwable e) {
            System.out.println("error: " + e);
            caughtError.set(e);
            latch.countDown();
        }

        @Override
        public void onNext(Long args) {
            throw new RuntimeException("forced failure");
        }
    };
    o.observeOn(Schedulers.newThread())
    .safeSubscribe(observer);

    latch.await(2000, TimeUnit.MILLISECONDS);
    assertNotNull(caughtError.get());
}
 
Example 13
Project: openjdk-jdk10   File: AtomicReference9Test.java   Source Code and License Vote up 5 votes
/**
 * getPlain returns the last value set
 */
public void testGetPlainSet() {
    AtomicReference<Integer> ai = new AtomicReference<>(one);
    assertEquals(one, ai.getPlain());
    ai.set(two);
    assertEquals(two, ai.getPlain());
    ai.set(m3);
    assertEquals(m3, ai.getPlain());
}
 
Example 14
Project: RxJava3-preview   File: ObservableOnErrorResumeNextViaFunctionTest.java   Source Code and License Vote up 5 votes
@Test
public void testResumeNextWithAsyncExecution() {
    final AtomicReference<Throwable> receivedException = new AtomicReference<Throwable>();
    Disposable s = mock(Disposable.class);
    TestObservable w = new TestObservable(s, "one");
    Function<Throwable, Observable<String>> resume = new Function<Throwable, Observable<String>>() {

        @Override
        public Observable<String> apply(Throwable t1) {
            receivedException.set(t1);
            return Observable.just("twoResume", "threeResume");
        }

    };
    Observable<String> o = Observable.unsafeCreate(w).onErrorResumeNext(resume);

    Observer<String> observer = TestHelper.mockObserver();

    o.subscribe(observer);

    try {
        w.t.join();
    } catch (InterruptedException e) {
        fail(e.getMessage());
    }

    verify(observer, Mockito.never()).onError(any(Throwable.class));
    verify(observer, times(1)).onComplete();
    verify(observer, times(1)).onNext("one");
    verify(observer, Mockito.never()).onNext("two");
    verify(observer, Mockito.never()).onNext("three");
    verify(observer, times(1)).onNext("twoResume");
    verify(observer, times(1)).onNext("threeResume");
    assertNotNull(receivedException.get());
}
 
Example 15
Project: googles-monorepo-demo   File: AbstractCacheTest.java   Source Code and License Vote up 5 votes
public void testGetIfPresent() {
  final AtomicReference<Object> valueRef = new AtomicReference<Object>();
  Cache<Object, Object> cache = new AbstractCache<Object, Object>() {
    @Override
    public Object getIfPresent(Object key) {
      return valueRef.get();
    }
  };

  assertNull(cache.getIfPresent(new Object()));

  Object newValue = new Object();
  valueRef.set(newValue);
  assertSame(newValue, cache.getIfPresent(new Object()));
}
 
Example 16
Project: creacoinj   File: WalletTest.java   Source Code and License Vote up 4 votes
@SuppressWarnings("ConstantConditions")
@Test
public void keyRotationHD2() throws Exception {
    // Check we handle the following scenario: a weak random key is created, then some good random keys are created
    // but the weakness of the first isn't known yet. The wallet is upgraded to HD based on the weak key. Later, we
    // find out about the weakness and set the rotation time to after the bad key's creation date. A new HD chain
    // should be created based on the oldest known good key and the old chain + bad random key should rotate to it.

    // We fix the private keys just to make the test deterministic (last byte differs).
    Utils.setMockClock();
    ECKey badKey = ECKey.fromPrivate(Utils.HEX.decode("00905b93f990267f4104f316261fc10f9f983551f9ef160854f40102eb71cffdbb"));
    badKey.setCreationTimeSeconds(Utils.currentTimeSeconds());
    Utils.rollMockClock(86400);
    ECKey goodKey = ECKey.fromPrivate(Utils.HEX.decode("00905b93f990267f4104f316261fc10f9f983551f9ef160854f40102eb71cffdcc"));
    goodKey.setCreationTimeSeconds(Utils.currentTimeSeconds());

    // Do an upgrade based on the bad key.
    final AtomicReference<List<DeterministicKeyChain>> fChains = new AtomicReference<>();
    KeyChainGroup kcg = new KeyChainGroup(PARAMS) {

        {
            fChains.set(chains);
        }
    };
    kcg.importKeys(badKey, goodKey);
    Utils.rollMockClock(86400);
    wallet = new Wallet(PARAMS, kcg);   // This avoids the automatic HD initialisation
    assertTrue(fChains.get().isEmpty());
    wallet.upgradeToDeterministic(null);
    DeterministicKey badWatchingKey = wallet.getWatchingKey();
    assertEquals(badKey.getCreationTimeSeconds(), badWatchingKey.getCreationTimeSeconds());
    sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, badWatchingKey.toAddress(PARAMS));

    // Now we set the rotation time to the time we started making good keys. This should create a new HD chain.
    wallet.setKeyRotationTime(goodKey.getCreationTimeSeconds());
    List<Transaction> txns = wallet.doMaintenance(null, false).get();
    assertEquals(1, txns.size());
    Address output = txns.get(0).getOutput(0).getAddressFromP2PKHScript(PARAMS);
    ECKey usedKey = wallet.findKeyFromPubHash(output.getHash160());
    assertEquals(goodKey.getCreationTimeSeconds(), usedKey.getCreationTimeSeconds());
    assertEquals(goodKey.getCreationTimeSeconds(), wallet.freshReceiveKey().getCreationTimeSeconds());
    assertEquals("mrM3TpCnav5YQuVA1xLercCGJH4DXujMtv", usedKey.toAddress(PARAMS).toString());
    DeterministicKeyChain c = fChains.get().get(1);
    assertEquals(c.getEarliestKeyCreationTime(), goodKey.getCreationTimeSeconds());
    assertEquals(2, fChains.get().size());

    // Commit the maint txns.
    wallet.commitTx(txns.get(0));

    // Check next maintenance does nothing.
    assertTrue(wallet.doMaintenance(null, false).get().isEmpty());
    assertEquals(c, fChains.get().get(1));
    assertEquals(2, fChains.get().size());
}
 
Example 17
Project: elasticsearch_my   File: FetchSearchPhaseTests.java   Source Code and License Vote up 4 votes
public void testCleanupIrrelevantContexts() throws IOException { // contexts that are not fetched should be cleaned up
    MockSearchPhaseContext mockSearchPhaseContext = new MockSearchPhaseContext(2);
    SearchPhaseController controller = new SearchPhaseController(Settings.EMPTY, BigArrays.NON_RECYCLING_INSTANCE, null);
    InitialSearchPhase.SearchPhaseResults<QuerySearchResultProvider> results =
        controller.newSearchPhaseResults(mockSearchPhaseContext.getRequest(), 2);
    AtomicReference<SearchResponse> responseRef = new AtomicReference<>();
    int resultSetSize = 1;
    QuerySearchResult queryResult = new QuerySearchResult(123, new SearchShardTarget("node1", new Index("test", "na"), 0));
    queryResult.topDocs(new TopDocs(1, new ScoreDoc[] {new ScoreDoc(42, 1.0F)}, 2.0F), new DocValueFormat[0]);
    queryResult.size(resultSetSize); // the size of the result set
    results.consumeResult(0, queryResult);

    queryResult = new QuerySearchResult(321, new SearchShardTarget("node2", new Index("test", "na"), 1));
    queryResult.topDocs(new TopDocs(1, new ScoreDoc[] {new ScoreDoc(84, 2.0F)}, 2.0F), new DocValueFormat[0]);
    queryResult.size(resultSetSize);
    results.consumeResult(1, queryResult);

    SearchTransportService searchTransportService = new SearchTransportService(
        Settings.builder().put("search.remote.connect", false).build(), null,  null) {
        @Override
        public void sendExecuteFetch(Transport.Connection connection, ShardFetchSearchRequest request, SearchTask task,
                                     ActionListener<FetchSearchResult> listener) {
            FetchSearchResult fetchResult = new FetchSearchResult();
            if (request.id() == 321) {
                fetchResult.hits(new SearchHits(new SearchHit[] {new SearchHit(84)}, 1, 2.0F));
            } else {
                fail("requestID 123 should not be fetched but was");
            }
            listener.onResponse(fetchResult);
        }
    };
    mockSearchPhaseContext.searchTransport = searchTransportService;
    FetchSearchPhase phase = new FetchSearchPhase(results, controller, mockSearchPhaseContext,
        (searchResponse) -> new SearchPhase("test") {
            @Override
            public void run() throws IOException {
                responseRef.set(searchResponse);
            }
        });
    assertEquals("fetch", phase.getName());
    phase.run();
    mockSearchPhaseContext.assertNoFailure();
    assertNotNull(responseRef.get());
    assertEquals(2, responseRef.get().getHits().totalHits);
    assertEquals(1, responseRef.get().getHits().internalHits().length);
    assertEquals(84, responseRef.get().getHits().getAt(0).docId());
    assertEquals(0, responseRef.get().getFailedShards());
    assertEquals(2, responseRef.get().getSuccessfulShards());
    assertEquals(1, mockSearchPhaseContext.releasedSearchContexts.size());
    assertTrue(mockSearchPhaseContext.releasedSearchContexts.contains(123L));
}
 
Example 18
Project: monarch   File: MockExtensionCommands.java   Source Code and License Vote up 4 votes
/**
 * Call <code>function</code> with <code>args</code> on all members, tabulate results and persist
 * shared config if changed.
 * 
 * @param function {@link Function} to execute.
 * @param addXmlElement If <code>true</code> then add result {@link XmlEntity} to the config,
 *        otherwise delete it.
 * @param args Arguments to pass to function.
 * @return {@link TabularResultData}
 * @since GemFire 8.1
 */
protected Result executeFunctionOnAllMembersTabulateResultPersist(final Function function,
    final boolean addXmlElement, final Object... args) {
  final Cache cache = CacheFactory.getAnyInstance();
  final Set<DistributedMember> members = CliUtil.getAllNormalMembers(cache);

  @SuppressWarnings("unchecked")
  final ResultCollector<CliFunctionResult, List<CliFunctionResult>> resultCollector =
      (ResultCollector<CliFunctionResult, List<CliFunctionResult>>) CliUtil
          .executeFunction(function, args, members);
  final List<CliFunctionResult> functionResults =
      (List<CliFunctionResult>) resultCollector.getResult();

  AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
  final TabularResultData tabularResultData = ResultBuilder.createTabularResultData();
  final String errorPrefix = "ERROR: ";
  for (CliFunctionResult functionResult : functionResults) {
    boolean success = functionResult.isSuccessful();
    tabularResultData.accumulate("Member", functionResult.getMemberIdOrName());
    if (success) {
      tabularResultData.accumulate("Status", functionResult.getMessage());
      xmlEntity.set(functionResult.getXmlEntity());
    } else {
      tabularResultData.accumulate("Status", errorPrefix + functionResult.getMessage());
      tabularResultData.setStatus(Status.ERROR);
    }
  }

  final Result result = ResultBuilder.buildResult(tabularResultData);

  System.out.println("MockExtensionCommands: persisting xmlEntity=" + xmlEntity);
  if (null != xmlEntity.get()) {
    if (addXmlElement) {
      persistClusterConfiguration(result,
          () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), null));
    } else {
      persistClusterConfiguration(result,
          () -> getSharedConfiguration().deleteXmlEntity(xmlEntity.get(), null));
    }
  }

  return result;
}
 
Example 19
Project: incubator-netbeans   File: ImportAnalysis2Test.java   Source Code and License Vote up 4 votes
public void testInternalChangesAreLightweight1() throws Exception {
    clearWorkDir();
    testFile = new File(getWorkDir(), "hierbas/del/litoral/Test.java");
    assertTrue(testFile.getParentFile().mkdirs());
    String code =
        "package hierbas.del.litoral;\n" +
        "\n" +
        "public class Test {\n" +
        "    {\n" +
        "        new Runnable() {\n" +
        "            public void run() {\n" +
        "|            }\n" +
        "        }\n" +
        "    }\n" +
        "}\n";
    final int pos = code.indexOf("|");
    TestUtilities.copyStringToFile(testFile, code.replaceAll(Pattern.quote("|"), ""));
    String golden =
        "package hierbas.del.litoral;\n\n" +
        "import java.util.List;\n" +
        "\n" +
        "public class Test {\n" +
        "    {\n" +
        "        new Runnable() {\n" +
        "            public void run() {\n" +
        "                List l;\n" +
        "            }\n" +
        "        }\n" +
        "    }\n" +
        "}\n";

    JavaSource src = getJavaSource(testFile);
    final AtomicReference<ElementOverlay> overlay = new AtomicReference<ElementOverlay>();
    Task<WorkingCopy> task = new Task<WorkingCopy>() {
        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();
            TreePath  tp = workingCopy.getTreeUtilities().pathFor(pos);
            BlockTree block = (BlockTree) tp.getLeaf();
            VariableTree vt = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "l", make.QualIdent("java.util.List"), null);
            workingCopy.rewrite(block, make.addBlockStatement(block, vt));
            overlay.set(JavaSourceAccessor.getINSTANCE().getJavacTask(workingCopy).getContext().get(ElementOverlay.class));
        }
    };
    src.runModificationTask(task).commit();
    assertEquals(0, overlay.get().totalMapsSize());
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
 
Example 20
Project: n4js   File: StyledTextDescriptor.java   Source Code and License Vote up 4 votes
/**
 * Creates and returns with a new {@link StyledText styled text} instance hooked up to the given parent composite.
 *
 * @param parent
 *            the parent of the styled text control.
 * @param style
 *            style bits for the new text control.
 * @return a new styled text control initialized from the descriptor.
 */
default StyledText toStyledText(final Composite parent, final int style) {

	final StyledText text = new StyledText(parent, READ_ONLY | style);
	text.setText(getText());
	text.setStyleRanges(getRanges());
	text.setFont(getFont());
	text.setEditable(false);
	text.setEnabled(false);

	final AtomicReference<Color> colorRef = new AtomicReference<>();
	final IPreferenceStore prefStore = EditorsUI.getPreferenceStore();
	if (null == prefStore
			|| prefStore.getBoolean(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) {

		colorRef.set(getDefault().getSystemColor(COLOR_LIST_BACKGROUND));

	} else {

		RGB rgb = null;
		if (prefStore.contains(PREFERENCE_COLOR_BACKGROUND)) {
			if (prefStore.isDefault(PREFERENCE_COLOR_BACKGROUND)) {
				rgb = getDefaultColor(prefStore, PREFERENCE_COLOR_BACKGROUND);
			} else {
				rgb = getColor(prefStore, PREFERENCE_COLOR_BACKGROUND);
			}
			if (rgb != null) {
				colorRef.set(new Color(text.getDisplay(), rgb));
			}
		}

	}

	if (null != colorRef.get()) {
		text.setBackground(colorRef.get());
		text.addDisposeListener(e -> {
			if (!colorRef.get().isDisposed()) {
				colorRef.get().dispose();
			}
		});
	}

	text.pack();
	return text;
}