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:password.pwm.http.servlet.resource.ResourceServletService.java

private String makeResourcePathNonce() throws PwmUnrecoverableException, IOException {
    final boolean enablePathNonce = Boolean.parseBoolean(
            pwmApplication.getConfig().readAppProperty(AppProperty.HTTP_RESOURCES_ENABLE_PATH_NONCE));
    if (!enablePathNonce) {
        return "";
    }//from  w w w .  j a v  a 2  s .  co m

    final Instant startTime = Instant.now();
    final ChecksumOutputStream checksumOs = new ChecksumOutputStream(PwmHashAlgorithm.MD5,
            new NullOutputStream());

    if (pwmApplication.getPwmEnvironment().getContextManager() != null) {
        try {
            final File webInfPath = pwmApplication.getPwmEnvironment().getContextManager()
                    .locateWebInfFilePath();
            if (webInfPath != null && webInfPath.exists()) {
                final File basePath = webInfPath.getParentFile();
                if (basePath != null && basePath.exists()) {
                    final File resourcePath = new File(basePath.getAbsolutePath() + File.separator + "public"
                            + File.separator + "resources");
                    if (resourcePath.exists()) {
                        final List<FileSystemUtility.FileSummaryInformation> fileSummaryInformations = new ArrayList<>();
                        fileSummaryInformations.addAll(FileSystemUtility.readFileInformation(resourcePath));
                        for (final FileSystemUtility.FileSummaryInformation fileSummaryInformation : fileSummaryInformations) {
                            checksumOs.write((fileSummaryInformation.getSha1sum())
                                    .getBytes(PwmConstants.DEFAULT_CHARSET));
                        }
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("unable to generate resource path nonce: " + e.getMessage());
        }
    }

    for (final FileResource fileResource : getResourceServletConfiguration().getCustomFileBundle().values()) {
        JavaHelper.copyWhilePredicate(fileResource.getInputStream(), checksumOs, o -> true);
    }

    if (getResourceServletConfiguration().getZipResources() != null) {
        for (final String key : getResourceServletConfiguration().getZipResources().keySet()) {
            final ZipFile value = getResourceServletConfiguration().getZipResources().get(key);
            checksumOs.write(key.getBytes(PwmConstants.DEFAULT_CHARSET));
            for (Enumeration<? extends ZipEntry> zipEnum = value.entries(); zipEnum.hasMoreElements();) {
                final ZipEntry entry = zipEnum.nextElement();
                checksumOs.write(Long.toHexString(entry.getSize()).getBytes(PwmConstants.DEFAULT_CHARSET));
            }
        }
    }

    final String nonce = JavaHelper.byteArrayToHexString(checksumOs.getInProgressChecksum()).toLowerCase();
    LOGGER.debug("completed generation of nonce '" + nonce + "' in "
            + TimeDuration.fromCurrent(startTime).asCompactString());

    final String noncePrefix = pwmApplication.getConfig()
            .readAppProperty(AppProperty.HTTP_RESOURCES_NONCE_PATH_PREFIX);
    return "/" + noncePrefix + nonce;
}

From source file:org.anarres.lzo.LzopInputStream.java

/**
 * Read and verify an lzo header, setting relevant block checksum options
 * and ignoring most everything else./*from w  w  w .j a v  a2s . c  o  m*/
 */
protected int readHeader() throws IOException {
    byte[] buf = new byte[9];
    readBytes(buf, 0, 9);
    if (!Arrays.equals(buf, LzopConstants.LZOP_MAGIC))
        throw new IOException("Invalid LZO header");
    Arrays.fill(buf, (byte) 0);
    Adler32 adler = new Adler32();
    CRC32 crc32 = new CRC32();
    int hitem = readHeaderItem(buf, 2, adler, crc32); // lzop version
    if (hitem > LzopConstants.LZOP_VERSION) {
        LOG.debug("Compressed with later version of lzop: " + Integer.toHexString(hitem) + " (expected 0x"
                + Integer.toHexString(LzopConstants.LZOP_VERSION) + ")");
    }
    hitem = readHeaderItem(buf, 2, adler, crc32); // lzo library version
    if (hitem > LzoVersion.LZO_LIBRARY_VERSION) {
        throw new IOException("Compressed with incompatible lzo version: 0x" + Integer.toHexString(hitem)
                + " (expected 0x" + Integer.toHexString(LzoVersion.LZO_LIBRARY_VERSION) + ")");
    }
    hitem = readHeaderItem(buf, 2, adler, crc32); // lzop extract version
    if (hitem > LzopConstants.LZOP_VERSION) {
        throw new IOException("Compressed with incompatible lzop version: 0x" + Integer.toHexString(hitem)
                + " (expected 0x" + Integer.toHexString(LzopConstants.LZOP_VERSION) + ")");
    }
    hitem = readHeaderItem(buf, 1, adler, crc32); // method
    switch (hitem) {
    case LzopConstants.M_LZO1X_1:
    case LzopConstants.M_LZO1X_1_15:
    case LzopConstants.M_LZO1X_999:
        break;
    default:
        throw new IOException("Invalid strategy " + Integer.toHexString(hitem));
    }
    readHeaderItem(buf, 1, adler, crc32); // ignore level

    // flags
    int flags = readHeaderItem(buf, 4, adler, crc32);
    boolean useCRC32 = (flags & LzopConstants.F_H_CRC32) != 0;
    boolean extraField = (flags & LzopConstants.F_H_EXTRA_FIELD) != 0;
    if ((flags & LzopConstants.F_MULTIPART) != 0)
        throw new IOException("Multipart lzop not supported");
    if ((flags & LzopConstants.F_H_FILTER) != 0)
        throw new IOException("lzop filter not supported");
    if ((flags & LzopConstants.F_RESERVED) != 0)
        throw new IOException("Unknown flags in header");
    // known !F_H_FILTER, so no optional block

    readHeaderItem(buf, 4, adler, crc32); // ignore mode
    readHeaderItem(buf, 4, adler, crc32); // ignore mtime
    readHeaderItem(buf, 4, adler, crc32); // ignore gmtdiff
    hitem = readHeaderItem(buf, 1, adler, crc32); // fn len
    if (hitem > 0) {
        byte[] tmp = (hitem > buf.length) ? new byte[hitem] : buf;
        readHeaderItem(tmp, hitem, adler, crc32); // skip filename
    }
    int checksum = (int) (useCRC32 ? crc32.getValue() : adler.getValue());
    hitem = readHeaderItem(buf, 4, adler, crc32); // read checksum
    if (hitem != checksum) {
        throw new IOException("Invalid header checksum: " + Long.toHexString(checksum) + " (expected 0x"
                + Integer.toHexString(hitem) + ")");
    }
    if (extraField) { // lzop 1.08 ultimately ignores this
        LOG.debug("Extra header field not processed");
        adler.reset();
        crc32.reset();
        hitem = readHeaderItem(buf, 4, adler, crc32);
        readHeaderItem(new byte[hitem], hitem, adler, crc32);
        checksum = (int) (useCRC32 ? crc32.getValue() : adler.getValue());
        if (checksum != readHeaderItem(buf, 4, adler, crc32)) {
            throw new IOException("Invalid checksum for extra header field");
        }
    }

    return flags;
}

From source file:com.hadoop.compression.lzo.LzopInputStream.java

/**
 * Read and verify an lzo header, setting relevant block checksum options
 * and ignoring most everything else.// w w w.  ja v  a2s . c om
 * @param in InputStream
 * @throws IOException if there is a error in lzo header
 */
protected void readHeader(InputStream in) throws IOException {
    readFully(in, buf, 0, 9);
    if (!Arrays.equals(buf, LzopCodec.LZO_MAGIC)) {
        throw new IOException("Invalid LZO header");
    }
    Arrays.fill(buf, (byte) 0);
    Adler32 adler = new Adler32();
    CRC32 crc32 = new CRC32();
    int hitem = readHeaderItem(in, buf, 2, adler, crc32); // lzop version
    if (hitem > LzopCodec.LZOP_VERSION) {
        LOG.debug("Compressed with later version of lzop: " + Integer.toHexString(hitem) + " (expected 0x"
                + Integer.toHexString(LzopCodec.LZOP_VERSION) + ")");
    }
    hitem = readHeaderItem(in, buf, 2, adler, crc32); // lzo library version
    if (hitem < LzoDecompressor.MINIMUM_LZO_VERSION) {
        throw new IOException("Compressed with incompatible lzo version: 0x" + Integer.toHexString(hitem)
                + " (expected at least 0x" + Integer.toHexString(LzoDecompressor.MINIMUM_LZO_VERSION) + ")");
    }
    hitem = readHeaderItem(in, buf, 2, adler, crc32); // lzop extract version
    if (hitem > LzopCodec.LZOP_VERSION) {
        throw new IOException("Compressed with incompatible lzop version: 0x" + Integer.toHexString(hitem)
                + " (expected 0x" + Integer.toHexString(LzopCodec.LZOP_VERSION) + ")");
    }
    hitem = readHeaderItem(in, buf, 1, adler, crc32); // method
    if (hitem < 1 || hitem > 3) {
        throw new IOException("Invalid strategy: " + Integer.toHexString(hitem));
    }
    readHeaderItem(in, buf, 1, adler, crc32); // ignore level

    // flags
    hitem = readHeaderItem(in, buf, 4, adler, crc32);
    try {
        for (DChecksum f : dflags) {
            if (0 == (f.getHeaderMask() & hitem)) {
                dflags.remove(f);
            } else {
                dcheck.put(f, (int) f.getChecksumClass().newInstance().getValue());
            }
        }
        for (CChecksum f : cflags) {
            if (0 == (f.getHeaderMask() & hitem)) {
                cflags.remove(f);
            } else {
                ccheck.put(f, (int) f.getChecksumClass().newInstance().getValue());
            }
        }
    } catch (InstantiationException e) {
        throw new RuntimeException("Internal error", e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException("Internal error", e);
    }
    ((LzopDecompressor) decompressor).initHeaderFlags(dflags, cflags);
    boolean useCRC32 = 0 != (hitem & 0x00001000); // F_H_CRC32
    boolean extraField = 0 != (hitem & 0x00000040); // F_H_EXTRA_FIELD
    if (0 != (hitem & 0x400)) { // F_MULTIPART
        throw new IOException("Multipart lzop not supported");
    }
    if (0 != (hitem & 0x800)) { // F_H_FILTER
        throw new IOException("lzop filter not supported");
    }
    if (0 != (hitem & 0x000FC000)) { // F_RESERVED
        throw new IOException("Unknown flags in header");
    }
    // known !F_H_FILTER, so no optional block

    readHeaderItem(in, buf, 4, adler, crc32); // ignore mode
    readHeaderItem(in, buf, 4, adler, crc32); // ignore mtime
    readHeaderItem(in, buf, 4, adler, crc32); // ignore gmtdiff
    hitem = readHeaderItem(in, buf, 1, adler, crc32); // fn len
    if (hitem > 0) {
        // skip filename
        int filenameLen = Math.max(4, hitem); // buffer must be at least 4 bytes for readHeaderItem to work.
        readHeaderItem(in, new byte[filenameLen], hitem, adler, crc32);
    }
    int checksum = (int) (useCRC32 ? crc32.getValue() : adler.getValue());
    hitem = readHeaderItem(in, buf, 4, adler, crc32); // read checksum
    if (hitem != checksum) {
        throw new IOException("Invalid header checksum: " + Long.toHexString(checksum) + " (expected 0x"
                + Integer.toHexString(hitem) + ")");
    }
    if (extraField) { // lzop 1.08 ultimately ignores this
        LOG.debug("Extra header field not processed");
        adler.reset();
        crc32.reset();
        hitem = readHeaderItem(in, buf, 4, adler, crc32);
        readHeaderItem(in, new byte[hitem], hitem, adler, crc32);
        checksum = (int) (useCRC32 ? crc32.getValue() : adler.getValue());
        if (checksum != readHeaderItem(in, buf, 4, adler, crc32)) {
            throw new IOException("Invalid checksum for extra header field");
        }
    }
}

From source file:org.tat.api.WebAppOptimizerMojo.java

private String getCheckSum(File file) throws IOException {
    Long checksum = FileUtils.checksumCRC32(file);
    return Long.toHexString(checksum) + "." + FilenameUtils.getExtension(file.getName());
}

From source file:com.example.jumpnote.web.server.JumpNoteServlet.java

public void enqueueDeviceMessage(PersistenceManager pm, UserInfo userInfo, String clientDeviceId) {

    Query query = pm.newQuery(DeviceRegistration.class);
    query.setFilter("ownerKey == ownerKeyParam");
    query.declareParameters(Key.class.getName() + " ownerKeyParam");
    @SuppressWarnings("unchecked")
    List<DeviceRegistration> registrations = (List<DeviceRegistration>) query.execute(userInfo.getKey());

    int numDeviceMessages = 0;
    for (DeviceRegistration registration : registrations) {
        if (registration.getDeviceId().equals(clientDeviceId) || registration.getRegistrationToken() == null)
            continue;
        if (DEVICE_TYPE_ANDROID.equals(registration.getDeviceType())) {
            ++numDeviceMessages;/*from  ww w  .j av a  2  s. c  om*/
            String email = userInfo.getEmail();

            String collapseKey = Long.toHexString(email.hashCode());

            try {
                C2DMessaging.get(getServletContext()).sendWithRetry(registration.getRegistrationToken(),
                        collapseKey, AllConfig.C2DM_MESSAGE_EXTRA, AllConfig.C2DM_MESSAGE_SYNC,
                        AllConfig.C2DM_ACCOUNT_EXTRA, email);
            } catch (IOException ex) {
                log.severe("Can't send C2DM message, next manual sync " + "will get the changes.");
            }
        }
    }

    log.info("Scheduled " + numDeviceMessages + " C2DM device messages for user " + userInfo.getEmail() + ".");
}

From source file:org.apache.marmotta.kiwi.sparql.builder.eval.ValueExpressionEvaluator.java

@Override
public void meet(BNodeGenerator gen) throws RuntimeException {
    if (gen.getNodeIdExpr() != null) {
        // get value of argument and express it as string
        optypes.push(ValueType.STRING);/*from   w w w .j a  va2  s  .  com*/
        gen.getNodeIdExpr().visit(this);
        optypes.pop();
    } else {
        builder.append("'").append(Long.toHexString(System.currentTimeMillis())
                + Integer.toHexString(anonIdGenerator.nextInt(1000))).append("'");
    }
}

From source file:org.dcm4che3.tool.dcmdict.DcmDict.java

private static void buildMatches(DcmDict main) {
    for (Iterator<String> iter = main.queryKeys.iterator(); iter.hasNext();) {
        String key = iter.next();

        if (isTag(key)) {
            key = key.replaceFirst("^0+(?!$)", "");
            int tagInDecimal = Integer.parseInt(key, 16);
            String keyWord = main.dict.keywordOf(tagInDecimal);
            String vr;/*from   w  ww.j  a  v  a  2  s  . c o  m*/
            String name;
            if (!keyWord.isEmpty()) {
                vr = main.dict.vrOf(tagInDecimal).toString();
                name = getName(keyWord);
                iter.remove();
                main.matches.add(name + "\t" + keyWord + "\t" + adjustHex(key) + "\t" + vr);
            }

        } else if (isUID(key)) {
            String name;
            try {
                name = UID.nameOf(key);
                if (!name.equalsIgnoreCase("?")) {
                    iter.remove();
                    main.matches.add(name + "\t" + name.replaceAll("\\s+", "") + "\t" + key + "\t" + "-");
                }
            } catch (IllegalArgumentException e) {
                //
            }
        } else {
            if (key.matches("[A-Z]+")) {
                if (main.camelCaseMap.get(key) != null && main.camelCaseMap.get(key).size() == 1)
                    key = main.camelCaseMap.get(key).get(0);
            }
            int tag = main.dict.tagForKeyword(key);
            String vr;
            String name;
            if (tag == -1) {
                try {
                    String uidStr = UID.forName(key);
                    name = UID.nameOf(uidStr);
                    iter.remove();
                    main.matches.add(name + "\t" + key + "\t" + uidStr + "\t" + "-");
                } catch (IllegalArgumentException e) {
                    //
                }
            } else {
                String hex = Long.toHexString(tag);
                String tagStr = adjustHex(hex);
                vr = main.dict.vrOf(tag).toString();
                name = getName(key);
                iter.remove();
                main.matches.add(name + "\t" + key + "\t" + tagStr + "\t" + vr);
            }

        }
    }
}

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

@Test
public void testChangeComment() throws Exception {
    // C1: create the ticket
    Change c1 = newChange("testChangeComment() " + Long.toHexString(System.currentTimeMillis()));
    TicketModel ticket = service.createTicket(getRepository(), c1);
    assertTrue(ticket.number > 0);//from ww  w .  ja  v  a  2  s  . co m
    assertTrue(ticket.changes.get(0).hasComment());

    ticket = service.updateComment(ticket, c1.comment.id, "E1", "I changed the comment");
    assertNotNull(ticket);
    assertTrue(ticket.changes.get(0).hasComment());
    assertEquals("I changed the comment", ticket.changes.get(0).comment.text);

    assertTrue(service.deleteTicket(getRepository(), ticket.number, "D"));
}

From source file:org.codenergic.theskeleton.user.impl.UserServiceImpl.java

@Override
@Transactional//from   w w  w.j a v  a 2  s . c  om
public UserEntity updateUserPicture(String username, InputStream image, String contentType) throws Exception {
    UserEntity user = findUserByUsername(username).orElseThrow(() -> new UsernameNotFoundException(username));
    String imageObjectName = StringUtils.join(user.getId(), "/", Long.toHexString(Instant.now().toEpochMilli()),
            "-", UUID.randomUUID().toString());
    minioClient.putObject(PICTURE_BUCKET_NAME, imageObjectName, image, contentType);
    user.setPictureUrl(minioClient.getObjectUrl(PICTURE_BUCKET_NAME, imageObjectName));
    return user;
}

From source file:org.dspace.identifier.DOIIdentifierProviderTest.java

/**
 * Create a DOI to an item./*from w w w .  j av a 2 s .c o  m*/
 * @param item Item the DOI should be created for.
 * @param status The status of the DOI.
 * @param metadata Whether the DOI should be included in the metadata of the item.
 * @param doi The doi or null if we should generate one.
 * @return the DOI
 * @throws SQLException if database error
 */
public String createDOI(Item item, Integer status, boolean metadata, String doi)
        throws SQLException, IdentifierException, AuthorizeException {
    context.turnOffAuthorisationSystem();
    // we need some random data. UUIDs would be bloated here
    Random random = new Random();
    if (null == doi) {
        doi = DOI.SCHEME + PREFIX + "/" + NAMESPACE_SEPARATOR + Long.toHexString(new Date().getTime()) + "-"
                + random.nextInt(997);
    }

    DOI doiRow = doiService.create(context);
    doiRow.setDoi(doi.substring(DOI.SCHEME.length()));
    doiRow.setDSpaceObject(item);
    doiRow.setStatus(status);
    doiService.update(context, doiRow);

    if (metadata) {
        itemService.addMetadata(context, item, DOIIdentifierProvider.MD_SCHEMA,
                DOIIdentifierProvider.DOI_ELEMENT, DOIIdentifierProvider.DOI_QUALIFIER, null,
                doiService.DOIToExternalForm(doi));
        itemService.update(context, item);
    }

    //we need to commit the changes so we don't block the table for testing
    context.restoreAuthSystemState();
    return doi;
}