Example usage for java.util Base64 getEncoder

List of usage examples for java.util Base64 getEncoder

Introduction

In this page you can find the example usage for java.util Base64 getEncoder.

Prototype

public static Encoder getEncoder() 

Source Link

Document

Returns a Encoder that encodes using the Basic type base64 encoding scheme.

Usage

From source file:org.apache.syncope.core.persistence.jpa.entity.AbstractPlainAttrValue.java

@Override
public String getValueAsString(final AttrSchemaType type) {
    String result;/*from  w  w  w .ja va  2s .  com*/
    switch (type) {

    case Boolean:
        result = getBooleanValue().toString();
        break;

    case Long:
        result = getAttr() == null || getAttr().getSchema() == null
                || getAttr().getSchema().getConversionPattern() == null ? getLongValue().toString()
                        : FormatUtils.format(getLongValue(), getAttr().getSchema().getConversionPattern());
        break;

    case Double:
        result = getAttr() == null || getAttr().getSchema() == null
                || getAttr().getSchema().getConversionPattern() == null ? getDoubleValue().toString()
                        : FormatUtils.format(getDoubleValue(), getAttr().getSchema().getConversionPattern());
        break;

    case Date:
        result = getAttr() == null || getAttr().getSchema() == null
                || getAttr().getSchema().getConversionPattern() == null ? FormatUtils.format(getDateValue())
                        : FormatUtils.format(getDateValue(), false,
                                getAttr().getSchema().getConversionPattern());
        break;

    case Binary:
        result = Base64.getEncoder().encodeToString(getBinaryValue());
        break;

    case String:
    case Enum:
    case Encrypted:
    default:
        result = getStringValue();
        break;
    }

    return result;
}

From source file:org.wso2.carbon.identity.inbound.provisioning.scim2.test.module.commons.utills.SCIMTestUtil.java

private static HttpURLConnection connection(String path, String method, boolean keepAlive,
        String authorizationHeader, String contentTypeHeader) throws IOException {

    URL url = new URL(SCIMTestConstant.BASE_URL + path);

    HttpURLConnection httpURLConnection = null;

    if (SCIMTestConstant.BASE_URL.contains("https")) {
        httpURLConnection = (HttpsURLConnection) url.openConnection();
    } else {/*from  w w w .  ja va  2s  .  c o  m*/
        httpURLConnection = (HttpURLConnection) url.openConnection();
    }

    if (method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT)) {
        httpURLConnection.setDoOutput(true);
    }
    httpURLConnection.setRequestMethod(method);
    if (!keepAlive) {
        httpURLConnection.setRequestProperty("CONNECTION", "CLOSE");
    }

    if (authorizationHeader != null) {
        String temp = new String(
                Base64.getEncoder().encode(authorizationHeader.getBytes(StandardCharsets.UTF_8)),
                StandardCharsets.UTF_8);

        authorizationHeader = "Basic " + temp;
        httpURLConnection.setRequestProperty(HttpHeaders.AUTHORIZATION, authorizationHeader);
    }
    if (contentTypeHeader != null) {
        httpURLConnection.setRequestProperty(HttpHeaders.CONTENT_TYPE, contentTypeHeader);
    }

    return httpURLConnection;

}

From source file:ddf.catalog.transformer.xml.MetacardMarshallerImpl.java

private String getStringValue(XmlPullParser parser, Attribute attribute, AttributeType.AttributeFormat format,
        Serializable value) throws IOException, CatalogTransformerException {
    switch (format) {

    case STRING://from  www .  ja va  2 s  .  c  o  m
    case BOOLEAN:
    case SHORT:
    case INTEGER:
    case LONG:
    case FLOAT:
    case DOUBLE:
        return value.toString();
    case DATE:
        Date date = (Date) value;
        return DateFormatUtils.formatUTC(date, DF_PATTERN);
    case GEOMETRY:
        return geoToXml(geometryTransformer.transform(attribute), parser);
    case OBJECT:
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try (ObjectOutput output = new ObjectOutputStream(bos)) {
            output.writeObject(attribute.getValue());
            return Base64.getEncoder().encodeToString(bos.toByteArray());
        }
    case BINARY:
        return Base64.getEncoder().encodeToString((byte[]) value);
    case XML:
        return value.toString().replaceAll("[<][?]xml.*[?][>]", "");
    default:
        LOGGER.warn("Unsupported attribute: {}", format);
        return value.toString();
    }
}

From source file:io.vertx.config.vault.utils.Certificates.java

/**
 * See https://stackoverflow.com/questions/3313020/write-x509-certificate-into-pem-formatted-string-in-java
 *
 * @param certificate An X509 certificate
 * @param file        the file/*from  w  ww.ja v a 2  s . c  o  m*/
 * @throws CertificateEncodingException
 * @throws FileNotFoundException
 */
private static void writeCertToPem(final X509Certificate certificate, final File file)
        throws CertificateEncodingException, IOException {
    final Base64.Encoder encoder = Base64.getEncoder();

    final String certHeader = "-----BEGIN CERTIFICATE-----\n";
    final String certFooter = "\n-----END CERTIFICATE-----";
    final byte[] certBytes = certificate.getEncoded();
    final String certContents = new String(encoder.encode(certBytes));
    final String certPem = certHeader + certContents + certFooter;
    FileUtils.write(file, certPem);
}

From source file:org.openhab.binding.amazonechocontrol.internal.Connection.java

public Connection(@Nullable Connection oldConnection) {
    String frc = null;// www  .j  av a 2  s  . co  m
    String serial = null;
    String deviceId = null;
    if (oldConnection != null) {
        frc = oldConnection.getFrc();
        serial = oldConnection.getSerial();
        deviceId = oldConnection.getDeviceId();

    }
    Random rand = new Random();
    if (frc != null) {
        this.frc = frc;
    } else {
        // generate frc
        byte[] frcBinary = new byte[313];
        rand.nextBytes(frcBinary);
        this.frc = Base64.getEncoder().encodeToString(frcBinary);
    }
    if (serial != null) {
        this.serial = serial;
    } else {
        // generate serial
        byte[] serialBinary = new byte[16];
        rand.nextBytes(serialBinary);
        this.serial = HexUtils.bytesToHex(serialBinary);
    }
    if (deviceId != null) {
        this.deviceId = deviceId;
    } else {
        // generate device id
        StringBuilder deviceIdBuilder = new StringBuilder();
        for (int i = 0; i < 64; i++) {
            deviceIdBuilder.append(rand.nextInt(9));
        }
        deviceIdBuilder.append("23413249564c5635564d32573831");
        this.deviceId = deviceIdBuilder.toString();
    }

    // build user agent
    this.userAgent = "AmazonWebView/Amazon Alexa/2.2.223830.0/iOS/11.4.1/iPhone";

    // setAmazonSite(amazonSite);

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonWithNullSerialization = gsonBuilder.create();
}

From source file:org.apache.nifi.processors.evtx.parser.BinaryReader.java

/**
 * Reads length bytes and Bas64 encodes them
 *
 * @param length the number of bytes/* ww  w.  j a v a2 s  .c  o m*/
 * @return a Base64 encoded string
 */
public String readAndBase64EncodeBinary(int length) {
    return Base64.getEncoder().encodeToString(readBytes(length));
}

From source file:com.web.mavenproject6.controller.CameraController.java

@RequestMapping(value = "/qr/{userId}/", method = RequestMethod.GET)
public @ResponseBody BufferedImage getQRCode(@PathVariable String userId)
        throws IOException, GeneralSecurityException {
    BufferedImage img;//from w  w  w.  ja  va2 s .  c om

    Object pObject = personalService.findByAccessNumber(userId);
    if (pObject instanceof personal) {
        personal p = (personal) pObject;
        String userDate = "{userId:" + p.getAccessNumber() + ",fname:" + p.getFname() + ",tname:" + p.getTname()
                + "}";
        ByteArrayOutputStream out = QRCode.from(Base64.getEncoder().encodeToString(userDate.getBytes()))
                .to(ImageType.JPG).stream();
        byte[] imageInByte;
        imageInByte = out.toByteArray();
        InputStream in = new ByteArrayInputStream(imageInByte);
        img = ImageIO.read(in);
        return img;
    }

    Object gObject = guestService.findByAccessNumber(userId);
    if (gObject instanceof guest) {
        guest g = (guest) gObject;
        String userDate = g.getAccessNumber() + " " + g.getFname() + " " + g.getTname();
        ByteArrayOutputStream out = QRCode.from(Base64.getEncoder().encodeToString(userDate.getBytes()))
                .to(ImageType.JPG).stream();
        byte[] imageInByte;
        imageInByte = out.toByteArray();
        InputStream in = new ByteArrayInputStream(imageInByte);
        img = ImageIO.read(in);
        return img;
    }

    InputStream in = servletContext.getResourceAsStream("/resources/img/qr-code.jpg");
    img = ImageIO.read(in);
    return img;

}

From source file:edu.harvard.iq.dataverse.ThumbnailServiceWrapper.java

public String getDatasetCardImageAsBase64Url(Dataset dataset, Long versionId) {
    Long datasetId = dataset.getId();
    if (datasetId != null) {
        if (this.dvobjectThumbnailsMap.containsKey(datasetId)) {
            // Yes, return previous answer
            // (at max, there could only be 2 cards for the same dataset
            // on the page - the draft, and the published version; but it's 
            // still nice to try and cache the result - especially if it's an
            // uploaded logo - we don't want to read it off disk twice). 

            if (!"".equals(this.dvobjectThumbnailsMap.get(datasetId))) {
                return this.dvobjectThumbnailsMap.get(datasetId);
            }//from ww w.j  a  va 2 s.c om
            return null;
        }
    }

    if (dataset.isUseGenericThumbnail()) {
        this.dvobjectThumbnailsMap.put(datasetId, "");
        return null;
    }

    String cardImageUrl = null;
    StorageIO<Dataset> dataAccess = null;

    try {
        dataAccess = DataAccess.getStorageIO(dataset);
    } catch (IOException ioex) {
        //  return null;
    }

    InputStream in = null;
    try {
        if (dataAccess
                .getAuxFileAsInputStream(datasetLogoThumbnail + thumb48addedByImageThumbConverter) != null) {
            in = dataAccess.getAuxFileAsInputStream(datasetLogoThumbnail + thumb48addedByImageThumbConverter);
        }
    } catch (Exception ioex) {
        //            return null;
        //ignore
    }

    if (in != null) {
        try {
            byte[] bytes = IOUtils.toByteArray(in);
            String base64image = Base64.getEncoder().encodeToString(bytes);
            cardImageUrl = FileUtil.DATA_URI_SCHEME + base64image;
            this.dvobjectThumbnailsMap.put(datasetId, cardImageUrl);
            return cardImageUrl;
        } catch (IOException ex) {
            this.dvobjectThumbnailsMap.put(datasetId, "");
            return null;
            // (alternatively, we could ignore the exception, and proceed with the 
            // regular process of selecting the thumbnail from the available 
            // image files - ?)
        }
    }

    if (dataset != null) {
        cardImageUrl = this.getAssignedDatasetImage(dataset);

        if (cardImageUrl != null) {
            //logger.info("dataset id " + result.getEntity().getId() + " has a dedicated image assigned; returning " + cardImageUrl);
            return cardImageUrl;
        }
    }

    Long thumbnailImageFileId = datasetVersionService.getThumbnailByVersionId(versionId);

    if (thumbnailImageFileId != null) {
        //cardImageUrl = FILE_CARD_IMAGE_URL + thumbnailImageFileId;
        if (this.dvobjectThumbnailsMap.containsKey(thumbnailImageFileId)) {
            // Yes, return previous answer
            //logger.info("using cached result for ... "+datasetId);
            if (!"".equals(this.dvobjectThumbnailsMap.get(thumbnailImageFileId))) {
                return this.dvobjectThumbnailsMap.get(thumbnailImageFileId);
            }
            return null;
        }

        DataFile thumbnailImageFile = null;

        if (dvobjectViewMap.containsKey(thumbnailImageFileId)
                && dvobjectViewMap.get(thumbnailImageFileId).isInstanceofDataFile()) {
            thumbnailImageFile = (DataFile) dvobjectViewMap.get(thumbnailImageFileId);
        } else {
            thumbnailImageFile = dataFileService.findCheapAndEasy(thumbnailImageFileId);
            if (thumbnailImageFile != null) {
                // TODO:
                // do we need this file on the map? - it may not even produce
                // a thumbnail!
                dvobjectViewMap.put(thumbnailImageFileId, thumbnailImageFile);
            } else {
                this.dvobjectThumbnailsMap.put(thumbnailImageFileId, "");
                return null;
            }
        }

        if (dataFileService.isThumbnailAvailable(thumbnailImageFile)) {
            cardImageUrl = ImageThumbConverter.getImageThumbnailAsBase64(thumbnailImageFile,
                    ImageThumbConverter.DEFAULT_CARDIMAGE_SIZE);
        }

        if (cardImageUrl != null) {
            this.dvobjectThumbnailsMap.put(thumbnailImageFileId, cardImageUrl);
        } else {
            this.dvobjectThumbnailsMap.put(thumbnailImageFileId, "");
        }
    }

    //logger.info("dataset id " + result.getEntityId() + ", returning " + cardImageUrl);

    return cardImageUrl;
}

From source file:com.amazonaws.sample.entitlement.services.AdministrationService.java

/**
 * Add user/*from  w w w  .j  ava 2s  .  c om*/
 * @throws ApplicationBadStateException if the application the current request is for is in an error state
 * @return prettified string of JSON
 */
public String addUser(String user) throws ApplicationBadStateException, UserBadIdentifierException {
    try {
        Item userItem = Item.fromJSON(user);
        String base64EncEmail = Base64.getEncoder().withoutPadding()
                .encodeToString(userItem.getString("email").getBytes("utf-8"));
        GetOpenIdTokenForDeveloperIdentityRequest req = new GetOpenIdTokenForDeveloperIdentityRequest();
        req.setIdentityPoolId(awsCognitoIdentityPool);
        req.addLoginsEntry(awsCognitoDeveloperProviderName, base64EncEmail);
        GetOpenIdTokenForDeveloperIdentityResult res = cognitoIdentityClient
                .getOpenIdTokenForDeveloperIdentity(req);
        String cognitoIdentityId = res.getIdentityId();
        userItem.withString("id", cognitoIdentityId);
        entitlementServiceUserTable.putItem(userItem).getItem();
        return userItem.toJSONPretty();
    } catch (AmazonServiceException e) {
        if (e.getErrorType().equals(AmazonServiceException.ErrorType.Service)) {
            log.error("An error occurred while getting data from DynamoDB: " + e);
        }
        throw e;
    } catch (UnsupportedEncodingException e) {
        String m = "An error occurred while encoding provided user's email address.";
        log.error(m + e);
        throw new UserBadIdentifierException(m);
    }
}

From source file:at.medevit.elexis.emediplan.core.internal.EMediplanServiceImpl.java

/**
 * Get the encoded (Header with zipped and Base64 encoded content) String. The header of the
 * current CHMED Version is added to the resulting String.
 * /*from  w ww  .  j  a va 2s  . c  o m*/
 * @param json
 * @return
 */
protected String getEncodedJson(@NonNull String json) {
    StringBuilder sb = new StringBuilder();
    // header for compresses json
    sb.append("CHMED16A1");

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try (GZIPOutputStream gzip = new GZIPOutputStream(out)) {
        gzip.write(json.getBytes());
    } catch (IOException e) {
        LoggerFactory.getLogger(getClass()).error("Error encoding json", e);
        throw new IllegalStateException("Error encoding json", e);
    }
    sb.append(Base64.getEncoder().encodeToString(out.toByteArray()));
    return sb.toString();
}