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:io.orchestrate.client.itest.KvTest.java

@Theory
public void patchKeyAsync(@ForAll(sampleSize = 10) final String key) throws InterruptedException {
    assumeThat(key, not(isEmptyString()));

    final KvMetadata kvMetadata = insertItem(key, "{}");

    String name = Long.toHexString(RAND.nextLong());

    final BlockingQueue<KvMetadata> queue = DataStructures.getLTQInstance(KvMetadata.class);
    client.kv(collection(), key).patch(JsonPatch.builder().add("name", name).build())
            .on(new ResponseAdapter<KvMetadata>() {
                @Override/*from  w  w  w  .j av  a2s .  com*/
                public void onFailure(final Throwable error) {
                    fail(error.getMessage());
                }

                @Override
                public void onSuccess(final KvMetadata object) {
                    queue.add(object);
                }
            });

    final KvMetadata patched = queue.poll(5000, TimeUnit.MILLISECONDS);

    assertNotEquals(kvMetadata, patched);

    final KvObject<ObjectNode> kvObject = client.kv(kvMetadata.getCollection(), kvMetadata.getKey())
            .get(ObjectNode.class).get();

    assertNotNull(kvMetadata);
    assertNotNull(kvObject);
    assertEquals(kvMetadata.getCollection(), kvObject.getCollection());
    assertEquals(kvMetadata.getKey(), kvObject.getKey());
    assertEquals(patched.getRef(), kvObject.getRef());
    assertEquals(name, kvObject.getValue().get("name").asText());
}

From source file:ch.rgw.tools.StringTool.java

/**
 * Gibt eine zufllige und eindeutige Zeichenfolge zurck
 * /*from w ww. j av a2 s .  c o  m*/
 * @param salt
 *            Ein beliebiger String oder null
 */
public static String unique(final String salt) {
    if (ipHash == 0) {
        Iterator<String> it = NetTool.IPs.iterator();
        while (it.hasNext()) {
            ipHash += (it.next()).hashCode();
        }
    }

    long t = System.currentTimeMillis();
    int t1 = System.getProperty("user.name").hashCode();
    long t2 = ((long) ipHash) << 32;
    long t3 = Math.round(Math.random() * Long.MAX_VALUE);
    long t4 = t + t1 + t2 + t3;
    if (salt != null) {
        long t0 = salt.hashCode();
        t4 ^= t0;
    }
    t4 += sequence++;
    if (sequence > 99999) {
        sequence = 0;
    }
    long idx = sequence % salties.length;
    char start = salties[(int) idx];
    return new StringBuilder().append(start).append(Long.toHexString(t4))
            .append(Long.toHexString((long) Math.random() * 1000)).append(sequence).toString();
}

From source file:net.wastl.webmail.misc.Helper.java

/**
 * Calculate session-ID for a session./*from   w  w w  .j a v a 2  s.  c  o  m*/
 *
 * @param a Adress of the remote host
 * @param h Requestheader of the remote user agent
 * @returns Session-ID
 */
public static String calcSessionCode(InetAddress a, HTTPRequestHeader h) {
    String temp = a.toString().replace('\n', ' ') + h.getHeader("User-Agent").replace('\n', ' ');
    temp = "" + Long.toHexString(Math.abs(temp.hashCode()));
    if (h.getContent("login") != null && !h.getContent("login").equals("")
            && h.getPath().startsWith("/login")) {
        temp += Long.toHexString(Math.abs(h.getContent("login").hashCode()));
        temp += Long.toHexString(System.currentTimeMillis());
    } else if (h.getPath().startsWith("/admin/login")) {
        temp += "admin";
    }

    return temp;
}

From source file:bookkeepr.xmlable.DatabaseManager.java

public IndexIndex getFromSession(Session session) {
    if (session.getClosed()) {
        Index[] arr = new Index[256];
        Arrays.fill(arr, null);/*from   ww  w. j  a  v a2s  . co m*/
        for (long id : session.getModifiedKey()) {
            IdAble item = this.getById(id);
            if (item == null) {
                Logger.getLogger(DatabaseManager.class.getName()).log(Level.INFO,
                        "Item " + Long.toHexString(id) + " Not found in correct container, assuming deleted.");
                item = new DeletedId(id);
            }
            int type = getType(item);
            if (arr[type] == null) {
                arr[type] = TypeIdManager.getIndexFromClass(item.getClass());
            }

            arr[type].addItem(item);
        }

        IndexIndex result = new IndexIndex();
        for (Index idx : arr) {
            if (idx == null) {
                continue;
            } else {
                result.addIndex(idx);
            }

        }

        return result;
    } else {
        return null;
    }

}

From source file:org.gss_project.gss.server.ejb.ExternalAPIBean.java

/**
  * A helper method that generates a unique file path for a stored file. The
  * files are stored using random hash names that are distributed evenly in
  * a 2-level tree of subdirectories named after the first two hex characters
  * in the name. For example, file ab1234cd5769f will be stored in the path
  * /file-repository-root/a/b/ab1234cd5769f. The directories will be created
  * if they don't already exist./*from  ww w .j  av  a  2  s. co m*/
  *
  * @return a unique new file path
  */
 private String generateRepositoryFilePath() {
     String filename = Long.toHexString(random.nextLong());
     String fileRepositoryPath = getConfiguration().getString("fileRepositoryPath", "/tmp");
     File root = new File(fileRepositoryPath);
     if (!root.exists())
         root.mkdirs();
     File firstFolder = new File(root + File.separator + filename.substring(0, 1));
     if (!firstFolder.exists())
         firstFolder.mkdir();
     File secondFolder = new File(firstFolder + File.separator + filename.substring(1, 2));
     if (!secondFolder.exists())
         secondFolder.mkdir();
     return secondFolder + File.separator + filename;
 }

From source file:org.sakaiproject.bbb.impl.bbbapi.BaseBBBAPI.java

/** Generate a random password */
protected String generatePassword() {
    return Long.toHexString(randomGenerator.nextLong());
}

From source file:com.cosmosource.app.personnel.service.UnitAdminManager.java

/**
* @Description????16,?// ww  w  . j av a2 s  .c  om
* @Authorhp
* @Date2013-5-7
* @param addr
* @return
**/
public static String convertHex(String order) {
    if (order == null || order == "") {
        // log.info("??!");
        return null;
    }
    //      String od = Integer.toHexString(Integer.parseInt(order));
    String od = Long.toHexString(Long.parseLong(order));
    String result = "";
    if (od.length() == 1) {
        result = "0" + od;
    } else {
        result = od;
    }
    return result.toUpperCase();
}

From source file:io.orchestrate.client.itest.KvTest.java

@Theory
public void conditionalPatchKey(@ForAll(sampleSize = 10) final String key) {
    assumeThat(key, not(isEmptyString()));

    final KvMetadata kvMetadata = insertItem(key, "{}");

    String name = Long.toHexString(RAND.nextLong());

    final KvMetadata patched = client.kv(collection(), key).ifMatch(kvMetadata.getRef())
            .patch(JsonPatch.builder().add("name", name).build()).get();

    assertNotEquals(kvMetadata, patched);

    final KvObject<ObjectNode> kvObject = client.kv(kvMetadata.getCollection(), kvMetadata.getKey())
            .get(ObjectNode.class).get();

    assertNotNull(kvMetadata);// w ww . j  a va 2  s .  co  m
    assertNotNull(kvObject);
    assertEquals(kvMetadata.getCollection(), kvObject.getCollection());
    assertEquals(kvMetadata.getKey(), kvObject.getKey());
    assertEquals(patched.getRef(), kvObject.getRef());
    assertEquals(name, kvObject.getValue().get("name").asText());
}

From source file:it.unimi.dsi.webgraph.algo.HyperBall.java

/** Creates a new HyperBall instance.
 * //from   ww  w.  j  av a  2 s .  com
 * @param g the graph whose neighbourhood function you want to compute.
 * @param gt the transpose of <code>g</code>, or <code>null</code>.
 * @param log2m the logarithm of the number of registers per counter.
 * @param pl a progress logger, or <code>null</code>.
 * @param numberOfThreads the number of threads to be used (0 for automatic sizing).
 * @param bufferSize the size of an I/O buffer in bytes (0 for {@link #DEFAULT_BUFFER_SIZE}).
 * @param granularity the number of node per task in a multicore environment (it will be rounded to the next multiple of 64), or 0 for {@link #DEFAULT_GRANULARITY}.
 * @param external if true, results of an iteration will be stored on disk.
 * @param doSumOfDistances whether the sum of distances from each node should be computed.
 * @param doSumOfInverseDistances whether the sum of inverse distances from each node should be computed.
 * @param discountFunction an array (possibly <code>null</code>) of discount functions. 
 * @param seed the random seed passed to {@link HyperLogLogCounterArray#HyperLogLogCounterArray(long, long, int, long)}.
 */
public HyperBall(final ImmutableGraph g, final ImmutableGraph gt, final int log2m, final ProgressLogger pl,
        final int numberOfThreads, final int bufferSize, final int granularity, final boolean external,
        final boolean doSumOfDistances, final boolean doSumOfInverseDistances,
        final Int2DoubleFunction[] discountFunction, final long seed) throws IOException {
    super(g.numNodes(), g.numNodes(), ensureRegisters(log2m), seed);

    info("Seed : " + Long.toHexString(seed));

    gotTranspose = gt != null;
    localNextMustBeChecked = gotTranspose
            ? IntSets.synchronize(new IntOpenHashSet(Hash.DEFAULT_INITIAL_SIZE, Hash.VERY_FAST_LOAD_FACTOR))
            : null;

    numNodes = g.numNodes();
    try {
        numArcs = g.numArcs();
    } catch (UnsupportedOperationException e) {
        // No number of arcs. We have to enumerate.
        long a = 0;
        final NodeIterator nodeIterator = g.nodeIterator();
        for (int i = g.numNodes(); i-- != 0;) {
            nodeIterator.nextInt();
            a += nodeIterator.outdegree();
        }
        numArcs = a;
    }
    squareNumNodes = (double) numNodes * numNodes;

    cumulativeOutdegrees = new EliasFanoCumulativeOutdegreeList(g, numArcs, Math.max(0, 64 / m - 1));

    modifiedCounter = new boolean[numNodes];
    modifiedResultCounter = external ? null : new boolean[numNodes];
    if (gt != null) {
        mustBeChecked = new boolean[numNodes];
        nextMustBeChecked = new boolean[numNodes];
        if (gt.numNodes() != g.numNodes())
            throw new IllegalArgumentException("The graph and its transpose have a different number of nodes");
        if (gt.numArcs() != g.numArcs())
            throw new IllegalArgumentException("The graph and its transpose have a different number of arcs");
    }

    this.pl = pl;
    this.external = external;
    this.doSumOfDistances = doSumOfDistances;
    this.doSumOfInverseDistances = doSumOfInverseDistances;
    this.discountFunction = discountFunction == null ? new Int2DoubleFunction[0] : discountFunction;
    this.numberOfThreads = numberOfThreads(numberOfThreads);
    this.granularity = numberOfThreads == 1 ? numNodes
            : granularity == 0 ? DEFAULT_GRANULARITY : ((granularity + Long.SIZE - 1) & ~(Long.SIZE - 1));
    this.bufferSize = Math.max(1, (bufferSize == 0 ? DEFAULT_BUFFER_SIZE : bufferSize)
            / ((Long.SIZE / Byte.SIZE) * (counterLongwords + 1)));

    info("Relative standard deviation: "
            + Util.format(100 * HyperLogLogCounterArray.relativeStandardDeviation(log2m)) + "% (" + m
            + " registers/counter, " + registerSize + " bits/register, " + Util.format(m * registerSize / 8.)
            + " bytes/counter)");
    if (external)
        info("Running " + this.numberOfThreads + " threads with a buffer of " + Util.formatSize(this.bufferSize)
                + " counters");
    else
        info("Running " + this.numberOfThreads + " threads");

    thread = new IterationThread[this.numberOfThreads];

    if (external) {
        info("Creating update list...");
        updateFile = File.createTempFile(HyperBall.class.getName(), "-temp");
        updateFile.deleteOnExit();
        fileChannel = (randomAccessFile = new RandomAccessFile(updateFile, "rw")).getChannel();
    } else {
        updateFile = null;
        fileChannel = null;
    }

    nodes = new AtomicInteger();
    arcs = new AtomicLong();
    modified = new AtomicInteger();
    unwritten = new AtomicInteger();

    neighbourhoodFunction = new DoubleArrayList();
    sumOfDistances = doSumOfDistances ? new float[numNodes] : null;
    sumOfInverseDistances = doSumOfInverseDistances ? new float[numNodes] : null;
    discountedCentrality = new float[this.discountFunction.length][];
    for (int i = 0; i < this.discountFunction.length; i++)
        discountedCentrality[i] = new float[numNodes];

    info("HyperBall memory usage: " + Util.formatSize2(usedMemory()) + " [not counting graph(s)]");

    if (!external) {
        info("Allocating result bit vectors...");
        // Allocate vectors that will store the result.
        resultBits = new long[bits.length][];
        resultRegisters = new LongBigList[bits.length];
        for (int i = bits.length; i-- != 0;)
            resultRegisters[i] = (LongArrayBitVector.wrap(resultBits[i] = new long[bits[i].length]))
                    .asLongBigList(registerSize);
    } else {
        resultBits = null;
        resultRegisters = null;
    }

    lock = new ReentrantLock();
    allWaiting = lock.newCondition();
    start = lock.newCondition();
    aliveThreads = this.numberOfThreads;

    if (this.numberOfThreads == 1)
        (thread[0] = new IterationThread(g, gt, 0)).start();
    else
        for (int i = 0; i < this.numberOfThreads; i++)
            (thread[i] = new IterationThread(g.copy(), gt != null ? gt.copy() : null, i)).start();

    // We wait for all threads being read to start.
    lock.lock();
    try {
        if (aliveThreads != 0)
            allWaiting.await();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } finally {
        lock.unlock();
    }
}

From source file:com.google.cloud.dns.testing.LocalDnsHelper.java

/**
 * Returns a hex string id (used for a record set) unique within the set of ids.
 *//*w w  w  .  jav a2 s.  com*/
@VisibleForTesting
static String getUniqueId(Set<String> ids) {
    String id;
    do {
        id = Long.toHexString(System.currentTimeMillis()) + Long.toHexString(Math.abs(ID_GENERATOR.nextLong()));
    } while (ids.contains(id));
    return id;
}