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:ar.com.qbe.siniestros.model.utils.MimeMagic.MagicMatcher.java

/**
 * test the data against a short//from www.  java2  s  .  c o m
 *
 * @param data the data we are testing
 *
 * @return if we have a match
 */
private boolean testShort(ByteBuffer data) {
    log.debug("testShort()");

    short val = 0;
    String test = new String(match.getTest().array());
    char comparator = match.getComparator();
    long bitmask = match.getBitmask();

    val = byteArrayToShort(data);

    // apply bitmask before the comparison
    val = (short) (val & (short) bitmask);

    short tst = 0;

    try {
        tst = Integer.decode(test).shortValue();
    } catch (NumberFormatException e) {
        log.error("testShort(): " + e);

        return false;

        //if (test.length() == 1) {   
        //   tst = new Integer(Character.getNumericValue(test.charAt(0))).shortValue();
        //}
    }

    log.debug("testShort(): testing '" + Long.toHexString(val) + "' against '" + Long.toHexString(tst) + "'");

    switch (comparator) {
    case '=':
        return val == tst;

    case '!':
        return val != tst;

    case '>':
        return val > tst;

    case '<':
        return val < tst;
    }

    return false;
}

From source file:pl.nask.hsn2.normalizers.URLNormalizerUtils.java

private static StringBuilder arrayToIPv6(long[] octets, boolean lastAsIPv4) throws URLHostParseException {
    StringBuilder sb = new StringBuilder();
    sb.append("[");
    int i = 0;// ww  w  .  ja v a  2  s .c om
    while (octets[i] == 0l) {
        i++;
    }

    switch (i) {
    case 3:
    case 4:
        if (lastAsIPv4) {
            sb.append("::");
        } else {
            i = 0;
        }
        break;
    case 5:
        if (octets[5] == 0xffffl) {
            octets[4] = octets[6] >> 8;
            octets[5] = octets[6] & 0xff;
            octets[6] = octets[7] >> 8;
            octets[7] = octets[7] & 0xff;
            octets[3] = 0xffffl;
            i = 3;
            lastAsIPv4 = true;
            sb.append("::");
        } else {
            i = 0;
        }
        break;
    case 6:
        octets[4] = octets[6] >> 8;
        octets[5] = octets[6] & 0xff;
        octets[6] = octets[7] >> 8;
        octets[7] = octets[7] & 0xff;
        i = 4;
        sb.append("::");
        lastAsIPv4 = true;

        break;
    default:
        i = 0;
        break;
    }
    if (lastAsIPv4) {
        checkIPv46correctness(octets);
    }
    for (; i < octets.length; i++) {
        if (!lastAsIPv4) {
            sb.append(Long.toHexString(octets[i])).append(":");
        } else {
            if (i < 4) {
                sb.append(Long.toHexString(octets[i])).append(":");
            } else {
                sb.append(Long.toString(octets[i])).append(".");
            }
        }
    }
    i = sb.length();
    sb.replace(i - 1, i, "]");
    return sb;
}

From source file:ar.com.qbe.siniestros.model.utils.MimeMagic.MagicMatcher.java

/**
 * test the data against a long/*from w w  w  .j  av  a  2 s  .c  o  m*/
 *
 * @param data the data we are testing
 *
 * @return if we have a match
 */
private boolean testLong(ByteBuffer data) {
    log.debug("testLong()");

    long val = 0;
    String test = new String(match.getTest().array());
    char comparator = match.getComparator();
    long bitmask = match.getBitmask();

    val = byteArrayToLong(data);

    // apply bitmask before the comparison
    val = val & bitmask;

    long tst = Long.decode(test).longValue();

    log.debug("testLong(): testing '" + Long.toHexString(val) + "' against '" + test + "' => '"
            + Long.toHexString(tst) + "'");

    switch (comparator) {
    case '=':
        return val == tst;

    case '!':
        return val != tst;

    case '>':
        return val > tst;

    case '<':
        return val < tst;
    }

    return false;
}

From source file:tv.ouya.sample.IapSampleActivity.java

public void requestPurchase(final Product product)
        throws GeneralSecurityException, UnsupportedEncodingException, JSONException {
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

    // This is an ID that allows you to associate a successful purchase with
    // it's original request. The server does nothing with this string except
    // pass it back to you, so it only needs to be unique within this instance
    // of your app to allow you to pair responses with requests.
    String uniqueId = Long.toHexString(sr.nextLong());

    JSONObject purchaseRequest = new JSONObject();
    purchaseRequest.put("uuid", uniqueId);
    purchaseRequest.put("identifier", product.getIdentifier());
    purchaseRequest.put("testing", "true"); // This value is only needed for testing, not setting it results in a live purchase
    String purchaseRequestJson = purchaseRequest.toString();

    byte[] keyBytes = new byte[16];
    sr.nextBytes(keyBytes);/* w w w  . j a  va  2 s  . c o m*/
    SecretKey key = new SecretKeySpec(keyBytes, "AES");

    byte[] ivBytes = new byte[16];
    sr.nextBytes(ivBytes);
    IvParameterSpec iv = new IvParameterSpec(ivBytes);

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, key, iv);
    byte[] payload = cipher.doFinal(purchaseRequestJson.getBytes("UTF-8"));

    cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, mPublicKey);
    byte[] encryptedKey = cipher.doFinal(keyBytes);

    Purchasable purchasable = new Purchasable(product.getIdentifier(),
            Base64.encodeToString(encryptedKey, Base64.NO_WRAP), Base64.encodeToString(ivBytes, Base64.NO_WRAP),
            Base64.encodeToString(payload, Base64.NO_WRAP));

    synchronized (mOutstandingPurchaseRequests) {
        mOutstandingPurchaseRequests.put(uniqueId, product);
    }
    ouyaFacade.requestPurchase(purchasable, new PurchaseListener(product));
}

From source file:com.marklogic.contentpump.RDFReader.java

private String object(RDFNode node) {
    if (node.isLiteral()) {
        Literal lit = node.asLiteral();/*  ww  w . j a va  2  s  .co  m*/
        String text = lit.getString();
        String lang = lit.getLanguage();
        String type = lit.getDatatypeURI();

        if (lang == null || "".equals(lang)) {
            lang = "";
        } else {
            lang = " xml:lang='" + escapeXml(lang) + "'";
        }

        if ("".equals(lang)) {
            if (type == null) {
                type = "http://www.w3.org/2001/XMLSchema#string";
            }
            type = " datatype='" + escapeXml(type) + "'";
        } else {
            type = "";
        }

        return "<sem:object" + type + lang + ">" + escapeXml(text) + "</sem:object>";
    } else if (node.isAnon()) {
        return "<sem:object>http://marklogic.com/semantics/blank/"
                + Long.toHexString(
                        fuse(scramble((long) node.hashCode()), fuse(scramble(milliSecs), randomValue)))
                + "</sem:object>";
    } else {
        return "<sem:object>" + escapeXml(node.toString()) + "</sem:object>";
    }
}

From source file:org.apache.hadoop.hbase.master.HMaster.java

/**
 * Initialize all ZK based system trackers.
 * @throws IOException//  w  ww .ja v a  2  s.co m
 * @throws InterruptedException
 * @throws KeeperException
 * @throws CoordinatedStateException
 */
void initializeZKBasedSystemTrackers()
        throws IOException, InterruptedException, KeeperException, CoordinatedStateException {
    this.balancer = LoadBalancerFactory.getLoadBalancer(conf);
    this.loadBalancerTracker = new LoadBalancerTracker(zooKeeper, this);
    this.loadBalancerTracker.start();
    this.assignmentManager = new AssignmentManager(this, serverManager, this.catalogTracker, this.balancer,
            this.service, this.metricsMaster, this.tableLockManager);
    zooKeeper.registerListenerFirst(assignmentManager);

    this.regionServerTracker = new RegionServerTracker(zooKeeper, this, this.serverManager);
    this.regionServerTracker.start();

    this.drainingServerTracker = new DrainingServerTracker(zooKeeper, this, this.serverManager);
    this.drainingServerTracker.start();

    // Set the cluster as up.  If new RSs, they'll be waiting on this before
    // going ahead with their startup.
    boolean wasUp = this.clusterStatusTracker.isClusterUp();
    if (!wasUp)
        this.clusterStatusTracker.setClusterUp();

    LOG.info("Server active/primary master=" + this.serverName + ", sessionid=0x"
            + Long.toHexString(this.zooKeeper.getRecoverableZooKeeper().getSessionId())
            + ", setting cluster-up flag (Was=" + wasUp + ")");

    // create/initialize the snapshot manager and other procedure managers
    this.snapshotManager = new SnapshotManager();
    this.mpmHost = new MasterProcedureManagerHost();
    this.mpmHost.register(this.snapshotManager);
    this.mpmHost.register(new MasterFlushTableProcedureManager());
    this.mpmHost.loadProcedures(conf);
    this.mpmHost.initialize(this, this.metricsMaster);
}

From source file:edu.indiana.lib.twinpeaks.search.singlesearch.web2.Web2Query.java

/**
 * Fetch the current transaction id
 * @return The ID
 */
private String getTransactionId() {
    return Long.toHexString(_transactionId);
}

From source file:org.b3log.xiaov.service.QQService.java

public void onQQGroupMessage(final GroupMessage message) {
    final long groupId = message.getGroupId();

    final String content = message.getContent();
    final String userName = Long.toHexString(message.getUserId());
    // Push to forum
    String qqMsg = content.replaceAll("\\[\"face\",[0-9]+\\]", "");
    if (StringUtils.isNotBlank(qqMsg)) {
        qqMsg = "<p>" + qqMsg + "</p>";
        sendToForum(qqMsg, userName);/*from   w  ww  . jav a 2 s.c  o  m*/
    }

    String msg = "";
    if (StringUtils.contains(content, XiaoVs.QQ_BOT_NAME)
            || (StringUtils.length(content) > 6
            && (StringUtils.contains(content, "?") || StringUtils.contains(content, "") || StringUtils.contains(content, "")))) {
        msg = answer(content, userName);
    }

    if (StringUtils.isBlank(msg)) {
        return;
    }

    if (RandomUtils.nextFloat() >= 0.9) {
        Long latestAdTime = GROUP_AD_TIME.get(groupId);
        if (null == latestAdTime) {
            latestAdTime = 0L;
        }

        final long now = System.currentTimeMillis();

        if (now - latestAdTime > 1000 * 60 * 30) {
            msg = msg + "\n\n" + ADS.get(RandomUtils.nextInt(ADS.size())) + "";

            GROUP_AD_TIME.put(groupId, now);
        }
    }

    sendMessageToGroup(groupId, msg);
}

From source file:org.jspresso.hrsample.backend.JspressoUnitOfWorkTest.java

/**
 * Tests in TX collection element update with // optimistic locking.
 *///from w w  w  . j  a va2  s . co m
@Test
public void testInTXCollectionElementUpdate() {
    final HibernateBackendController hbc = (HibernateBackendController) getBackendController();

    final AtomicInteger countDown = new AtomicInteger(10);
    ExecutorService es = Executors.newFixedThreadPool(countDown.get());
    List<Future<Set<String>>> futures = new ArrayList<Future<Set<String>>>();
    for (int t = countDown.intValue(); t > 0; t--) {
        futures.add(es.submit(new Callable<Set<String>>() {

            @Override
            public Set<String> call() throws Exception {
                final HibernateBackendController threadHbc = getApplicationContext()
                        .getBean("applicationBackController", HibernateBackendController.class);
                final TransactionTemplate threadTT = threadHbc.getTransactionTemplate();
                threadHbc.start(hbc.getLocale(), hbc.getClientTimeZone());
                threadHbc.setApplicationSession(hbc.getApplicationSession());
                BackendControllerHolder.setThreadBackendController(threadHbc);
                return threadTT.execute(new TransactionCallback<Set<String>>() {

                    /**
                     * {@inheritDoc}
                     */
                    @Override
                    public Set<String> doInTransaction(TransactionStatus status) {
                        DetachedCriteria compCrit = DetachedCriteria.forClass(Company.class);
                        Set<String> names = new HashSet<String>();
                        Company c = (Company) compCrit.getExecutableCriteria(threadHbc.getHibernateSession())
                                .list().iterator().next();

                        synchronized (countDown) {
                            countDown.decrementAndGet();
                            // wait for all threads to arrive here so that we are sure they
                            // have all read the same data.
                            try {
                                countDown.wait();
                            } catch (InterruptedException ex) {
                                throw new BackendException("Test has been interrupted");
                            }
                        }

                        if (c.getName().startsWith("TX_")) {
                            throw new BackendException("Wrong data read from DB");
                        }
                        c.setName("TX_" + Long.toHexString(System.currentTimeMillis()));
                        names.add(c.getName());
                        for (Department d : c.getDepartments()) {
                            d.setName(Long.toHexString(System.currentTimeMillis()));
                            names.add(d.getName());
                        }
                        return names;
                    }
                });
            }
        }));
    }
    while (countDown.get() > 0) {
        try {
            Thread.sleep(200);
        } catch (InterruptedException ex) {
            throw new BackendException("Test has been interrupted");
        }
    }
    synchronized (countDown) {
        countDown.notifyAll();
    }
    int successfullTxCount = 0;
    Set<String> names = new HashSet<String>();
    for (Future<Set<String>> f : futures) {
        try {
            names = f.get();
            successfullTxCount++;
        } catch (Exception ex) {
            if (ex.getCause() instanceof OptimisticLockingFailureException) {
                // safely ignore since this is what we are testing.
            } else {
                throw new BackendException(ex);
            }
        }
    }
    es.shutdown();
    assertTrue("Only 1 TX succeeded", successfullTxCount == 1);

    DetachedCriteria compCrit = DetachedCriteria.forClass(Company.class);
    Company c = hbc.findFirstByCriteria(compCrit, EMergeMode.MERGE_LAZY, Company.class);
    assertTrue("the company name is the one of the successfull TX", names.contains(c.getName()));
    for (Department d : c.getDepartments()) {
        assertTrue("the department name is the one of the successfull TX", names.contains(d.getName()));
    }
}

From source file:edu.oregonstate.eecs.mcplan.domains.tetris.TetrisState.java

@Override
public String toString() {
    final StringBuilder sb = new StringBuilder();
    sb.append("[t: ").append(t).append(", r: ").append(r).append(", next: ").append(queued_tetro.type)
            .append("/").append(queued_tetro.rotation).append(", cells: [");
    final long[] bits = cells.toLongArray();
    for (int i = 0; i < bits.length; ++i) {
        if (i > 0) {
            sb.append(",");
        }//from   w  ww .  ja  v a 2  s.c  o  m
        sb.append(Long.toHexString(bits[i]));
    }
    sb.append("]").append("]");

    //      sb.append( "\n" ).append( new TetrisBertsekasRepresenter( params ).encode( this ) );

    //      sb.append( "\n" ).append( frozen );

    //      sb.append( "\n" );
    //      for( int y = params.Nrows - 1; y >= 0; --y ) {
    //         for( int x = 0; x < params.Ncolumns; ++x ) {
    ////            sb.append( cells[y][x] );
    ////            sb.append( cells.get( y ).get( x ) ? "X" : "." );
    //            sb.append( cell( y, x ) ? "X" : "." );
    //         }
    //         sb.append( "\n" );
    //      }

    return sb.toString();
}