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.apache.accumulo.shell.commands.TraceCommand.java

@Override
public int execute(final String fullCommand, final CommandLine cl, final Shell shellState) throws IOException {
    if (cl.getArgs().length == 1) {
        if (cl.getArgs()[0].equalsIgnoreCase("on")) {
            Trace.on("shell:" + shellState.getPrincipal());
        } else if (cl.getArgs()[0].equalsIgnoreCase("off")) {
            if (Trace.isTracing()) {
                final long trace = Trace.currentTraceId();
                Trace.off();//from ww w.j a v a2  s  . c  o m
                StringBuilder sb = new StringBuilder();
                int traceCount = 0;
                for (int i = 0; i < 30; i++) {
                    sb = new StringBuilder();
                    try {
                        final Map<String, String> properties = shellState.getConnector().instanceOperations()
                                .getSystemConfiguration();
                        final String table = properties.get(Property.TRACE_TABLE.getKey());
                        final String user = shellState.getConnector().whoami();
                        final Authorizations auths = shellState.getConnector().securityOperations()
                                .getUserAuthorizations(user);
                        final Scanner scanner = shellState.getConnector().createScanner(table, auths);
                        scanner.setRange(new Range(new Text(Long.toHexString(trace))));
                        final StringBuilder finalSB = sb;
                        traceCount = TraceDump.printTrace(scanner, new Printer() {
                            @Override
                            public void print(final String line) {
                                try {
                                    finalSB.append(line + "\n");
                                } catch (Exception ex) {
                                    throw new RuntimeException(ex);
                                }
                            }
                        });
                        if (traceCount > 0) {
                            shellState.getReader().print(sb.toString());
                            break;
                        }
                    } catch (Exception ex) {
                        shellState.printException(ex);
                    }
                    shellState.getReader().println("Waiting for trace information");
                    shellState.getReader().flush();
                    sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
                }
                if (traceCount < 0) {
                    // display the trace even though there are unrooted spans
                    shellState.getReader().print(sb.toString());
                }
            } else {
                shellState.getReader().println("Not tracing");
            }
        } else
            throw new BadArgumentException("Argument must be 'on' or 'off'", fullCommand,
                    fullCommand.indexOf(cl.getArgs()[0]));
    } else if (cl.getArgs().length == 0) {
        shellState.getReader().println(Trace.isTracing() ? "on" : "off");
    } else {
        shellState.printException(new IllegalArgumentException(
                "Expected 0 or 1 argument. There were " + cl.getArgs().length + "."));
        printHelp(shellState);
        return 1;
    }
    return 0;
}

From source file:org.LinuxdistroCommunity.android.client.PostEntry.java

/**
 * Fire the task to post the media entry. The media information is encoded
 * in Bundles. Each Bundle MUST contain the KEY_FILE_PATH pointing to the
 * resource. Bundles MAY contain KEY_TITLE and KEY_DESCRIPTION for passing
 * additional metadata./*from w  ww  .  ja v  a  2  s. c o m*/
 *
 */
@Override
protected JSONObject doInBackground(Bundle... mediaInfoBundles) {

    Bundle mediaInfo = mediaInfoBundles[0];
    HttpURLConnection connection = null;

    Uri.Builder uri_builder = Uri.parse(mServer + API_BASE + API_POST_ENTRY).buildUpon();
    uri_builder.appendQueryParameter(PARAM_ACCESS_TOKEN, mToken);

    String charset = "UTF-8";

    File binaryFile = new File(mediaInfo.getString(KEY_FILE_PATH));

    // Semi-random value to act as the boundary
    String boundary = Long.toHexString(System.currentTimeMillis());
    String CRLF = "\r\n"; // Line separator required by multipart/form-data.
    PrintWriter writer = null;

    try {
        URL url = new URL(uri_builder.toString());
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        OutputStream output = connection.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(output, charset), true); // true = autoFlush, important!

        // Send metadata
        if (mediaInfo.containsKey(KEY_TITLE)) {
            writer.append("--" + boundary).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"title\"").append(CRLF);
            writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
            writer.append(CRLF);
            writer.append(mediaInfo.getString(KEY_TITLE)).append(CRLF).flush();
        }
        if (mediaInfo.containsKey(KEY_DESCRIPTION)) {
            writer.append("--" + boundary).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"description\"").append(CRLF);
            writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
            writer.append(CRLF);
            writer.append(mediaInfo.getString(KEY_DESCRIPTION)).append(CRLF).flush();
        }

        // Send binary file.
        writer.append("--" + boundary).append(CRLF);
        writer.append(
                "Content-Disposition: form-data; name=\"file\"; filename=\"" + binaryFile.getName() + "\"")
                .append(CRLF);
        writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName()))
                .append(CRLF);
        writer.append("Content-Transfer-Encoding: binary").append(CRLF);
        writer.append(CRLF).flush();
        InputStream input = null;
        try {
            input = new FileInputStream(binaryFile);
            byte[] buffer = new byte[1024];
            for (int length = 0; (length = input.read(buffer)) > 0;) {
                output.write(buffer, 0, length);
            }
            output.flush(); // Important! Output cannot be closed. Close of
                            // writer will close output as well.
        } finally {
            if (input != null)
                try {
                    input.close();
                } catch (IOException logOrIgnore) {
                }
        }
        writer.append(CRLF).flush(); // CRLF is important! It indicates end
                                     // of binary boundary.

        // End of multipart/form-data.
        writer.append("--" + boundary + "--").append(CRLF);
        writer.close();

        // read the response
        int serverResponseCode = connection.getResponseCode();
        String serverResponseMessage = connection.getResponseMessage();
        Log.d(TAG, Integer.toString(serverResponseCode));
        Log.d(TAG, serverResponseMessage);

        InputStream is = connection.getInputStream();

        // parse token_response as JSON to get the token out
        String str_response = NetworkUtilities.readStreamToString(is);
        Log.d(TAG, str_response);
        JSONObject response = new JSONObject(str_response);

        return response;
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        // if (writer != null) writer.close();
    }

    return null;
}

From source file:fr.gael.dhus.datastore.HierarchicalDirectoryBuilder.java

/**
 * Build a path from a given counter and according to a maximum number of
 * entry per level. The path steps are expressed in hexadecimal numbers with
 * an "x" prefix and are separated by a slash. All paths begin by a leading
 * slash./*w  w w .  j a v a 2 s.co m*/
 *
 * The algorithm is equivalent to the base conversion of the input <code>
 * counter</code> to a base radix equal to the <code>max_occurence</code>.
 * As a consequence, the <code>counter</code> shall not be negative and the
 * <code>max_occurence</code> shall be greater or equal to 2.
 *
 * Example, for a counter running from 0 to 100 with a max_occurrence of 3:
 *
 * <pre>
 * 0 -> "/x0"
 * 1 -> "/x1"
 * 2 -> "/x2"
 * 3 -> "/x3"
 * 4 -> "/x4"
 * 5 -> "/x5"
 * 6 -> "/x6"
 * 7 -> "/x7"
 * 8 -> "/x8"
 * 9 -> "/x9"
 * 10 -> "/xA"
 * 11 -> "/xB"
 * 12 -> "/xC"
 * 13 -> "/xD"
 * 14 -> "/xE"
 * 15 -> "/xF"
 * 16 -> "/x0/x1"
 * 17 -> "/x1/x1"
 * 18 -> "/x2/x1"
 * 19 -> "/x3/x1"
 * ...
 * 89 -> "/x9/x5"
 * 90 -> "/xA/x5"
 * 91 -> "/xB/x5"
 * 92 -> "/xC/x5"
 * 93 -> "/xD/x5"
 * 94 -> "/xE/x5"
 * 95 -> "/xF/x5"
 * 96 -> "/x0/x6"
 * 97 -> "/x1/x6"
 * 98 -> "/x2/x6"
 * 99 -> "/x3/x6"
 * </pre>
 *
 * @param counter the counter to be converted (positive or null).
 * @param max_occurrence the maximum number of entries per level (greater or
 *    equal to 2).
 * @return the hierarchical path (never null).
 */
static String getHierarchicalPath(final long counter, final long max_occurrence)
        throws IllegalArgumentException {
    // Check that counter is positive or null
    if (counter < 0) {
        throw new IllegalArgumentException("Negative counter");
    }

    // Check that counter is strictly greater than 1
    if (max_occurrence <= 1) {
        throw new IllegalArgumentException("Maximum occurrence shall be greater than 1");
    }

    // Prepare output path
    String output_path = "";

    // Prepare a quotient, equal to the input counter
    long running_quotient = counter;

    // Loop until quotient reaches 0
    do {
        // Concatenate the remainder to the output path
        output_path += "/x" + Long.toHexString(running_quotient % max_occurrence).toUpperCase();

        // !update the quotient
        running_quotient = running_quotient / max_occurrence;
    } while (running_quotient > 0);

    // Return the built path
    return output_path;

}

From source file:alma.acs.container.archive.IdentifierJMock.java

/** 
 * This is the only method that's currently implemented
 * @see alma.xmlstore.IdentifierJ#getNewRange()
 *//* w w w.  ja  v a2 s  .c  o  m*/
public IdentifierRange getNewRange() throws NotAvailable {
    //Create the entity information
    IdentifierRangeEntityT entityt = new IdentifierRangeEntityT();
    //The id of the range is the 0 document id in that range.
    entityt.setEntityId(createUid());

    IdentifierRange range = new IdentifierRange();
    range.setIdentifierRangeEntity(entityt);

    //set the time stamp
    String ts = IsoDateFormat.formatCurrentDate(); // todo: pass in time externally?
    range.setCreatedTimeStamp(ts);

    range.setIsLocked(false);

    String archiveIdString = Long.toHexString(archiveid);
    archiveIdString = "X" + StringUtils.leftPad(archiveIdString, archiveIdLength, '0');
    range.setArchiveID(archiveIdString);

    RangeT ranget = new RangeT();
    ranget.setRangeID(Long.toHexString(rangeid));
    ranget.setBaseDocumentID("1");
    range.setRange(ranget);

    rangeid++;
    //      this.setRangeId(rangeid);

    return range;
}

From source file:org.ambiance.codec.YEncDecoder.java

/**
 * Decode a single file//from   w  w  w. ja va 2  s  . c  o  m
 */
public void decode(File input) throws DecoderException {
    try {
        YEncFile yencFile = new YEncFile(input);

        // Get the output file
        StringBuffer outputName = new StringBuffer(outputDirName);
        outputName.append(File.separator);
        outputName.append(yencFile.getHeader().getName());
        RandomAccessFile output = new RandomAccessFile(outputName.toString(), "rw");

        // Place the pointer to the begining of data to decode
        long pos = yencFile.getDataBegin();
        yencFile.getInput().seek(pos);

        // Bufferise the file
        // TODO - A Amliorer
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while (pos < yencFile.getDataEnd()) {
            baos.write(yencFile.getInput().read());
            pos++;
        }

        byte[] buff = decoder.decode(baos.toByteArray());

        // Write and close output
        output.write(buff);
        output.close();

        // Warn if CRC32 check is not OK
        CRC32 crc32 = new CRC32();
        crc32.update(buff);
        if (!yencFile.getTrailer().getCrc32().equals(Long.toHexString(crc32.getValue()).toUpperCase()))
            throw new DecoderException("Error in CRC32 check.");

    } catch (YEncException ye) {
        throw new DecoderException("Input file is not a YEnc file or contains error : " + ye.getMessage());
    } catch (FileNotFoundException fnfe) {
        throw new DecoderException("Enable to create output file : " + fnfe.getMessage());
    } catch (IOException ioe) {
        throw new DecoderException("Enable to read input file : " + ioe.getMessage());
    }
}

From source file:org.jitsi.jicofo.rest.Health.java

/**
 * Generates a pseudo-random room name which is not guaranteed to be unique.
 *
 * @return a pseudo-random room name which is not guaranteed to be unique
 *///w ww. j  a v  a2  s.com
private static String generateRoomName() {
    return Health.class.getName() + "-" + Long.toHexString(System.currentTimeMillis() + RANDOM.nextLong());
}

From source file:com.github.bfour.fpliteraturecollector.service.FileStorageService.java

private String getFileNameForLiterature(Literature lit) {

    // take title, removing all special characters
    String name = Normalizer.normalize(lit.getTitle(), Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", "");

    name = name.replaceAll("[^A-z\\s]", "");

    // remove unnecessary words
    name = name.replaceAll("\\sa\\s", " ");
    name = name.replaceAll("\\sthe\\s", " ");
    name = name.replaceAll("\\sA\\s", " ");
    name = name.replaceAll("\\sThe\\s", " ");

    // trim/*from  w  ww. ja  v  a 2  s.  c o m*/
    if (name.length() > 68)
        name = name.substring(0, 68);

    // add kind-of GUID
    name += "_" + Long.toHexString(new Date().getTime());

    return name;

}

From source file:eu.semlibproject.annotationserver.managers.UtilsManager.java

/**
 * Compute the CRC32 checksum of a String. This can be useful to
 * short an URL.//  w  ww. jav  a  2 s.  co  m
 * 
 * @param text  the text from which the checksum will be computed
 * @return      the CRC32 checksum
 */
public String CRC32(String text) {
    CRC32 checksumer = new CRC32();
    checksumer.update(text.getBytes());
    String finalhash = Long.toHexString(checksumer.getValue());
    // correctly format the finalHash (e.g. number starting with 00 that was stripped)
    return StringUtils.leftPad(finalhash, 8, "0");
}

From source file:es.osoco.grails.plugins.otp.OneTimePasswordService.java

private String toStepsTimeHex(int stepTime) {
    String steps = Long.toHexString(stepTime).toUpperCase();
    while (steps.length() < 16) {
        steps = "0" + steps;
    }/*from   ww  w  . j  a  v  a2s  .c  o m*/
    return steps;
}

From source file:org.apache.accumulo.core.trace.TraceFormatter.java

@Override
public String next() {
    Entry<Key, Value> next = scanner.next();
    if (next.getKey().getColumnFamily().equals(SPAN_CF)) {
        StringBuilder result = new StringBuilder();
        SimpleDateFormat dateFormatter = new SimpleDateFormat(DATE_FORMAT);
        RemoteSpan span = getRemoteSpan(next);
        result.append("----------------------\n");
        result.append(String.format(" %12s:%s%n", "name", span.description));
        result.append(String.format(" %12s:%s%n", "trace", Long.toHexString(span.traceId)));
        result.append(String.format(" %12s:%s%n", "loc", span.svc + "@" + span.sender));
        result.append(String.format(" %12s:%s%n", "span", Long.toHexString(span.spanId)));
        result.append(String.format(" %12s:%s%n", "parent", Long.toHexString(span.parentId)));
        result.append(String.format(" %12s:%s%n", "start", dateFormatter.format(span.start)));
        result.append(String.format(" %12s:%s%n", "ms", span.stop - span.start));
        for (Entry<String, String> entry : span.data.entrySet()) {
            result.append(String.format(" %12s:%s%n", entry.getKey(), entry.getValue()));
        }// w ww .  j av a 2s . c o m

        if (printTimeStamps) {
            result.append(String.format(" %-12s:%d%n", "timestamp", next.getKey().getTimestamp()));
        }
        return result.toString();
    }
    return DefaultFormatter.formatEntry(next, printTimeStamps);
}