Example usage for java.lang Long toHexString

List of usage examples for java.lang Long toHexString

Introduction

In this page you can find the example usage for java.lang Long toHexString.

Prototype

public static String toHexString(long i) 

Source Link

Document

Returns a string representation of the long argument as an unsigned integer in base 16.

Usage

From source file:com.trsst.server.TrsstAdapter.java

protected boolean syncToService(String id, Storage storage, String serviceUrl) {
    Feed localFeed = fetchFeedFromStorage(id, storage);
    Feed remoteFeed = pullFromService(serviceUrl, id, "count=1");
    if (localFeed != null && remoteFeed != null) {
        // find which is most recent
        long[] entryIds = storage.getEntryIdsForFeedId(id, 0, 1, null, null, null, null, null, null);
        List<Entry> remoteEntries = remoteFeed.getEntries();
        if (entryIds.length == 0) {
            // no local entries: treat as no feed and drop below
            localFeed = null;/* w w w  .  java2s  . c o  m*/
        }
        if (remoteEntries.size() == 0) {
            // no remote entries: treat as no feed and drop below
            remoteFeed = null;
        }
        if (localFeed != null && remoteFeed != null) {
            // compare timestamps
            Date localDate = new Date(entryIds[0]);
            Date remoteDate = remoteEntries.get(0).getUpdated();
            if (localDate.before(remoteDate)) {
                // remote has latest info: pull difference
                try {
                    remoteFeed = pullFromService(serviceUrl, id,
                            "count=99&after=" + Long.toHexString(localDate.getTime()));
                    ingestFeed(storage, remoteFeed);
                    return true;
                } catch (IllegalArgumentException e) {
                    log.warn("syncToService: ingest latest remote: invalid feed: " + id + " : " + serviceUrl
                            + " : " + Long.toHexString(localDate.getTime()));
                } catch (XMLSignatureException e) {
                    log.warn("syncToService: ingest latest remote: invalid signature: " + id + " : "
                            + serviceUrl + " : " + Long.toHexString(localDate.getTime()));
                } catch (Exception e) {
                    log.error("syncToService: ingest latest remote: unexpected error: " + id + " : "
                            + serviceUrl + " : " + Long.toHexString(localDate.getTime()));
                }
            } else if (remoteDate.before(localDate)) {
                // local has latest info: push difference
                entryIds = storage.getEntryIdsForFeedId(id, 0, 99, remoteDate, null, null, null, null, null);
                for (long entryId : entryIds) {
                    localFeed.addEntry(getEntry(storage, id, entryId).getRoot());
                }
                return pushToService(localFeed, serviceUrl);
            }
            // otherwise: feeds are in sync
            return true;
        }
    }

    if (localFeed == null && remoteFeed != null) {
        // local is missing: ingest remote
        try {
            ingestFeed(storage, remoteFeed);
            return true;
        } catch (IllegalArgumentException e) {
            log.warn("syncToService: ingest remote: invalid feed: " + id + " : " + serviceUrl);
        } catch (XMLSignatureException e) {
            log.warn("syncToService: ingest remote: invalid signature: " + id + " : " + serviceUrl);
        } catch (Exception e) {
            log.error("syncToService: ingest remote: unexpected error: " + id + " : " + serviceUrl);
        }
    } else if (localFeed != null && remoteFeed == null) {
        // remote is missing: push local with (all?) entries
        long[] entryIds = storage.getEntryIdsForFeedId(id, 0, 99, null, null, null, null, null, null);
        for (long entryId : entryIds) {
            localFeed.addEntry(getEntry(storage, id, entryId).getRoot());
        }
        return pushToService(localFeed, serviceUrl);
    }
    return false;
}

From source file:org.apache.bookkeeper.bookie.BookieShell.java

/**
 * Scan over an entry log file for entries in the given position range
 * /*ww  w .  j  a  v a2  s.com*/
 * @param logId
 *          Entry Log File id.
 * @param rangeStartPos
 *          Start position of the entry we are looking for
 * @param rangeEndPos
 *          End position of the entry we are looking for (-1 for till the end of the entrylog)
 * @param printMsg
 *          Whether printing the entry data.
 * @throws Exception
 */
protected void scanEntryLogForPositionRange(long logId, final long rangeStartPos, final long rangeEndPos,
        final boolean printMsg) throws Exception {
    System.out.println("Scan entry log " + logId + " (" + Long.toHexString(logId) + ".log)"
            + " for PositionRange: " + rangeStartPos + " - " + rangeEndPos);
    final MutableBoolean entryFound = new MutableBoolean(false);
    scanEntryLog(logId, new EntryLogScanner() {
        private MutableBoolean stopScanning = new MutableBoolean(false);

        @Override
        public boolean accept(long ledgerId) {
            return !stopScanning.booleanValue();
        }

        @Override
        public void process(long ledgerId, long entryStartPos, ByteBuffer entry) {
            if (!stopScanning.booleanValue()) {
                if ((rangeEndPos != -1) && (entryStartPos > rangeEndPos)) {
                    stopScanning.setValue(true);
                } else {
                    int entrySize = entry.limit();
                    /**
                     * entrySize of an entry (inclusive of payload and
                     * header) value is stored as int value in log file, but
                     * it is not counted in the entrySize, hence for calculating
                     * the end position of the entry we need to add additional
                     * 4 (intsize of entrySize). Please check
                     * EntryLogger.scanEntryLog.
                     */
                    long entryEndPos = entryStartPos + entrySize + 4 - 1;
                    if (((rangeEndPos == -1) || (entryStartPos <= rangeEndPos))
                            && (rangeStartPos <= entryEndPos)) {
                        formatEntry(entryStartPos, entry, printMsg);
                        entryFound.setValue(true);
                    }
                }
            }
        }
    });
    if (!entryFound.booleanValue()) {
        System.out.println("Entry log " + logId + " (" + Long.toHexString(logId)
                + ".log) doesn't has any entry in the range " + rangeStartPos + " - " + rangeEndPos
                + ". Probably the position range, you have provided is lesser than the LOGFILE_HEADER_SIZE (1024) "
                + "or greater than the current log filesize.");
    }
}

From source file:services.object.ObjectService.java

public void readBuildoutDatatable(DatatableVisitor buildoutTable, Planet planet, float x1, float z1)
        throws InstantiationException, IllegalAccessException {

    CrcStringTableVisitor crcTable = ClientFileManager.loadFile("misc/object_template_crc_string_table.iff",
            CrcStringTableVisitor.class);
    String planetName = planet.getName();
    Map<Long, Long> duplicate = new HashMap<Long, Long>();

    for (int i = 0; i < buildoutTable.getRowCount(); i++) {
        String template;/*from www.j  a v  a  2 s  .  c  o  m*/

        if (buildoutTable.getColumnCount() <= 11)
            template = crcTable.getTemplateString((Integer) buildoutTable.getObject(i, 0));
        else
            template = crcTable.getTemplateString((Integer) buildoutTable.getObject(i, 3));

        if (template != null) {

            float px, py, pz, qw, qx, qy, qz, radius;
            long objectId = 0, containerId = 0, objectId2 = 0, containerId2 = 0;
            int type = 0, cellIndex = 0, portalCRC;

            if (buildoutTable.getColumnCount() <= 11) {

                objectId2 = (((Integer) buildoutTable.getObject(i, 0) == 0) ? 0
                        : Delta.createBuffer(8).putInt((Integer) buildoutTable.getObject(i, 0))
                                .putInt(0xF986FFFF).flip().getLong());
                cellIndex = (Integer) buildoutTable.getObject(i, 1);
                px = (Float) buildoutTable.getObject(i, 2);
                py = (Float) buildoutTable.getObject(i, 3);
                pz = (Float) buildoutTable.getObject(i, 4);
                qw = (Float) buildoutTable.getObject(i, 5);
                qx = (Float) buildoutTable.getObject(i, 6);
                qy = (Float) buildoutTable.getObject(i, 7);
                qz = (Float) buildoutTable.getObject(i, 8);
                radius = (Float) buildoutTable.getObject(i, 9);
                portalCRC = (Integer) buildoutTable.getObject(i, 10);

            } else {

                // Since the ids are just ints, they append 0xFFFF86F9 to them
                // This is demonstated in the packet sent to the server when you /target client-spawned objects
                objectId = (((Integer) buildoutTable.getObject(i, 0) == 0) ? 0
                        : Delta.createBuffer(8).putInt((Integer) buildoutTable.getObject(i, 0))
                                .putInt(0xF986FFFF).flip().getLong());
                objectId2 = Long.valueOf((Integer) buildoutTable.getObjectByColumnNameAndIndex("objid", i));
                containerId = (((Integer) buildoutTable.getObject(i, 1) == 0) ? 0
                        : Delta.createBuffer(8).putInt((Integer) buildoutTable.getObject(i, 1))
                                .putInt(0xF986FFFF).flip().getLong());
                containerId2 = Long
                        .valueOf((Integer) buildoutTable.getObjectByColumnNameAndIndex("container", i));
                type = (Integer) buildoutTable.getObject(i, 2);
                cellIndex = (Integer) buildoutTable.getObject(i, 4);

                px = (Float) buildoutTable.getObject(i, 5);
                py = (Float) buildoutTable.getObject(i, 6);
                pz = (Float) buildoutTable.getObject(i, 7);
                qw = (Float) buildoutTable.getObject(i, 8);
                qx = (Float) buildoutTable.getObject(i, 9);
                qy = (Float) buildoutTable.getObject(i, 10);
                qz = (Float) buildoutTable.getObject(i, 11);
                radius = (Float) buildoutTable.getObject(i, 12);
                portalCRC = (Integer) buildoutTable.getObject(i, 13);

            }

            // Treeku - Refactored to work around duplicate objectIds
            // Required for instances/heroics which are duplicated ie. 10 times
            //if(!template.equals("object/cell/shared_cell.iff") && objectId != 0 && getObject(objectId) != null) {
            if (!template.equals("object/cell/shared_cell.iff") && objectId != 0
                    && checkIfObjectAlreadyInList(objectId)) {
                SWGObject object = getObject(objectId);

                // Same coordinates is a true duplicate
                if ((px + ((containerId == 0) ? 0 : x1)) == object.getPosition().x
                        && py == object.getPosition().y
                        && (pz + ((containerId == 0) ? 0 : z1)) == object.getPosition().z) {
                    //System.out.println("Duplicate buildout object: " + template);
                    continue;
                }
            }

            if (duplicate.containsKey(containerId)) {
                containerId = duplicate.get(containerId);
            }

            // TODO needs to a way to work for mustafar and kashyyyk which both have instances
            //if (objectId != 0 && getObject(objectId) != null && (planetName.contains("dungeon") || planetName.contains("adventure"))) {
            if (objectId != 0 && checkIfObjectAlreadyInList(objectId)
                    && (planetName.contains("dungeon") || planetName.contains("adventure"))) {
                SWGObject container = getObject(containerId);
                float x = (px + ((container == null) ? x1 : container.getPosition().x));
                float z = (pz + ((container == null) ? z1 : container.getPosition().z));
                String key = "" + CRC.StringtoCRC(planet.getName()) + CRC.StringtoCRC(template) + type
                        + containerId + cellIndex + x + py + z;
                long newObjectId = 0;

                if (core.getDuplicateIdODB().contains(key)) {
                    newObjectId = ((DuplicateId) core.getDuplicateIdODB().get(key)).getObjectId();
                } else {
                    newObjectId = generateObjectID();
                    core.getDuplicateIdODB().put(key, new DuplicateId(key, newObjectId));
                }

                duplicate.put(objectId, newObjectId);
                objectId = newObjectId;
            }

            List<Long> containers = new ArrayList<Long>();
            SWGObject object;
            if (objectId != 0 && containerId == 0) {
                if (portalCRC != 0) { // Is building
                    //if (core.getSWGObjectODB().contains(objectId) && !duplicate.containsValue(objectId)){
                    if (core.getSWGObjectODB().contains(objectId)) {
                        if (buildoutDEBUG)
                            System.err.println("core.getSWGObjectODB().contains(objectId)" + template + "  "
                                    + Long.toHexString(objectId));
                        continue;
                    }
                    if (duplicate.containsValue(objectId)) {
                        if (buildoutDEBUG)
                            System.err.println("duplicate.containsValue(objectId)" + template + "  "
                                    + Long.toHexString(objectId));
                        continue;
                    }
                    if (checkIfObjectAlreadyInList(objectId)) {
                        if (buildoutDEBUG)
                            System.err.println("checkIfObjectAlreadyInList(objectId) " + template + "  "
                                    + Long.toHexString(objectId));
                        continue;
                    }

                    containers.add(objectId);
                    object = createObject(template, objectId, planet, new Point3D(px + x1, py, pz + z1),
                            new Quaternion(qw, qx, qy, qz), null, true, true);
                    object.setAttachment("childObjects", null);

                    // must use the objectListId to identify the building later with cellMap.get(containerId)
                    buildingMap.put(objectId, ((BuildingObject) object));
                    //System.out.println("buildingMap put " + Long.toHexString(objectId));
                    /*if (!duplicate.containsValue(objectId)) {
                       ((BuildingObject) object).createTransaction(core.getBuildingODB().getEnvironment());
                       core.getBuildingODB().put((BuildingObject) object, Long.class, BuildingObject.class, ((BuildingObject) object).getTransaction());
                       ((BuildingObject) object).getTransaction().commitSync();
                    }*/
                } else { // building without portal, Seems to never happen
                    object = createObject(template, 0, planet, new Point3D(px + x1, py, pz + z1),
                            new Quaternion(qw, qx, qy, qz), null, false, true);

                }
                if (object == null) {
                    //System.err.println("Buildout table contained an entry that can't be instantiated!");
                    continue;
                }
                object.setContainerPermissions(WorldPermissions.WORLD_PERMISSIONS);
                if (radius > 256)
                    object.setAttachment("bigSpawnRange", new Boolean(true));

                if (!duplicate.containsValue(objectId) && object instanceof BuildingObject && portalCRC != 0) {
                    synchronized (persistentBuildings) {
                        persistentBuildings.add((BuildingObject) object);
                    }
                }

            } else if (containerId != 0) {
                object = createObject(template, 0, planet, new Point3D(px, py, pz),
                        new Quaternion(qw, qx, qy, qz), null, false, true);
                if (containers.contains(containerId)) {
                    object.setContainerPermissions(WorldPermissions.WORLD_PERMISSIONS);
                    object.setisInSnapshot(false);
                    //containers.add(objectId); // ?!?!?!
                }
                if (object instanceof CellObject && cellIndex != 0) {
                    object.setContainerPermissions(WorldCellPermissions.WORLD_CELL_PERMISSIONS);
                    ((CellObject) object).setCellNumber(cellIndex);
                    List<CellObject> cellList = cellMap.get(containerId);
                    //System.out.println("Cell containerId " + Long.toHexString(containerId));
                    if (cellList != null) {
                        cellList.add(((CellObject) object));
                        cellMap.put(containerId, cellList);
                    } else {
                        cellList = new ArrayList<CellObject>();
                        cellList.add(((CellObject) object));
                        cellMap.put(containerId, cellList);
                    }
                }
                //               SWGObject parent = getObject(containerId);
                //               
                //               if(parent != null && object != null) {
                //                  if(parent instanceof BuildingObject && ((BuildingObject) parent).getCellByCellNumber(cellIndex) != null)
                //                     continue;
                //                  parent.add(object);
                //               }
            } else {
                object = createObject(template, 0, planet, new Point3D(px + x1, py, pz + z1),
                        new Quaternion(qw, qx, qy, qz), null, false, true);
                object.setContainerPermissions(WorldPermissions.WORLD_PERMISSIONS);

            }

            if (object != null && object instanceof TangibleObject && !(object instanceof CreatureObject)) {
                ((TangibleObject) object).setStaticObject(true);
            }

            //System.out.println("Spawning: " + template + " at: X:" + object.getPosition().x + " Y: " + object.getPosition().y + " Z: " + object.getPosition().z);
            if (object != null)
                object.setAttachment("isBuildout", new Boolean(true));
        }

    }

    //      for(BuildingObject building : persistentBuildings) {
    //         building.setAttachment("buildoutBuilding", true);
    //         core.getSWGObjectODB().put(building.getObjectID(), building);
    //         destroyObject(building);
    //      }

}

From source file:org.apache.bookkeeper.bookie.BookieShell.java

/**
 * Scan a journal file// w  w  w  .  j av  a2s.  c  o m
 *
 * @param journalId
 *          Journal File Id
 * @param printMsg
 *          Whether printing the entry data.
 */
protected void scanJournal(long journalId, final boolean printMsg) throws Exception {
    System.out.println("Scan journal " + journalId + " (" + Long.toHexString(journalId) + ".txn)");
    scanJournal(journalId, new JournalScanner() {
        boolean printJournalVersion = false;

        @Override
        public void process(int journalVersion, long offset, ByteBuffer entry) throws IOException {
            if (!printJournalVersion) {
                System.out.println("Journal Version : " + journalVersion);
                printJournalVersion = true;
            }
            formatEntry(offset, entry, printMsg);
        }
    });
}

From source file:org.apache.bookkeeper.bookie.BookieShell.java

/**
 * Print last log mark/*from w  w w  .  j  a  v a 2s  .  co m*/
 */
protected void printLastLogMark() throws IOException {
    LogMark lastLogMark = getJournal().getLastLogMark().getCurMark();
    System.out.println("LastLogMark: Journal Id - " + lastLogMark.getLogFileId() + "("
            + Long.toHexString(lastLogMark.getLogFileId()) + ".txn), Pos - " + lastLogMark.getLogFileOffset());
}

From source file:com.peterbochs.instrument.InstrumentPanel.java

private void addCells(Object parent) {
    setMarkerMaxAndMinSize();/*  w ww.j  a  v a 2  s.  c  o m*/

    final int minX = 50;
    final int minY = 20;
    final int cellHeight = 20;

    int count = graph.getModel().getChildCount(parent);
    for (int x = 0; x < count; x++) {
        graph.getModel().remove(graph.getModel().getChildAt(parent, 0));
    }
    callGraphRawTableModel.removeAll();
    graph.getModel().beginUpdate();
    try {
        mxCell lastPort = null;
        jStatusProgressBar.setMaximum(MAX_NUMBER_OF_VERTEX);
        for (int x = JmpSocketServer.jmpDataVector.size() - 1, counter = 0; x >= 0
                && counter <= MAX_NUMBER_OF_VERTEX; x--, counter++) {
            jStatusLabel.setText("Updating call graph " + x + "/" + JmpSocketServer.jmpDataVector.size());
            jStatusProgressBar.setValue(counter);
            JmpData jumpData = JmpSocketServer.jmpDataVector.get(x);
            callGraphRawTableModel.add(jumpData);
            int positionX = (int) ((jumpData.segmentStart - graphComponent.markerOffset)
                    / graphComponent.addressPerPixel);
            positionX += minX;
            mxCell node = (mxCell) graph.insertVertex(parent, null,
                    "0x" + Long.toHexString(jumpData.segmentStart) + " -> " + "0x"
                            + Long.toHexString(jumpData.segmentEnd),
                    positionX, minY + (counter * 30),
                    (jumpData.segmentEnd - jumpData.segmentStart) / graphComponent.addressPerPixel, cellHeight);

            mxCell ports[] = addPort(node);

            if (lastPort != null) {
                // graph.insertEdge(parent, null, x, lastPort, ports[0],
                // "edgeStyle=elbowEdgeStyle;elbow=horizontal;"
                // +
                // "exitX=1;exitY=0.5;exitPerimeter=1;entryX=0;entryY=0;entryPerimeter=1;");
                graph.insertEdge(parent, null, "", lastPort, ports[0], "edgeStyle=entityRelationEdgeStyle;");
            }
            lastPort = ports[1];
        }
        jStatusProgressBar.setValue(jStatusProgressBar.getMaximum());
    } finally {
        graph.getModel().endUpdate();
    }
}

From source file:org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.TestResourceLocalizationService.java

@Test
@SuppressWarnings("unchecked")
public void testPublicResourceAddResourceExceptions() throws Exception {
    List<Path> localDirs = new ArrayList<Path>();
    String[] sDirs = new String[4];
    for (int i = 0; i < 4; ++i) {
        localDirs.add(lfs.makeQualified(new Path(basedir, i + "")));
        sDirs[i] = localDirs.get(i).toString();
    }//from   w  w w . ja va  2 s.c  om
    conf.setStrings(YarnConfiguration.NM_LOCAL_DIRS, sDirs);
    conf.setBoolean(Dispatcher.DISPATCHER_EXIT_ON_ERROR_KEY, true);

    DrainDispatcher dispatcher = new DrainDispatcher();
    EventHandler<ApplicationEvent> applicationBus = mock(EventHandler.class);
    dispatcher.register(ApplicationEventType.class, applicationBus);
    EventHandler<ContainerEvent> containerBus = mock(EventHandler.class);
    dispatcher.register(ContainerEventType.class, containerBus);

    ContainerExecutor exec = mock(ContainerExecutor.class);
    DeletionService delService = mock(DeletionService.class);
    LocalDirsHandlerService dirsHandler = new LocalDirsHandlerService();
    LocalDirsHandlerService dirsHandlerSpy = spy(dirsHandler);
    dirsHandlerSpy.init(conf);

    dispatcher.init(conf);
    dispatcher.start();

    try {
        ResourceLocalizationService rawService = new ResourceLocalizationService(dispatcher, exec, delService,
                dirsHandlerSpy, nmContext);
        ResourceLocalizationService spyService = spy(rawService);
        doReturn(mockServer).when(spyService).createServer();
        doReturn(lfs).when(spyService).getLocalFileContext(isA(Configuration.class));

        spyService.init(conf);
        spyService.start();

        final String user = "user0";
        final String userFolder = "user0Folder";
        // init application
        final Application app = mock(Application.class);
        final ApplicationId appId = BuilderUtils.newApplicationId(314159265358979L, 3);
        when(app.getUser()).thenReturn(user);
        when(app.getUserFolder()).thenReturn(userFolder);
        when(app.getAppId()).thenReturn(appId);
        spyService.handle(
                new ApplicationLocalizationEvent(LocalizationEventType.INIT_APPLICATION_RESOURCES, app));
        dispatcher.await();

        // init resources
        Random r = new Random();
        r.setSeed(r.nextLong());

        // Queue localization request for the public resource
        final LocalResource pubResource = getPublicMockedResource(r);
        final LocalResourceRequest pubReq = new LocalResourceRequest(pubResource);
        Map<LocalResourceVisibility, Collection<LocalResourceRequest>> req = new HashMap<LocalResourceVisibility, Collection<LocalResourceRequest>>();
        req.put(LocalResourceVisibility.PUBLIC, Collections.singletonList(pubReq));

        // init container.
        final Container c = getMockContainer(appId, 42, user, userFolder);

        // first test ioexception
        Mockito.doThrow(new IOException()).when(dirsHandlerSpy).getLocalPathForWrite(isA(String.class),
                Mockito.anyLong(), Mockito.anyBoolean());
        // send request
        spyService.handle(new ContainerLocalizationRequestEvent(c, req));
        dispatcher.await();
        LocalResourcesTracker tracker = spyService.getLocalResourcesTracker(LocalResourceVisibility.PUBLIC,
                user, appId);
        Assert.assertNull(tracker.getLocalizedResource(pubReq));

        // test IllegalArgumentException
        String name = Long.toHexString(r.nextLong());
        URL url = getPath("/local/PRIVATE/" + name + "/");
        final LocalResource rsrc = BuilderUtils.newLocalResource(url, LocalResourceType.FILE,
                LocalResourceVisibility.PUBLIC, r.nextInt(1024) + 1024L, r.nextInt(1024) + 2048L, false);
        final LocalResourceRequest pubReq1 = new LocalResourceRequest(rsrc);
        Map<LocalResourceVisibility, Collection<LocalResourceRequest>> req1 = new HashMap<LocalResourceVisibility, Collection<LocalResourceRequest>>();
        req1.put(LocalResourceVisibility.PUBLIC, Collections.singletonList(pubReq1));
        Mockito.doCallRealMethod().when(dirsHandlerSpy).getLocalPathForWrite(isA(String.class),
                Mockito.anyLong(), Mockito.anyBoolean());
        // send request
        spyService.handle(new ContainerLocalizationRequestEvent(c, req1));
        dispatcher.await();
        tracker = spyService.getLocalResourcesTracker(LocalResourceVisibility.PUBLIC, user, appId);
        Assert.assertNull(tracker.getLocalizedResource(pubReq));

        // test RejectedExecutionException by shutting down the thread pool
        PublicLocalizer publicLocalizer = spyService.getPublicLocalizer();
        publicLocalizer.threadPool.shutdown();

        spyService.handle(new ContainerLocalizationRequestEvent(c, req));
        dispatcher.await();
        tracker = spyService.getLocalResourcesTracker(LocalResourceVisibility.PUBLIC, user, appId);
        Assert.assertNull(tracker.getLocalizedResource(pubReq));

    } finally {
        // if we call stop with events in the queue, an InterruptedException gets
        // thrown resulting in the dispatcher thread causing a system exit
        dispatcher.await();
        dispatcher.stop();
    }
}

From source file:org.apache.hadoop.hbase.HBaseTestingUtility.java

/**
 * Expire a ZooKeeper session as recommended in ZooKeeper documentation
 * http://wiki.apache.org/hadoop/ZooKeeper/FAQ#A4
 * There are issues when doing this:/*w  ww .j  av a2 s.  c  om*/
 * [1] http://www.mail-archive.com/dev@zookeeper.apache.org/msg01942.html
 * [2] https://issues.apache.org/jira/browse/ZOOKEEPER-1105
 *
 * @param nodeZK - the ZK watcher to expire
 * @param checkStatus - true to check if we can create an HTable with the
 *                    current configuration.
 */
public void expireSession(ZooKeeperWatcher nodeZK, boolean checkStatus) throws Exception {
    Configuration c = new Configuration(this.conf);
    String quorumServers = ZKConfig.getZKQuorumServersString(c);
    ZooKeeper zk = nodeZK.getRecoverableZooKeeper().getZooKeeper();
    byte[] password = zk.getSessionPasswd();
    long sessionID = zk.getSessionId();

    // Expiry seems to be asynchronous (see comment from P. Hunt in [1]),
    //  so we create a first watcher to be sure that the
    //  event was sent. We expect that if our watcher receives the event
    //  other watchers on the same machine will get is as well.
    // When we ask to close the connection, ZK does not close it before
    //  we receive all the events, so don't have to capture the event, just
    //  closing the connection should be enough.
    ZooKeeper monitor = new ZooKeeper(quorumServers, 1000, new org.apache.zookeeper.Watcher() {
        @Override
        public void process(WatchedEvent watchedEvent) {
            LOG.info("Monitor ZKW received event=" + watchedEvent);
        }
    }, sessionID, password);

    // Making it expire
    ZooKeeper newZK = new ZooKeeper(quorumServers, 1000, EmptyWatcher.instance, sessionID, password);

    //ensure that we have connection to the server before closing down, otherwise
    //the close session event will be eaten out before we start CONNECTING state
    long start = System.currentTimeMillis();
    while (newZK.getState() != States.CONNECTED && System.currentTimeMillis() - start < 1000) {
        Thread.sleep(1);
    }
    newZK.close();
    LOG.info("ZK Closed Session 0x" + Long.toHexString(sessionID));

    // Now closing & waiting to be sure that the clients get it.
    monitor.close();

    if (checkStatus) {
        new HTable(new Configuration(conf), TableName.META_TABLE_NAME).close();
    }
}

From source file:com.gigabytedevelopersinc.app.calculator.Calculator.java

private String newBase(String originalNumber, int originalBase, int base) throws SyntaxException {
    String[] split = originalNumber.split("\\.");
    if (split.length == 0) {
        split = new String[1];
        split[0] = "0";
    }/*from w w  w.ja  v  a  2  s .c  o  m*/
    if (split[0].isEmpty()) {
        split[0] = "0";
    }
    if (originalBase != 10) {
        split[0] = Long.toString(Long.parseLong(split[0], originalBase));
    }

    String wholeNumber = "";
    switch (base) {
    case 2:
        wholeNumber = Long.toBinaryString(Long.parseLong(split[0]));
        break;
    case 8:
        wholeNumber = Long.toOctalString(Long.parseLong(split[0]));
        break;
    case 10:
        wholeNumber = split[0];
        break;
    case 16:
        wholeNumber = Long.toHexString(Long.parseLong(split[0]));
        break;
    }
    if (split.length == 1)
        return wholeNumber.toUpperCase(Locale.US);

    // Catch overflow (it's a decimal, it can be (slightly) rounded
    if (split[1].length() > 13) {
        split[1] = split[1].substring(0, 13);
    }

    Solver solver = new Solver();
    double decimal = 0;
    if (originalBase != 10) {
        String decimalFraction = Long.toString(Long.parseLong(split[1], originalBase)) + "/" + originalBase
                + "^" + split[1].length();
        decimal = solver.eval(decimalFraction);
    } else {
        decimal = Double.parseDouble("0." + split[1]);
    }
    if (decimal == 0)
        return wholeNumber.toUpperCase(Locale.US);

    String decimalNumber = "";
    for (int i = 0; decimal != 0 && i <= 8; i++) {
        decimal *= base;
        int id = (int) Math.floor(decimal);
        decimal -= id;
        decimalNumber += Integer.toHexString(id);
    }
    return (wholeNumber + "." + decimalNumber).toUpperCase(Locale.US);
}