Example usage for org.apache.commons.codec.binary Base64 encodeBase64Chunked

List of usage examples for org.apache.commons.codec.binary Base64 encodeBase64Chunked

Introduction

In this page you can find the example usage for org.apache.commons.codec.binary Base64 encodeBase64Chunked.

Prototype

public static byte[] encodeBase64Chunked(final byte[] binaryData) 

Source Link

Document

Encodes binary data using the base64 algorithm and chunks the encoded output into 76 character blocks

Usage

From source file:com.zimbra.cs.service.formatter.VCard.java

public static VCard formatContact(Contact con, Collection<String> vcattrs, boolean includeXProps,
        boolean includeZimbraXProps) {
    Map<String, String> fields = con.getFields();
    List<Attachment> attachments = con.getAttachments();
    List<String> emails = con.getEmailAddresses(DerefGroupMembersOption.NONE);

    StringBuilder sb = new StringBuilder();
    sb.append("BEGIN:VCARD\r\n");

    // This is from RFC 2426 (vCard version 3.0) Section 1:
    // Profile special notes: The vCard object MUST contain the FN, N and VERSION types.

    if (vcattrs == null || vcattrs.contains("VERSION"))
        sb.append("VERSION:3.0\r\n");

    // FN is a mandatory component of the vCard -- try our best to find or generate one
    String fn = fields.get(ContactConstants.A_fullName);
    if (vcattrs == null || vcattrs.contains("FN")) {
        if (fn == null || fn.trim().equals(""))
            try {
                fn = con.getFileAsString();
            } catch (ServiceException e) {
                fn = "";
            }//from  w w w.ja  v a  2 s . c o  m
        if (fn.trim().equals("") && !emails.isEmpty())
            fn = emails.get(0);
        if (fn.trim().equals("")) {
            String org = fields.get(ContactConstants.A_company);
            if (org != null && !org.trim().equals("")) {
                fn = org;
            }
        }
        sb.append("FN:").append(vcfEncode(fn)).append("\r\n");
    }

    if (vcattrs == null || vcattrs.contains("N")) {
        StringBuilder nSb = new StringBuilder();
        nSb.append(vcfEncode(fields.get(ContactConstants.A_lastName))).append(';')
                .append(vcfEncode(fields.get(ContactConstants.A_firstName))).append(';')
                .append(vcfEncode(fields.get(ContactConstants.A_middleName))).append(';')
                .append(vcfEncode(fields.get(ContactConstants.A_namePrefix))).append(';')
                .append(vcfEncode(fields.get(ContactConstants.A_nameSuffix)));
        String n = nSb.toString();
        // N is mandatory according to  RFC 2426 Section 1, so include it even if all components are empty
        // In fact, clients like Mac OS X Mavericks Contacts will just have blank names if it is blank,
        // so, try to avoid that.
        if (";;;;".equals(n)) {
            n = vcfEncode(fn) + ";;;;";
        }
        sb.append("N:").append(n).append("\r\n");
    }

    if (vcattrs == null || vcattrs.contains("NICKNAME"))
        encodeField(sb, "NICKNAME", fields.get(ContactConstants.A_nickname));
    if (vcattrs == null || vcattrs.contains("PHOTO"))
        encodeField(sb, "PHOTO;VALUE=URI", fields.get(ContactConstants.A_image));
    if (vcattrs == null || vcattrs.contains("BDAY")) {
        String bday = fields.get(ContactConstants.A_birthday);
        if (bday != null) {
            Date date = DateUtil.parseDateSpecifier(bday);
            if (date != null)
                sb.append("BDAY;VALUE=date:").append(new SimpleDateFormat("yyyy-MM-dd").format(date))
                        .append("\r\n");
        }
    }

    if (vcattrs == null || vcattrs.contains("ADR")) {
        encodeAddress(sb, "home,postal,parcel", ContactConstants.A_homeStreet, ContactConstants.A_homeCity,
                ContactConstants.A_homeState, ContactConstants.A_homePostalCode, ContactConstants.A_homeCountry,
                2, fields);
        encodeAddress(sb, "work,postal,parcel", ContactConstants.A_workStreet, ContactConstants.A_workCity,
                ContactConstants.A_workState, ContactConstants.A_workPostalCode, ContactConstants.A_workCountry,
                2, fields);
        encodeAddress(sb, "postal,parcel", ContactConstants.A_otherStreet, ContactConstants.A_otherCity,
                ContactConstants.A_otherState, ContactConstants.A_otherPostalCode,
                ContactConstants.A_otherCountry, 2, fields);
    }

    if (vcattrs == null || vcattrs.contains("TEL")) {
        // omitting callback phone for now
        encodePhone(sb, "car,voice", ContactConstants.A_carPhone, 2, fields);
        encodePhone(sb, "home,fax", ContactConstants.A_homeFax, 2, fields);
        encodePhone(sb, "home,voice", ContactConstants.A_homePhone, 2, fields);
        encodePhone(sb, "cell,voice", ContactConstants.A_mobilePhone, 2, fields);
        encodePhone(sb, "fax", ContactConstants.A_otherFax, 2, fields);
        encodePhone(sb, "voice", ContactConstants.A_otherPhone, 2, fields);
        encodePhone(sb, "pager", ContactConstants.A_pager, 2, fields);
        encodePhone(sb, "work,fax", ContactConstants.A_workFax, 2, fields);
        encodePhone(sb, "work,voice", ContactConstants.A_workPhone, 2, fields);
    }

    if (vcattrs == null || vcattrs.contains("EMAIL")) {
        encodeField(sb, "EMAIL;TYPE=internet", ContactConstants.A_email, false, 2, fields);
        encodeField(sb, "EMAIL;TYPE=internet", "workEmail", true, 1, fields);
    }

    if (vcattrs == null || vcattrs.contains("URL")) {
        encodeField(sb, "URL;TYPE=home", ContactConstants.A_homeURL, false, 2, fields);
        encodeField(sb, "URL", ContactConstants.A_otherURL, false, 2, fields);
        encodeField(sb, "URL;TYPE=work", ContactConstants.A_workURL, false, 2, fields);
    }

    if (vcattrs == null || vcattrs.contains("ORG")) {
        String org = fields.get(ContactConstants.A_company);
        if (org != null && !org.trim().equals("")) {
            org = vcfEncode(org);
            String dept = fields.get(ContactConstants.A_department);
            if (dept != null && !dept.trim().equals("")) {
                org += ';' + vcfEncode(dept);
            }
            sb.append("ORG:").append(org).append("\r\n");
        }
    }
    if (vcattrs == null || vcattrs.contains("TITLE"))
        encodeField(sb, "TITLE", fields.get(ContactConstants.A_jobTitle));

    if (vcattrs == null || vcattrs.contains("NOTE"))
        encodeField(sb, "NOTE", fields.get(ContactConstants.A_notes));

    if ((vcattrs == null || vcattrs.contains("PHOTO")) && attachments != null) {
        for (Attachment attach : attachments) {
            try {
                if (attach.getName().equalsIgnoreCase(ContactConstants.A_image)) {
                    String field = "PHOTO;ENCODING=B";
                    if (attach.getContentType().startsWith("image/")) {
                        // We want just the subtype, ignoring any name etc
                        try {
                            ContentType ct = new ContentType(attach.getContentType());
                            if (ct != null) {
                                String subType = ct.getSubType();
                                if (!Strings.isNullOrEmpty(subType)) {
                                    field += ";TYPE=" + ct.getSubType().toUpperCase();
                                }
                            }
                        } catch (ParseException e) {
                        }
                    }
                    String encoded = new String(Base64.encodeBase64Chunked(attach.getContent())).trim()
                            .replace("\r\n", "\r\n ");
                    sb.append(field).append(":\r\n ").append(encoded).append("\r\n");
                }
            } catch (OutOfMemoryError e) {
                Zimbra.halt("out of memory", e);
            } catch (Throwable t) {
                ZimbraLog.misc.info("error fetching attachment content: " + attach.getName(), t);
            }
        }
    }

    if (vcattrs == null || vcattrs.contains("KEY")) {
        String smimeCert = fields.get(ContactConstants.A_userSMIMECertificate);
        if (smimeCert == null) {
            smimeCert = fields.get(ContactConstants.A_userCertificate);
        }
        if (smimeCert != null) {
            smimeCert = smimeCert.trim().replace("\r\n", "\r\n ");
            String field = "KEY;ENCODING=B";
            sb.append(field).append(":\r\n ").append(smimeCert).append("\r\n");
        }
    }

    if (vcattrs == null || vcattrs.contains("CATEGORIES")) {
        String[] tags = con.getTags();
        if (tags.length > 0) {
            StringBuilder sbtags = new StringBuilder();
            for (String tagName : tags) {
                sbtags.append(sbtags.length() == 0 ? "" : ",").append(vcfEncode(tagName));
            }
            sb.append("CATEGORIES:").append(sbtags).append("\r\n");
        }
    }

    String uid = getUid(con);
    if (vcattrs == null || vcattrs.contains("REV")) {
        sb.append("REV:")
                .append(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(new Date(con.getDate())))
                .append("\r\n");
    }
    if (vcattrs == null || vcattrs.contains("UID")) {
        sb.append("UID:").append(uid).append("\r\n");
    }
    // sb.append("MAILER:Zimbra ").append(BuildInfo.VERSION).append("\r\n");
    if ((vcattrs == null && includeZimbraXProps)
            || (vcattrs != null && vcattrs.contains("X-ZIMBRA-IMADDRESS"))) {
        encodeField(sb, "X-ZIMBRA-IMADDRESS", "imAddress", true, 1, fields);
    }
    if ((vcattrs == null && includeZimbraXProps)
            || (vcattrs != null && vcattrs.contains("X-ZIMBRA-ANNIVERSARY"))) {
        encodeField(sb, "X-ZIMBRA-ANNIVERSARY", ContactConstants.A_anniversary, false, 2, fields);
    }
    if ((vcattrs == null && includeZimbraXProps)
            || (vcattrs != null && vcattrs.contains("X-ZIMBRA-MAIDENNAME"))) {
        String maidenName = con.get(ContactConstants.A_maidenName);
        if (maidenName != null)
            sb.append("X-ZIMBRA-MAIDENNAME:").append(maidenName).append("\r\n");
    }
    if (includeXProps) {
        ListMultimap<String, VCardParamsAndValue> unknownVCardProps = con.getUnknownVCardProps();
        for (String key : unknownVCardProps.keySet()) {
            for (VCardParamsAndValue paramsAndValue : unknownVCardProps.get(key)) {
                StringWriter sw = new StringWriter();
                try (FoldingWriter writer = new FoldingWriter(sw)) {
                    writer.write(key);
                    String value = paramsAndValue.getValue();
                    Set<String> params = paramsAndValue.getParams();
                    if (!params.isEmpty()) {
                        writer.write(";");
                        writer.write(Joiner.on(";").join(params));
                    }
                    String vcfEncodedValue;
                    if (params.contains("ENCODING=B")) {
                        vcfEncodedValue = value; // should be raw BASE64
                    } else {
                        vcfEncodedValue = vcfEncode(value);
                    }
                    writer.write(":");
                    writer.write(vcfEncodedValue);
                    writer.write("\r\n");
                    sb.append(sw.toString());
                } catch (IOException e) {
                    ZimbraLog.misc.debug("Problem with adding property '%s' to VCARD - ignoring", key, e);
                }
            }
        }
    }
    sb.append("END:VCARD\r\n");
    return new VCard(fn, sb.toString(), fields, attachments, uid);
}

From source file:com.voxbone.kelpie.Session.java

public void packetTransferred(PacketEvent evt) {
    try {/*from   w  ww  .j a  va 2  s. c o  m*/
        JID local = evt.getData().getTo();
        JID remote = evt.getData().getFrom();

        logger.debug("[[" + internalCallId + "]] got message of " + evt.getData().getQualifiedName());

        if (evt.getData().getQualifiedName().equals("db:result")) {
            String type = evt.getData().getAttributeValue("type");
            if (type != null && type.length() > 0) {
                synchronized (this) {
                    confirm();
                    while (!queue.isEmpty()) {
                        conn.send(queue.remove(0));
                    }
                }
                return;
            }

            String result = evt.getData().normalizeText();
            evt.setHandled(true);

            // this isn't a dialback connection - add it to the list of connections
            // we don't save this because it can only be used for inbound stuff
            //SessionManager.addSession(this);

            logger.debug("[[" + internalCallId + "]] Got a result response: " + evt.getData().normalizeText());
            logger.debug("[[" + internalCallId + "]] Packet is of type: " + evt.getData().getClass().getName());

            DialbackSession dbs = new DialbackSession(internalCallId, local, remote,
                    conn.getOutboundContext().getID(), result);

            boolean valid = dbs.doDialback();
            Packet p = null;
            if (valid) {
                logger.debug("[[" + internalCallId + "]] Session is valid!");
                p = conn.getDataFactory().createPacketNode(new NSI("result", "jabber:server:dialback"),
                        Packet.class);
                p.setFrom(local);
                p.setTo(remote);
                p.setAttributeValue("type", "valid");
                confirm();
            } else {
                logger.debug("[[" + internalCallId + "]] Session is NOT valid!");
                p = conn.getDataFactory().createPacketNode(new NSI("result", "jabber:server:dialback"),
                        Packet.class);
                p.setFrom(local);
                p.setTo(remote);
                p.setAttributeValue("type", "invalid");
            }

            try {
                conn.send(p);
            } catch (StreamException e) {
                logger.error("Error sending packet!", e);
            }

            if (!valid) {
                // close the stream if invalid
                conn.close();
            }
        } else if (evt.getData().getQualifiedName().equals("db:verify")) {
            String key = evt.getData().normalizeText();
            // if we get a db:verify here and n
            logger.debug("[[" + internalCallId + "]] Got a verification token " + key);
            Session sess = SessionManager.getSession(evt.getData().getFrom());

            boolean valid = false;
            if (sess != null) {
                logger.debug("[[" + internalCallId + "]] Found matching session");

                if (key.equals(sess.getSessionKey())) {
                    logger.debug("[[" + internalCallId + "]] Keys Match! Sending the ok");
                    valid = true;
                }
            }

            Packet p;
            if (valid) {
                logger.debug("[[" + internalCallId + "]] Session is valid!");
                p = conn.getDataFactory().createPacketNode(new NSI("verify", "jabber:server:dialback"),
                        Packet.class);
                p.setFrom(local);
                p.setTo(remote);
                p.setID(evt.getData().getID());
                p.setAttributeValue("type", "valid");
            } else {
                logger.debug("[[" + internalCallId + "]] Session is NOT valid!");
                p = conn.getDataFactory().createPacketNode(new NSI("verify", "jabber:server:dialback"),
                        Packet.class);
                p.setFrom(local);
                p.setTo(remote);
                p.setAttributeValue("type", "invalid");
            }

            try {
                conn.send(p);
            } catch (StreamException e) {
                logger.error("Steam error in session", e);
            }

        } else if (evt.getData().getQualifiedName().equals(":message")
                && evt.getData().getAttributeValue("type") != null)
        //&& evt.getData().getAttributeValue("type").equals("chat"))
        {
            if (evt.getData().getAttributeValue("type").equals("error")) {
                logger.debug("[[" + internalCallId + "]] got an MESSAGE error ");
                // should we notify this error to the sender?
            } else if (evt.getData().getAttributeValue("type").equals("chat")) {
                logger.debug("[[" + internalCallId + "]] Got an IM");

                StreamElement body = evt.getData().getFirstElement("body");
                if (body != null) {
                    String msg = body.normalizeText();
                    logger.debug("[[" + internalCallId + "]] Body=" + msg);

                    MessageMessage mm = new MessageMessage(evt.getData());

                    if (msg.equals("callback")) {
                        CallSession cs = new CallSession();
                        logger.debug("[[" + internalCallId + "]] created call session : [[" + cs.internalCallId
                                + "]]");

                        cs.offerPayloads.add(CallSession.PAYLOAD_PCMU);
                        cs.offerPayloads.add(CallSession.PAYLOAD_PCMA);

                        Session sess = SessionManager.findCreateSession(cs.jabberLocal.getDomain(),
                                cs.jabberRemote);

                        sess.startCall(cs, evt.getData().getTo().getNode(),
                                UriMappings.toSipId(evt.getData().getFrom()));
                    }

                    else if (msg.toLowerCase().startsWith("/dtmf:") || msg.toLowerCase().startsWith("/dial:")) {
                        logger.debug("[[" + internalCallId + "]] DIAL command detected");
                        CallSession cs = CallManager.getSession(evt.getData().getFrom(), evt.getData().getTo());
                        if (cs != null) {
                            logger.debug("[[" + internalCallId + "]] got call session : [[" + cs.internalCallId
                                    + "]]");
                            logger.debug("[[" + internalCallId + "]] Call found, sending dtmfs");
                            for (int i = "/dial:".length(); i < msg.length(); i++) {
                                if (useDtmfInfo) {
                                    SipService.sendDTMFinfo(cs, msg.charAt(i), dtmfDuration);
                                } else {
                                    cs.relay.sendSipDTMF(msg.charAt(i));

                                }
                            }
                        }
                    }

                    else if (msg.equals("/echo") || msg.startsWith("/echo")) {
                        logger.debug("[[" + internalCallId + "]] Got an ECHO request");
                        Packet p = conn.getDataFactory().createPacketNode(new NSI("message", "jabber:server"),
                                Packet.class);

                        p.setFrom(evt.getData().getTo());
                        p.setTo(evt.getData().getFrom());
                        p.setID(evt.getData().getID());
                        p.addElement("body");
                        String echo = msg.substring(msg.lastIndexOf('/') + 5);
                        p.getFirstElement("body").addText("Echo: " + echo);
                        p.setAttributeValue("type", "chat");
                        p.setAttributeValue("iconset", "round");
                        // initial experiment with chatstates
                        StreamElement chatstate = conn.getDataFactory()
                                .createElementNode(new NSI("active", "http://jabber.org/protocol/chatstates"));
                        p.add(chatstate);
                        Session sess = SessionManager.findCreateSession(evt.getData().getTo().getDomain(),
                                evt.getData().getFrom());
                        sess.sendPacket(p);
                    } else if (msg.equals("/me") || msg.startsWith("/me")) {

                        String slashme = msg.substring(msg.lastIndexOf('/') + 3);
                        StreamElement newbody = conn.getDataFactory()
                                .createElementNode(new NSI("body", slashme));
                        body = newbody;
                        logger.debug("[[" + internalCallId + "]] Got a SLASHME request:");
                        String domain = host;

                        SipSubscription sub = SipSubscriptionManager.getWatcher(mm.from, mm.to);
                        if (sub != null) {
                            domain = ((SipURI) sub.remoteParty.getURI()).getHost();
                        }
                        SipService.sendMessageMessage(mm, domain);

                    }

                    else {
                        /* Forward the message to SIP side */
                        /* For coherence, we try to use the domain he has used in his subscription */
                        String domain = host;

                        SipSubscription sub = SipSubscriptionManager.getWatcher(mm.from, mm.to);
                        if (sub != null) {
                            domain = ((SipURI) sub.remoteParty.getURI()).getHost();
                        }
                        SipService.sendMessageMessage(mm, domain);
                    }
                }
            }

        }

        else if (evt.getData().getQualifiedName().equals(":presence")) {
            logger.debug("[[" + internalCallId + "]] Got presence stanza");
            String type = evt.getData().getAttributeValue("type");

            if (type == null || type.equals("unavailable")) {
                logger.debug(
                        "[[" + internalCallId + "]] Got a presence message from " + evt.getData().getFrom());

                StreamElement caps = evt.getData()
                        .getFirstElement(new NSI("c", "http://jabber.org/protocol/caps"));

                if (caps != null && caps.getAttributeValue("ext") != null) {
                    logger.debug("[[" + internalCallId + "]] Caps found");
                    if (caps.getAttributeValue("ext").contains("voice-v1")) {
                        logger.debug("[[" + internalCallId + "]] Voice support detected, taking note");
                        UriMappings.addVoiceResource(evt.getData().getFrom());
                    }
                    /*
                    if (caps.getAttributeValue("ext").contains("video-v1"))
                    {
                       logger.debug("[[" + internalCallId + "]] Video support detected, not taking note");
                    }
                            
                    if (caps.getAttributeValue("ext").contains("vainvite-v1"))
                    {
                       logger.debug("[[" + internalCallId + "]] 'vainvite' undocumented feature. Ignored for now. [" + evt.getData().getFrom() + "]" );
                    }
                    */
                }
                Presence pres = new Presence(evt.getData());
                String from = UriMappings.toSipId(evt.getData().getFrom());
                String to = evt.getData().getTo().getNode();
                SipSubscription sub = SipSubscriptionManager.getWatcher(from, to);
                if (sub != null) {
                    logger.debug("[[" + internalCallId + "]] Found matching subscription! Sending NOTIFY");
                    sub.sendNotify(false, pres);
                }
            } else {
                if (type.equals("subscribe")) {
                    logger.debug("[[" + internalCallId + "]] New subscription received from "
                            + evt.getData().getFrom());
                    String from = UriMappings.toSipId(evt.getData().getFrom());
                    String to = evt.getData().getTo().getNode();

                    if (!to.equals(fakeId)) {
                        SipSubscription sub = SipSubscriptionManager.getSubscription(from, to);
                        if (sub == null) {
                            logger.debug("[[" + internalCallId + "]] No existing subscription, sending one");
                            sub = new SipSubscription(from, to);
                            SipSubscriptionManager.addSubscriber(from, sub);
                            sub.sendSubscribe(false);
                        } else if (sub.remoteTag != null) {
                            logger.debug("[[" + internalCallId + "]] Subscription exists, sending refresh");
                            sub.sendSubscribe(false);
                        }
                    } else {
                        logger.debug("[[" + internalCallId + "]] Subscription to " + fakeId
                                + ", sending dummy accept");
                        Session sess = SessionManager.findCreateSession(host, evt.getData().getFrom());
                        sess.sendSubscribeRequest(new JID(fakeId + "@" + host), evt.getData().getFrom(),
                                "subscribed");
                    }
                } else if (type.equals("unsubscribe")) {
                    logger.debug("[[" + internalCallId + "]] Unsubscribe  request");

                    String from = UriMappings.toSipId(evt.getData().getFrom());
                    String to = evt.getData().getTo().getNode();
                    if (!to.equals(fakeId)) {
                        SipSubscription sub = SipSubscriptionManager.removeSubscription(from, to);
                        if (sub != null) {
                            logger.debug("[[" + internalCallId + "]] Removing subscription");
                            sub.sendSubscribe(true);
                        }

                        sub = SipSubscriptionManager.getWatcher(from, to);
                        if (sub != null) {
                            logger.debug("[[" + internalCallId + "]] Removing watcher");
                            SipSubscriptionManager.removeWatcher(from, sub);
                            sub.sendNotify(true, null);
                        }
                    }

                } else if (type.equals("subscribed")) {
                    logger.debug(
                            "[[" + internalCallId + "]] Jabber client accepted subscription, sending notify");
                    String from = UriMappings.toSipId(evt.getData().getFrom());
                    String to = evt.getData().getTo().getNode();
                    if (!to.equals(fakeId)) {
                        SipSubscription sub = SipSubscriptionManager.getWatcher(from, to);
                        sub.sendNotify(false, null);
                    }
                } else if (type.equals("probe")) {
                    String from = UriMappings.toSipId(evt.getData().getFrom());
                    String to = evt.getData().getTo().getNode();
                    logger.debug("[[" + internalCallId + "]] Probe received from " + from + " to " + to);

                    if (to.equals(fakeId) || subscribeEmu) {
                        // subscribe emulation is forced or fake, send a dummy presence stanza + subscribed status
                        Session sess = SessionManager.findCreateSession(host, evt.getData().getFrom());

                        if (subscribeEmu) {
                            logger.debug("[[" + internalCallId + "]] Probe from " + from
                                    + ", sending emulated presence from " + to);
                            sess.sendSubscribeRequest(new JID(to + "@" + host), evt.getData().getFrom(),
                                    "subscribed");
                            sess.sendPresence(Presence.buildOnlinePresence(to, from, host));
                        } else {
                            logger.debug("[[" + internalCallId + "]] Probe to " + fakeId
                                    + ", sending dummy presence to " + from);
                            sess.sendSubscribeRequest(new JID(fakeId + "@" + host), evt.getData().getFrom(),
                                    "subscribed");
                            sess.sendPresence(Presence.buildOnlinePresence(fakeId, from, host));
                        }

                    } else if (!to.equals(fakeId)) {
                        SipSubscription sub = SipSubscriptionManager.getSubscription(from, to);
                        if (sub != null) {
                            logger.debug(
                                    "[[" + internalCallId + "]] Found a subscription, sending re-subscribe");
                            sub.sendSubscribe(false);
                        } else {
                            logger.debug("[[" + internalCallId
                                    + "]] No Subscription for this person, sending 0 length one");
                            sub = new SipSubscription(from, to);
                            SipSubscriptionManager.addSubscriber(from, sub);
                            sub.sendSubscribe(false);
                        }

                    }

                }
            }
        } else if (evt.getData().getQualifiedName().equals(":iq")) {
            Packet packet = evt.getData();
            logger.debug("[[" + internalCallId + "]] got disco packet");
            if (packet.getAttributeValue("type").equals("get") && packet.getFirstElement().getNSI()
                    .equals(new NSI("query", "http://jabber.org/protocol/disco#info"))) {
                logger.debug("[[" + internalCallId + "]] Got a feature query");
                Packet p = conn.getDataFactory().createPacketNode(new NSI("iq", "jabber:server"), Packet.class);

                p.setFrom(packet.getTo());
                p.setTo(packet.getFrom());
                p.setID(packet.getID());
                p.setAttributeValue("type", "result");

                StreamElement query = conn.getDataFactory()
                        .createElementNode(new NSI("query", "http://jabber.org/protocol/disco#info"));
                query.setAttributeValue("node", clientName + "#" + clientVersion);

                // Google-Centric Feature Set

                if (featPMUC) {
                    query.addElement("feature").setAttributeValue("var",
                            "http://www.google.com/xmpp/protocol/pmuc/v1");
                }
                if (featSMS) {
                    query.addElement("feature").setAttributeValue("var",
                            "http://www.google.com/xmpp/protocol/pmuc/v1");
                }

                // Voice MUST be enabled
                query.addElement("feature").setAttributeValue("var",
                        "http://www.google.com/xmpp/protocol/voice/v1");

                if (featVID) {
                    query.addElement("feature").setAttributeValue("var",
                            "http://www.google.com/xmpp/protocol/video/v1");
                    query.addElement("feature").setAttributeValue("var",
                            "http://www.google.com/xmpp/protocol/camera/v1");
                }

                // General XEP Set

                if (featPING) {
                    // xep-0199
                    query.addElement("feature").setAttributeValue("var", "urn:xmpp:ping");
                }

                if (featPMUC && featPMUC_UNI) {
                    // xep-0199
                    query.addElement("feature").setAttributeValue("var",
                            "http://jabber.org/protocol/muc#unique");
                }

                p.add(query);

                Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(), packet.getFrom());
                sess.sendPacket(p);
            }

            // XEP-0307 (used in G+ hangouts)
            else if (packet.getAttributeValue("type").equals("get") && packet.getFirstElement().getNSI()
                    .equals(new NSI("unique", "http://jabber.org/protocol/muc#unique"))) {

                Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(), packet.getFrom());

                if (featPMUC && featPMUC_UNI) {
                    // Result with UUID
                    sess.unIQ(packet);
                } else {
                    // Status Unavailable - not required by XEP specification
                    // sess.errorIQ(packet, "unavailable");
                }

            }

            // XEP-0199
            else if (packet.getAttributeValue("type").equals("get")
                    && packet.getFirstElement().getNSI().equals(new NSI("ping", "urn:xmpp:ping"))) {

                Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(), packet.getFrom());

                if (featPING) {
                    // Result Pong
                    sess.ackIQ(packet);
                } else {
                    // XMPP Ping Not Supported
                    sess.cancelIQ(packet);
                }

            }

            else if (packet.getAttributeValue("type").equals("error")) {
                logger.debug("[[" + internalCallId + "]] Got error stanza");

                StreamElement error = packet.getFirstElement("error");
                if (error != null) {
                    logger.debug("[[" + internalCallId + "]] Error code: " + error.getAttributeValue("code")
                            + " type: " + error.getAttributeValue("type"));
                    if (error.getAttributeValue("type") == "cancel") {
                        logger.debug("[[" + internalCallId + "]] Sending cancel...");
                        String sessionId = packet
                                .getFirstElement(new NSI("session", "http://www.google.com/session")).getID();
                        CallSession cs = CallManager.getSession(sessionId);
                        if (cs != null) {
                            SipService.sendReject(cs);
                            logger.debug("[[" + internalCallId + "]] Removing session... ");
                            CallManager.removeSession(cs);
                        }
                    } else {
                        logger.debug("[[" + internalCallId + "]] Proceeding... ");
                    }
                }
            }

            else if (packet.getAttributeValue("type").equals("set")
                    && packet.getFirstElement(new NSI("jingle", "urn:xmpp:jingle:1")) != null && clientJingle) {
                StreamElement session = packet.getFirstElement(new NSI("jingle", "urn:xmpp:jingle:1"));
                String action = session.getAttributeValue("action");

                if (action.equals("session-initiate")) {
                    handleInitate(packet, true);
                } else if (action.equals("transport-info")) {
                    logger.debug("[[" + internalCallId + "]] Got candidate");
                    Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(),
                            packet.getFrom());
                    sess.ackIQ(packet);
                    String sessionId = session.getAttributeValue("sid");
                    CallSession cs = CallManager.getSession(sessionId);
                    for (Object objContent : session.listElements("content")) {
                        StreamElement content = (StreamElement) objContent;
                        StreamElement origTransport = content.getFirstElement("transport");
                        handleTransportList(sess, origTransport, cs);
                    }

                } else if (action.equals("session-accept")) {
                    logger.debug("[[" + internalCallId + "]] Got session accept");
                    Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(),
                            packet.getFrom());
                    sess.ackIQ(packet);
                    String sessionId = session.getAttributeValue("sid");
                    CallSession cs = CallManager.getSession(sessionId);
                    if (cs != null) {
                        logger.debug(
                                "[[" + internalCallId + "]] got call session : [[" + cs.internalCallId + "]]");
                        logger.debug("[[" + internalCallId + "]] Call found sending 200 OK");
                        cs.parseAccept(packet, true);
                        SipService.acceptCall(cs);
                    }
                } else if (action.equals("session-terminate")) {
                    logger.debug("[[" + internalCallId + "]] Got session terminate");
                    Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(),
                            packet.getFrom());
                    sess.ackIQ(packet);
                    String sessionId = session.getAttributeValue("sid");
                    CallSession cs = CallManager.getSession(sessionId);
                    if (cs != null) {
                        logger.debug(
                                "[[" + internalCallId + "]] got call session : [[" + cs.internalCallId + "]]");

                        if (cs.sipDialog.getState() == null || cs.sipDialog.getState() != DialogState.EARLY) {
                            logger.debug("[[" + internalCallId + "]] Call found sending BYE");
                        } else {
                            logger.debug(
                                    "[[" + internalCallId + "]] Call found in Early state, sending CANCEL");
                        }

                        SipService.sendBye(cs);

                        CallManager.removeSession(cs);
                    }
                } else if (action.equals("session-info")) {
                    logger.debug("[[" + internalCallId + "]] Got session-info request");
                    Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(),
                            packet.getFrom());
                    sess.ackIQ(packet);
                    String sessionId = session.getAttributeValue("sid");
                    CallSession cs = CallManager.getSession(sessionId);
                    for (Object objContent : session.listElements("content")) {
                        StreamElement content = (StreamElement) objContent;
                        StreamElement origTransport = content.getFirstElement("transport");
                        handleTransportList(sess, origTransport, cs);
                    }

                } else {
                    logger.debug("[[" + internalCallId + "]] Unhandled action: " + action);
                }

            }

            // gingle  call
            else if (packet.getAttributeValue("type").equals("set")
                    && packet.getFirstElement(new NSI("session", "http://www.google.com/session")) != null) {
                if (packet.getFirstElement(new NSI("session", "http://www.google.com/session"))
                        .getAttributeValue("type").equals("initiate")) {
                    handleInitate(packet, false);
                } else if (packet.getFirstElement(new NSI("session", "http://www.google.com/session"))
                        .getAttributeValue("type").equals("transport-info")) {
                    logger.debug("[[" + internalCallId + "]] Got transport info");
                    Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(),
                            packet.getFrom());
                    sess.ackIQ(packet);
                    StreamElement session = packet
                            .getFirstElement(new NSI("session", "http://www.google.com/session"));
                    String sessionId = session.getID();
                    CallSession cs = CallManager.getSession(sessionId);

                    StreamElement origTransport = packet
                            .getFirstElement(new NSI("session", "http://www.google.com/session"))
                            .getFirstElement("transport");
                    handleTransportList(sess, origTransport, cs);

                } else if (packet.getFirstElement(new NSI("session", "http://www.google.com/session"))
                        .getAttributeValue("type").equals("candidates")) {
                    logger.debug("[[" + internalCallId + "]] Got candidate");
                    Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(),
                            packet.getFrom());
                    sess.ackIQ(packet);

                    StreamElement session = packet
                            .getFirstElement(new NSI("session", "http://www.google.com/session"));
                    String sessionId = session.getID();
                    CallSession cs = CallManager.getSession(sessionId);
                    handleTransportList(sess, session, cs);
                } else if (packet.getFirstElement(new NSI("session", "http://www.google.com/session"))
                        .getAttributeValue("type").equals("transport-accept")) {
                    logger.debug("[[" + internalCallId + "]] Got transport accept");
                    Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(),
                            packet.getFrom());
                    sess.ackIQ(packet);
                } else if (packet.getFirstElement(new NSI("session", "http://www.google.com/session"))
                        .getAttributeValue("type").equals("accept")) {
                    logger.debug("[[" + internalCallId + "]] Got transport accept");
                    Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(),
                            packet.getFrom());
                    sess.ackIQ(packet);
                    CallSession cs = CallManager.getSession(packet
                            .getFirstElement(new NSI("session", "http://www.google.com/session")).getID());
                    if (cs != null) {
                        logger.debug(
                                "[[" + internalCallId + "]] got call session : [[" + cs.internalCallId + "]]");
                        logger.debug("[[" + internalCallId + "]] Call found sending 200 OK");
                        cs.parseAccept(packet, false);
                        SipService.acceptCall(cs);
                    }
                } else if (packet.getFirstElement(new NSI("session", "http://www.google.com/session"))
                        .getAttributeValue("type").equals("terminate")) {
                    logger.debug("[[" + internalCallId + "]] Got a terminate");
                    String sessionId = packet
                            .getFirstElement(new NSI("session", "http://www.google.com/session")).getID();
                    CallSession cs = CallManager.getSession(sessionId);
                    if (cs != null) {
                        logger.debug(
                                "[[" + internalCallId + "]] got call session : [[" + cs.internalCallId + "]]");
                        if (cs.sipDialog.getState() != DialogState.EARLY) {
                            logger.debug("[[" + internalCallId + "]] Call found sending BYE");
                            SipService.sendBye(cs);
                        } else {
                            logger.debug(
                                    "[[" + internalCallId + "]] Call found in Early state, sending CANCEL");
                            SipService.sendReject(cs);
                        }
                        CallManager.removeSession(cs);
                    }
                }

                else if (packet.getFirstElement(new NSI("session", "http://www.google.com/session"))
                        .getAttributeValue("type").equals("reject")) {
                    logger.debug("[[" + internalCallId + "]] Got a reject");
                    String sessionId = packet
                            .getFirstElement(new NSI("session", "http://www.google.com/session")).getID();
                    CallSession cs = CallManager.getSession(sessionId);
                    if (cs != null) {
                        logger.debug(
                                "[[" + internalCallId + "]] got call session : [[" + cs.internalCallId + "]]");
                        logger.debug("[[" + internalCallId + "]] found call session, forwarding reject");
                        SipService.sendReject(cs);
                        CallManager.removeSession(cs);
                    }

                }
            }

            else if (packet.getAttributeValue("type").equals("set")
                    && packet.getFirstElement(new NSI("otr", "http://jabber.org/protocol/archive")) != null) {
                logger.debug("[[" + internalCallId
                        + "]] Got a Jabber Archive/Record status change, forwarding.... ");

                String otr = "";
                Packet p = conn.getDataFactory().createPacketNode(new NSI("iq", "jabber:server"), Packet.class);
                p.setFrom(packet.getTo());
                p.setTo(packet.getFrom());
                p.setID(packet.getID());

                MessageMessage mm = new MessageMessage(evt.getData());

                if (packet.getFirstElement(new NSI("otr", "http://jabber.org/protocol/archive"))
                        .getFirstElement("record").getAttributeValue("otr").equals("true")) {
                    logger.info("[[" + internalCallId + "]] chat session is OFF the records ");
                    otr = "Chat session is OFF RECORDS";
                } else if (packet.getFirstElement(new NSI("otr", "http://jabber.org/protocol/archive"))
                        .getFirstElement("record").getAttributeValue("otr").equals("false")) {
                    logger.info("[[" + internalCallId + "]] chat session is RECORDED ");
                    otr = "Chat session is RECORDED";
                }

                mm.body = "[" + otr + "]";
                String domain = host;

                SipSubscription sub = SipSubscriptionManager.getWatcher(mm.from, mm.to);
                if (sub != null) {
                    domain = ((SipURI) sub.remoteParty.getURI()).getHost();
                }
                SipService.sendMessageMessage(mm, domain);
            }

            else if (packet.getAttributeValue("type").equals("get")
                    && packet.getFirstElement().getNSI().equals(new NSI("vCard", "vcard-temp"))) {
                logger.debug("[[" + internalCallId + "]] Got an ICON request!");
                Packet p = conn.getDataFactory().createPacketNode(new NSI("iq", "jabber:server"), Packet.class);

                p.setFrom(packet.getTo());
                p.setTo(packet.getFrom());
                p.setID(packet.getID());
                p.setAttributeValue("type", "result");

                StreamElement query = conn.getDataFactory().createElementNode(new NSI("vCard", "vcard-temp"));

                StreamElement fullName = query.addElement("FN");

                //if a telephone number  add a + to be pretty
                if (packet.getTo().getNode().toString().matches("[0-9]+")) {
                    fullName.addText("+" + packet.getTo().getNode().toString());
                } else {
                    fullName.addText(packet.getTo().getNode().toString());
                }
                StreamElement photo = query.addElement("PHOTO");
                StreamElement type = photo.addElement("TYPE");
                type.addText("image/jpeg");
                StreamElement binval = photo.addElement("BINVAL");
                byte[] encoded = Base64.encodeBase64Chunked(iconData);
                binval.addText(new String(encoded));

                p.add(query);

                Session sess = SessionManager.findCreateSession(packet.getTo().getDomain(), packet.getFrom());

                sess.sendPacket(p);
            }
        }
    } catch (Exception e) {
        logger.error("Exception in packetTransferred", e);
    }
}

From source file:com.zimbra.cs.account.ProvUtil.java

private void printAttr(String attrName, String value, Integer idx, boolean isBinary, String timestamp)
        throws ServiceException {
    if (isBinary) {
        byte[] binary = ByteUtil.decodeLDAPBase64(value);
        if (outputBinaryToFile()) {
            outputBinaryAttrToFile(attrName, idx, binary, timestamp);
        } else {/*from ww w. jav  a  2s.com*/
            // print base64 encoded content
            // follow ldapsearch notion of using two colons when printing base64 encoded data
            // re-encode into 76 character blocks
            String based64Chunked = new String(Base64.encodeBase64Chunked(binary));
            // strip off the \n at the end
            if (based64Chunked.charAt(based64Chunked.length() - 1) == '\n') {
                based64Chunked = based64Chunked.substring(0, based64Chunked.length() - 1);
            }
            printOutput(attrName + ":: " + based64Chunked);
        }
    } else {
        printOutput(attrName + ": " + value);
    }
}

From source file:org.apache.airavata.workflow.model.wf.Workflow.java

/**
 * Returns the XmlElement of the workflow.
 * /*from   w w  w .  j av a 2s  . c o m*/
 * @return The XmlElement of the workflow
 */
public XmlElement toXML() {
    // This must be before graph.toXML() to set WSDL ID to each node.
    Map<String, WsdlDefinitions> wsdls = getWSDLs();

    XmlElement workflowElement = XMLUtil.BUILDER.newFragment(NS_XWF, WORKFLOW_TAG);

    // Version
    workflowElement.setAttributeValue(NS_XWF, VERSION_ATTRIBUTE, ApplicationVersion.VERSION.getVersion());

    // Date
    // TODO add modification time
    // XmlElement modifiedTimeElement = graphElement.addElement(
    // XgraphSchema.NS, "modifiedTime");
    // modifiedTimeElement.addChild(new GregorianCalendar().toString());

    // Graph
    workflowElement.addElement(this.graph.toXML());

    // WSDLs
    XmlElement wsdlsElement = workflowElement.addElement(NS_XWF, WSDLS_TAG);
    for (String id : wsdls.keySet()) {
        WsdlDefinitions wsdl = wsdls.get(id);
        XmlElement wsdlElement = wsdlsElement.addElement(NS_XWF, WSDL_TAG);
        wsdlElement.setAttributeValue(NS_XWF, ID_ATTRIBUTE, id);
        wsdlElement.setText(XMLUtil.xmlElementToString(wsdl.xml()));
    }

    // Image
    if (this.image != null) {
        try {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            ImageIO.write(this.image, WorkflowConstants.PNG_FORMAT_NAME, outStream);
            byte[] bytes = outStream.toByteArray();
            byte[] base64 = Base64.encodeBase64Chunked(bytes);

            XmlElement imageElement = workflowElement.addElement(NS_XWF, IMAGE_TAG);
            imageElement.setText(new String(base64));
        } catch (IOException e) {
            // No image
            logger.error(e.getMessage(), e);
        }
    }

    // BPEL
    if (this.gpelProcess != null) {
        XmlElement bpelElement = workflowElement.addElement(NS_XWF, BPEL_TAG);
        bpelElement.setText(this.gpelProcess.xmlStringPretty());
    }

    // Workflow WSDL
    if (this.workflowWSDL != null) {
        XmlElement workflowWSDLElement = workflowElement.addElement(NS_XWF, WORKFLOW_WSDL_TAG);
        workflowWSDLElement.setText(this.workflowWSDL.xmlStringPretty());
    }

    return workflowElement;
}

From source file:org.apache.ofbiz.base.util.KeyStoreUtil.java

public static String certToString(Certificate cert) throws CertificateEncodingException {
    byte[] certBuf = cert.getEncoded();
    StringBuilder buf = new StringBuilder();
    buf.append("-----BEGIN CERTIFICATE-----\n");
    buf.append(new String(Base64.encodeBase64Chunked(certBuf)));
    buf.append("\n-----END CERTIFICATE-----\n");
    return buf.toString();
}

From source file:org.bedework.util.security.pki.PkiUtil.java

/** Dump a byte array as a base 64 encoded value. We also check that the
 *  form we emit can be decoded and produce an identical key.
 *  <p>//from w  w  w  . ja v a2s  .  c o m
 *  We then go on to encode and decode our testText to see if they match.
 *
 * @param key
 * @return boolean
 * @throws Exception
 */
private boolean dumpKey(final byte[] key) throws Exception {
    byte[] encoded = Base64.encodeBase64Chunked(key);
    String encText = new String(encoded);

    System.out.println("Copy the text between the delimiters");
    System.out.println("Take all below this line ----------------------->");
    System.out.println(encText);
    System.out.println("<--------------- up to and not including this line");

    // See if it decodes
    byte[] decoded = Base64.encodeBase64Chunked(encText.getBytes());

    if (decoded.length != key.length) {
        error("Validity check failed: lengths not equal " + "(decoded=" + decoded.length + " key=" + key.length
                + ")");
        dumpHex(decoded);
        error(" ");
        dumpHex(key);
        return false;
    }

    for (int i = 0; i < decoded.length; i++) {
        if (decoded[i] != key[i]) {
            error("Validity check failed: byte at position " + i + " not equal");
            dumpHex(decoded);
            error(" ");
            dumpHex(key);

            return false;
        }
    }

    return true;
}

From source file:org.eclipse.koneki.ldt.support.lua51.internal.interpreter.TransportLayerModule.java

private static NamedJavaFunction b64() {
    return new NamedJavaFunction() {

        @Override//from  w w w . j  a  v a 2s  .co m
        public int invoke(LuaState l) {
            String string = l.checkString(1);
            byte[] b64Result = Base64.encodeBase64Chunked(string.getBytes());
            String b64String = new String(b64Result);
            l.pushString(b64String);
            return 1;
        }

        @Override
        public String getName() {
            return "b64"; //$NON-NLS-1$
        }
    };
}

From source file:org.tolven.key.bean.UserKeyBean.java

@Override
public String getUserX509CertificateString(String uid, String realm) {
    X509Certificate x509Certificate = getUserX509Certificate(uid, realm);
    if (x509Certificate == null) {
        return null;
    }//from  ww w .j a  v  a  2 s.  c  om
    try {
        StringBuffer buff = new StringBuffer();
        buff.append("-----BEGIN CERTIFICATE-----");
        buff.append("\n");
        String pemFormat = new String(Base64.encodeBase64Chunked(x509Certificate.getEncoded()));
        buff.append(pemFormat);
        buff.append("\n");
        buff.append("-----END CERTIFICATE-----");
        buff.append("\n");
        return buff.toString();
    } catch (Exception ex) {
        throw new RuntimeException("Could not convert X509Certificate into a String", ex);
    }
}

From source file:org.tolven.session.OpenAMSessionWrapper.java

@Override
public String getUserX509CertificateString() {
    X509Certificate x509Certificate = getUserX509Certificate();
    if (x509Certificate == null) {
        return null;
    }/*from  ww w. ja  va  2 s.c  om*/
    try {
        StringBuffer buff = new StringBuffer();
        buff.append("-----BEGIN CERTIFICATE-----");
        buff.append("\n");
        String pemFormat = new String(Base64.encodeBase64Chunked(x509Certificate.getEncoded()));
        buff.append(pemFormat);
        buff.append("\n");
        buff.append("-----END CERTIFICATE-----");
        buff.append("\n");
        return buff.toString();
    } catch (Exception ex) {
        throw new RuntimeException("Could not convert X509Certificate into a String", ex);
    }
}

From source file:pt.lsts.neptus.util.ByteUtil.java

/**
  * Return the byte array encoded as a base64 string.
  * //from w w  w. j  ava 2s  .c o  m
 * @param source
 * @param chunked
 * @return
 */
public static byte[] encodeAsBase64(byte[] source, boolean chunked) {
    if (chunked)
        return Base64.encodeBase64Chunked(source);
    else
        return Base64.encodeBase64(source);
}