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.wealdtech.WID.java

@JsonValue
@Override/*from  w  ww.  j a  va2 s  . c  om*/
public String toString() {
    if (hasSubId()) {
        return Long.toHexString(this.id) + WID_SEPARATOR + Long.toHexString(this.subId.get());
    } else {
        return Long.toHexString(this.id);
    }
}

From source file:org.spout.engine.world.SpoutWorld.java

public SpoutWorld(String name, SpoutEngine engine, long seed, long age, WorldGenerator generator, UUID uid,
        StringMap itemMap) {/*  ww w  .j  a v a 2s  . c  o m*/
    super(1, new ThreadAsyncExecutor(toString(name, uid, age)), engine);
    this.engine = engine;
    if (!StringSanitizer.isAlphaNumericUnderscore(name)) {
        name = Long.toHexString(System.currentTimeMillis());
        Spout.getEngine().getLogger()
                .severe("World name " + name + " is not valid, using " + name + " instead");
    }
    this.name = name;
    this.uid = uid;
    this.itemMap = itemMap;
    this.seed = seed;

    this.generator = generator;
    regions = new RegionSource(this, snapshotManager);

    worldDirectory = new File(SharedFileSystem.WORLDS_DIRECTORY, name);
    worldDirectory.mkdirs();

    regionFileManager = new RegionFileManager(worldDirectory);

    heightMapBAAs = new TSyncIntPairObjectHashMap<BAAWrapper>();

    this.hashcode = new HashCodeBuilder(27, 971).append(uid).toHashCode();

    this.lightingManager = new SpoutWorldLighting(this);
    this.lightingManager.start();

    parallelTaskManager = new SpoutParallelTaskManager(engine.getScheduler(), this);

    AsyncExecutor e = getExecutor();
    Thread t;
    if (e instanceof Thread) {
        t = (Thread) e;
    } else {
        throw new IllegalStateException("AsyncExecutor should be instance of Thread");
    }

    this.age = new SnapshotableLong(snapshotManager, age);
    taskManager = new SpoutTaskManager(getEngine().getScheduler(), false, t, age);
    spawnLocation.set(new Transform(new Point(this, 1, 100, 1), Quaternion.IDENTITY, Vector3.ONE));
    selfReference = new WeakReference<World>(this);
    componentHolder = new WorldComponentHolder(this);
}

From source file:com.amazonaws.auth.AwsChunkedEncodingInputStream.java

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

From source file:edu.stanford.junction.sample.partyware.ImgurUploadService.java

/**
 * This method uploads an image from the given uri. It does the uploading in
 * small chunks to make sure it doesn't over run the memory.
 * /*from w w  w.j  a  v a2  s .  c o m*/
 * @param uri
 *            image location
 * @return map containing data from interaction
 */
private String readPictureDataAndUpload(final Uri uri) {
    Log.i(this.getClass().getName(), "in readPictureDataAndUpload(Uri)");
    try {
        final AssetFileDescriptor assetFileDescriptor = getContentResolver().openAssetFileDescriptor(uri, "r");
        final int totalFileLength = (int) assetFileDescriptor.getLength();
        assetFileDescriptor.close();

        // Create custom progress notification
        mProgressNotification = new Notification(R.drawable.icon, getString(R.string.imgur_upload_in_progress),
                System.currentTimeMillis());
        // set as ongoing
        mProgressNotification.flags |= Notification.FLAG_ONGOING_EVENT;
        // set custom view to notification
        mProgressNotification.contentView = generateProgressNotificationView(0, totalFileLength);
        //empty intent for the notification
        final Intent progressIntent = new Intent();
        final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, progressIntent, 0);
        mProgressNotification.contentIntent = contentIntent;
        // add notification to manager
        mNotificationManager.notify(NOTIFICATION_ID, mProgressNotification);

        final InputStream inputStream = getContentResolver().openInputStream(uri);

        final String boundaryString = "Z." + Long.toHexString(System.currentTimeMillis())
                + Long.toHexString((new Random()).nextLong());
        final String boundary = "--" + boundaryString;
        final HttpURLConnection conn = (HttpURLConnection) (new URL("http://imgur.com/api/upload.json"))
                .openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-type", "multipart/form-data; boundary=\"" + boundaryString + "\"");
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setChunkedStreamingMode(CHUNK_SIZE);
        final OutputStream hrout = conn.getOutputStream();
        final PrintStream hout = new PrintStream(hrout);
        hout.println(boundary);
        hout.println("Content-Disposition: form-data; name=\"key\"");
        hout.println("Content-Type: text/plain");
        hout.println();

        Random rng = new Random();
        String key = API_KEYS[rng.nextInt(API_KEYS.length)];
        hout.println(key);

        hout.println(boundary);
        hout.println("Content-Disposition: form-data; name=\"image\"");
        hout.println("Content-Transfer-Encoding: base64");
        hout.println();
        hout.flush();
        {
            final Base64OutputStream bhout = new Base64OutputStream(hrout);
            final byte[] pictureData = new byte[READ_BUFFER_SIZE_BYTES];
            int read = 0;
            int totalRead = 0;
            long lastLogTime = 0;
            while (read >= 0) {
                read = inputStream.read(pictureData);
                if (read > 0) {
                    bhout.write(pictureData, 0, read);
                    totalRead += read;
                    if (lastLogTime < (System.currentTimeMillis() - PROGRESS_UPDATE_INTERVAL_MS)) {
                        lastLogTime = System.currentTimeMillis();
                        Log.d(this.getClass().getName(), "Uploaded " + totalRead + " of " + totalFileLength
                                + " bytes (" + (100 * totalRead) / totalFileLength + "%)");

                        //make a final version of the total read to make the handler happy
                        final int totalReadFinal = totalRead;
                        mHandler.post(new Runnable() {
                            public void run() {
                                mProgressNotification.contentView = generateProgressNotificationView(
                                        totalReadFinal, totalFileLength);
                                mNotificationManager.notify(NOTIFICATION_ID, mProgressNotification);
                            }
                        });
                    }
                    bhout.flush();
                    hrout.flush();
                }
            }
            Log.d(this.getClass().getName(), "Finishing upload...");
            // This close is absolutely necessary, this tells the
            // Base64OutputStream to finish writing the last of the data
            // (and including the padding). Without this line, it will miss
            // the last 4 chars in the output, missing up to 3 bytes in the
            // final output.
            bhout.close();
            Log.d(this.getClass().getName(), "Upload complete...");
            mProgressNotification.contentView.setProgressBar(R.id.UploadProgress, totalFileLength, totalRead,
                    false);
            mNotificationManager.cancelAll();
        }

        hout.println(boundary);
        hout.flush();
        hrout.close();

        inputStream.close();

        Log.d(this.getClass().getName(), "streams closed, " + "now waiting for response from server");

        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final StringBuilder rData = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            rData.append(line).append('\n');
        }

        return rData.toString();
    } catch (final IOException e) {
        Log.e(this.getClass().getName(), "Upload failed", e);
    }

    return null;
}

From source file:it.infn.ct.indigo.futuregateway.server.FGServerManager.java

/**
 * Add files into a resource on FG service.
 *
 * @param companyId The id of the instance
 * @param collection The name of the collection to post the new resource
 * @param resourceId The resource requiring the files
 * @param files The files to add to the resource
 * @param token The token of the user performing the action
 * @throws PortalException Cannot retrieve the server endpoint
 * @throws IOException Connect communicate with the server
 *///from w w  w  .j a  va  2 s  .  c o  m
public final void submitFilesResource(final long companyId, final String collection, final String resourceId,
        final Map<String, InputStream> files, final String token) throws PortalException, IOException {
    String boundary = Long.toHexString(System.currentTimeMillis());
    String crlf = "\r\n";
    log.info("Adding new files to " + collection + "/" + resourceId);

    HttpURLConnection connection = getFGConnection(companyId, collection, resourceId + "/input", token,
            HttpMethods.POST, "multipart/form-data; boundary=" + boundary);
    try (OutputStream output = connection.getOutputStream();
            PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8),
                    true);) {
        for (String fName : files.keySet()) {
            writer.append("--" + boundary).append(crlf);
            writer.append("Content-Disposition: form-data; " + "name=\"file[]\"; filename=\"" + fName + "\"")
                    .append(crlf);
            writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fName)).append(crlf);
            writer.append("Content-Transfer-Encoding: binary").append(crlf);
            writer.append(crlf).flush();
            IOUtils.copy(files.get(fName), output);
            writer.append(crlf).flush();
            files.get(fName).close();
        }
        writer.append("--" + boundary + "--").append(crlf).flush();
    }
    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
        throw new IOException("Impossible to post files to the resource " + collection + "/" + resourceId
                + ". Server response with code: " + connection.getResponseCode());
    }
}

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

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

    ticket = service.deleteComment(ticket, c1.comment.id, "D1");
    assertNotNull(ticket);
    assertEquals(1, ticket.changes.size());
    assertFalse(ticket.changes.get(0).hasComment());

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

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

private void testChecksum(Checksum csum, int value, byte[] data, int off, int len) throws IOException {
    if (csum == null)
        return;//from   w w  w .j  a  v a 2  s.  co m
    csum.reset();
    csum.update(data, off, len);
    if (value != (int) csum.getValue())
        throw new IOException("Checksum failure: " + "Expected " + Integer.toHexString(value) + "; got "
                + Long.toHexString(csum.getValue()));
}

From source file:tv.ouya.sample.game.OptionsActivity.java

private void requestPurchase(final Options.Level level)
        throws GeneralSecurityException, JSONException, UnsupportedEncodingException {
    final String productId = getProductIdForLevel(level);

    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

    // This is an ID that allows you to associate a successful purchase with
    // it's original request. The server does nothing with this string except
    // pass it back to you, so it only needs to be unique within this instance
    // of your app to allow you to pair responses with requests.
    String uniqueId = Long.toHexString(sr.nextLong());

    JSONObject purchaseRequest = new JSONObject();
    purchaseRequest.put("uuid", uniqueId);
    purchaseRequest.put("identifier", productId);
    purchaseRequest.put("testing", "true"); // This value is only needed for testing, not setting it results in a live purchase
    String purchaseRequestJson = purchaseRequest.toString();

    byte[] keyBytes = new byte[16];
    sr.nextBytes(keyBytes);/* w ww.j a v a  2  s . c  om*/
    SecretKey key = new SecretKeySpec(keyBytes, "AES");

    byte[] ivBytes = new byte[16];
    sr.nextBytes(ivBytes);
    IvParameterSpec iv = new IvParameterSpec(ivBytes);

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, key, iv);
    byte[] payload = cipher.doFinal(purchaseRequestJson.getBytes("UTF-8"));

    cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, mPublicKey);
    byte[] encryptedKey = cipher.doFinal(keyBytes);

    Purchasable purchasable = new Purchasable(productId, Base64.encodeToString(encryptedKey, Base64.NO_WRAP),
            Base64.encodeToString(ivBytes, Base64.NO_WRAP), Base64.encodeToString(payload, Base64.NO_WRAP));

    synchronized (mOutstandingPurchaseRequests) {
        mOutstandingPurchaseRequests.put(uniqueId, productId);
    }
    mOuyaFacade.requestPurchase(purchasable, new OuyaResponseListener<String>() {
        @Override
        public void onSuccess(String result) {
            String responseProductId;
            try {
                OuyaEncryptionHelper helper = new OuyaEncryptionHelper();

                JSONObject response = new JSONObject(result);
                String responseUUID = helper.decryptPurchaseResponse(response, mPublicKey);
                synchronized (mOutstandingPurchaseRequests) {
                    responseProductId = mOutstandingPurchaseRequests.remove(responseUUID);
                }
                if (responseProductId == null || !responseProductId.equals(productId)) {
                    onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS,
                            "Purchased product is not the same as purchase request product", Bundle.EMPTY);
                    return;
                }
            } catch (JSONException e) {
                onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
                return;
            } catch (ParseException e) {
                onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
                return;
            } catch (IOException e) {
                onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
                return;
            } catch (GeneralSecurityException e) {
                onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
                return;
            }

            if (responseProductId.equals(getProductIdForLevel(level))) {
                setNeedsPurchaseText(levelToRadioButton.get(level), false);
                Toast.makeText(OptionsActivity.this, "Level purchased!", Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onFailure(int errorCode, String errorMessage, Bundle optionalData) {
            levelToRadioButton.get(FREEDOM).setChecked(true);
            Toast.makeText(OptionsActivity.this,
                    "Error making purchase!\n\nError " + errorCode + "\n" + errorMessage + ")",
                    Toast.LENGTH_LONG).show();

        }

        @Override
        public void onCancel() {
            levelToRadioButton.get(FREEDOM).setChecked(true);
            Toast.makeText(OptionsActivity.this, "You cancelled the purchase!", Toast.LENGTH_LONG).show();
        }
    });
}

From source file:com.github.rnewson.couchdb.lucene.SearchRequest.java

private String getETag(final IndexSearcher searcher) {
    return Long.toHexString(searcher.getIndexReader().getVersion());
}

From source file:org.got5.tapestry5.jquery.mobile.services.JQueryMobileModule.java

public void contributeMarkupRenderer(OrderedConfiguration<MarkupRendererFilter> configuration,

        @Symbol(SymbolConstants.OMIT_GENERATOR_META) final boolean omitGeneratorMeta,

        @Symbol(SymbolConstants.TAPESTRY_VERSION) final String tapestryVersion,

        @Symbol(SymbolConstants.COMPACT_JSON) final boolean compactJSON,

        final Environment environment,

        final Request request,

        final JavaScriptStackSource javascriptStackSource,

        final JavaScriptStackPathConstructor javascriptStackPathConstructor,

        final JQMobilePageIdentifier jQMobilePageIdentifier) {

    MarkupRendererFilter javaScriptSupport = new MarkupRendererFilter() {
        public void renderMarkup(MarkupWriter writer, MarkupRenderer renderer) {
            DocumentLinker linker = environment.peekRequired(DocumentLinker.class);
            JavaScriptSupportImpl support;

            if (jQMobilePageIdentifier.isJQMobilePage()) {
                String uid = Long.toHexString(System.currentTimeMillis());
                String namespace = "_" + uid;
                IdAllocator idAllocator = new IdAllocator(namespace);
                support = new JavaScriptSupportImpl(linker, javascriptStackSource,
                        javascriptStackPathConstructor, idAllocator, true);
            } else
                support = new JavaScriptSupportImpl(linker, javascriptStackSource,
                        javascriptStackPathConstructor);

            environment.push(JavaScriptSupport.class, support);

            renderer.renderMarkup(writer);

            environment.pop(JavaScriptSupport.class);

            support.commit();/*w  w w.  j a va2 s  . co m*/
        }
    };
    configuration.override("JavaScriptSupport", javaScriptSupport, "after:DocumentLinker");
}