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:org.opendaylight.openflowplugin.openflow.md.lldp.LLDPSpeaker.java

private byte[] lldpDataFrom(InstanceIdentifier<Node> nodeInstanceId,
        InstanceIdentifier<NodeConnector> nodeConnectorInstanceId, MacAddress src) {

    NodeId nodeId = InstanceIdentifier.keyOf(nodeInstanceId).getId();
    NodeConnectorId nodeConnectorId = InstanceIdentifier.keyOf(nodeConnectorInstanceId).getId();
    // Create LLDP TTL TLV
    byte[] ttl = new byte[] { (byte) 0, (byte) 120 };
    LLDPTLV ttlTlv = new LLDPTLV();
    ttlTlv.setType(LLDPTLV.TLVType.TTL.getValue()).setLength((short) ttl.length).setValue(ttl);

    // Create LLDP ChassisID TLV
    byte[] cidValue = LLDPTLV.createChassisIDTLVValue(colonize(StringUtils
            .leftPad(Long.toHexString(InventoryDataServiceUtil.dataPathIdFromNodeId(nodeId)), 16, "0")));
    LLDPTLV chassisIdTlv = new LLDPTLV();
    chassisIdTlv.setType(LLDPTLV.TLVType.ChassisID.getValue());
    chassisIdTlv.setType(LLDPTLV.TLVType.ChassisID.getValue()).setLength((short) cidValue.length)
            .setValue(cidValue);//ww w .j ava 2 s.  c  o  m

    // Create LLDP SystemName TLV
    byte[] snValue = LLDPTLV.createSystemNameTLVValue(nodeId.getValue());
    LLDPTLV systemNameTlv = new LLDPTLV();
    systemNameTlv.setType(LLDPTLV.TLVType.SystemName.getValue());
    systemNameTlv.setType(LLDPTLV.TLVType.SystemName.getValue()).setLength((short) snValue.length)
            .setValue(snValue);

    // Create LLDP PortID TL
    Long portNo = InventoryDataServiceUtil.portNumberfromNodeConnectorId(nodeConnectorId);
    String hexString = Long.toHexString(portNo);
    byte[] pidValue = LLDPTLV.createPortIDTLVValue(hexString);
    LLDPTLV portIdTlv = new LLDPTLV();
    portIdTlv.setType(LLDPTLV.TLVType.PortID.getValue()).setLength((short) pidValue.length).setValue(pidValue);
    portIdTlv.setType(LLDPTLV.TLVType.PortID.getValue());

    // Create LLDP Custom TLV
    byte[] customValue = LLDPTLV.createCustomTLVValue(nodeConnectorId.getValue());
    LLDPTLV customTlv = new LLDPTLV();
    customTlv.setType(LLDPTLV.TLVType.Custom.getValue()).setLength((short) customValue.length)
            .setValue(customValue);

    // Create LLDP Custom Option list
    List<LLDPTLV> customList = new ArrayList<LLDPTLV>();
    customList.add(customTlv);

    // Create discovery pkt
    LLDP discoveryPkt = new LLDP();
    discoveryPkt.setChassisId(chassisIdTlv).setPortId(portIdTlv).setTtl(ttlTlv).setSystemNameId(systemNameTlv)
            .setOptionalTLVList(customList);

    // Create ethernet pkt
    byte[] sourceMac = HexEncode.bytesFromHexString(src.getValue());
    Ethernet ethPkt = new Ethernet();
    ethPkt.setSourceMACAddress(sourceMac).setDestinationMACAddress(LLDP.LLDPMulticastMac)
            .setEtherType(EtherTypes.LLDP.shortValue()).setPayload(discoveryPkt);

    try {
        byte[] data = ethPkt.serialize();
        return data;
    } catch (PacketException e) {
        LOG.error("Error creating LLDP packet", e);
    }
    return null;
}

From source file:com.dsi.ant.antplus.pluginsampler.geocache.Dialog_GeoRequestAuthToken.java

@Override
public void onStart() {
    super.onStart(); //super.onStart() is where dialog.show() is actually called on the underlying dialog, so we have to do it after this point
    AlertDialog d = (AlertDialog) getDialog();
    if (d != null) {
        Button positiveButton = d.getButton(Dialog.BUTTON_POSITIVE);
        positiveButton.setOnClickListener(new View.OnClickListener() {
            @Override/*w ww .j  ava 2s .c o  m*/
            public void onClick(View v) {
                final Dialog_ProgressWaiter progressDialog = new Dialog_ProgressWaiter("Requesting Auth Token");

                int nonce;
                long serialNum;
                try {
                    nonce = Integer.parseInt(editText_Nonce.getText().toString());
                    serialNum = Long.parseLong(editText_SerialNumber.getText().toString());
                } catch (NumberFormatException e) {
                    Toast.makeText(getActivity(), "Could not parse number", Toast.LENGTH_SHORT).show();
                    return;
                }

                //Use the current deviceID and PIN
                boolean reqSubmitted = geoPcc.requestAuthToken(deviceID, nonce, serialNum,
                        new IAuthTokenRequestFinishedReceiver() {
                            @Override
                            public void onNewAuthTokenRequestFinished(GeocacheRequestStatus status,
                                    final long authToken) {
                                StringBuilder resultDesc = new StringBuilder("Error Requesting Token: ");

                                switch (status) {
                                case SUCCESS:
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            progressDialog.dismiss();
                                            textView_Status.setText("Authentication token received: 0x"
                                                    + Long.toHexString(authToken));
                                        }
                                    });
                                    return;

                                case FAIL_DEVICE_NOT_IN_LIST:
                                    resultDesc.append("Device no longer in list");
                                    break;
                                case FAIL_ALREADY_BUSY_EXTERNAL:
                                    resultDesc.append("Device is busy");
                                    break;
                                case FAIL_DEVICE_COMMUNICATION_FAILURE:
                                    resultDesc.append("Communication with device failed");
                                    break;
                                case FAIL_BAD_PARAMS:
                                    resultDesc.append("Bad Parameters");
                                    break;
                                case UNRECOGNIZED:
                                    //TODO This flag indicates that an unrecognized value was sent by the service, an upgrade of your PCC may be required to handle this new value.
                                    resultDesc.append("Unrecognized failure");
                                    break;
                                }

                                final String resultStr = resultDesc.toString();
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        progressDialog.dismiss();
                                        Toast.makeText(getActivity(), resultStr, Toast.LENGTH_LONG).show();
                                    }
                                });
                            }
                        }, progressDialog.getUpdateReceiver());

                if (reqSubmitted)
                    progressDialog.show(getActivity().getSupportFragmentManager(), "RequestAuthTokenDialog");
                else
                    Toast.makeText(getActivity(), "Error Requesting Token: PCC already busy or dead",
                            Toast.LENGTH_SHORT).show();

                //now both dialogs stay open. They get closed in the programming result handler.
            }
        });
    }
}

From source file:com.lvlstudios.gtmessage.server.RegisterServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    log.info("doPost " + req.getRequestURI());
    resp.setContentType("text/plain");

    RequestInfo reqInfo = RequestInfo.processRequest(req, resp, getServletContext());
    if (reqInfo == null) {
        return;//from   www .ja v  a 2s .  c  o  m
    }

    if (reqInfo.deviceRegistrationID == null) {
        resp.setStatus(400);
        resp.getWriter().println(ERROR_STATUS + "(Must specify devregid)");
        log.severe("Missing registration id ");
        return;
    }

    String deviceName = reqInfo.getParameter("deviceName");
    if (deviceName == null) {
        deviceName = "Phone";
    }
    // TODO: generate the device name by adding a number suffix for multiple
    // devices of same type. Change android app to send model/type.

    String deviceType = reqInfo.getParameter("deviceType");
    if (deviceType == null) {
        deviceType = "ac2dm";
    }

    // Because the deviceRegistrationId isn't static, we use a static
    // identifier for the device. (Can be null in older clients)
    String deviceId = reqInfo.getParameter("deviceId");

    // Context-shared PMF.
    PersistenceManager pm = C2DMessaging.getPMF(getServletContext()).getPersistenceManager();

    try {
        List<DeviceInfo> registrations = reqInfo.devices;

        if (registrations.size() > MAX_DEVICES) {
            // we could return an error - but user can't handle it yet.
            // we can't let it grow out of bounds.
            // TODO: we should also define a 'ping' message and expire/remove
            // unused registrations
            DeviceInfo oldest = registrations.get(0);
            if (oldest.getRegistrationTimestamp() == null) {
                reqInfo.deleteRegistration(oldest.getDeviceRegistrationID());
            } else {
                long oldestTime = oldest.getRegistrationTimestamp().getTime();
                for (int i = 1; i < registrations.size(); i++) {
                    if (registrations.get(i).getRegistrationTimestamp().getTime() < oldestTime) {
                        oldest = registrations.get(i);
                        oldestTime = oldest.getRegistrationTimestamp().getTime();
                    }
                }
                reqInfo.deleteRegistration(oldest.getDeviceRegistrationID());
            }
        }

        // Get device if it already exists, else create
        String suffix = (deviceId != null ? "#" + Long.toHexString(Math.abs(deviceId.hashCode())) : "");
        Key key = KeyFactory.createKey(DeviceInfo.class.getSimpleName(), reqInfo.userName + suffix);

        DeviceInfo device = null;
        try {
            device = pm.getObjectById(DeviceInfo.class, key);
        } catch (JDOObjectNotFoundException e) {
        }
        if (device == null) {
            device = new DeviceInfo(key, reqInfo.deviceRegistrationID);
            device.setType(deviceType);
        } else {
            // update registration id
            device.setDeviceRegistrationID(reqInfo.deviceRegistrationID);
            device.setRegistrationTimestamp(new Date());
        }

        device.setName(deviceName); // update display name
        // TODO: only need to write if something changed, for chrome nothing
        // changes, we just create a new channel
        pm.makePersistent(device);
        log.log(Level.INFO, "Registered device " + reqInfo.userName + " " + deviceType);

        if (device.getType().equals(DeviceInfo.TYPE_CHROME)) {
            String channelId = ChannelServiceFactory.getChannelService()
                    .createChannel(reqInfo.deviceRegistrationID);
            resp.getWriter().println(OK_STATUS + " " + channelId);
        } else {
            resp.getWriter().println(OK_STATUS);
        }
    } catch (Exception e) {
        resp.setStatus(500);
        resp.getWriter().println(ERROR_STATUS + " (Error registering device)");
        log.log(Level.WARNING, "Error registering device.", e);
    } finally {
        pm.close();
    }
}

From source file:org.accelio.jxio.ClientSession.java

/**
 * Constructor of ClientSession.//  w  w  w .  j  a  va 2 s . co m
 * 
 * @param eqh
 *            - EventQueueHAndler on which the events
 *            (onResponse, onSessionEstablished etc) of this client will arrive
 * @param uri
 *            - URI of the server to which this Client will connect
 *            of the server
 * @param callbacks
 *            - implementation of Interface ClientSession.Callbacks
 */
public ClientSession(EventQueueHandler eqh, URI uri, Callbacks callbacks) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("CS CTOR entry");
    }
    this.eqh = eqh;
    this.callbacks = callbacks;
    if (!uri.getScheme().equals("rdma") && !uri.getScheme().equals("tcp")) {
        LOG.fatal("mal formatted URI: " + uri);
    }
    String uriStr = uri.toString();
    long cacheId = eqh.getId();
    if (uri.getPath().compareTo("") == 0) {
        uriStr += "/";
    }
    if (uri.getQuery() == null) {
        uriStr += "?" + WorkerCache.CACHE_TAG + "=" + cacheId;
    } else {
        uriStr += "&" + WorkerCache.CACHE_TAG + "=" + cacheId;
    }
    final long id = Bridge.startSessionClient(uriStr, eqh.getId());
    this.name = "jxio.CS[" + Long.toHexString(id) + "]";
    this.nameForLog = this.name + ": ";
    if (id == 0) {
        LOG.error(this.toLogString() + "there was an error creating session");
        return;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug(this.toLogString() + "connecting to " + uriStr);
    }
    this.setId(id);
    this.eqh.addEventable(this);

    if (!Bridge.connectSessionClient(this.getId())) {
        LOG.error(this.toLogString() + "there was an error connecting session");
        return;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug(this.toLogString() + "CS CTOR done");
    }
}

From source file:org.rhq.enterprise.server.scheduler.jobs.RepoSyncJob.java

/**
 * Performs similar to {#createJobName} except adds uniqueness to the name regardless of the
 * parameters. In other words, calling this method multiple times on the same parameters
 * will always (almost, it's based on system time) produce a <em>unique</em> name.
 *
 * @param repo may not be <code>null</code>
 * @return name to use to schedule the job; will not be <code>null</code>
 *//*from  w  ww . j  a v  a  2 s  .  c  o  m*/
public static String createUniqueJobName(Repo repo) {
    // Append current time to add uniqueness to exising job name algorithm
    String jobName = createJobName(repo);

    String uniquifier = Long.toHexString(System.currentTimeMillis());
    jobName = jobName + "-" + uniquifier;

    if (jobName.length() > 80) {
        throw new IllegalArgumentException(
                "Job names max size is 80 chars due to DB column " + "size restrictions: " + jobName);
    }

    return jobName;
}

From source file:com.github.lukaszbudnik.dqueue.QueueClientPerformanceTest.java

@Test
public void doIt5Filters() throws ExecutionException, InterruptedException {

    byte[] data = new byte[2045];
    Random r = new Random();
    r.nextBytes(data);//from  w w w  .  j  ava  2  s  .c  om
    ByteBuffer buffer = ByteBuffer.wrap(data);

    Map<String, String> filters = ImmutableMap.of(
            // f1
            "f1", Long.toHexString(r.nextLong()),
            // f2
            "f2", Long.toHexString(r.nextLong()),
            // f3
            "f3", Long.toHexString(r.nextLong()),
            // f4
            "f4", Long.toHexString(r.nextLong()),
            // f5
            "f5", Long.toHexString(r.nextLong()));

    IntStream.range(0, NUMBER_OF_ITERATIONS).forEach((i) -> {
        UUID startTime = UUIDs.timeBased();
        Future<UUID> id = queueClient.publish(new Item(startTime, buffer, filters));
        try {
            Assert.assertEquals(startTime, id.get());
        } catch (Exception e) {
            fail(e.getMessage());
        }
    });

    IntStream.range(0, NUMBER_OF_ITERATIONS).forEach((i) -> {
        Future<Optional<Item>> itemFuture = queueClient.consume(filters);

        Optional<Item> item = null;
        try {
            item = itemFuture.get();
        } catch (Exception e) {
            fail(e.getMessage());
        }

        assertTrue(item.isPresent());
    });

}

From source file:at.spardat.xma.xdelta.JarDelta.java

/**
 * Compute delta.//from   w  w w.jav a2  s .  com
 *
 * @param source the source
 * @param target the target
 * @param output the output
 * @param list the list
 * @param prefix the prefix
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void computeDelta(ZipFile source, ZipFile target, ZipArchiveOutputStream output, PrintWriter list,
        String prefix) throws IOException {
    try {
        for (Enumeration<ZipArchiveEntry> enumer = target.getEntries(); enumer.hasMoreElements();) {
            calculatedDelta = null;
            ZipArchiveEntry targetEntry = enumer.nextElement();
            ZipArchiveEntry sourceEntry = findBestSource(source, target, targetEntry);
            String nextEntryName = prefix + targetEntry.getName();
            if (sourceEntry != null && zipFilesPattern.matcher(sourceEntry.getName()).matches()
                    && !equal(sourceEntry, targetEntry)) {
                nextEntryName += "!";
            }
            nextEntryName += "|" + Long.toHexString(targetEntry.getCrc());
            if (sourceEntry != null) {
                nextEntryName += ":" + Long.toHexString(sourceEntry.getCrc());
            } else {
                nextEntryName += ":0";
            }
            list.println(nextEntryName);
            if (targetEntry.isDirectory()) {
                if (sourceEntry == null) {
                    ZipArchiveEntry outputEntry = entryToNewName(targetEntry, prefix + targetEntry.getName());
                    output.putArchiveEntry(outputEntry);
                    output.closeArchiveEntry();
                }
            } else {
                if (sourceEntry == null || sourceEntry.getSize() <= Delta.DEFAULT_CHUNK_SIZE
                        || targetEntry.getSize() <= Delta.DEFAULT_CHUNK_SIZE) { // new Entry od. alter Eintrag od. neuer Eintrag leer
                    ZipArchiveEntry outputEntry = entryToNewName(targetEntry, prefix + targetEntry.getName());
                    output.putArchiveEntry(outputEntry);
                    try (InputStream in = target.getInputStream(targetEntry)) {
                        int read = 0;
                        while (-1 < (read = in.read(buffer))) {
                            output.write(buffer, 0, read);
                        }
                        output.flush();
                    }
                    output.closeArchiveEntry();
                } else {
                    if (!equal(sourceEntry, targetEntry)) {
                        if (zipFilesPattern.matcher(sourceEntry.getName()).matches()) {
                            File embeddedTarget = File.createTempFile("jardelta-tmp", ".zip");
                            File embeddedSource = File.createTempFile("jardelta-tmp", ".zip");
                            try (FileOutputStream out = new FileOutputStream(embeddedSource);
                                    InputStream in = source.getInputStream(sourceEntry);
                                    FileOutputStream out2 = new FileOutputStream(embeddedTarget);
                                    InputStream in2 = target.getInputStream(targetEntry)) {
                                int read = 0;
                                while (-1 < (read = in.read(buffer))) {
                                    out.write(buffer, 0, read);
                                }
                                out.flush();
                                read = 0;
                                while (-1 < (read = in2.read(buffer))) {
                                    out2.write(buffer, 0, read);
                                }
                                out2.flush();
                                computeDelta(new ZipFile(embeddedSource), new ZipFile(embeddedTarget), output,
                                        list, prefix + sourceEntry.getName() + "!");
                            } finally {
                                embeddedSource.delete();
                                embeddedTarget.delete();
                            }
                        } else {
                            ZipArchiveEntry outputEntry = new ZipArchiveEntry(
                                    prefix + targetEntry.getName() + ".gdiff");
                            outputEntry.setTime(targetEntry.getTime());
                            outputEntry.setComment("" + targetEntry.getCrc());
                            output.putArchiveEntry(outputEntry);
                            if (calculatedDelta != null) {
                                output.write(calculatedDelta);
                                output.flush();
                            } else {
                                try (ByteArrayOutputStream outbytes = new ByteArrayOutputStream()) {
                                    Delta d = new Delta();
                                    DiffWriter diffWriter = new GDiffWriter(new DataOutputStream(outbytes));
                                    int sourceSize = (int) sourceEntry.getSize();
                                    byte[] sourceBytes = new byte[sourceSize];
                                    try (InputStream sourceStream = source.getInputStream(sourceEntry)) {
                                        for (int erg = sourceStream.read(
                                                sourceBytes); erg < sourceBytes.length; erg += sourceStream
                                                        .read(sourceBytes, erg, sourceBytes.length - erg))
                                            ;
                                    }
                                    d.compute(sourceBytes, target.getInputStream(targetEntry), diffWriter);
                                    output.write(outbytes.toByteArray());
                                }
                            }
                            output.closeArchiveEntry();
                        }
                    }
                }
            }
        }
    } finally {
        source.close();
        target.close();
    }
}

From source file:org.mrgeo.utils.HadoopVectorUtils.java

/**
 * Creates a random string filled with hex values.
 *//*from   www .j ava  2  s  . c  o  m*/
public static synchronized String createRandomString(final int size) {
    // create a random string of about 1000 characters. This will force the
    // sequence file to split appropriately. Certainly a hack, but shouldn't
    // cause much of a difference in speed, or storage.
    String randomString = "";
    while (randomString.length() < size) {
        randomString += Long.toHexString(random.nextLong());
    }
    return randomString.substring(0, size);
}

From source file:com.mellanox.jxio.ServerPortal.java

/**
 * This constructor is for the ServerPortal listener that uses worker cache. It listens on a well known port and redirects
 * the request for a new session to ServerPortal worker
 * //from w w w . j a v a 2  s . c  o  m
 * @param eqh
 *            - EventQueueHAndler on which the events
 *            (onSessionNew, onSessionEvent etc) of this portal will arrive
 * @param uri
 *            - on which the ServerPortal will listen. Should contain a well known port
 * @param callbacks
 *            - implementation of Interface ServerPortal.Callbacks
 * @param workerProvider
 *            - implementation of Interface WorkerCache.WorkerProvider
 */
public ServerPortal(EventQueueHandler eqh, URI uri, Callbacks callbacks,
        WorkerCache.WorkerProvider workerProvider) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("SP CTOR entry");
    }
    this.eqh = eqh;
    this.callbacks = callbacks;

    if (!uri.getScheme().equals("rdma") && !uri.getScheme().equals("tcp")) {
        LOG.fatal("mal formatted URI: " + uri);
    }

    long[] ar = Bridge.startServerPortal(uri.toString(), eqh.getId());
    this.setId(ar[0]);
    this.port = (int) ar[1];
    this.name = "jxio.SP[" + Long.toHexString(getId()) + "]";
    this.nameForLog = this.name + ": ";

    if (getId() == 0) {
        LOG.fatal(this.toLogString() + "there was an error creating ServerPortal");
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug(this.toLogString() + "listening to " + uri);
    }
    this.uriPort0 = replacePortInURI(uri, 0);
    this.uri = replacePortInURI(uri, this.port);

    this.eqh.addEventable(this);

    if (workerProvider != null) {
        this.cache = new WorkerCache(workerProvider);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug(this.toLogString() + "SP CTOR done");
    }
}

From source file:com.google.android.chrometophone.server.RegisterServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/plain");

    RequestInfo reqInfo = RequestInfo.processRequest(req, resp, getServletContext());
    if (reqInfo == null) {
        return;//from w ww .j  a v a2  s  .  c  om
    }

    if (reqInfo.deviceRegistrationID == null) {
        resp.setStatus(400);
        resp.getWriter().println(ERROR_STATUS + "(Must specify devregid)");
        log.severe("Missing registration id ");
        return;
    }

    String deviceName = reqInfo.getParameter("deviceName");
    if (deviceName == null) {
        deviceName = "Phone";
    }
    // TODO: generate the device name by adding a number suffix for multiple
    // devices of same type. Change android app to send model/type.

    String deviceType = reqInfo.getParameter("deviceType");
    if (deviceType == null) {
        deviceType = "ac2dm";
    }

    String gcm = reqInfo.getParameter("gcm");
    boolean isGcm = gcm != null && gcm.equalsIgnoreCase("true");

    // Because the deviceRegistrationId isn't static, we use a static
    // identifier for the device. (Can be null in older clients)
    String deviceId = reqInfo.getParameter("deviceId");

    // Context-shared PMF.
    PersistenceManager pm = C2DMessaging.getPMF(getServletContext()).getPersistenceManager();
    try {
        List<DeviceInfo> registrations = reqInfo.devices;

        if (registrations.size() > MAX_DEVICES) {
            // we could return an error - but user can't handle it yet.
            // we can't let it grow out of bounds.
            // TODO: we should also define a 'ping' message and expire/remove
            // unused registrations
            DeviceInfo oldest = registrations.get(0);
            if (oldest.getRegistrationTimestamp() == null) {
                reqInfo.deleteRegistration(oldest.getDeviceRegistrationID(), deviceType);
            } else {
                long oldestTime = oldest.getRegistrationTimestamp().getTime();
                for (int i = 1; i < registrations.size(); i++) {
                    if (registrations.get(i).getRegistrationTimestamp().getTime() < oldestTime) {
                        oldest = registrations.get(i);
                        oldestTime = oldest.getRegistrationTimestamp().getTime();
                    }
                }
                reqInfo.deleteRegistration(oldest.getDeviceRegistrationID(), deviceType);
            }
        }

        // Get device if it already exists, else create
        String suffix = (deviceId != null ? "#" + Long.toHexString(Math.abs(deviceId.hashCode())) : "");
        Key key = KeyFactory.createKey(DeviceInfo.class.getSimpleName(), reqInfo.userName + suffix);

        DeviceInfo device = null;
        try {
            device = pm.getObjectById(DeviceInfo.class, key);
        } catch (JDOObjectNotFoundException e) {
        }
        if (device == null) {
            device = new DeviceInfo(key, reqInfo.deviceRegistrationID);
            device.setType(deviceType);
        } else {
            // update registration id
            device.setDeviceRegistrationID(reqInfo.deviceRegistrationID);
            // must update type, as this could be a C2DM to GCM migration
            device.setType(deviceType);
            device.setRegistrationTimestamp(new Date());
        }

        device.setName(deviceName); // update display name
        device.setGcm(isGcm);
        // TODO: only need to write if something changed, for chrome nothing
        // changes, we just create a new channel
        pm.makePersistent(device);
        log.log(Level.INFO,
                "Registered device " + reqInfo.userName + " " + deviceType + "(gcm: " + isGcm + ")");

        if (device.getType().equals(DeviceInfo.TYPE_CHROME)) {
            String channelId = ChannelServiceFactory.getChannelService()
                    .createChannel(reqInfo.deviceRegistrationID);
            resp.getWriter().println(OK_STATUS + " " + channelId);
        } else {
            resp.getWriter().println(OK_STATUS);
        }
    } catch (Exception e) {
        resp.setStatus(500);
        resp.getWriter().println(ERROR_STATUS + " (Error registering device)");
        log.log(Level.WARNING, "Error registering device.", e);
    } finally {
        pm.close();
    }
}