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:interactivespaces.sandbox.service.interactivespaces.master.internal.NativeInteractiveSpacesMasterClient.java

/**
 * Generate a new request ID.
 *
 * @return a new request ID
 */
private String newRequestId() {
    return Long.toHexString(requestIdGenerator.getAndIncrement());
}

From source file:info.guardianproject.gpg.KeyListFragment.java

private void keyserverOperation(final int operation, final ActionMode mode) {
    new AsyncTask<Void, Void, Void>() {
        final Context context = getActivity().getApplicationContext();
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        final String host = prefs.getString(GpgPreferenceActivity.PREF_KEYSERVER,
                "ipv4.pool.sks-keyservers.net");
        final long[] selected = mListView.getCheckedItemIds();
        final Intent intent = new Intent(context, ImportFileActivity.class);

        @Override//www .java2  s .  c  o m
        protected Void doInBackground(Void... params) {
            HkpKeyServer keyserver = new HkpKeyServer(host);
            if (operation == DELETE_KEYS) {
                String args = "--batch --yes --delete-keys";
                for (int i = 0; i < selected.length; i++) {
                    args += " " + Long.toHexString(selected[i]);
                }
                GnuPG.gpg2(args);
            } else if (operation == KEYSERVER_SEND) {
                String args = "--keyserver " + host + " --send-keys ";
                for (int i = 0; i < selected.length; i++) {
                    args += " " + Long.toHexString(selected[i]);
                }
                // TODO this should use the Java keyserver stuff
                GnuPG.gpg2(args);
            } else if (operation == KEYSERVER_RECEIVE) {
                String keys = "";
                for (int i = 0; i < selected.length; i++) {
                    try {
                        keys += keyserver.get(selected[i]);
                        keys += "\n\n";
                    } catch (QueryException e) {
                        e.printStackTrace();
                    }
                }
                // An Intent can carry very much data, so write it
                // to a cached file
                try {
                    File privateFile = File.createTempFile("keyserver", ".pkr", mCurrentActivity.getCacheDir());
                    FileUtils.writeStringToFile(privateFile, keys);
                    intent.setType(getString(R.string.pgp_keys));
                    intent.setAction(Intent.ACTION_SEND);
                    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(privateFile));
                } catch (IOException e) {
                    e.printStackTrace();
                    // try sending the key data inline in the Intent
                    intent.setType("text/plain");
                    intent.setAction(Intent.ACTION_SEND);
                    intent.putExtra(Intent.EXTRA_TEXT, keys);
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void v) {
            GpgApplication.triggerContactsSync();
            mCurrentActivity.setSupportProgressBarIndeterminateVisibility(false);
            mode.finish(); // Action picked, so close the CAB
            if (operation == KEYSERVER_RECEIVE)
                startActivity(intent);
        }
    }.execute();
}

From source file:com.parse.ParseCommandCache.java

/**
 * Attempts to run the given command and any pending commands. Adds the command to the pending set
 * if it can't be run yet./*from www.j av a2s  .  c om*/
 *
 * @param command
 *          - The command to run.
 * @param preferOldest
 *          - When the disk is full, if preferOldest, drop new commands. Otherwise, the oldest
 *          commands will be deleted to make room.
 * @param object
 *          - See runEventually.
 */
private Task<JSONObject> enqueueEventuallyAsync(ParseRESTCommand command, boolean preferOldest,
        ParseObject object) {
    Parse.requirePermission(Manifest.permission.ACCESS_NETWORK_STATE);
    Task<JSONObject>.TaskCompletionSource tcs = Task.create();
    byte[] json;
    try {
        // If this object doesn't have an objectId yet, store the localId so we can remap it to the
        // objectId after the save completes.
        if (object != null && object.getObjectId() == null) {
            command.setLocalId(object.getOrCreateLocalId());
        }
        JSONObject jsonObject = command.toJSONObject();
        json = jsonObject.toString().getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        if (Parse.LOG_LEVEL_WARNING >= Parse.getLogLevel()) {
            log.log(Level.WARNING, "UTF-8 isn't supported.  This shouldn't happen.", e);
        }
        notifyTestHelper(TestHelper.COMMAND_NOT_ENQUEUED);
        return Task.forResult(null);
    }

    // If this object by itself is larger than the full disk cache, then don't
    // even bother trying.
    if (json.length > maxCacheSizeBytes) {
        if (Parse.LOG_LEVEL_WARNING >= Parse.getLogLevel()) {
            log.warning("Unable to save command for later because it's too big.");
        }
        notifyTestHelper(TestHelper.COMMAND_NOT_ENQUEUED);
        return Task.forResult(null);
    }

    synchronized (lock) {
        try {
            // Is there enough free storage space?
            String[] fileNames = cachePath.list();
            if (fileNames != null) {
                Arrays.sort(fileNames);
                int size = 0;
                for (String fileName : fileNames) {
                    File file = new File(cachePath, fileName);
                    // Should be safe to convert long to int, because we don't allow
                    // files larger than 2GB.
                    size += (int) file.length();
                }
                size += json.length;
                if (size > maxCacheSizeBytes) {
                    if (preferOldest) {
                        if (Parse.LOG_LEVEL_WARNING >= Parse.getLogLevel()) {
                            log.warning("Unable to save command for later because storage is full.");
                        }
                        return Task.forResult(null);
                    } else {
                        if (Parse.LOG_LEVEL_WARNING >= Parse.getLogLevel()) {
                            log.warning("Deleting old commands to make room in command cache.");
                        }
                        int indexToDelete = 0;
                        while (size > maxCacheSizeBytes && indexToDelete < fileNames.length) {
                            File file = new File(cachePath, fileNames[indexToDelete++]);
                            size -= (int) file.length();
                            removeFile(file);
                        }
                    }
                }
            }

            // Get the current time to store in the filename, so that we process them in order.
            String prefix1 = Long.toHexString(System.currentTimeMillis());
            if (prefix1.length() < 16) {
                char[] zeroes = new char[16 - prefix1.length()];
                Arrays.fill(zeroes, '0');
                prefix1 = new String(zeroes) + prefix1;
            }

            // Then add another incrementing number in case we enqueue items faster than the system's
            // time granularity.
            String prefix2 = Integer.toHexString(filenameCounter++);
            if (prefix2.length() < 8) {
                char[] zeroes = new char[8 - prefix2.length()];
                Arrays.fill(zeroes, '0');
                prefix2 = new String(zeroes) + prefix2;
            }

            String prefix = "CachedCommand_" + prefix1 + "_" + prefix2 + "_";

            // Get a unique filename to store this command in.
            File path = File.createTempFile(prefix, "", cachePath);

            // Write the command to that file.
            pendingTasks.put(path, tcs);
            command.retainLocalIds();
            ParseFileUtils.writeByteArrayToFile(path, json);

            notifyTestHelper(TestHelper.COMMAND_ENQUEUED);

            unprocessedCommandsExist = true;
        } catch (IOException e) {
            if (Parse.LOG_LEVEL_WARNING >= Parse.getLogLevel()) {
                log.log(Level.WARNING, "Unable to save command for later.", e);
            }
        } finally {
            lock.notifyAll();
        }
    }
    return tcs.getTask();
}

From source file:io.warp10.standalone.StandaloneIngressHandler.java

@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    String token = null;//w w  w.  java  2  s  .  c  o m

    if (target.equals(Constants.API_ENDPOINT_UPDATE)) {
        baseRequest.setHandled(true);
    } else if (target.startsWith(Constants.API_ENDPOINT_UPDATE + "/")) {
        baseRequest.setHandled(true);
        token = target.substring(Constants.API_ENDPOINT_UPDATE.length() + 1);
    } else if (target.equals(Constants.API_ENDPOINT_META)) {
        handleMeta(target, baseRequest, request, response);
        return;
    } else {
        return;
    }

    try {
        //
        // CORS header
        //

        response.setHeader("Access-Control-Allow-Origin", "*");

        long nano = System.nanoTime();

        //
        // Extract DatalogRequest if specified
        //

        String datalogHeader = request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_DATALOG));

        DatalogRequest dr = null;

        boolean forwarded = false;

        if (null != datalogHeader) {
            byte[] bytes = OrderPreservingBase64.decode(datalogHeader.getBytes(Charsets.US_ASCII));

            if (null != datalogPSK) {
                bytes = CryptoUtils.unwrap(datalogPSK, bytes);
            }

            if (null == bytes) {
                throw new IOException("Invalid Datalog header.");
            }

            TDeserializer deser = new TDeserializer(new TCompactProtocol.Factory());

            try {
                dr = new DatalogRequest();
                deser.deserialize(dr, bytes);
            } catch (TException te) {
                throw new IOException();
            }

            token = dr.getToken();

            Map<String, String> labels = new HashMap<String, String>();
            labels.put(SensisionConstants.SENSISION_LABEL_ID, new String(
                    OrderPreservingBase64.decode(dr.getId().getBytes(Charsets.US_ASCII)), Charsets.UTF_8));
            labels.put(SensisionConstants.SENSISION_LABEL_TYPE, dr.getType());
            Sensision.update(SensisionConstants.CLASS_WARP_DATALOG_REQUESTS_RECEIVED, labels, 1);
            forwarded = true;
        }

        //
        // TODO(hbs): Extract producer/owner from token
        //

        if (null == token) {
            token = request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_TOKENX));
        }

        WriteToken writeToken;

        try {
            writeToken = Tokens.extractWriteToken(token);
        } catch (WarpScriptException ee) {
            throw new IOException(ee);
        }

        String application = writeToken.getAppName();
        String producer = Tokens.getUUID(writeToken.getProducerId());
        String owner = Tokens.getUUID(writeToken.getOwnerId());

        Map<String, String> sensisionLabels = new HashMap<String, String>();
        sensisionLabels.put(SensisionConstants.SENSISION_LABEL_PRODUCER, producer);

        long count = 0;
        long total = 0;

        File loggingFile = null;
        PrintWriter loggingWriter = null;

        try {
            if (null == producer || null == owner) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid token.");
                return;
            }

            //
            // Build extra labels
            //

            Map<String, String> extraLabels = new HashMap<String, String>();

            // Add labels from the WriteToken if they exist
            if (writeToken.getLabelsSize() > 0) {
                extraLabels.putAll(writeToken.getLabels());
            }

            // Force internal labels
            extraLabels.put(Constants.PRODUCER_LABEL, producer);
            extraLabels.put(Constants.OWNER_LABEL, owner);
            // FIXME(hbs): remove me, apps should be set in all tokens now...
            if (null != application) {
                extraLabels.put(Constants.APPLICATION_LABEL, application);
                sensisionLabels.put(SensisionConstants.SENSISION_LABEL_APPLICATION, application);
            } else {
                // remove application label
                extraLabels.remove(Constants.APPLICATION_LABEL);
            }

            //
            // Determine if content if gzipped
            //

            boolean gzipped = false;

            if (null != request.getHeader("Content-Type")
                    && "application/gzip".equals(request.getHeader("Content-Type"))) {
                gzipped = true;
            }

            BufferedReader br = null;

            if (gzipped) {
                GZIPInputStream is = new GZIPInputStream(request.getInputStream());
                br = new BufferedReader(new InputStreamReader(is));
            } else {
                br = request.getReader();
            }

            //
            // Get the present time
            //

            Long now = TimeSource.getTime();

            //
            // Check the value of the 'now' header
            //
            // The following values are supported:
            //
            // A number, which will be interpreted as an absolute time reference,
            // i.e. a number of time units since the Epoch.
            //
            // A number prefixed by '+' or '-' which will be interpreted as a
            // delta from the present time.
            //
            // A '*' which will mean to not set 'now', and to recompute its value
            // each time it's needed.
            //

            String nowstr = null != dr ? dr.getNow()
                    : request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_NOW_HEADERX));

            if (null != nowstr) {
                if ("*".equals(nowstr)) {
                    now = null;
                } else if (nowstr.startsWith("+")) {
                    try {
                        long delta = Long.parseLong(nowstr.substring(1));
                        now = now + delta;
                    } catch (Exception e) {
                        throw new IOException("Invalid base timestamp.");
                    }
                } else if (nowstr.startsWith("-")) {
                    try {
                        long delta = Long.parseLong(nowstr.substring(1));
                        now = now - delta;
                    } catch (Exception e) {
                        throw new IOException("Invalid base timestamp.");
                    }
                } else {
                    try {
                        now = Long.parseLong(nowstr);
                    } catch (Exception e) {
                        throw new IOException("Invalid base timestamp.");
                    }
                }
            }

            //
            // Open the logging file if logging is enabled
            //

            if (null != loggingDir) {
                long nanos = null != dr ? dr.getTimestamp() : TimeSource.getNanoTime();
                StringBuilder sb = new StringBuilder();
                sb.append(Long.toHexString(nanos));
                sb.insert(0, "0000000000000000", 0, 16 - sb.length());
                sb.append("-");
                if (null != dr) {
                    sb.append(dr.getId());
                } else {
                    sb.append(datalogId);
                }

                sb.append("-");
                sb.append(dtf.print(nanos / 1000000L));
                sb.append(Long.toString(1000000L + (nanos % 1000000L)).substring(1));
                sb.append("Z");

                if (null == dr) {
                    dr = new DatalogRequest();
                    dr.setTimestamp(nanos);
                    dr.setType(Constants.DATALOG_UPDATE);
                    dr.setId(datalogId);
                    dr.setToken(token);

                    if (null == now) {
                        //
                        // We MUST force 'now', otherwise forwarded metrics will not have a
                        // coherent time. This alters the semantics slightly but make it
                        // coherent across the board.
                        //
                        now = TimeSource.getTime();
                    }
                    dr.setNow(Long.toString(now));
                }

                if (null != dr && (!forwarded || (forwarded && this.logforwarded))) {

                    //
                    // Serialize the request
                    //

                    TSerializer ser = new TSerializer(new TCompactProtocol.Factory());

                    byte[] encoded;

                    try {
                        encoded = ser.serialize(dr);
                    } catch (TException te) {
                        throw new IOException(te);
                    }

                    if (null != this.datalogPSK) {
                        encoded = CryptoUtils.wrap(this.datalogPSK, encoded);
                    }

                    encoded = OrderPreservingBase64.encode(encoded);

                    loggingFile = new File(loggingDir, sb.toString());

                    loggingWriter = new PrintWriter(new FileWriterWithEncoding(loggingFile, Charsets.UTF_8));

                    //
                    // Write request
                    //

                    loggingWriter.println(new String(encoded, Charsets.US_ASCII));
                }

                //
                // Force 'now'
                //

                now = Long.parseLong(dr.getNow());
            }

            //
            // Loop on all lines
            //

            GTSEncoder lastencoder = null;
            GTSEncoder encoder = null;

            //
            // Chunk index when archiving
            //

            do {

                String line = br.readLine();

                if (null == line) {
                    break;
                }

                line = line.trim();

                if (0 == line.length()) {
                    continue;
                }

                //
                // Ignore comments
                //

                if ('#' == line.charAt(0)) {
                    continue;
                }

                //
                // Check for pushback
                // TODO(hbs): implement the actual push back if we are over the subscribed limit
                //

                if (count % PUSHBACK_CHECK_INTERVAL == 0) {
                    Sensision.update(
                            SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_UPDATE_DATAPOINTS_RAW,
                            sensisionLabels, count);
                    total += count;
                    count = 0;
                }

                count++;

                try {
                    encoder = GTSHelper.parse(lastencoder, line, extraLabels, now, maxValueSize, false);
                    //nano2 += System.nanoTime() - nano0;
                } catch (ParseException pe) {
                    Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_UPDATE_PARSEERRORS,
                            sensisionLabels, 1);
                    throw new IOException("Parse error at '" + line + "'", pe);
                }

                if (encoder != lastencoder || lastencoder.size() > ENCODER_SIZE_THRESHOLD) {

                    //
                    // Check throttling
                    //

                    if (null != lastencoder) {

                        // 128BITS
                        lastencoder.setClassId(GTSHelper.classId(classKeyLongs, lastencoder.getName()));
                        lastencoder.setLabelsId(
                                GTSHelper.labelsId(labelsKeyLongs, lastencoder.getMetadata().getLabels()));

                        ThrottlingManager.checkMADS(lastencoder.getMetadata(), producer, owner, application,
                                lastencoder.getClassId(), lastencoder.getLabelsId());
                        ThrottlingManager.checkDDP(lastencoder.getMetadata(), producer, owner, application,
                                (int) lastencoder.getCount());
                    }

                    //
                    // Build metadata object to push
                    //

                    if (encoder != lastencoder) {
                        Metadata metadata = new Metadata(encoder.getMetadata());
                        metadata.setSource(Configuration.INGRESS_METADATA_SOURCE);
                        //nano6 += System.nanoTime() - nano0;
                        this.directoryClient.register(metadata);
                        //nano5 += System.nanoTime() - nano0;
                    }

                    if (null != lastencoder) {
                        this.storeClient.store(lastencoder);
                    }

                    if (encoder != lastencoder) {
                        lastencoder = encoder;
                    } else {
                        //lastencoder = null
                        //
                        // Allocate a new GTSEncoder and reuse Metadata so we can
                        // correctly handle a continuation line if this is what occurs next
                        //
                        Metadata metadata = lastencoder.getMetadata();
                        lastencoder = new GTSEncoder(0L);
                        lastencoder.setMetadata(metadata);
                    }
                }

                //
                // Write the line last, so we do not write lines which triggered exceptions
                //

                if (null != loggingWriter) {
                    loggingWriter.println(line);
                }
            } while (true);

            br.close();

            if (null != lastencoder && lastencoder.size() > 0) {
                // 128BITS
                lastencoder.setClassId(GTSHelper.classId(classKeyLongs, lastencoder.getName()));
                lastencoder
                        .setLabelsId(GTSHelper.labelsId(labelsKeyLongs, lastencoder.getMetadata().getLabels()));

                ThrottlingManager.checkMADS(lastencoder.getMetadata(), producer, owner, application,
                        lastencoder.getClassId(), lastencoder.getLabelsId());
                ThrottlingManager.checkDDP(lastencoder.getMetadata(), producer, owner, application,
                        (int) lastencoder.getCount());
                this.storeClient.store(lastencoder);
            }

            //
            // TODO(hbs): should we update the count in Sensision periodically so you can't trick the throttling mechanism?
            //
        } catch (WarpException we) {
            throw new IOException(we);
        } finally {
            this.storeClient.store(null);
            this.directoryClient.register(null);
            Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_UPDATE_DATAPOINTS_RAW,
                    sensisionLabels, count);
            Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_UPDATE_REQUESTS,
                    sensisionLabels, 1);
            Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_UPDATE_TIME_US,
                    sensisionLabels, (System.nanoTime() - nano) / 1000);

            if (null != loggingWriter) {
                Map<String, String> labels = new HashMap<String, String>();
                labels.put(SensisionConstants.SENSISION_LABEL_ID, new String(
                        OrderPreservingBase64.decode(dr.getId().getBytes(Charsets.US_ASCII)), Charsets.UTF_8));
                labels.put(SensisionConstants.SENSISION_LABEL_TYPE, dr.getType());
                Sensision.update(SensisionConstants.CLASS_WARP_DATALOG_REQUESTS_LOGGED, labels, 1);

                loggingWriter.close();
                loggingFile.renameTo(new File(loggingFile.getAbsolutePath() + DatalogForwarder.DATALOG_SUFFIX));
            }

            //
            // Update stats with CDN
            //

            String cdn = request.getHeader(Constants.OVH_CDN_GEO_HEADER);

            if (null != cdn) {
                sensisionLabels.put(SensisionConstants.SENSISION_LABEL_CDN, cdn);
                // Per CDN stat is updated at the end, so update with 'total' + 'count'
                Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_UPDATE_DATAPOINTS_RAW,
                        sensisionLabels, count + total);
                Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_UPDATE_REQUESTS,
                        sensisionLabels, 1);
                Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_UPDATE_TIME_US,
                        sensisionLabels, (System.nanoTime() - nano) / 1000);
            }
        }

        response.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
        if (!response.isCommitted()) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            return;
        }
    }
}

From source file:com.tvh.gmaildrafter.Drafter.java

private static void composeMail(Credentials credentials, String subjectText, String bodyText,
        String[] attachments, String[] attachmentnames, String[] destinations, String[] cc, String[] bcc,
        Boolean sendImmediately) throws IOException, AuthenticationFailedException {
    if (subjectText == null) {
        subjectText = "";
    }// www . jav  a  2 s . c  o  m
    if (bodyText == null) {
        bodyText = "";
    }

    try {
        Properties props = null;
        Session session = null;
        if (!sendImmediately) {
            props = System.getProperties();
            props.setProperty("mail.store.protocol", "imaps");
            session = Session.getDefaultInstance(props, null);
        } else {
            props = new Properties();
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");
            final String username = credentials.getUsername();
            final String password = credentials.getPassword();

            session = Session.getInstance(props, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
        }

        String signature = Signature.getSignature(credentials);
        if (signature == null)
            signature = "";

        // Create the message
        Message draftMail = new MimeMessage(session);
        draftMail.setSubject(subjectText);
        Multipart parts = new MimeMultipart();
        BodyPart body = new MimeBodyPart();

        if (bodyText.toLowerCase().indexOf("<body") < 0) // rough guess to see if the body is html
        {
            bodyText = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head><body>"
                    + StringEscapeUtils.escapeHtml(bodyText).replace("\n", "<br />" + "\n") + "<br>"
                    + "</body></html>";
        }

        if (signature != null && signature != "") {
            StringBuilder b = new StringBuilder(bodyText);
            if (signature.indexOf("</") < 0) // assume it's  html if there's no </, rough guess
            {
                signature = StringEscapeUtils.escapeHtml(signature);
            }
            b.replace(bodyText.lastIndexOf("</body>"), bodyText.lastIndexOf("</body>") + 7,
                    "<br>" + signature + "</body>");
            bodyText = b.toString();
        }

        body.setContent(bodyText, "text/html; charset=utf-8");

        body.setDisposition("inline");

        parts.addBodyPart(body);
        if (attachments != null) {
            for (int i = 0; i < attachments.length; i++) {
                BodyPart attachment = new MimeBodyPart();
                DataSource source = new FileDataSource(attachments[i]);
                attachment.setDataHandler(new DataHandler(source));
                if (attachmentnames != null && attachmentnames.length > i) {
                    attachment.setFileName(attachmentnames[i]);
                } else {
                    File file = new File(attachments[i]);
                    attachment.setFileName(file.getName());
                }
                parts.addBodyPart(attachment);
            }
        }
        draftMail.setContent(parts);
        if (destinations != null && destinations.length > 0)
            draftMail.setRecipients(Message.RecipientType.TO, stringToInternetAddress(destinations));
        if (cc != null && cc.length > 0)
            draftMail.setRecipients(Message.RecipientType.CC, stringToInternetAddress(cc));
        if (bcc != null && bcc.length > 0)
            draftMail.setRecipients(Message.RecipientType.BCC, stringToInternetAddress(bcc));
        draftMail.setFlag(Flags.Flag.SEEN, true);

        if (sendImmediately) {
            Transport.send(draftMail);
        } else {
            URLName url = new URLName("imaps://imap.gmail.com");
            IMAPSSLStore store = new IMAPSSLStore(session, url);
            store.connect(credentials.getUsername(), credentials.getPassword());

            Folder[] f = store.getDefaultFolder().xlist("*");
            long threadId = 0;
            for (Folder fd : f) {
                IMAPFolder folder = (IMAPFolder) fd;
                boolean thisIsDrafts = false;
                String atts[] = folder.getAttributes();
                for (String a : atts) {
                    if (a.equalsIgnoreCase("\\Drafts")) {
                        thisIsDrafts = true;
                        break;
                    }
                }

                if (thisIsDrafts) {

                    folder.open(Folder.READ_WRITE);

                    Message[] messages = new Message[1];
                    messages[0] = draftMail;
                    folder.appendMessages(messages);

                    /*
                    * Determine the Google Message Id, needed to open it in the
                    * browser. Because we just created the message it is
                    * reasonable to assume it is the last message in the draft
                    * folder. If this turns out not to be the case we could
                    * start creating the message with a random unique dummy
                    * subject, find it using that subject and then modify the
                    * subject to what it was supposed to be.
                    */
                    messages[0] = folder.getMessage(folder.getMessageCount());
                    FetchProfile fp = new FetchProfile();
                    fp.add(IMAPFolder.FetchProfileItem.X_GM_THRID);
                    folder.fetch(messages, fp);
                    IMAPMessage googleMessage = (IMAPMessage) messages[0];
                    threadId = googleMessage.getGoogleMessageThreadId();
                    folder.close(false);
                }
            }
            if (threadId == 0) {
                System.exit(6);
            }

            store.close();

            // Open the message in the default browser
            Runtime rt = Runtime.getRuntime();
            String drafturl = "https://mail.google.com/mail/#drafts/" + Long.toHexString(threadId);

            File chrome = new File("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe");
            if (!chrome.exists())
                chrome = new File("C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe");
            if (!chrome.exists()) {
                // Chrome not found, using default browser
                rt.exec("rundll32 url.dll,FileProtocolHandler " + drafturl);
            } else {
                String[] commandLine = new String[2];
                commandLine[0] = chrome.getPath();
                commandLine[1] = drafturl;
                rt.exec(commandLine);
            }

        } // else branch for sendImmediately

    } catch (NoSuchProviderException e) {
        e.printStackTrace();
        System.exit(4);
    } catch (AuthenticationFailedException e) {
        throw (e);
    } catch (MessagingException e) {

        e.printStackTrace();
        System.exit(5);
    }

}

From source file:org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher.java

/**
 * Called when there is a connection-related event via the Watcher callback.
 * <p>/*from w  w  w  . j  av  a  2s.  c  o m*/
 * If Disconnected or Expired, this should shutdown the cluster. But, since
 * we send a KeeperException.SessionExpiredException along with the abort
 * call, it's possible for the Abortable to catch it and try to create a new
 * session with ZooKeeper. This is what the client does in HCM.
 * <p>
 * @param event
 */
private void connectionEvent(WatchedEvent event) {
    switch (event.getState()) {
    case SyncConnected:
        // Now, this callback can be invoked before the this.zookeeper is set.
        // Wait a little while.
        long finished = System.currentTimeMillis()
                + this.conf.getLong("hbase.zookeeper.watcher.sync.connected.wait", 2000);
        while (System.currentTimeMillis() < finished) {
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                LOG.warn("Interrupted while sleeping");
                throw new RuntimeException("Interrupted while waiting for" + " recoverableZooKeeper is set");
            }
            if (this.recoverableZooKeeper != null)
                break;
        }

        if (this.recoverableZooKeeper == null) {
            LOG.error(
                    "ZK is null on connection event -- see stack trace "
                            + "for the stack trace when constructor was called on this zkw",
                    this.constructorCaller);
            throw new NullPointerException("ZK is null");
        }
        this.identifier = this.identifier + "-0x" + Long.toHexString(this.recoverableZooKeeper.getSessionId());
        // Update our identifier.  Otherwise ignore.
        LOG.debug(this.identifier + " connected");
        break;

    // Abort the server if Disconnected or Expired
    case Disconnected:
        LOG.debug(prefix("Received Disconnected from ZooKeeper, ignoring"));
        break;

    case Expired:
        String msg = prefix(this.identifier + " received expired from " + "ZooKeeper, aborting");
        // TODO: One thought is to add call to ZooKeeperListener so say,
        // ZooKeeperNodeTracker can zero out its data values.
        if (this.abortable != null) {
            this.abortable.abort(msg, new KeeperException.SessionExpiredException());
        }
        break;

    case ConnectedReadOnly:
    case SaslAuthenticated:
    case AuthFailed:
        break;

    default:
        throw new IllegalStateException("Received event is not valid: " + event.getState());
    }
}

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

private boolean handleEvent(ByteBuffer eventQueue) {

    Eventable eventable;/*from   ww  w . ja  va2 s.  co  m*/
    int eventType = eventQueue.getInt();
    long id = eventQueue.getLong();
    boolean userNotified = false;
    switch (eventType) {

    case 0: // session error event
    {
        int errorType = eventQueue.getInt();
        int reason = eventQueue.getInt();
        EventSession evSes = new EventSession(eventType, id, errorType, reason);
        synchronized (eventables) {
            eventable = eventables.get(id);
        }
        if (eventable == null) {
            LOG.warn(
                    this.toLogString() + "eventable with id " + Long.toHexString(id) + " was not found in map");
            break;
        }
        userNotified = eventable.onEvent(evSes);
    }
        break;

    case 1: // msg error server
    {

        // msg was added to msgsPendingNewRequest after sendResponce. the real lookup of the Msg is done on C
        // side. msgsPendingNewRequest is used for look up of the java object based on the id
        Msg msg = this.msgsPendingNewRequest.remove(id);
        final long session_id = eventQueue.getLong();
        final int reason = eventQueue.getInt();
        eventable = eventables.get(session_id);
        if (eventable == null) {
            LOG.warn(this.toLogString() + "eventable with id " + Long.toHexString(session_id)
                    + " was not found in map");
            break;
        }
        EventMsgError evMsgErr = new EventMsgError(eventType, id, msg, reason);
        userNotified = eventable.onEvent(evMsgErr);
    }
        break;

    case 2: // msg error client
    {
        Msg msg = msgsPendingReply.remove(id);
        final int reason = eventQueue.getInt();
        EventMsgError evMsgErr = new EventMsgError(eventType, id, msg, reason);
        eventable = msg.getClientSession();
        userNotified = eventable.onEvent(evMsgErr);

    }
        break;

    case 3: // session established
    {
        EventSessionEstablished evSesEstab = new EventSessionEstablished(eventType, id);
        eventable = eventables.get(id);
        if (eventable == null) {
            LOG.warn(
                    this.toLogString() + "eventable with id " + Long.toHexString(id) + " was not found in map");
            break;
        }
        userNotified = eventable.onEvent(evSesEstab);
    }
        break;

    case 4: // on request (server side)
    {
        Msg msg = this.msgsPendingNewRequest.remove(id);
        msg.resetPositions();
        final int msg_in_size = eventQueue.getInt();
        msg.getIn().limit(msg_in_size);
        int msg_out_size = eventQueue.getInt();
        if (msg_out_size > msg.getOut().capacity())
            msg_out_size = msg.getOut().capacity();
        msg.getOut().limit(msg_out_size);
        final long session_id = eventQueue.getLong();
        if (LOG.isTraceEnabled()) {
            LOG.trace(this.toLogString() + "session refToCObject " + Long.toHexString(session_id));
        }
        eventable = eventables.get(session_id);
        if (eventable == null) {
            LOG.warn(this.toLogString() + "eventable with id " + Long.toHexString(session_id)
                    + " was not found in map");
            break;
        }
        EventNewMsg evMsg = new EventNewMsg(eventType, id, msg);
        userNotified = eventable.onEvent(evMsg);
    }
        break;

    case 5: // on response (client side)
    {
        Msg msg = msgsPendingReply.remove(id);
        final int msg_size = eventQueue.getInt();
        msg.getIn().limit(msg_size);
        if (LOG.isTraceEnabled()) {
            LOG.trace(this.toLogString() + "got msg " + msg);
        }
        EventNewMsg evMsg = new EventNewMsg(eventType, id, msg);
        eventable = msg.getClientSession();
        if (LOG.isTraceEnabled()) {
            LOG.trace(this.toLogString() + "eventable is " + eventable);
        }
        userNotified = eventable.onEvent(evMsg);
    }
        break;

    case 6: // on new session
    {
        long ptrSes = eventQueue.getLong();
        String uri = readString(eventQueue);
        String srcIP = readString(eventQueue);

        synchronized (eventables) {
            eventable = eventables.get(id);
        }
        if (eventable == null) {
            LOG.warn(
                    this.toLogString() + "eventable with id " + Long.toHexString(id) + " was not found in map");
            break;
        }
        EventNewSession evNewSes = new EventNewSession(eventType, id, ptrSes, uri, srcIP);
        userNotified = eventable.onEvent(evNewSes);
    }
        break;

    case 8: // on fd ready
    {
        /*
         * int fd = eventQueue.getInt(); int events = eventQueue.getInt();
         */
        LOG.error(this.toLogString() + "received FD Ready event - not handled");
    }
        break;

    default:
        LOG.error(this.toLogString() + "received an unknown event " + eventType);
        // TODO: throw exception
    }
    return userNotified;
}

From source file:interactivespaces.liveactivity.runtime.standalone.StandaloneActivityRunner.java

/**
 * Get a live activity instance./*from  ww  w  .j av  a  2s . c o  m*/
 *
 * @return installed live activity instance
 */
private InstalledLiveActivity getLiveActivity() {
    final InstalledLiveActivity liveActivity = new SimpleInstalledLiveActivity();

    Date installedDate = new Date(controller.getSpaceEnvironment().getTimeProvider().getCurrentTime());

    File activityFile = activityFilesystem.getInstallFile("activity.xml");

    InputStream activityDescriptionStream = null;
    Version version;
    String identifyingName;
    try {
        activityDescriptionStream = new FileInputStream(activityFile);
        ActivityDescriptionReader reader = new JdomActivityDescriptionReader();
        ActivityDescription activityDescription = reader.readDescription(activityDescriptionStream);
        version = Version.parseVersion(activityDescription.getVersion());
        identifyingName = activityDescription.getIdentifyingName();
    } catch (Exception e) {
        throw new InteractiveSpacesException(
                "Could not read activity file description from " + activityFile.getAbsolutePath(), e);
    } finally {
        Closeables.closeQuietly(activityDescriptionStream);
    }

    liveActivity.setUuid(Long.toHexString((long) (Math.random() * RANDOM_UUID_MAX)));
    liveActivity.setBaseInstallationLocation(activityFilesystem.getInstallDirectory().getAbsolutePath());
    liveActivity.setIdentifyingName(identifyingName);
    liveActivity.setVersion(version);
    liveActivity.setLastDeployedDate(installedDate);
    liveActivity.setLastActivityState(ActivityState.READY);
    liveActivity.setInstallationStatus(ActivityInstallationStatus.OK);
    liveActivity.setRuntimeStartupType(ActivityRuntimeStartupType.READY);

    return liveActivity;
}

From source file:functionaltests.RestSmartProxyTest.java

private String uniqueSessionId() {
    return String.format("TEST_SID_%s", Long.toHexString(System.currentTimeMillis()));
}

From source file:com.livinglogic.ul4.FunctionFormat.java

public static String call(long obj, String formatString, Locale locale) {
    IntegerFormat format = new IntegerFormat(formatString);

    if (locale == null)
        locale = Locale.ENGLISH;//from   www. ja va2  s .  c  o  m

    String output = null;

    boolean neg = obj < 0;
    if (neg)
        obj = -obj;

    switch (format.type) {
    case 'b':
        output = Long.toBinaryString(obj);
        break;
    case 'c':
        if (neg || obj > 0xffff)
            throw new RuntimeException("value out of bounds for c format");
        output = Character.toString((char) obj);
        break;
    case 'd':
        output = Long.toString(obj);
        break;
    case 'o':
        output = Long.toOctalString(obj);
        break;
    case 'x':
        output = Long.toHexString(obj);
        break;
    case 'X':
        output = Long.toHexString(obj).toUpperCase();
        break;
    case 'n':
        // FIXME: locale formatting
        output = Long.toString(obj);
        break;
    }
    return formatIntegerString(output, neg, format);
}