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.magnet.mmx.server.plugin.mmxmgmt.db.MessageDAOImplTest.java

@Test
public void testInsert1() {
    MessageEntity me = new MessageEntity();
    me.setMessageId(Long.toHexString(System.nanoTime()));
    me.setState(MessageEntity.MessageState.PENDING);
    //public JID(java.lang.String node, java.lang.String domain, java.lang.String resource)
    String appkey = "PrivateApp1";
    String targetDeviceId = "device2";
    JID from = new JID("login3" + JIDUtil.APP_ID_DELIMITER + appkey, "localhost", "device1");
    JID to = new JID("otheruser" + JIDUtil.APP_ID_DELIMITER + appkey, "localhost", targetDeviceId);

    me.setAppId(appkey);/*from w ww  . j  a  va  2 s.  co  m*/
    me.setTo(to.toString());
    me.setFrom(from.toString());
    me.setDeviceId(targetDeviceId);
    me.setState(MessageEntity.MessageState.DELIVERY_ATTEMPTED);
    MessageDAO dao = new MessageDAOImpl(new BasicDataSourceConnectionProvider(ds));

    dao.persist(me);

    assertTrue(true);
}

From source file:com.gitblit.tests.TicketServiceTest.java

@Test
public void testLifecycle() throws Exception {
    // query non-existent ticket
    TicketModel nonExistent = service.getTicket(getRepository(), 0);
    assertNull(nonExistent);//from ww  w . jav a2  s. c o  m

    // create and insert a ticket
    Change c1 = newChange("testCreation() " + Long.toHexString(System.currentTimeMillis()));
    TicketModel ticket = service.createTicket(getRepository(), c1);
    assertTrue(ticket.number > 0);

    // retrieve ticket and compare
    TicketModel constructed = service.getTicket(getRepository(), ticket.number);
    compare(ticket, constructed);

    assertEquals(1, constructed.changes.size());

    // C1: create the ticket
    int changeCount = 0;
    c1 = newChange("testUpdates() " + Long.toHexString(System.currentTimeMillis()));
    ticket = service.createTicket(getRepository(), c1);
    assertTrue(ticket.number > 0);
    changeCount++;

    constructed = service.getTicket(getRepository(), ticket.number);
    compare(ticket, constructed);
    assertEquals(1, constructed.changes.size());

    // C2: set owner
    Change c2 = new Change("C2");
    c2.comment("I'll fix this");
    c2.setField(Field.responsible, c2.author);
    constructed = service.updateTicket(getRepository(), ticket.number, c2);
    assertNotNull(constructed);
    assertEquals(2, constructed.changes.size());
    assertEquals(c2.author, constructed.responsible);
    changeCount++;

    // C3: add a note
    Change c3 = new Change("C3");
    c3.comment("yeah, this is working");
    constructed = service.updateTicket(getRepository(), ticket.number, c3);
    assertNotNull(constructed);
    assertEquals(3, constructed.changes.size());
    changeCount++;

    if (service.supportsAttachments()) {
        // C4: add attachment
        Change c4 = new Change("C4");
        Attachment a = newAttachment();
        c4.addAttachment(a);
        constructed = service.updateTicket(getRepository(), ticket.number, c4);
        assertNotNull(constructed);
        assertTrue(constructed.hasAttachments());
        Attachment a1 = service.getAttachment(getRepository(), ticket.number, a.name);
        assertEquals(a.content.length, a1.content.length);
        assertTrue(Arrays.areEqual(a.content, a1.content));
        changeCount++;
    }

    // C5: close the issue
    Change c5 = new Change("C5");
    c5.comment("closing issue");
    c5.setField(Field.status, Status.Resolved);
    constructed = service.updateTicket(getRepository(), ticket.number, c5);
    assertNotNull(constructed);
    changeCount++;
    assertTrue(constructed.isClosed());
    assertEquals(changeCount, constructed.changes.size());

    List<TicketModel> allTickets = service.getTickets(getRepository());
    List<TicketModel> openTickets = service.getTickets(getRepository(), new TicketFilter() {
        @Override
        public boolean accept(TicketModel ticket) {
            return ticket.isOpen();
        }
    });
    List<TicketModel> closedTickets = service.getTickets(getRepository(), new TicketFilter() {
        @Override
        public boolean accept(TicketModel ticket) {
            return ticket.isClosed();
        }
    });
    assertTrue(allTickets.size() > 0);
    assertEquals(1, openTickets.size());
    assertEquals(1, closedTickets.size());

    // build a new Lucene index
    service.reindex(getRepository());
    List<QueryResult> hits = service.searchFor(getRepository(), "working", 1, 10);
    assertEquals(1, hits.size());

    // reindex a ticket
    ticket = allTickets.get(0);
    Change change = new Change("reindex");
    change.comment("this is a test of reindexing a ticket");
    service.updateTicket(getRepository(), ticket.number, change);
    ticket = service.getTicket(getRepository(), ticket.number);

    hits = service.searchFor(getRepository(), "reindexing", 1, 10);
    assertEquals(1, hits.size());

    service.stop();
    service = getService(false);

    // Lucene field query
    List<QueryResult> results = service.queryFor(Lucene.status.matches(Status.New.name()), 1, 10,
            Lucene.created.name(), true);
    assertEquals(1, results.size());
    assertTrue(results.get(0).title.startsWith("testCreation"));

    // Lucene field query
    results = service.queryFor(Lucene.status.matches(Status.Resolved.name()), 1, 10, Lucene.created.name(),
            true);
    assertEquals(1, results.size());
    assertTrue(results.get(0).title.startsWith("testUpdates"));

    // check the ids
    assertEquals("[1, 2]", service.getIds(getRepository()).toString());

    // delete all tickets
    for (TicketModel aTicket : allTickets) {
        assertTrue(service.deleteTicket(getRepository(), aTicket.number, "D"));
    }
}

From source file:org.apache.accumulo.master.tableOps.Utils.java

public static long reserveTable(String tableId, long tid, boolean writeLock, boolean tableMustExist,
        TableOperation op) throws Exception {
    if (getLock(tableId, tid, writeLock).tryLock()) {
        if (tableMustExist) {
            Instance instance = HdfsZooInstance.getInstance();
            IZooReaderWriter zk = ZooReaderWriter.getRetryingInstance();
            if (!zk.exists(ZooUtil.getRoot(instance) + Constants.ZTABLES + "/" + tableId))
                throw new ThriftTableOperationException(tableId, "", op, TableOperationExceptionType.NOTFOUND,
                        "Table does not exist");
        }//from w  ww.  ja v a  2 s.  com
        log.info("table " + tableId + " (" + Long.toHexString(tid) + ") locked for "
                + (writeLock ? "write" : "read") + " operation: " + op);
        return 0;
    } else
        return 100;
}

From source file:edu.umd.cs.marmoset.utilities.MarmosetUtilities.java

public static String toFullLengthHexString(long x) {
    return leftZeroPad(Long.toHexString(x));
}

From source file:ly.count.android.api.ConnectionProcessor.java

URLConnection urlConnectionForEventData(final String eventData) throws IOException {
    final String urlStr = serverURL_ + "/i?" + eventData;
    final URL url = new URL(urlStr);
    final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(CONNECT_TIMEOUT_IN_MILLISECONDS);
    conn.setReadTimeout(READ_TIMEOUT_IN_MILLISECONDS);
    conn.setUseCaches(false);/*from   w  w  w.j a  va2 s.  c  om*/
    conn.setDoInput(true);
    String picturePath = UserData.getPicturePathFromQuery(url);
    if (Countly.sharedInstance().isLoggingEnabled()) {
        Log.d(Countly.TAG, "Got picturePath: " + picturePath);
    }
    if (!picturePath.equals("")) {
        //Uploading files:
        //http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests

        File binaryFile = new File(picturePath);
        conn.setDoOutput(true);
        // Just generate some unique random value.
        String boundary = Long.toHexString(System.currentTimeMillis());
        // Line separator required by multipart/form-data.
        String CRLF = "\r\n";
        String charset = "UTF-8";
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        OutputStream output = conn.getOutputStream();
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
        // Send binary file.
        writer.append("--" + boundary).append(CRLF);
        writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName()
                + "\"").append(CRLF);
        writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName()))
                .append(CRLF);
        writer.append("Content-Transfer-Encoding: binary").append(CRLF);
        writer.append(CRLF).flush();
        FileInputStream fileInputStream = new FileInputStream(binaryFile);
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fileInputStream.read(buffer)) != -1) {
            output.write(buffer, 0, len);
        }
        output.flush(); // Important before continuing with writer!
        writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
        fileInputStream.close();

        // End of multipart/form-data.
        writer.append("--" + boundary + "--").append(CRLF).flush();
    } else {
        conn.setDoOutput(false);
    }
    return conn;
}

From source file:org.apache.hadoop.hdfs.server.blockmanagement.TestBlockReportRateLimiting.java

@Test(timeout = 180000)
public void testRateLimitingDuringDataNodeStartup() throws Exception {
    Configuration conf = new Configuration();
    conf.setInt(DFS_NAMENODE_MAX_FULL_BLOCK_REPORT_LEASES, 1);
    conf.setLong(DFS_NAMENODE_FULL_BLOCK_REPORT_LEASE_LENGTH_MS, 20L * 60L * 1000L);

    final Semaphore fbrSem = new Semaphore(0);
    final HashSet<DatanodeID> expectedFbrDns = new HashSet<>();
    final HashSet<DatanodeID> fbrDns = new HashSet<>();
    final AtomicReference<String> failure = new AtomicReference<String>("");

    final BlockManagerFaultInjector injector = new BlockManagerFaultInjector() {
        private int numLeases = 0;

        @Override/*from ww  w.  j av a  2 s .  c  o m*/
        public void incomingBlockReportRpc(DatanodeID nodeID, BlockReportContext context) throws IOException {
            LOG.info("Incoming full block report from " + nodeID + ".  Lease ID = 0x"
                    + Long.toHexString(context.getLeaseId()));
            if (context.getLeaseId() == 0) {
                setFailure(failure,
                        "Got unexpected rate-limiting-" + "bypassing full block report RPC from " + nodeID);
            }
            fbrSem.acquireUninterruptibly();
            synchronized (this) {
                fbrDns.add(nodeID);
                if (!expectedFbrDns.remove(nodeID)) {
                    setFailure(failure, "Got unexpected full block report " + "RPC from " + nodeID
                            + ".  expectedFbrDns = " + Joiner.on(", ").join(expectedFbrDns));
                }
                LOG.info("Proceeding with full block report from " + nodeID + ".  Lease ID = 0x"
                        + Long.toHexString(context.getLeaseId()));
            }
        }

        @Override
        public void requestBlockReportLease(DatanodeDescriptor node, long leaseId) {
            if (leaseId == 0) {
                return;
            }
            synchronized (this) {
                numLeases++;
                expectedFbrDns.add(node);
                LOG.info("requestBlockReportLease(node=" + node + ", leaseId=0x" + Long.toHexString(leaseId)
                        + ").  " + "expectedFbrDns = " + Joiner.on(", ").join(expectedFbrDns));
                if (numLeases > 1) {
                    setFailure(failure, "More than 1 lease was issued at once.");
                }
            }
        }

        @Override
        public void removeBlockReportLease(DatanodeDescriptor node, long leaseId) {
            LOG.info("removeBlockReportLease(node=" + node + ", leaseId=0x" + Long.toHexString(leaseId) + ")");
            synchronized (this) {
                numLeases--;
            }
        }
    };
    BlockManagerFaultInjector.instance = injector;

    final int NUM_DATANODES = 5;
    MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(NUM_DATANODES).build();
    cluster.waitActive();
    for (int n = 1; n <= NUM_DATANODES; n++) {
        LOG.info("Waiting for " + n + " datanode(s) to report in.");
        fbrSem.release();
        Uninterruptibles.sleepUninterruptibly(20, TimeUnit.MILLISECONDS);
        final int currentN = n;
        GenericTestUtils.waitFor(new Supplier<Boolean>() {
            @Override
            public Boolean get() {
                synchronized (injector) {
                    if (fbrDns.size() > currentN) {
                        setFailure(failure,
                                "Expected at most " + currentN
                                        + " datanodes to have sent a block report, but actually "
                                        + fbrDns.size() + " have.");
                    }
                    return (fbrDns.size() >= currentN);
                }
            }
        }, 25, 50000);
    }
    cluster.shutdown();
    Assert.assertEquals("", failure.get());
}

From source file:org.spiffyui.hellospiffyauth.server.SampleAuthServer.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String authHeader = request.getHeader(AUTHORIZATION);
    response.setContentType("application/json");

    ServletOutputStream out = response.getOutputStream();
    StringBuffer buff = new StringBuffer();

    if (authHeader == null) {
        /*/*from   w  w w .j a  va 2 s  .  c  om*/
         * This means someone tried to get a token but didn't specify any credentials
         */
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        buff.append(generateFault("Sender", "NoAuthHeader", ""));
        out.println(buff.toString());
        return;
    }

    String[] fields = authHeader.trim().split(" ");
    if (fields.length != 2) {
        /*
         * This means someone specified an invalid authorization header
         */
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        buff.append(generateFault("Sender", "InvalidAuthHeader", "The authorization header '" + authHeader
                + "' is invalid.  " + "The format should be BASIC <username:password> base64 encoded."));
        out.println(buff.toString());
        return;
    }
    String cred;
    try {
        cred = new String(Base64.decodeBase64(fields[1].getBytes("UTF-8")), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException(e);
    }
    String[] creds = cred.split(":");
    if (creds.length != 2) {
        /*
         * This means someone specified an invalid authorization header
         */
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        buff.append(generateFault("Sender", "InvalidAuthHeader", "The authorization header '" + authHeader
                + "' is invalid.  " + "The format should be BASIC <username:password> base64 encoded."));
        out.println(buff.toString());
        return;
    }

    /*
     * At this point we can generate our token.  In our case we just use the username followed
     * by a random number.  The token can be any format.
     */
    String random = Long.toHexString(Double.doubleToLongBits(Math.random()));
    buff.append("{\"Token\":\"" + creds[0] + "-" + random + "\"}");

    out.println(buff.toString());
}

From source file:com.gmobi.poponews.util.HttpHelper.java

public static Response upload(String url, InputStream is) {
    Response response = new Response();
    String boundary = Long.toHexString(System.currentTimeMillis());
    HttpURLConnection connection = null;
    try {//  w w  w  . j a v a 2s.  com
        URL httpURL = new URL(url);
        connection = (HttpURLConnection) httpURL.openConnection();
        connection.setConnectTimeout(15000);
        connection.setReadTimeout(30000);
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        byte[] st = ("--" + boundary + "\r\n"
                + "Content-Disposition: form-data; name=\"file\"; filename=\"data\"\r\n"
                + "Content-Type: application/octet-stream; charset=UTF-8\r\n"
                + "Content-Transfer-Encoding: binary\r\n\r\n").getBytes();
        byte[] en = ("\r\n--" + boundary + "--\r\n").getBytes();
        connection.setRequestProperty("Content-Length", String.valueOf(st.length + en.length + is.available()));
        OutputStream os = connection.getOutputStream();
        os.write(st);
        FileHelper.copy(is, os);
        os.write(en);
        os.flush();
        os.close();
        response.setStatusCode(connection.getResponseCode());
        connection = null;
    } catch (Exception e) {
        Logger.error(e);
    }

    return response;
}

From source file:com.microsoft.tfs.core.util.notifications.MessageWindowNotificationManager.java

/**
 * Creates a {@link MessageWindowNotificationManager}. On Windows this
 * constructor creates a hidden message-only window ({@link MessageWindow})
 * to do IPC. On non-Windows platforms, the class sends or receives no
 * messages./*from   w  w  w. ja va 2 s .c o  m*/
 * <p>
 * The application must be in a state where window creation will succeed
 * when this constructor is used.
 */
public MessageWindowNotificationManager() {
    super();

    if (Platform.isCurrentPlatform(Platform.WINDOWS)) {
        this.messageWindow = new MessageWindow(0, MESSAGE_WINDOW_CLASS_NAME, MESSAGE_WINDOW_TITLE,
                NotificationWindowVersion.LATEST, new MessageListener() {
                    @Override
                    public void messageReceived(final int msg, final long wParam, final long lParam) {
                        final Notification n = Notification.fromValue(msg);
                        if (n == null) {
                            log.info(MessageFormat.format(
                                    "Ignoring unknown notification msg={0}, wParam={1}, lParam={2}", //$NON-NLS-1$
                                    Integer.toString(msg), Long.toHexString(wParam), Long.toHexString(lParam)));
                        } else {
                            fireNotificationReceived(n, wParam, lParam);
                        }
                    }
                });

        // Schedule a recurring sender task
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                sendQueuedNotifications();
            }
        }, SEND_DELAY_MS, SEND_PERIOD_MS);
    } else {
        this.messageWindow = null;
    }
}

From source file:com.yifanlu.PSXperiaTool.Extractor.CrashBandicootExtractor.java

private void processConfig() throws IOException, UnsupportedOperationException {
    long crc32 = ZpakCreate.getCRC32(mApkFile);
    String crcString = Long.toHexString(crc32).toUpperCase();
    InputStream inConfig = null;/*from   ww w. j  a  v  a2  s  . com*/
    if ((inConfig = PSXperiaTool.class
            .getResourceAsStream("/resources/patches/" + crcString + "/config.xml")) == null) {
        throw new FileNotFoundException("Cannot find config for this APK (CRC32: " + crcString + ")");
    }
    Properties config = new Properties();
    config.loadFromXML(inConfig);
    inConfig.close();
    Logger.info("Identified " + config.getProperty("game_name", "Unknown Game") + " "
            + config.getProperty("game_region") + " Version " + config.getProperty("game_version", "Unknown")
            + ", CRC32: " + config.getProperty("game_crc32", "Unknown"));
    if (config.getProperty("valid", "yes").equals("no"))
        throw new UnsupportedOperationException("This APK is not supported.");
    Logger.verbose("Copying config files.");
    FileUtils.copyInputStreamToFile(
            PSXperiaTool.class.getResourceAsStream("/resources/patches/" + crcString + "/config.xml"),
            new File(mOutputDir, "/config/config.xml"));
    FileUtils.copyInputStreamToFile(
            PSXperiaTool.class.getResourceAsStream("/resources/patches/" + crcString + "/filelist.txt"),
            new File(mOutputDir, "/config/filelist.txt"));
    FileUtils.copyInputStreamToFile(
            PSXperiaTool.class
                    .getResourceAsStream("/resources/patches/" + crcString + "/stringReplacements.txt"),
            new File(mOutputDir, "/config/stringReplacements.txt"));
    String emulatorPatch = config.getProperty("emulator_patch", "");
    String gamePatch = config.getProperty("iso_patch", "");
    if (!gamePatch.equals("")) {
        FileUtils.copyInputStreamToFile(
                PSXperiaTool.class.getResourceAsStream("/resources/patches/" + crcString + "/" + gamePatch),
                new File(mOutputDir, "/config/game-patch.bin"));
    }
    if (!emulatorPatch.equals("")) {
        FileUtils.copyInputStreamToFile(
                PSXperiaTool.class.getResourceAsStream("/resources/patches/" + crcString + "/" + emulatorPatch),
                new File(mOutputDir, "/config/" + emulatorPatch));
    }
}