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.workfront.api.StreamClient.java

private Object request(String path, Map<String, Object> params, Set<String> fields, String method,
        int retryCount, File file) throws StreamClientException {
    HttpURLConnection conn = null;
    int responseCode = -1;

    try {/*from w  w w .  ja v a2  s . c o  m*/
        String authenticationParam = "";
        if (apiKey != null) {
            authenticationParam += "apiKey=" + apiKey;
        } else if (sessionID != null) {
            authenticationParam += "sessionID=" + sessionID;
        }
        String methodParam = "method=" + method;
        String query = authenticationParam + "&" + methodParam;

        if (params != null) {
            for (String key : params.keySet()) {
                if (params.get(key) instanceof String[]) {
                    String[] paramVal = (String[]) params.get(key);
                    for (int i = 0; i < paramVal.length; i++) {
                        String val = paramVal[i];
                        query += "&" + URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(val, "UTF-8");
                    }
                } else {
                    query += "&" + URLEncoder.encode(key, "UTF-8") + "="
                            + URLEncoder.encode(String.valueOf(params.get(key)), "UTF-8");
                }
            }
        }

        if (fields != null) {
            query += "&fields=";
            for (String field : fields) {
                query += URLEncoder.encode(field, "UTF-8") + ",";
            }
            query = query.substring(0, query.lastIndexOf(","));
        }

        conn = createConnection(hostname + path, method);

        String boundary = Long.toHexString(System.currentTimeMillis());

        if (file != null) {
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            conn.setRequestProperty("User-Agent", "Workfront Java StreamClient");
        }

        // Send request
        OutputStream outputStream = conn.getOutputStream();
        Writer out = new OutputStreamWriter(outputStream);
        if (file != null) {
            addFileToRequest(boundary, out, outputStream, file);
        } else {
            out.write(query);
        }

        out.flush();
        out.close();

        // Get response code
        responseCode = conn.getResponseCode();

        // Read response
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;

        while ((line = in.readLine()) != null) {
            response.append(line);
        }

        in.close();

        // Decode JSON
        JSONObject result = new JSONObject(response.toString());

        // Verify result
        if (result.has("error")) {
            throw new StreamClientException(result.getJSONObject("error").getString("message"));
        } else if (!result.has("data")) {
            throw new StreamClientException("Invalid response from server");
        }

        // Manage the session
        if (path.equals(PATH_LOGIN)) {
            sessionID = result.getJSONObject("data").getString("sessionID");
        } else if (path.equals(PATH_LOGOUT)) {
            sessionID = null;
        }

        return result.get("data");
    } catch (ConnectException connectException) {
        throw new StreamClientException("Unable to connect to " + hostname + path);
    } catch (IOException e) {
        //getErrorStream() can return null if no error data was sent back
        if (conn.getErrorStream() != null) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();

            try {
                copyStream(conn.getErrorStream(), out);
            } catch (IOException e1) {
                // Removed printStackTrace call
            }

            throw new StreamClientException(new String(out.toByteArray()));
        } else {
            //I believe this use case happens when the we are sending to many requests at one time...
            if (retryCount < 3) {
                return request(path, params, fields, method, ++retryCount);
            } else {
                throw new StreamClientException(
                        "An error happened but no error data was sent... 3 time... Response Code = "
                                + responseCode);
            }
        }
    } catch (Exception e) {
        throw new StreamClientException(e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:org.ireland.jnetty.loader.WebAppClassLoader.java

@Override
public String toString() {
    return "WebAppClassLoader=" + _name + "@" + Long.toHexString(hashCode());
}

From source file:com.yobidrive.diskmap.buckets.BucketTableManager.java

private File getCreateFile(long indexNumber, String extension) throws BucketTableManagerException {
    File indexFile = null;/*from w w w  . j a  va 2s.  co m*/
    try {
        String fileName = Long.toHexString(indexNumber);
        while (fileName.length() < 16)
            fileName = "0" + fileName;
        fileName = fileName + extension;
        indexFile = new File(tableDir, fileName);
        if (indexFile.exists())
            indexFile.delete();
        indexFile.createNewFile();
        return indexFile;
    } catch (IOException ie) {
        throw new BucketTableManagerException(
                "Error creating bucket table file " + indexFile == null ? "null" : indexFile.getAbsolutePath());
    }
}

From source file:org.onosproject.EvacuateCommand.java

/**
 * Prints flows./*from ww  w  . j av  a  2 s .c o  m*/
 *
 * @param d     the device
 * @param flows the set of flows for that device
 * @param coreService core system service
 */
protected void printFlows(Device d, List<FlowEntry> flows, CoreService coreService) {
    boolean empty = flows == null || flows.isEmpty();
    print("deviceId=%s, flowRuleCount=%d", d.id(), empty ? 0 : flows.size());
    if (!empty) {
        for (FlowEntry f : flows) {
            ApplicationId appId = coreService.getAppId(f.appId());
            print(FMT, Long.toHexString(f.id().value()), f.state(), f.bytes(), f.packets(), f.life(),
                    f.priority(), f.tableId(), appId != null ? appId.name() : "<none>",
                    f.payLoad() == null ? null : f.payLoad().payLoad().toString());
            print(SFMT, f.selector().criteria());
            print(TFMT, f.treatment());
        }
    }
}

From source file:org.opendaylight.genius.alivenessmonitor.protocols.internal.AlivenessProtocolHandlerLLDP.java

public Ethernet makeLLDPPacket(String nodeId, long portNum, int serviceId, byte[] srcMac,
        String sourceInterface) {

    // Create LLDP TTL TLV
    LLDPTLV lldpTlvTTL = buildLLDTLV(LLDPTLV.TLVType.TTL, new byte[] { (byte) 0, (byte) 120 });

    LLDPTLV lldpTlvChassisId = buildLLDTLV(LLDPTLV.TLVType.ChassisID,
            LLDPTLV.createChassisIDTLVValue(colonize(StringUtils
                    .leftPad(Long.toHexString(MDSALUtil.getDpnIdFromNodeName(nodeId).longValue()), 16, "0"))));
    LLDPTLV lldpTlvSystemName = buildLLDTLV(TLVType.SystemName, LLDPTLV.createSystemNameTLVValue(nodeId));

    LLDPTLV lldpTlvPortId = buildLLDTLV(TLVType.PortID,
            LLDPTLV.createPortIDTLVValue(Long.toHexString(portNum)));

    String customValue = sourceInterface + "#" + getPacketId();

    LOG.debug("Sending LLDP packet, custome value " + customValue);

    LLDPTLV lldpTlvCustom = buildLLDTLV(TLVType.Custom, customValue.getBytes(LLDPTLV_CHARSET));

    @SuppressWarnings("AbbreviationAsWordInName")
    List<LLDPTLV> lstLLDPTLVCustom = new ArrayList<>();
    lstLLDPTLVCustom.add(lldpTlvCustom);

    LLDP lldpDiscoveryPacket = new LLDP();
    lldpDiscoveryPacket.setChassisId(lldpTlvChassisId).setPortId(lldpTlvPortId).setTtl(lldpTlvTTL)
            .setSystemNameId(lldpTlvSystemName).setOptionalTLVList(lstLLDPTLVCustom);

    byte[] destMac = LLDP.LLDPMulticastMac;

    Ethernet ethernetPacket = new Ethernet();
    ethernetPacket.setSourceMACAddress(srcMac).setDestinationMACAddress(destMac)
            .setEtherType(EtherTypes.LLDP.shortValue()).setPayload(lldpDiscoveryPacket);

    return ethernetPacket;
}

From source file:com.yoho.core.trace.Span.java

/**
 * Represents given long id as hex string
 */
public static String idToHex(long id) {
    return Long.toHexString(id);
}

From source file:com.serotonin.bacnet4j.util.sero.StreamUtils.java

public static String toHex(long l) {
    return StringUtils.leftPad(Long.toHexString(l), 16, '0');
}

From source file:com.ibm.og.s3.v4.AwsChunkedEncodingInputStream.java

private static long calculateSignedChunkLength(final long chunkDataSize) {
    return Long.toHexString(chunkDataSize).length() + CHUNK_SIGNATURE_HEADER.length() + SIGNATURE_LENGTH
            + CRLF.length() + chunkDataSize + CRLF.length();
}

From source file:org.apache.zookeeper.server.persistence.TxnLogToolkit.java

private void printTxn(byte[] bytes, String prefix) throws IOException {
    TxnHeader hdr = new TxnHeader();
    Record txn = SerializeUtils.deserializeTxn(bytes, hdr);
    String txnStr = getDataStrFromTxn(txn);
    String txns = String.format("%s session 0x%s cxid 0x%s zxid 0x%s %s %s",
            DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG).format(new Date(hdr.getTime())),
            Long.toHexString(hdr.getClientId()), Long.toHexString(hdr.getCxid()),
            Long.toHexString(hdr.getZxid()), TraceFormatter.op2String(hdr.getType()), txnStr);
    if (prefix != null && !"".equals(prefix.trim())) {
        System.out.print(prefix + " - ");
    }/*  w w  w .j a  va2s  .c  om*/
    if (txns.endsWith("\n")) {
        System.out.print(txns);
    } else {
        System.out.println(txns);
    }
}

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

@Test
public void testEntryLogPerLedgerCreationWithPreAllocation() throws Exception {
    /*/*  w  w  w. ja v  a 2  s  .c o  m*/
     * I wish I could shorten this testcase or split it into multiple testcases,
     * but I want to cover a scenario and it requires multiple operations in
     * sequence and validations along the way. Please bear with the length of this
     * testcase, I added as many comments as I can to simplify it.
     */

    ServerConfiguration conf = TestBKConfiguration.newServerConfiguration();

    // Creating a new configuration with a number of ledger directories.
    conf.setLedgerDirNames(ledgerDirs);
    conf.setIsForceGCAllowWhenNoSpace(true);
    // preAllocation is Enabled
    conf.setEntryLogFilePreAllocationEnabled(true);
    conf.setEntryLogPerLedgerEnabled(true);
    LedgerDirsManager ledgerDirsManager = new LedgerDirsManager(conf, conf.getLedgerDirs(),
            new DiskChecker(conf.getDiskUsageThreshold(), conf.getDiskUsageWarnThreshold()));
    EntryLogger entryLogger = new EntryLogger(conf, ledgerDirsManager);
    EntryLoggerAllocator entryLoggerAllocator = entryLogger.entryLoggerAllocator;
    EntryLogManagerForEntryLogPerLedger entryLogManager = (EntryLogManagerForEntryLogPerLedger) entryLogger
            .getEntryLogManager();
    // set same thread executor for entryLoggerAllocator's allocatorExecutor
    setSameThreadExecutorForEntryLoggerAllocator(entryLoggerAllocator);

    /*
     * no entrylog will be created during initialization
     */
    int expectedPreAllocatedLogID = -1;
    Assert.assertEquals("PreallocatedlogId after initialization of Entrylogger", expectedPreAllocatedLogID,
            entryLoggerAllocator.getPreallocatedLogId());

    int numOfLedgers = 6;

    for (long i = 0; i < numOfLedgers; i++) {
        /* since we are starting creation of new ledgers, entrylogid will be ledgerid */
        entryLogManager.createNewLog(i);
    }

    /*
     * preallocation is enabled so though entryLogId starts with 0, preallocatedLogId would be equal to numOfLedgers
     */
    expectedPreAllocatedLogID = numOfLedgers;
    Assert.assertEquals("PreallocatedlogId after creation of logs for ledgers", expectedPreAllocatedLogID,
            entryLoggerAllocator.getPreallocatedLogId());
    Assert.assertEquals("Number of current ", numOfLedgers, entryLogManager.getCopyOfCurrentLogs().size());
    Assert.assertEquals("Number of LogChannels to flush", 0, entryLogManager.getRotatedLogChannels().size());

    // create dummy entrylog file with id - (expectedPreAllocatedLogID + 1)
    String logFileName = Long.toHexString(expectedPreAllocatedLogID + 1) + ".log";
    File dir = ledgerDirsManager.pickRandomWritableDir();
    LOG.info("Picked this directory: " + dir);
    File newLogFile = new File(dir, logFileName);
    newLogFile.createNewFile();

    /*
     * since there is already preexisting entrylog file with id -
     * (expectedPreAllocatedLogIDDuringInitialization + 1), when new
     * entrylog is created it should have
     * (expectedPreAllocatedLogIDDuringInitialization + 2) id
     */
    long rotatedLedger = 1L;
    entryLogManager.createNewLog(rotatedLedger);

    expectedPreAllocatedLogID = expectedPreAllocatedLogID + 2;
    Assert.assertEquals("PreallocatedlogId ", expectedPreAllocatedLogID,
            entryLoggerAllocator.getPreallocatedLogId());
    Assert.assertEquals("Number of current ", numOfLedgers, entryLogManager.getCopyOfCurrentLogs().size());
    List<BufferedLogChannel> rotatedLogChannels = entryLogManager.getRotatedLogChannels();
    Assert.assertEquals("Number of LogChannels rotated", 1, rotatedLogChannels.size());
    Assert.assertEquals("Rotated logchannel logid", rotatedLedger,
            rotatedLogChannels.iterator().next().getLogId());
    entryLogger.flush();
    /*
     * when flush is called all the rotatedlogchannels are flushed and
     * removed from rotatedlogchannels list. But here since entrylogId - 0,
     * is not yet rotated and flushed yet, getLeastUnflushedLogId will still
     * return 0.
     */
    rotatedLogChannels = entryLogManager.getRotatedLogChannels();
    Assert.assertEquals("Number of LogChannels rotated", 0, rotatedLogChannels.size());
    Assert.assertEquals("Least UnflushedLoggerId", 0, entryLogger.getLeastUnflushedLogId());

    entryLogManager.createNewLog(0L);
    rotatedLogChannels = entryLogManager.getRotatedLogChannels();
    Assert.assertEquals("Number of LogChannels rotated", 1, rotatedLogChannels.size());
    Assert.assertEquals("Least UnflushedLoggerId", 0, entryLogger.getLeastUnflushedLogId());
    entryLogger.flush();
    /*
     * since both entrylogids 0, 1 are rotated and flushed,
     * leastunFlushedLogId should be 2
     */
    Assert.assertEquals("Least UnflushedLoggerId", 2, entryLogger.getLeastUnflushedLogId());
    expectedPreAllocatedLogID = expectedPreAllocatedLogID + 1;

    /*
     * we should be able to get entryLogMetadata from all the active
     * entrylogs and the logs which are moved toflush list. Since no entry
     * is added, all the meta should be empty.
     */
    for (int i = 0; i <= expectedPreAllocatedLogID; i++) {
        EntryLogMetadata meta = entryLogger.getEntryLogMetadata(i);
        Assert.assertTrue("EntryLogMetadata should be empty", meta.isEmpty());
        Assert.assertTrue("EntryLog usage should be 0", meta.getTotalSize() == 0);
    }
}