Example usage for javax.xml.bind DatatypeConverter printBase64Binary

List of usage examples for javax.xml.bind DatatypeConverter printBase64Binary

Introduction

In this page you can find the example usage for javax.xml.bind DatatypeConverter printBase64Binary.

Prototype

public static String printBase64Binary(byte[] val) 

Source Link

Document

Converts an array of bytes into a string.

Usage

From source file:org.wso2.carbon.repository.core.ResourceStorer.java

private void dumpRecursively(String path, XMLStreamWriter xmlWriter, Writer writer)
        throws RepositoryException, XMLStreamException {
    // adding resource meta data
    ResourceImpl resource = resourceDAO.getResourceMetaData(path);

    if (resource == null) {
        return;/* w  ww  . j a  v  a  2 s.  c  o m*/
    }

    xmlWriter.writeStartElement(DumpConstants.RESOURCE);

    // adding path as an attribute, updated dump has name instead of path
    xmlWriter.writeAttribute(DumpConstants.RESOURCE_NAME, RepositoryUtils.getResourceName(path));

    //adding dump attribute
    xmlWriter.writeAttribute(DumpConstants.RESOURCE_STATUS, DumpConstants.RESOURCE_DUMP);

    // adding isCollection as an attribute
    xmlWriter.writeAttribute(DumpConstants.RESOURCE_IS_COLLECTION,
            (resource instanceof CollectionImpl) ? DumpConstants.RESOURCE_IS_COLLECTION_TRUE
                    : DumpConstants.RESOURCE_IS_COLLECTION_FALSE);

    // set media type
    String mediaType = resource.getMediaType();

    xmlWriter.writeStartElement(DumpConstants.MEDIA_TYPE);
    xmlWriter.writeCharacters(mediaType != null ? mediaType : "");
    xmlWriter.writeEndElement();

    // set version
    long version = resource.getVersionNumber();

    xmlWriter.writeStartElement(DumpConstants.VERSION);
    xmlWriter.writeCharacters(Long.toString(version) != null ? Long.toString(version) : "");
    xmlWriter.writeEndElement();

    // set creator
    String creator = resource.getAuthorUserName();

    xmlWriter.writeStartElement(DumpConstants.CREATOR);
    xmlWriter.writeCharacters(creator != null ? creator : "");
    xmlWriter.writeEndElement();

    // set createdTime
    Date createdTime = resource.getCreatedTime();

    xmlWriter.writeStartElement(DumpConstants.CREATED_TIME);
    xmlWriter.writeCharacters(
            Long.toString(createdTime.getTime()) != null ? Long.toString(createdTime.getTime()) : "");
    xmlWriter.writeEndElement();

    // set updater
    String updater = resource.getLastUpdaterUserName();

    xmlWriter.writeStartElement(DumpConstants.LAST_UPDATER);
    xmlWriter.writeCharacters(updater != null ? updater : "");
    xmlWriter.writeEndElement();

    // set LastModified
    Date lastModified = resource.getLastModified();

    xmlWriter.writeStartElement(DumpConstants.LAST_MODIFIED);
    xmlWriter.writeCharacters(
            Long.toString(lastModified.getTime()) != null ? Long.toString(lastModified.getTime()) : "");
    xmlWriter.writeEndElement();

    // set UUID
    String uuid = resource.getUUID();

    xmlWriter.writeStartElement(DumpConstants.UUID);
    xmlWriter.writeCharacters(uuid != null ? uuid : "");
    xmlWriter.writeEndElement();

    // set Description
    String description = resource.getDescription();

    xmlWriter.writeStartElement(DumpConstants.DESCRIPTION);
    xmlWriter.writeCharacters(description != null ? description : "");
    xmlWriter.writeEndElement();

    // fill properties
    resourceDAO.fillResourceProperties(resource);
    xmlWriter.writeStartElement(DumpConstants.PROPERTIES);

    for (Object keyObject : resource.getPropertyKeys()) {
        String key = (String) keyObject;
        List<String> propValues = resource.getPropertyValues(key);
        for (String value : propValues) {
            xmlWriter.writeStartElement(DumpConstants.PROPERTY_ENTRY);
            // adding the key and value as attributes

            xmlWriter.writeAttribute(DumpConstants.PROPERTY_ENTRY_KEY, key);

            if (value != null) {
                xmlWriter.writeCharacters(value != null ? value : "");
            }

            xmlWriter.writeEndElement();
        }
    }
    xmlWriter.writeEndElement();

    // adding contents..
    if (!(resource instanceof CollectionImpl)) {
        resourceDAO.fillResourceContent(resource);

        byte[] content = (byte[]) resource.getContent();
        if (content != null) {
            xmlWriter.writeStartElement(DumpConstants.CONTENT);
            xmlWriter.writeCharacters(DatatypeConverter.printBase64Binary(content) != null
                    ? DatatypeConverter.printBase64Binary(content)
                    : "");
            xmlWriter.writeEndElement();
        }
    }

    // getting children and applying dump recursively
    if (resource instanceof CollectionImpl) {
        CollectionImpl collection = (CollectionImpl) resource;
        resourceDAO.fillChildren(collection, 0, -1);
        String childPaths[] = collection.getChildPaths();

        xmlWriter.writeStartElement(DumpConstants.CHILDREN);
        xmlWriter.writeCharacters("");

        xmlWriter.flush();

        for (String childPath : childPaths) {
            // we would be writing the start element of the child and its name here.
            try {
                String resourceName = RepositoryUtils.getResourceName(childPath);
                writer.write("<resource name=\"" + resourceName + "\"");
                writer.flush();
            } catch (IOException e) {
                String msg = "Error in writing the start element for the path: " + childPath + ".";
                log.error(msg, e);
                throw new RepositoryException(msg, e);
            }

            recursionRepository.dumpRecursively(childPath, new DumpWriter(writer));
        }
        xmlWriter.writeEndElement();
    }

    xmlWriter.writeEndElement();
    xmlWriter.flush();
}

From source file:org.wso2.ei.bpmn.analytics.core.utils.BPMNAnalyticsCoreUtils.java

/**
 * Get authorization header//from w w  w.j ava2s .  c  o  m
 *
 * @return encoded auth header
 */
public static String getAuthorizationHeader() {
    String userName = BPMNAnalyticsCoreServerHolder.getInstance().getBPMNAnalyticsCoreServer()
            .getBPSAnalyticsConfiguration().getAnalyticsServerUsername();
    String password = BPMNAnalyticsCoreServerHolder.getInstance().getBPMNAnalyticsCoreServer()
            .getBPSAnalyticsConfiguration().getAnalyticsServerPassword();
    if (userName != null && password != null) {
        return BPMNAnalyticsCoreConstants.AUTH_BASIC_HEADER + " " + DatatypeConverter
                .printBase64Binary((userName + ":" + password).getBytes(StandardCharsets.UTF_8));
    }
    return null;
}

From source file:org.xwiki.contrib.websocket.script.XWikiWebSocketScriptService.java

/**
 * Get a token which corrisponds to a document reference.
 *
 * If the current user does not have permission to access the document, this function
 * will return the string "ENOPERM"./*from  w w w  .  ja va  2 s . com*/
 * The motivation is to allow a secret value for encryption or realtime channel creation
 * so that users who are auhorized and able to access the websocket are still not able
 * to join websocket sessions based on documents for which they do not have edit access.
 *
 * @param ref a reference to the document to check.
 * @return a base64 string or, if the user does not have access, "ENOPERM".
 */
public String getDocumentKey(DocumentReference ref) {
    if (!this.authMgr.hasAccess(Right.EDIT, getUser(), ref)) {
        return "ENOPERM";
    }
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        return DatatypeConverter.printBase64Binary(md.digest((this.secret + ref).getBytes()));
    } catch (Exception e) {
        throw new RuntimeException("should never happen");
    }
}

From source file:org.zstack.test.mevoco.TestLicense.java

@Test
public void test() throws Exception {
    File licpath = PathUtil.findFileOnClassPath("license.txt", true);
    File privpath = PathUtil.findFileOnClassPath("priv.key", true);
    File capath = PathUtil.findFileOnClassPath("ca.pem", true);

    FileInputStream lic = new FileInputStream(licpath);
    FileInputStream priv = new FileInputStream(privpath);
    FileInputStream ca = new FileInputStream(capath);

    //SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
    //Date d = f.parsed("2015-12-30T11:25:22+08:00", new ParsePosition(0));
    //DateFormat df = DateFormat.getDateInstance();
    //Date d = df.parse("2015-12-30T11:25:22+08:00");
    //System.out.println(d.toString());

    DateTime d = new DateTime("2015-12-30T11:25:22+08:00");
    System.out.println(d.toString());

    LicenseChecker checker = new LicenseChecker(lic, priv, ca);
    LicenseInfo info = checker.getLicenseInfo();

    System.out.println("user: " + info.getUser());
    System.out.println("hostnum: " + info.getHostNum());
    System.out.println("type: " + info.getLicenseType());
    System.out.println("issue time: " + info.getIssueTime());
    System.out.println("expired time: " + info.getExpireTime());

    for (Object o : info.getThumbprint().entrySet()) {
        Map.Entry pair = (Map.Entry) o;
        System.out.println(pair.getKey() + " = " + pair.getValue());
    }/* ww w  .  j  av  a  2s . c  o m*/

    ca.close();
    priv.close();
    lic.close();

    String pkey = FileUtils.readFileToString(privpath);
    String licreq = "eyJ0aHVtYnByaW50IjoiZXlKMlpYSnphVzl1SWpvaU1DNHhJaXdpYUc5emRHNWhiV1VpT2lKc2IyTmhiR2h2YzNRaUxDSmpjSFZ6SWpvaU5DSXNJbU53ZFcxdlpHVnNJam9pU1c1MFpXd29VaWtnUTI5eVpTaFVUU2tnYVRjdE5qVXdNRlVnUTFCVklFQWdNaTQxTUVkSWVpSXNJbTFsYldsdWEySWlPaUkwTURNek5qTTJJbjA9IiwicHVia2V5IjoiLS0tLS1CRUdJTiBSU0EgUFVCTElDIEtFWS0tLS0tXG5NSUlCSERBTkJna3Foa2lHOXcwQkFRRUZBQU9DQVFrQU1JSUJCQUtCL0Rmd1I2c0NGZDVleDdWcHpYa2dLd25zXG4rKzhyWElkblBKQ0swaStvaHVVUWl5b1hKUnhwMmJqZXJsM1JSbW1WeGtjMlRQeU1xWjVhR0hMMElpdHhPVlVkXG5JcmtHblFVeHEyc2JGRHJIVXplNHA0MWtRWStWbTB4REo1Tmk0bTRQZUp4eDVBVkNaMkVCSzN0RlA2REl4R0ZpXG5VUDdvMGdGeFhLU1VvVzFncFhITjNpbUJSUWh5cEYrQldmQ0pmeThSL2tPbGI1KytCZHovc2EvRzByMTNHQU5aXG5qUkZuVFhSMDZoaWd3TzI2a0ttcTlsdDd2UVNaSXpGaDJVbzZGdzlIL0M3bkk2U00rZDE4R3drdXVNUUIyZFZVXG55S2FkK1h3dE1xN1JqT2xrdGdUcE56SEpMa05IdUJHcEZveE1yLzRtdUxKYVRCUHdSR202M1VqMWp3SURBUUFCXG4tLS0tLUVORCBSU0EgUFVCTElDIEtFWS0tLS0tXG4ifQ==";
    Map<String, String> m = new HashMap<String, String>();
    m.put("privateKey", pkey);
    m.put("license", licreq);
    String jstr = JSONObjectUtil.toJsonString(m);
    String encoded = DatatypeConverter.printBase64Binary(jstr.getBytes());
    System.out.println(encoded);
    byte[] decoded = DatatypeConverter.parseBase64Binary(encoded);
    String jstr1 = new String(decoded);
    System.out.println(jstr1);
    m = JSONObjectUtil.toObject(jstr1, HashMap.class);
    System.out.println(m.get("privateKey"));
    System.out.println(m.get("license"));
}

From source file:pt.lsts.neptus.plugins.sunfish.awareness.ArgosLocationProvider.java

private void setArgosPassword(String password) {
    if (password == null)
        this.argosPassword = null;

    this.argosPassword = DatatypeConverter.printBase64Binary(password.getBytes(Charset.forName("UTF8")));
}

From source file:pt.lsts.neptus.util.credentials.Credentials.java

/**
 * Change password/*from w  ww .  j a  v  a2s .c om*/
 * @param password The (plain) password for this login 
 */
public void setPassword(String password) {
    if (password == null)
        this.password = null;

    this.password = DatatypeConverter.printBase64Binary(password.getBytes(Charset.forName("UTF8")));
}

From source file:ru.codeinside.gses.webui.executor.ArchiveFactory.java

public static String toBase64HumanString(byte[] bytes) {
    return Joiner.on('\n').join(Splitter.fixedLength(64).split(DatatypeConverter.printBase64Binary(bytes)));
}

From source file:ru.codeinside.gws.crypto.cryptopro.CryptoProvider.java

public void sign(final SOAPMessage message) {
    try {/*  w w w.  j  av a2s .c o  m*/
        loadCertificate();

        final long startMs = System.currentTimeMillis();

        final SOAPPart doc = message.getSOAPPart();
        final QName wsuId = doc.getEnvelope().createQName("Id", "wsu");
        final SOAPHeader header = message.getSOAPHeader();
        final QName actor = header.createQName("actor", header.getPrefix());

        final SOAPElement security = header.addChildElement("Security", "wsse", WSSE);
        security.addAttribute(actor, ACTOR_SMEV);
        SOAPElement binarySecurityToken = security.addChildElement("BinarySecurityToken", "wsse");
        binarySecurityToken.setAttribute("EncodingType", WSS_BASE64_BINARY);
        binarySecurityToken.setAttribute("ValueType", WSS_X509V3);
        binarySecurityToken.setValue(DatatypeConverter.printBase64Binary(cert.getEncoded()));
        binarySecurityToken.addAttribute(wsuId, "CertId");

        XMLSignature signature = new XMLSignature(doc, "", XMLSignature.ALGO_ID_SIGNATURE_GOST_GOST3410_3411,
                Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
        {
            Element element = signature.getElement();
            Element keyInfo = doc.createElementNS(Constants.SignatureSpecNS, "KeyInfo");
            Element securityTokenReference = doc.createElementNS(WSSE, "SecurityTokenReference");
            Element reference = doc.createElementNS(WSSE, "Reference");
            reference.setAttribute("URI", "#CertId");
            reference.setAttribute("ValueType", WSS_X509V3);
            securityTokenReference.appendChild(reference);
            keyInfo.appendChild(securityTokenReference);
            element.appendChild(keyInfo);
            security.appendChild(element);
        }
        Transforms transforms = new Transforms(doc);
        transforms.addTransform(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
        signature.addDocument("#body", transforms, MessageDigestAlgorithm.ALGO_ID_DIGEST_GOST3411);
        signature.sign(privateKey);
        if (log.isDebugEnabled()) {
            log.debug("SIGN: " + (System.currentTimeMillis() - startMs) + "ms");
        }
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:sernet.verinice.encryption.test.CryptoTest.java

private String convertToPem(byte[] data, boolean isKey, boolean isCert) {
    String prefix = "";
    String suffix = "";
    if (isCert && !isKey) {
        prefix = "-----BEGIN CERTIFICATE-----\n";
        suffix = "\n-----END CERTIFICATE-----";
    }/*  w ww . ja va 2s. co m*/
    if (!isCert && isKey) {
        prefix = "-----BEGIN PRIVATE KEY-----\n";
        suffix = "\n-----END PRIVATE KEY-----";
    }
    String certData;
    try {
        return certData = prefix + DatatypeConverter.printBase64Binary(data) + suffix;
    } catch (Exception e) {
        LOG.error("Error converting cert", e);
    }
    return null;
}

From source file:tds.itemrenderer.processing.ITSUrlBase64.java

private String replaceHtmlMatch(Matcher matcher) {
    String basePath = _filePath.replace(Path.getFileName(_filePath), "");
    String imageFile = matcher.group("src");
    String imagePath = Path.combine(basePath, imageFile);

    byte[] binaryData = null;
    try {//from  w  w  w .j a va2 s  . c  om
        binaryData = FileUtils.readFileToByteArray(new File(imagePath));
    } catch (IOException e) {
        throw new ITSDocumentProcessingException(e);
    }

    final String base64Format = "data:image/%s;base64,%s";
    String extension = Path.getExtension(imageFile).replace(".", "");
    String base64 = String.format(base64Format, extension, DatatypeConverter.printBase64Binary(binaryData));

    String imageTag = matcher.group("img");

    Matcher matcher2 = matcher.pattern().matcher(imageTag);
    StringBuilder sb = new StringBuilder(imageTag);
    matcher2.find();
    return sb.replace(matcher2.start(2), matcher2.end(2), base64).toString();

}