Example usage for java.util.concurrent.atomic AtomicBoolean set

List of usage examples for java.util.concurrent.atomic AtomicBoolean set

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicBoolean set.

Prototype

public final void set(boolean newValue) 

Source Link

Document

Sets the value to newValue , with memory effects as specified by VarHandle#setVolatile .

Usage

From source file:de.willuhn.jameica.hbci.passports.pintan.ChipTANDialog.java

/**
* @see de.willuhn.jameica.gui.dialogs.PasswordDialog#paint(org.eclipse.swt.widgets.Composite)
*///from w ww  .j  a v  a2  s .  c om
protected void paint(final Composite parent) throws Exception {
    Container container = new SimpleContainer(parent);

    if (this.usb) {
        Application.getMessagingFactory().sendMessage(new StatusBarMessage(
                i18n.tr("Legen Sie die bitte Chipkarte ein."), StatusBarMessage.TYPE_INFO));

        this.setShowPassword(true); // Bei ChipTAN USB immer die TAN anzeigen, damit der User vergleichen kann.
        container.addHeadline(i18n.tr("ChipTAN USB"));
        container.addText(i18n.tr(
                "Legen Sie die Chipkarte ein und folgen Sie den Anweisungen des Kartenlesers. Klicken Sie auf \"OK\", wenn die TAN korrekt bertragen wurde."),
                true);

        ProgressBar progress = new ProgressBar(container.getComposite(), SWT.INDETERMINATE);
        final GridData gd = new GridData(GridData.FILL_HORIZONTAL);
        gd.horizontalSpan = 2;
        progress.setLayoutData(gd);

        final AtomicBoolean cancelled = new AtomicBoolean(false);

        final Thread usbThread = new Thread() {
            public void run() {
                try {
                    Logger.info("trying to get TAN using USB cardreader");
                    String s = StringUtils.trimToNull(service.getTan(code));
                    if (s != null && !cancelled.get()) {
                        setPassword(s, parent);
                    } else {
                        throw new Exception(i18n.tr("Keine TAN bertragen"));
                    }
                } catch (Exception e) {
                    if (!cancelled.get()) {
                        Logger.error("unable to get tan from chipcard", e);
                        setErrorText(i18n.tr("Fehler bei TAN-Ermittlung: {0}", e.getMessage()));
                    }
                }
            }
        };
        usbThread.start();

        parent.addDisposeListener(new DisposeListener() {
            @Override
            public void widgetDisposed(DisposeEvent e) {
                cancelled.set(true);
                // Nur fuer den Fall, dass der Thread noch laeuft.
                try {
                    if (usbThread != null)
                        usbThread.interrupt();
                } catch (Throwable th) {
                    Logger.error("unable to interrupt USB thread", th);
                }
            }
        });
    } else {
        container.addHeadline(i18n.tr(this.usb ? "ChipTAN USB" : "Flicker-Grafik"));
        container.addText(i18n.tr("Klicken Sie \"-\" bzw. \"+\", um die Breite anzupassen."), true);
        FlickerPart flicker = new FlickerPart(this.code);
        flicker.paint(parent);
    }

    // Hier stehen dann noch die Anweisungen von der Bank drin
    super.paint(parent);

    if (!this.usb) {
        // Wir muessen das Fenster wenigstens gross genug machen, damit der Flickercode reinpasst, falls
        // der User den recht verbreitert hat
        int width = settings.getInt("width", -1);
        if (width > 0)
            width += 10; // Wenigstens noch 10 Pixel Rand hinzufuegen.
        // Wir nehmen den groesseren von beiden Werten

        getShell().setMinimumSize(getShell().computeSize(width > WINDOW_WIDTH ? width : WINDOW_WIDTH,
                smallDisplay ? 520 : SWT.DEFAULT));
    }
}

From source file:test.java.com.spotify.docker.client.DefaultDockerClientTest.java

@Test
public void testBuildWithPull() throws Exception {
    assumeTrue("We need Docker API >= v1.19 to run this test." + "This Docker API is "
            + sut.version().apiVersion(), versionCompare(sut.version().apiVersion(), "1.19") >= 0);

    final String dockerDirectory = Resources.getResource("dockerDirectory").getPath();
    final String pullMsg = "Pulling from";

    // Build once to make sure we have cached images.
    sut.build(Paths.get(dockerDirectory));

    // Build again with PULL set, and verify we pulled the base image
    final AtomicBoolean pulled = new AtomicBoolean(false);
    sut.build(Paths.get(dockerDirectory), "test", new ProgressHandler() {
        @Override//  www . j  a  va 2 s  .  c o  m
        public void progress(ProgressMessage message) throws DockerException {
            if (message.status().contains(pullMsg)) {
                pulled.set(true);
            }
        }
    }, PULL_NEWER_IMAGE);
    assertTrue(pulled.get());
}

From source file:test.java.com.spotify.docker.client.DefaultDockerClientTest.java

@Test
public void testBuildNoCache() throws Exception {
    final String dockerDirectory = Resources.getResource("dockerDirectory").getPath();
    final String usingCache = "Using cache";

    // Build once to make sure we have cached images.
    sut.build(Paths.get(dockerDirectory));

    // Build again and make sure we used cached image by parsing output.
    final AtomicBoolean usedCache = new AtomicBoolean(false);
    sut.build(Paths.get(dockerDirectory), "test", new ProgressHandler() {
        @Override//from  ww  w. ja va 2s . c  om
        public void progress(ProgressMessage message) throws DockerException {
            if (message.stream().contains(usingCache)) {
                usedCache.set(true);
            }
        }
    });
    assertTrue(usedCache.get());

    // Build again with NO_CACHE set, and verify we don't use cache.
    sut.build(Paths.get(dockerDirectory), "test", new ProgressHandler() {
        @Override
        public void progress(ProgressMessage message) throws DockerException {
            assertThat(message.stream(), not(containsString(usingCache)));
        }
    }, NO_CACHE);
}

From source file:com.microsoft.tfs.client.common.ui.config.UITransportRequestHandler.java

/**
 * {@inheritDoc}/*w ww.j  ava 2 s  .c  o  m*/
 */
@Override
public Status prepareRequest(final SOAPService service, final SOAPRequest request, final AtomicBoolean cancel) {
    final ConnectionInstanceData connectionInstanceData = getConnectionInstanceData();
    final Credentials credentials = connectionInstanceData.getCredentials();

    log.debug(" Preparing request with the cedentials: " + credentials == null ? "null" //$NON-NLS-1$ //$NON-NLS-2$
            : credentials.getClass().getName());

    if (credentials == null || !(credentials instanceof UsernamePasswordCredentials)) {
        return Status.CONTINUE;
    }

    final UsernamePasswordCredentials oldCredentials = (UsernamePasswordCredentials) credentials;

    /*
     * If the user has provided UsernamePasswordCredentials with an empty
     * password, this cannot be correct, so prompt them.
     */
    if (StringUtil.isNullOrEmpty(oldCredentials.getPassword())) {
        log.debug(" UsernamePasswordCredentials with an empty password detected"); //$NON-NLS-1$
        final Credentials newCredentials = getCredentials(new UITransportUsernamePasswordAuthRunnable(
                connectionInstanceData.getServerURI(), connectionInstanceData.getCredentials()));

        if (newCredentials == null) {
            log.debug(" New UsernamePasswordCredentials not provided. Cancelling the request"); //$NON-NLS-1$
            cancel.set(true);
            return Status.CONTINUE;
        }

        log.debug(" New UsernamePasswordCredentials provided"); //$NON-NLS-1$

        // Apply the credentials data to the existing client.
        connectionInstanceData.setCredentials(newCredentials);

        getClientFactory().configureClientCredentials(service.getClient(), service.getClient().getState(),
                connectionInstanceData);
    }

    return Status.CONTINUE;
}

From source file:com.jivesoftware.os.amza.service.storage.binary.BinaryRowReaderWriterTest.java

@Test(enabled = false)
public void testConcurrency() throws Exception {
    MemoryBackedWALFiler walFiler = new MemoryBackedWALFiler(
            new MultiAutoGrowingByteBufferBackedFiler(32, 1_024 * 1_024, new HeapByteBufferFactory()));
    IoStats ioStats = new IoStats();
    BinaryRowReader binaryRowReader = new BinaryRowReader(walFiler);
    BinaryRowWriter binaryRowWriter = new BinaryRowWriter(walFiler);

    ExecutorService executors = Executors.newFixedThreadPool(9);
    AtomicBoolean running = new AtomicBoolean(true);
    AtomicLong scanned = new AtomicLong();
    List<Future<?>> futures = Lists.newArrayList();
    for (int i = 0; i < 8; i++) {
        futures.add(executors.submit(() -> {
            try {
                while (running.get()) {
                    binaryRowReader.scan(ioStats, 0, false, (rowFP, rowTxId, rowType, row) -> {
                        scanned.incrementAndGet();
                        return true;
                    });/*from  ww  w . j  a  v  a  2 s.c o  m*/
                }
                return true;
            } catch (Throwable t) {
                t.printStackTrace();
                throw t;
            }
        }));
    }
    futures.add(executors.submit(() -> {
        try {
            for (int i = 0; i < 1_000_000; i++) {
                byte[] row = UIO.intBytes(i);
                binaryRowWriter.write(ioStats, i, RowType.primary, 1, 16, stream -> stream.stream(row),
                        stream -> true,
                        (txId, prefix, key, value, valueTimestamp, valueTombstoned, valueVersion, fp) -> true,
                        false, false);
                if (i % 10_000 == 0) {
                    System.out.println("Finished i:" + i + " scanned:" + scanned.get());
                }
            }
        } finally {
            running.set(false);
        }
        return null;
    }));

    for (Future<?> future : futures) {
        future.get();
    }
}

From source file:com.alibaba.wasp.meta.FMetaServicesImplWithoutRetry.java

public boolean isTableAvailable(final byte[] tableName) throws IOException {
    final AtomicBoolean available = new AtomicBoolean(true);
    final AtomicInteger entityGroupCount = new AtomicInteger(0);
    FMetaScanner.MetaScannerVisitor visitor = new FMetaScanner.MetaScannerVisitorBase() {
        @Override//from ww  w.j  a  v a 2  s  .c o  m
        public boolean processRow(Result row) throws IOException {
            EntityGroupInfo info = FMetaScanner.getEntityGroupInfo(row);
            if (info != null) {
                if (Bytes.equals(tableName, info.getTableName())) {
                    ServerName sn = ServerName.getServerName(row);
                    if (sn == null) {
                        available.set(false);
                        return false;
                    }
                    entityGroupCount.incrementAndGet();
                }
            }
            return true;
        }
    };
    FMetaScanner.metaScan(getConf(), visitor);
    return available.get() && (entityGroupCount.get() > 0);
}

From source file:com.jkoolcloud.tnt4j.streams.parsers.ActivityJsonParser.java

/**
 * Gets field raw data value resolved by locator and formats it according locator definition.
 *
 * @param locator/* ww  w.j  a  v a 2s.com*/
 *            activity field locator
 * @param cData
 *            {@link JsonPath} document context to read
 * @param formattingNeeded
 *            flag to set if value formatting is not needed
 * @return value formatted based on locator definition or {@code null} if locator is not defined
 *
 * @throws ParseException
 *             if exception occurs while resolving raw data value or applying locator format properties to specified
 *             value
 *
 * @see ActivityFieldLocator#formatValue(Object)
 */
@Override
@SuppressWarnings("unchecked")
protected Object resolveLocatorValue(ActivityFieldLocator locator, ActivityContext cData,
        AtomicBoolean formattingNeeded) throws ParseException {
    Object val = null;
    String locStr = locator.getLocator();

    if (StringUtils.isNotEmpty(locStr)) {
        if (!locStr.startsWith(JSON_PATH_ROOT)) {
            locStr = JSON_PATH_ROOT + JSON_PATH_SEPARATOR + locStr;
        }

        Object jsonValue = null;
        try {
            jsonValue = cData.getData().read(locStr);
        } catch (JsonPathException exc) {
            logger().log(!locator.isOptional() ? OpLevel.WARNING : OpLevel.DEBUG, StreamsResources
                    .getString(StreamsResources.RESOURCE_BUNDLE_NAME, "ActivityJsonParser.path.exception"),
                    locStr, exc.getLocalizedMessage());
        }

        if (jsonValue != null) {
            List<Object> jsonValuesList;
            if (jsonValue instanceof List) {
                jsonValuesList = (List<Object>) jsonValue;
            } else {
                jsonValuesList = new ArrayList<>(1);
                jsonValuesList.add(jsonValue);
            }

            if (CollectionUtils.isNotEmpty(jsonValuesList)) {
                List<Object> valuesList = new ArrayList<>(jsonValuesList.size());
                for (Object jsonValues : jsonValuesList) {
                    valuesList.add(locator.formatValue(jsonValues));
                }

                val = Utils.simplifyValue(valuesList);
                formattingNeeded.set(false);
            }
        }
    }

    return val;
}

From source file:org.apache.nifi.processors.standard.servlets.ListenHTTPServlet.java

@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    final ProcessContext context = processContext;

    ProcessSessionFactory sessionFactory;
    do {/*  w w w.  j  a va2s. co  m*/
        sessionFactory = sessionFactoryHolder.get();
        if (sessionFactory == null) {
            try {
                Thread.sleep(10);
            } catch (final InterruptedException e) {
            }
        }
    } while (sessionFactory == null);

    final ProcessSession session = sessionFactory.createSession();
    FlowFile flowFile = null;
    String holdUuid = null;
    String foundSubject = null;
    try {
        final long n = filesReceived.getAndIncrement() % FILES_BEFORE_CHECKING_DESTINATION_SPACE;
        if (n == 0 || !spaceAvailable.get()) {
            if (context.getAvailableRelationships().isEmpty()) {
                spaceAvailable.set(false);
                if (logger.isDebugEnabled()) {
                    logger.debug("Received request from " + request.getRemoteHost()
                            + " but no space available; Indicating Service Unavailable");
                }
                response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                return;
            } else {
                spaceAvailable.set(true);
            }
        }
        response.setHeader("Content-Type", MediaType.TEXT_PLAIN);

        final boolean contentGzipped = Boolean.parseBoolean(request.getHeader(GZIPPED_HEADER));

        final X509Certificate[] certs = (X509Certificate[]) request
                .getAttribute("javax.servlet.request.X509Certificate");
        foundSubject = DEFAULT_FOUND_SUBJECT;
        if (certs != null && certs.length > 0) {
            for (final X509Certificate cert : certs) {
                foundSubject = cert.getSubjectDN().getName();
                if (authorizedPattern.matcher(foundSubject).matches()) {
                    break;
                } else {
                    logger.warn("Rejecting transfer attempt from " + foundSubject
                            + " because the DN is not authorized, host=" + request.getRemoteHost());
                    response.sendError(HttpServletResponse.SC_FORBIDDEN, "not allowed based on dn");
                    return;
                }
            }
        }

        final String destinationVersion = request.getHeader(PROTOCOL_VERSION_HEADER);
        Integer protocolVersion = null;
        if (destinationVersion != null) {
            try {
                protocolVersion = Integer.valueOf(destinationVersion);
            } catch (final NumberFormatException e) {
                // Value was invalid. Treat as if the header were missing.
            }
        }

        final boolean destinationIsLegacyNiFi = (protocolVersion == null);
        final boolean createHold = Boolean.parseBoolean(request.getHeader(FLOWFILE_CONFIRMATION_HEADER));
        final String contentType = request.getContentType();

        final InputStream unthrottled = contentGzipped ? new GZIPInputStream(request.getInputStream())
                : request.getInputStream();

        final InputStream in = (streamThrottler == null) ? unthrottled
                : streamThrottler.newThrottledInputStream(unthrottled);

        if (logger.isDebugEnabled()) {
            logger.debug("Received request from " + request.getRemoteHost() + ", createHold=" + createHold
                    + ", content-type=" + contentType + ", gzip=" + contentGzipped);
        }

        final AtomicBoolean hasMoreData = new AtomicBoolean(false);
        final FlowFileUnpackager unpackager;
        if (APPLICATION_FLOW_FILE_V3.equals(contentType)) {
            unpackager = new FlowFileUnpackagerV3();
        } else if (APPLICATION_FLOW_FILE_V2.equals(contentType)) {
            unpackager = new FlowFileUnpackagerV2();
        } else if (APPLICATION_FLOW_FILE_V1.equals(contentType)) {
            unpackager = new FlowFileUnpackagerV1();
        } else {
            unpackager = null;
        }

        final Set<FlowFile> flowFileSet = new HashSet<>();

        do {
            final long startNanos = System.nanoTime();
            final Map<String, String> attributes = new HashMap<>();
            flowFile = session.create();
            flowFile = session.write(flowFile, new OutputStreamCallback() {
                @Override
                public void process(final OutputStream rawOut) throws IOException {
                    try (final BufferedOutputStream bos = new BufferedOutputStream(rawOut, 65536)) {
                        if (unpackager == null) {
                            IOUtils.copy(in, bos);
                            hasMoreData.set(false);
                        } else {
                            attributes.putAll(unpackager.unpackageFlowFile(in, bos));

                            if (destinationIsLegacyNiFi) {
                                if (attributes.containsKey("nf.file.name")) {
                                    // for backward compatibility with old nifi...
                                    attributes.put(CoreAttributes.FILENAME.key(),
                                            attributes.remove("nf.file.name"));
                                }

                                if (attributes.containsKey("nf.file.path")) {
                                    attributes.put(CoreAttributes.PATH.key(),
                                            attributes.remove("nf.file.path"));
                                }
                            }

                            hasMoreData.set(unpackager.hasMoreData());
                        }
                    }
                }
            });

            final long transferNanos = System.nanoTime() - startNanos;
            final long transferMillis = TimeUnit.MILLISECONDS.convert(transferNanos, TimeUnit.NANOSECONDS);

            // put metadata on flowfile
            final String nameVal = request.getHeader(CoreAttributes.FILENAME.key());
            if (StringUtils.isNotBlank(nameVal)) {
                attributes.put(CoreAttributes.FILENAME.key(), nameVal);
            }

            // put arbitrary headers on flow file
            for (Enumeration<String> headerEnum = request.getHeaderNames(); headerEnum.hasMoreElements();) {
                String headerName = headerEnum.nextElement();
                if (headerPattern != null && headerPattern.matcher(headerName).matches()) {
                    String headerValue = request.getHeader(headerName);
                    attributes.put(headerName, headerValue);
                }
            }

            String sourceSystemFlowFileIdentifier = attributes.get(CoreAttributes.UUID.key());
            if (sourceSystemFlowFileIdentifier != null) {
                sourceSystemFlowFileIdentifier = "urn:nifi:" + sourceSystemFlowFileIdentifier;

                // If we receveied a UUID, we want to give the FlowFile a new UUID and register the sending system's
                // identifier as the SourceSystemFlowFileIdentifier field in the Provenance RECEIVE event
                attributes.put(CoreAttributes.UUID.key(), UUID.randomUUID().toString());
            }

            flowFile = session.putAllAttributes(flowFile, attributes);
            session.getProvenanceReporter().receive(flowFile, request.getRequestURL().toString(),
                    sourceSystemFlowFileIdentifier, "Remote DN=" + foundSubject, transferMillis);
            flowFile = session.putAttribute(flowFile, "restlistener.remote.source.host",
                    request.getRemoteHost());
            flowFile = session.putAttribute(flowFile, "restlistener.remote.user.dn", foundSubject);
            flowFileSet.add(flowFile);

            if (holdUuid == null) {
                holdUuid = flowFile.getAttribute(CoreAttributes.UUID.key());
            }
        } while (hasMoreData.get());

        if (createHold) {
            String uuid = (holdUuid == null) ? UUID.randomUUID().toString() : holdUuid;

            if (flowFileMap.containsKey(uuid)) {
                uuid = UUID.randomUUID().toString();
            }

            final FlowFileEntryTimeWrapper wrapper = new FlowFileEntryTimeWrapper(session, flowFileSet,
                    System.currentTimeMillis());
            FlowFileEntryTimeWrapper previousWrapper;
            do {
                previousWrapper = flowFileMap.putIfAbsent(uuid, wrapper);
                if (previousWrapper != null) {
                    uuid = UUID.randomUUID().toString();
                }
            } while (previousWrapper != null);

            response.setStatus(HttpServletResponse.SC_SEE_OTHER);
            final String ackUri = "/" + basePath + "/holds/" + uuid;
            response.addHeader(LOCATION_HEADER_NAME, ackUri);
            response.addHeader(LOCATION_URI_INTENT_NAME, LOCATION_URI_INTENT_VALUE);
            response.getOutputStream().write(ackUri.getBytes("UTF-8"));
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "Ingested {} from Remote Host: [{}] Port [{}] SubjectDN [{}]; placed hold on these {} files with ID {}",
                        new Object[] { flowFileSet, request.getRemoteHost(), request.getRemotePort(),
                                foundSubject, flowFileSet.size(), uuid });
            }
        } else {
            response.setStatus(HttpServletResponse.SC_OK);
            logger.info(
                    "Received from Remote Host: [{}] Port [{}] SubjectDN [{}]; transferring to 'success' {}",
                    new Object[] { request.getRemoteHost(), request.getRemotePort(), foundSubject, flowFile });

            session.transfer(flowFileSet, ListenHTTP.RELATIONSHIP_SUCCESS);
            session.commit();
        }
    } catch (final Throwable t) {
        session.rollback();
        if (flowFile == null) {
            logger.error("Unable to receive file from Remote Host: [{}] SubjectDN [{}] due to {}",
                    new Object[] { request.getRemoteHost(), foundSubject, t });
        } else {
            logger.error("Unable to receive file {} from Remote Host: [{}] SubjectDN [{}] due to {}",
                    new Object[] { flowFile, request.getRemoteHost(), foundSubject, t });
        }
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, t.toString());
    }
}

From source file:test.java.com.spotify.docker.client.DefaultDockerClientTest.java

@Test
public void testBuildNoRm() throws Exception {
    final String dockerDirectory = Resources.getResource("dockerDirectory").getPath();
    final String removingContainers = "Removing intermediate container";

    // Test that intermediate containers are removed with FORCE_RM by parsing output. We must
    // set NO_CACHE so that docker will generate some containers to remove.
    final AtomicBoolean removedContainer = new AtomicBoolean(false);
    sut.build(Paths.get(dockerDirectory), "test", new ProgressHandler() {
        @Override/*  w  w w .  ja  v  a 2  s.  c o  m*/
        public void progress(ProgressMessage message) throws DockerException {
            if (containsIgnoreCase(message.stream(), removingContainers)) {
                removedContainer.set(true);
            }
        }
    }, NO_CACHE, FORCE_RM);
    assertTrue(removedContainer.get());

    // Set NO_RM and verify we don't get message that containers were removed.
    sut.build(Paths.get(dockerDirectory), "test", new ProgressHandler() {
        @Override
        public void progress(ProgressMessage message) throws DockerException {
            assertThat(message.stream(), not(containsString(removingContainers)));
        }
    }, NO_CACHE, NO_RM);
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.TestDelegationTokenRenewer.java

@Test
public void testRMRestartWithExpiredToken() throws Exception {
    Configuration yarnConf = new YarnConfiguration();
    yarnConf.setBoolean(YarnConfiguration.RM_PROXY_USER_PRIVILEGES_ENABLED, true);
    yarnConf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "kerberos");
    yarnConf.setBoolean(YarnConfiguration.RECOVERY_ENABLED, true);
    FileSystem fs;//ww  w  .  j  a v a2s.  co m
    Path tmpDir;
    fs = FileSystem.get(new Configuration());
    tmpDir = new Path(new File("target", this.getClass().getSimpleName() + "-tmpDir").getAbsolutePath());
    fs.delete(tmpDir, true);
    fs.mkdirs(tmpDir);
    try {
        conf.set(YarnConfiguration.FS_RM_STATE_STORE_URI, tmpDir.toString());
        conf.set(YarnConfiguration.RM_STORE, FileSystemRMStateStore.class.getName());
        UserGroupInformation.setConfiguration(yarnConf);

        // create Token1:
        Text userText1 = new Text("user1");
        DelegationTokenIdentifier dtId1 = new DelegationTokenIdentifier(userText1, new Text("renewer1"),
                userText1);
        final Token<DelegationTokenIdentifier> originalToken = new Token<>(dtId1.getBytes(),
                "password1".getBytes(), dtId1.getKind(), new Text("service1"));
        Credentials credentials = new Credentials();
        credentials.addToken(userText1, originalToken);

        MockRM rm1 = new TestSecurityMockRM(yarnConf);
        rm1.start();
        RMApp app = rm1.submitApp(200, "name", "user", new HashMap<ApplicationAccessType, String>(), false,
                "default", 1, credentials);

        // create token2
        Text userText2 = new Text("user1");
        DelegationTokenIdentifier dtId2 = new DelegationTokenIdentifier(userText1, new Text("renewer2"),
                userText2);
        final Token<DelegationTokenIdentifier> updatedToken = new Token<DelegationTokenIdentifier>(
                dtId2.getBytes(), "password2".getBytes(), dtId2.getKind(), new Text("service2"));
        final AtomicBoolean firstRenewInvoked = new AtomicBoolean(false);
        final AtomicBoolean secondRenewInvoked = new AtomicBoolean(false);
        MockRM rm2 = new TestSecurityMockRM(yarnConf) {
            @Override
            protected DelegationTokenRenewer createDelegationTokenRenewer() {
                return new DelegationTokenRenewer() {

                    @Override
                    protected void renewToken(final DelegationTokenToRenew dttr) throws IOException {

                        if (dttr.token.equals(updatedToken)) {
                            secondRenewInvoked.set(true);
                            super.renewToken(dttr);
                        } else if (dttr.token.equals(originalToken)) {
                            firstRenewInvoked.set(true);
                            throw new InvalidToken("Failed to renew");
                        } else {
                            throw new IOException("Unexpected");
                        }
                    }

                    @Override
                    protected Token<?>[] obtainSystemTokensForUser(String user, final Credentials credentials)
                            throws IOException {
                        credentials.addToken(updatedToken.getService(), updatedToken);
                        return new Token<?>[] { updatedToken };
                    }
                };
            }
        };

        // simulating restart the rm
        rm2.start();

        // check nm can retrieve the token
        final MockNM nm1 = new MockNM("127.0.0.1:1234", 15120, rm2.getResourceTrackerService());
        nm1.registerNode();
        NodeHeartbeatResponse response = nm1.nodeHeartbeat(true);
        ByteBuffer tokenBuffer = response.getSystemCredentialsForApps().get(app.getApplicationId());
        Assert.assertNotNull(tokenBuffer);
        Credentials appCredentials = new Credentials();
        DataInputByteBuffer buf = new DataInputByteBuffer();
        tokenBuffer.rewind();
        buf.reset(tokenBuffer);
        appCredentials.readTokenStorageStream(buf);
        Assert.assertTrue(firstRenewInvoked.get() && secondRenewInvoked.get());
        Assert.assertTrue(appCredentials.getAllTokens().contains(updatedToken));
    } finally {
        fs.delete(tmpDir, true);
    }
}