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.yobidrive.diskmap.buckets.BucketTableManager.java

private File getFile(long indexNumber, String extension) throws BucketTableManagerException {
    String fileName = Long.toHexString(indexNumber);
    while (fileName.length() < 16)
        fileName = "0" + fileName;
    fileName = fileName + extension;//  w w w . j av  a2s  .  c  o m
    File indexFile = new File(tableDir, fileName);
    return indexFile;
}

From source file:edu.rit.flick.genetics.FastFileDeflator.java

protected void processNucleotides() throws IOException {
    while (fastIn.available() > 0 && (dnaByte = (byte) fastIn.read()) != -1) {
        beforeProcessNucleotide();/*from  ww  w . ja  va2  s. c  o  m*/

        switch (dnaByte) {
        // Check for N
        case N:
            if (!writingToNFile) {
                writingToNFile = true;
                final String nPositionStr = Long.toHexString(dnaPosition.longValue()).toUpperCase() + RANGE;
                nfile.write(nPositionStr.getBytes());
            }
            dnaPosition.increment();
            continue;
        // Check for uppercase nucleotides
        case A:
        case C:
        case G:
        case T:
        case U:

            // Check for U
            if (dnaByte == U || dnaByte == u) {
                isRNAData = true;
                dnaByte = T;
            }

            if (writingToNFile) {
                final String nPositionStr = Long.toHexString(dnaPosition.longValue()).toUpperCase() + PIPE;
                nfile.write(nPositionStr.getBytes());
                writingToNFile = false;
            }

            processConventionalNucleotide();

            dnaPosition.increment();
            continue;
        case CARRIAGE_RETURN:
            containsCarriageReturns = true;
            continue;
        case NEWLINE:
            if (seqLineSize < localSeqLineSize)
                seqLineSize = localSeqLineSize;
            localSeqLineSize = 0;
            continue;
        default:
            if (getSequenceEscapes().contains(dnaByte))
                return;

            if (writingToNFile) {
                final String nPositionStr = Long.toHexString(dnaPosition.longValue()).toUpperCase() + PIPE;
                nfile.write(nPositionStr.getBytes());
                writingToNFile = false;
            }

            // File for IUPAC codes and erroneous characters
            final String iupacBase = format("%s-%s|", Long.toHexString(dnaPosition.longValue()),
                    (char) dnaByte + "");
            iupacfile.write(iupacBase.getBytes());
            dnaPosition.increment();
        }
    }
}

From source file:bookkeepr.managers.SyncManager.java

public void sync() {
    HttpClient httpclient = obsdb.getBookkeepr().checkoutHttpClient();

    for (BookkeeprHost host : config.getBookkeeprHostList()) {
        Logger.getLogger(SyncManager.class.getName()).log(Level.INFO,
                "Attempting to sync with " + host.getUrl());
        try {/*from   w w  w  . ja va2  s  .com*/

            HttpGet httpget = new HttpGet(host.getUrl() + "/ident/");
            HttpResponse response = httpclient.execute(httpget);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                InputStream in = response.getEntity().getContent();
                BookkeeprHost rhost = (BookkeeprHost) XMLReader.read(in);
                in.close();

                Logger.getLogger(SyncManager.class.getName()).log(Level.FINE,
                        "Managed to connect to " + host.getUrl() + "/ident/ ");
                host.setOriginId(rhost.getOriginId());

                host.setMaxOriginId(rhost.getMaxOriginId());
                host.setVersion(rhost.getVersion());
                if (host.getVersion() != obsdb.getBookkeepr().getHost().getVersion()) {
                    Logger.getLogger(SyncManager.class.getName()).log(Level.INFO, "Host " + host.getUrl()
                            + " is not of the same BookKeepr version as us! (Cannot sync)");
                    if (host.getVersion() > obsdb.getBookkeepr().getHost().getVersion()) {
                    }
                    Logger.getLogger(SyncManager.class.getName()).log(Level.INFO,
                            "There are newer versions of the BookKeepr on the network. Please update this software!");
                }

            } else {
                Logger.getLogger(SyncManager.class.getName()).log(Level.WARNING,
                        "Host " + host.getUrl() + " could not be identified");
                continue;
            }

        } catch (SAXException ex) {
            Logger.getLogger(SyncManager.class.getName()).log(Level.SEVERE, null, ex);
            continue;
        } catch (IOException ex) {
            Logger.getLogger(SyncManager.class.getName()).log(Level.INFO,
                    "Host " + host.getUrl() + " was not avaiable for syncing");
            continue;
        } catch (HttpException ex) {
            Logger.getLogger(SyncManager.class.getName()).log(Level.INFO,
                    "Host " + host.getUrl() + " was not avaiable for syncing");
            continue;
        } catch (URISyntaxException ex) {
            Logger.getLogger(SyncManager.class.getName()).log(Level.SEVERE, null, ex);
            continue;
        }

        ArrayList<Session> sessions = new ArrayList<Session>();

        for (int originId = 0; originId <= host.getMaxOriginId(); originId++) {

            long maxRequestId;
            try {

                String url = host.getUrl() + "/sync/" + originId + "/"
                        + TypeIdManager.getTypeFromClass(Session.class);
                HttpGet httpget = new HttpGet(url);
                HttpResponse response = httpclient.execute(httpget);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                    Logger.getLogger(SyncManager.class.getName()).log(Level.FINE,
                            "Managed to connect to " + host.getUrl() + "/sync/ ");

                } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                    Logger.getLogger(SyncManager.class.getName()).log(Level.INFO, "Up-to-date with host");
                    continue;
                } else {
                    Logger.getLogger(SyncManager.class.getName()).log(Level.INFO, "Got an unexpected "
                            + response.getStatusLine().getStatusCode() + " response from " + host.getUrl());
                    continue;
                }

                InputStream in = response.getEntity().getContent();
                Session topSession = (Session) XMLReader.read(in);
                in.close();

                maxRequestId = topSession.getId();
            } catch (ClassCastException ex) {
                Logger.getLogger(SyncManager.class.getName()).log(Level.WARNING, "Server " + host.getUrl()
                        + " returned something that was not as session when asked for the latest session.", ex);
                continue;
            } catch (HttpException ex) {
                Logger.getLogger(SyncManager.class.getName()).log(Level.INFO,
                        "Host " + host.getUrl() + " could not be contacted");
                continue;
            } catch (URISyntaxException ex) {
                Logger.getLogger(SyncManager.class.getName()).log(Level.WARNING, "Bad url " + host.getUrl()
                        + "/sync/" + originId + "/" + TypeIdManager.getTypeFromClass(Session.class), ex);
                continue;
            } catch (SAXException ex) {
                Logger.getLogger(SyncManager.class.getName()).log(Level.WARNING,
                        "Malformed XML file received from server " + host.getOriginId(), ex);
                continue;
            } catch (IOException ex) {
                Logger.getLogger(SyncManager.class.getName()).log(Level.INFO,
                        "Host " + host.getUrl() + " was not avaiable for syncing");
                continue;
            }

            long startId = sessionManager.getNextId(originId);
            Logger.getLogger(SyncManager.class.getName()).log(Level.INFO,
                    "Expecting next session: " + Long.toHexString(startId));
            for (long requestId = startId; requestId <= maxRequestId; requestId++) {
                if (originId == 0) {
                    Logger.getLogger(SyncManager.class.getName()).log(Level.SEVERE, "Server " + host.getUrl()
                            + " claims that there are items created by server 0, which is impossible.");
                    break;
                }
                if (originId == obsdb.getOriginId()) {
                    Logger.getLogger(SyncManager.class.getName()).log(Level.SEVERE,
                            "There are more up-to-date versions of data we created than in our database!");
                    break;
                }
                Logger.getLogger(SyncManager.class.getName()).log(Level.INFO,
                        "Updating to session " + Long.toHexString(requestId));
                try {
                    String url = host.getUrl() + "/update/" + Long.toHexString(requestId);

                    HttpGet httpget = new HttpGet(url);
                    HttpResponse response = httpclient.execute(httpget);
                    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    } else {
                        Logger.getLogger(SyncManager.class.getName()).log(Level.INFO, "Got an unexpected "
                                + response.getStatusLine().getStatusCode() + " response from " + host.getUrl());
                        continue;
                    }

                    InputStream in = response.getEntity().getContent();
                    IndexIndex idxidx = (IndexIndex) XMLReader.read(in);
                    in.close();

                    Session session = new Session();
                    session.setId(requestId);

                    for (Index idx : idxidx.getIndexList()) {
                        for (Object idable : idx.getIndex()) {
                            obsdb.add((IdAble) idable, session);
                        }
                    }
                    sessions.add(session);
                    //obsdb.save(session);
                } catch (HttpException ex) {
                    Logger.getLogger(SyncManager.class.getName()).log(Level.INFO,
                            "HTTP exception connecting to host " + host.getUrl());
                    continue;
                } catch (URISyntaxException ex) {
                    Logger.getLogger(SyncManager.class.getName()).log(Level.WARNING, ex.getMessage(), ex);
                    break;
                } catch (SAXException ex) {
                    Logger.getLogger(SyncManager.class.getName()).log(Level.WARNING, ex.getMessage(), ex);
                    break;
                } catch (IOException ex) {
                    Logger.getLogger(SyncManager.class.getName()).log(Level.WARNING, ex.getMessage(), ex);
                    break;
                }
            }
        }
        if (!sessions.isEmpty()) {
            try {
                Logger.getLogger(SyncManager.class.getName()).log(Level.INFO, "Saving updates to database");
                obsdb.save(sessions);
                Logger.getLogger(SyncManager.class.getName()).log(Level.INFO,
                        "Database Synchronised with " + host.getUrl());
            } catch (BookKeeprException ex) {
                Logger.getLogger(SyncManager.class.getName()).log(Level.SEVERE,
                        "Somehow tried to modify external elements from a database sync. This should never happen!",
                        ex);
            }
        }
    }
    this.obsdb.getBookkeepr().returnHttpClient(httpclient);
}

From source file:org.unitime.timetable.events.EventEmail.java

public void send(SessionContext context) throws UnsupportedEncodingException, MessagingException {
    try {//from   w w w.  ja v  a 2s .co  m
        if (!request().isEmailConfirmation())
            return;

        if (ApplicationProperty.EmailConfirmationEvents.isFalse()) {
            response().info(MESSAGES.emailDisabled());
            return;
        }

        Email email = Email.createEmail();
        if (event().hasContact() && event().getContact().getEmail() != null
                && !event().getContact().getEmail().isEmpty())
            email.addRecipient(event().getContact().getEmail(), event().getContact().getName(MESSAGES));
        if (event().hasAdditionalContacts()) {
            for (ContactInterface contact : event().getAdditionalContacts()) {
                if (contact.getEmail() != null && !contact.getEmail().isEmpty())
                    email.addRecipient(contact.getEmail(), contact.getName(MESSAGES));
            }
        }
        if (event().hasSponsor() && event().getSponsor().hasEmail())
            email.addRecipientCC(event().getSponsor().getEmail(), event().getSponsor().getName());
        if (event().hasEmail()) {
            String suffix = ApplicationProperty.EmailDefaultAddressSuffix.value();
            for (String address : event().getEmail().split("[\n,]")) {
                if (!address.trim().isEmpty()) {
                    if (suffix != null && address.indexOf('@') < 0)
                        email.addRecipientCC(address.trim() + suffix, null);
                    else
                        email.addRecipientCC(address.trim(), null);
                }
            }
        }
        if (event().hasInstructors() && ApplicationProperty.EmailConfirmationEventInstructors.isTrue()) {
            for (ContactInterface contact : event().getInstructors()) {
                if (contact.getEmail() != null && !contact.getEmail().isEmpty())
                    email.addRecipientCC(contact.getEmail(), contact.getName(MESSAGES));
            }
        }
        if (event().hasCoordinators() && ApplicationProperty.EmailConfirmationEventCoordinators.isTrue()) {
            for (ContactInterface contact : event().getCoordinators()) {
                if (contact.getEmail() != null && !contact.getEmail().isEmpty())
                    email.addRecipientCC(contact.getEmail(), contact.getName(MESSAGES));
            }
        }

        if (ApplicationProperty.EmailConfirmationEventManagers.isTrue()) {
            Set<Long> locationIds = new HashSet<Long>();
            if (event().hasMeetings()) {
                for (MeetingInterface m : event().getMeetings()) {
                    if (m.hasLocation())
                        locationIds.add(m.getLocation().getId());
                }
            }
            if (response().hasDeletedMeetings()) {
                for (MeetingInterface m : response().getDeletedMeetings())
                    if (m.hasLocation())
                        locationIds.add(m.getLocation().getId());
            }
            org.hibernate.Session hibSession = SessionDAO.getInstance().getSession();
            NameFormat nf = NameFormat.fromReference(context.getUser().getProperty(UserProperty.NameFormat));
            for (TimetableManager m : (List<TimetableManager>) hibSession.createQuery(
                    "select distinct m from Location l inner join l.eventDepartment.timetableManagers m inner join m.managerRoles r where "
                            + "l.uniqueId in :locationIds and m.emailAddress is not null and r.receiveEmails = true and :permission in elements (r.role.rights)")
                    .setParameterList("locationIds", locationIds, new LongType())
                    .setString("permission", Right.EventLookupContact.name()).list()) {
                email.addRecipientCC(m.getEmailAddress(), nf.format(m));
            }
        }

        if (replyTo() != null) {
            email.setReplyTo(replyTo().getAddress(), replyTo().getPersonal());
        } else if (context != null && context.isAuthenticated() && context.getUser().getEmail() != null) {
            email.setReplyTo(context.getUser().getEmail(), context.getUser().getName());
        } else {
            email.setReplyTo(event().getContact().getEmail(), event().getContact().getName(MESSAGES));
        }

        if (event().getId() != null && ApplicationProperty.InboundEmailsEnabled.isTrue()
                && ApplicationProperty.InboundEmailsReplyToAddress.value() != null) {
            email.setSubject("[EVENT-" + Long.toHexString(event().getId()) + "] " + event().getName() + " ("
                    + event().getType().getName(CONSTANTS) + ")");
            email.addReplyTo(ApplicationProperty.InboundEmailsReplyToAddress.value(),
                    ApplicationProperty.InboundEmailsReplyToAddressName.value());
        } else {
            email.setSubject(event().getName() + " (" + event().getType().getName(CONSTANTS) + ")");
        }

        if (context != null) {
            final FileItem file = (FileItem) context.getAttribute(UploadServlet.SESSION_LAST_FILE);
            if (file != null) {
                email.addAttachment(new DataSource() {
                    @Override
                    public OutputStream getOutputStream() throws IOException {
                        throw new IOException("No output stream.");
                    }

                    @Override
                    public String getName() {
                        return file.getName();
                    }

                    @Override
                    public InputStream getInputStream() throws IOException {
                        return file.getInputStream();
                    }

                    @Override
                    public String getContentType() {
                        return file.getContentType();
                    }
                });
            }
        }

        if (attachment() != null)
            email.addAttachment(attachment());

        final String ical = icalendar();
        if (ical != null) {
            email.addAttachment(new DataSource() {
                @Override
                public OutputStream getOutputStream() throws IOException {
                    throw new IOException("No output stream.");
                }

                @Override
                public String getName() {
                    return "event.ics";
                }

                @Override
                public InputStream getInputStream() throws IOException {
                    return new ByteArrayInputStream(ical.getBytes("UTF-8"));
                }

                @Override
                public String getContentType() {
                    return "text/calendar; charset=UTF-8";
                }
            });
        }

        email.setHTML(message());

        Long eventId = (response().hasEventWithId() ? response().getEvent().getId()
                : request().getEvent().getId());
        if (eventId != null) {
            String messageId = sMessageId.get(eventId);
            if (messageId != null)
                email.setInReplyTo(messageId);
        }

        email.send();

        if (eventId != null) {
            String messageId = email.getMessageId();
            if (messageId != null)
                sMessageId.put(eventId, messageId);
        }

        response().info(MESSAGES.infoConfirmationEmailSent(
                event().hasContact() ? event().getContact().getName(MESSAGES) : "?"));
    } catch (Exception e) {
        response().error(MESSAGES.failedToSendConfirmationEmail(e.getMessage()));
        sLog.warn(MESSAGES.failedToSendConfirmationEmail(e.getMessage()), e);
    }
}

From source file:org.callimachusproject.webdriver.helpers.BrowserFunctionalTestCase.java

private static String getBuild() {
    String build = System.getProperty("org.callimachusproject.test.build");
    String implementationVersion = Version.class.getPackage().getImplementationVersion();
    if (build != null) {
        return build;
    } else if (implementationVersion != null) {
        return implementationVersion;
    } else {//from  w ww .ja v  a2s . c o m
        RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
        long startTime = bean.getStartTime();
        long code = startTime % (1000 * 60 * 60 * 24 * 30) / 1000 / 60;
        String version = Version.getInstance().getVersionCode();
        return version + "+" + Long.toHexString(code);
    }
}

From source file:com.trsst.Common.java

public static final String toEntryUrn(String feedId, long entryId) {
    return ENTRY_URN_PREFIX + feedId + URN_SEPARATOR + Long.toHexString(entryId);
}

From source file:com.jaeksoft.searchlib.util.ActiveDirectory.java

/**
 * The binary data is in the form: byte[0] - revision level byte[1] - count
 * of sub-authorities byte[2-7] - 48 bit authority (big-endian) and then
 * count x 32 bit sub authorities (little-endian)
 * /*from  w  w  w.  java2s. c  o m*/
 * The String value is: S-Revision-Authority-SubAuthority[n]...
 * 
 * Based on code from here -
 * http://forums.oracle.com/forums/thread.jspa?threadID=1155740&tstart=0
 */
public static String decodeSID(byte[] sid) {

    final StringBuilder strSid = new StringBuilder("S-");

    // get version
    final int revision = sid[0];
    strSid.append(Integer.toString(revision));

    // next byte is the count of sub-authorities
    final int countSubAuths = sid[1] & 0xFF;

    // get the authority
    long authority = 0;
    // String rid = "";
    for (int i = 2; i <= 7; i++) {
        authority |= ((long) sid[i]) << (8 * (5 - (i - 2)));
    }
    strSid.append("-");
    strSid.append(Long.toHexString(authority));

    // iterate all the sub-auths
    int offset = 8;
    int size = 4; // 4 bytes for each sub auth
    for (int j = 0; j < countSubAuths; j++) {
        long subAuthority = 0;
        for (int k = 0; k < size; k++) {
            subAuthority |= (long) (sid[offset + k] & 0xFF) << (8 * k);
        }

        strSid.append("-");
        strSid.append(subAuthority);

        offset += size;
    }

    return strSid.toString();
}

From source file:org.openo.sdnhub.overlayvpndriver.sbi.impl.IpsecImpl.java

/**
 * Adds IPSec VPN configuration using a specific controller.<br>
 *
 * @param ctrlUuid Controller UUID/*from w ww .ja  va2 s  .  c om*/
 * @param deviceId device id
 * @param list collection of ip-security connection
 * @return ResultRsp object with collection of ip-security connection configuration status data
 * @throws ServiceException when input validation fails
 * @since SDNHUB 0.5
 */
public ResultRsp<List<IpsecConnList>> configIpsec(String ctrlUuid, String deviceId, List<IpsecConnList> list)
        throws ServiceException {

    ResultRsp<List<IpsecConnList>> resultRsp = new ResultRsp<>(ErrorCode.OVERLAYVPN_SUCCESS,
            new ArrayList<IpsecConnList>());
    if (StringUtils.isEmpty(deviceId)) {
        LOGGER.error("Device id is null or empty.");
        throw new ParameterServiceException("Device id is null or empty.");
    }

    for (IpsecConnList ipSecModel : list) {
        ResultRsp<List<IpsecConnList>> result = queryIpsecByDevice(ctrlUuid, deviceId,
                ipSecModel.getInterfaceName());

        if (!CollectionUtils.isEmpty(result.getData())) {
            ipSecModel.setName(result.getData().get(0).getName());
            IpsecConnection ipsecConn = ipSecModel.getIpsecConnection().get(0);
            if ("true".equals(ipsecConn.getType())) {
                continue;
            }
        } else {
            int randomNumber = (int) Math.round(Math.random() * (99 - 1) + 1);
            String hexTime = Long.toHexString(System.nanoTime());
            int length = hexTime.length();
            if (length > 13) {
                hexTime = hexTime.substring(length - 13, length);
            }

            ipSecModel.setName(hexTime + randomNumber);
        }

        ResultRsp<IpsecConnList> rsp = handleIpsecByDevice(ctrlUuid, deviceId, ipSecModel, false);
        if (!rsp.isSuccess()) {
            resultRsp.setErrorCode(ErrorCode.OVERLAYVPN_FAILED);
            return resultRsp;
        }
        resultRsp.getData().add(rsp.getData());

        if (CollectionUtils.isNotEmpty(ipSecModel.getIpsecConnection())
                && "true".equals(ipSecModel.getIpsecConnection().get(0).getType())) {
            break;
        }
    }
    return resultRsp;
}

From source file:com.sastix.cms.server.services.cache.hazelcast.HazelcastCacheService.java

@Override
public String getUID(String region) {
    CRC32 CRC_32 = new CRC32();
    LOG.info("HazelcastCacheService->GET_UID");
    IdGenerator idGenerator = cm.getIdGenerator(region);
    final String uid = String.valueOf(idGenerator.newId()); //assures uniqueness during the life cycle of the cluster
    final String uuid = UUID.randomUUID().toString();
    String ret = new StringBuilder(uuid).append(region).append(uid).toString();
    CRC_32.reset();/*from   w  w  w  .j  ava  2  s. com*/
    CRC_32.update(ret.getBytes());
    return Long.toHexString(CRC_32.getValue());
}

From source file:com.conwet.silbops.connectors.comet.CometAPIHandler.java

private String getNewStreamId() {

    return Long.toHexString(nextStreamID.incrementAndGet());
}