Example usage for java.util Base64 getDecoder

List of usage examples for java.util Base64 getDecoder

Introduction

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

Prototype

public static Decoder getDecoder() 

Source Link

Document

Returns a Decoder that decodes using the Basic type base64 encoding scheme.

Usage

From source file:org.wso2.carbon.webapp.authenticator.framework.authenticator.BasicAuthAuthenticator.java

private Credentials getCredentials(Request request) {
    Credentials credentials = null;/*from   www . j  av a  2 s. com*/
    String username;
    String password = null;
    MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders()
            .getValue(Constants.HTTPHeaders.HEADER_HTTP_AUTHORIZATION);
    if (authorization != null) {
        authorization.toBytes();
        String authorizationString = authorization.getByteChunk().toString();
        if (authorizationString.toLowerCase().startsWith(AUTH_HEADER)) {
            // Authorization: Basic base64credentials
            String base64Credentials = authorizationString.substring(AUTH_HEADER.length()).trim();
            String decodedString = new String(Base64.getDecoder().decode(base64Credentials),
                    Charset.forName("UTF-8"));
            int colon = decodedString.indexOf(':', 0);
            if (colon < 0) {
                username = decodedString;
            } else {
                username = decodedString.substring(0, colon);
                password = decodedString.substring(colon + 1);
            }
            credentials = new Credentials(username, password);
        }
    }
    return credentials;
}

From source file:com.github.cambierr.lorawanpacket.semtech.Txpk.java

public Txpk(JSONObject _json) throws MalformedPacketException {

    /**/* w  w  w.  j  av  a2  s .co m*/
     * imme
     */
    if (!_json.has("imme")) {
        imme = false;
    } else {
        imme = _json.getBoolean("imme");
    }

    /**
     * tmst
     */
    if (!_json.has("tmst")) {
        tmst = Integer.MAX_VALUE;
    } else {
        tmst = _json.getInt("tmst");
    }

    /**
     * time
     */
    if (!_json.has("time")) {
        time = null;
    } else {
        time = _json.getString("time");
    }

    /**
     * rfch
     */
    if (!_json.has("rfch")) {
        throw new MalformedPacketException("missing rfch");
    } else {
        rfch = _json.getInt("rfch");
    }

    /**
     * freq
     */
    if (!_json.has("freq")) {
        throw new MalformedPacketException("missing freq");
    } else {
        freq = _json.getDouble("stat");
    }

    /**
     * powe
     */
    if (!_json.has("powe")) {
        throw new MalformedPacketException("missing powe");
    } else {
        powe = _json.getInt("powe");
    }

    /**
     * modu
     */
    if (!_json.has("modu")) {
        throw new MalformedPacketException("missing modu");
    } else {
        modu = Modulation.parse(_json.getString("modu"));
    }

    /**
     * datr
     */
    if (!_json.has("datr")) {
        throw new MalformedPacketException("missing datr");
    } else {
        switch (modu) {
        case FSK:
            datr = _json.getInt("datr");
            break;
        case LORA:
            datr = _json.getString("datr");
            break;
        }
    }

    /**
     * codr
     */
    if (!_json.has("codr")) {
        if (modu.equals(Modulation.FSK)) {
            codr = null;
        } else {
            throw new MalformedPacketException("missing codr");
        }
    } else {
        codr = _json.getString("codr");
    }

    /**
     * fdev
     */
    if (!_json.has("fdev")) {
        if (modu.equals(Modulation.LORA)) {
            fdev = Integer.MAX_VALUE;
        } else {
            throw new MalformedPacketException("missing fdev");
        }
    } else {
        fdev = _json.getInt("fdev");
    }

    /**
     * ipol
     */
    if (!_json.has("ipol")) {
        if (modu.equals(Modulation.FSK)) {
            ipol = false;
        } else {
            throw new MalformedPacketException("missing ipol");
        }
    } else {
        ipol = _json.getBoolean("ipol");
    }

    /**
     * prea
     */
    if (!_json.has("prea")) {
        throw new MalformedPacketException("missing prea");
    } else {
        prea = _json.getInt("prea");
    }

    /**
     * size
     */
    if (!_json.has("size")) {
        throw new MalformedPacketException("missing size");
    } else {
        size = _json.getInt("size");
    }

    /**
     * data
     */
    if (!_json.has("data")) {
        throw new MalformedPacketException("missing data");
    } else {
        byte[] raw;

        try {
            raw = Base64.getDecoder().decode(_json.getString("data"));
        } catch (IllegalArgumentException ex) {
            throw new MalformedPacketException("malformed data");
        }

        data = new PhyPayload(ByteBuffer.wrap(raw));
    }

    /**
     * ncrc
     */
    if (!_json.has("ncrc")) {
        ncrc = false;
    } else {
        ncrc = _json.getBoolean("ncrc");
    }
}

From source file:org.springframework.session.web.http.DefaultCookieSerializer.java

/**
 * Decode the value using Base64./*  w ww  .ja va  2 s.c  o m*/
 * @param base64Value the Base64 String to decode
 * @return the Base64 decoded value
 * @since 1.2.2
 */
private String base64Decode(String base64Value) {
    try {
        byte[] decodedCookieBytes = Base64.getDecoder().decode(base64Value);
        return new String(decodedCookieBytes);
    } catch (Exception ex) {
        logger.debug("Unable to Base64 decode value: " + base64Value);
        return null;
    }
}

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

@Override
public void parseValue(final PlainSchema schema, final String value) {
    Exception exception = null;/*  w  w  w.  j  a va 2  s .c o m*/

    switch (schema.getType()) {

    case Boolean:
        this.setBooleanValue(Boolean.parseBoolean(value));
        break;

    case Long:
        try {
            this.setLongValue(schema.getConversionPattern() == null ? Long.valueOf(value)
                    : FormatUtils.parseNumber(value, schema.getConversionPattern()).longValue());
        } catch (Exception pe) {
            exception = pe;
        }
        break;

    case Double:
        try {
            this.setDoubleValue(schema.getConversionPattern() == null ? Double.valueOf(value)
                    : FormatUtils.parseNumber(value, schema.getConversionPattern()).doubleValue());
        } catch (Exception pe) {
            exception = pe;
        }
        break;

    case Date:
        try {
            this.setDateValue(schema.getConversionPattern() == null ? FormatUtils.parseDate(value)
                    : new Date(FormatUtils.parseDate(value, schema.getConversionPattern()).getTime()));
        } catch (Exception pe) {
            exception = pe;
        }
        break;

    case Encrypted:
        try {
            this.setStringValue(
                    Encryptor.getInstance(schema.getSecretKey()).encode(value, schema.getCipherAlgorithm()));
        } catch (Exception pe) {
            exception = pe;
        }
        break;

    case Binary:
        this.setBinaryValue(Base64.getDecoder().decode(value));
        break;

    case String:
    case Enum:
    default:
        this.setStringValue(value);
    }

    if (exception != null) {
        throw new ParsingValidationException("While trying to parse '" + value + "' as " + schema.getKey(),
                exception);
    }
}

From source file:org.jaqpot.algorithms.resource.Standarization.java

@POST
@Path("prediction")
public Response prediction(PredictionRequest request) {
    try {// www. j a va2 s.  com
        if (request.getDataset().getDataEntry().isEmpty()
                || request.getDataset().getDataEntry().get(0).getValues().isEmpty()) {
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity("Dataset is empty. Cannot make predictions on empty dataset.").build();
        }
        List<String> features = request.getDataset().getDataEntry().stream().findFirst().get().getValues()
                .keySet().stream().collect(Collectors.toList());
        String base64Model = (String) request.getRawModel();
        byte[] modelBytes = Base64.getDecoder().decode(base64Model);
        ByteArrayInputStream bais = new ByteArrayInputStream(modelBytes);
        ObjectInput in = new ObjectInputStream(bais);
        ScalingModel model = (ScalingModel) in.readObject();
        in.close();
        bais.close();

        List<LinkedHashMap<String, Object>> predictions = new ArrayList<>();

        for (DataEntry dataEntry : request.getDataset().getDataEntry()) {
            LinkedHashMap<String, Object> data = new LinkedHashMap<>();
            for (String feature : features) {
                Double stdev = model.getMaxValues().get(feature);
                Double mean = model.getMinValues().get(feature);
                Double value = Double.parseDouble(dataEntry.getValues().get(feature).toString());
                if (stdev != null && stdev != 0.0 && mean != null) {
                    value = (value - mean) / stdev;
                } else {
                    value = 1.0;
                }
                data.put("Standarized " + feature, value);
            }
            predictions.add(data);
        }

        PredictionResponse response = new PredictionResponse();
        response.setPredictions(predictions);

        return Response.ok(response).build();
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, null, ex);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
    }
}

From source file:org.onehippo.forge.content.pojo.model.BinaryValue.java

/**
 * Converts the given {@code dataUri} which is supposed to be a <code>data:</code> URL
 * to a {@link BinaryValue} object.//  ww  w .j  a  va2s .co m
 * @param dataUri a <code>data:</code> URL
 * @return a {@link BinaryValue} object converted from the given {@code dataUri}
 */
public static BinaryValue fromDataURI(String dataUri) {
    if (!StringUtils.startsWith(dataUri, "data:")) {
        throw new IllegalArgumentException("Invalid data uri.");
    }

    int offset = StringUtils.indexOf(dataUri, ',');

    if (offset == -1) {
        throw new IllegalArgumentException("Invalid data uri.");
    }

    String mediaType = null;
    String charset = null;
    String metadata = dataUri.substring(5, offset);
    String[] tokens = StringUtils.split(metadata, ";");

    if (tokens != null) {
        for (String token : tokens) {
            if (token.startsWith("charset=")) {
                charset = token.substring(8);
            } else if (!token.equals("base64")) {
                mediaType = token;
            }
        }
    }

    String dataString = dataUri.substring(offset + 1);

    byte[] data = Base64.getDecoder().decode(dataString);
    BinaryValue binaryValue = new BinaryValue(data, mediaType, charset);

    return binaryValue;
}

From source file:oracle.custom.ui.utils.ServerUtils.java

public static PublicKey getServerPublicKey(String domainName) throws Exception {
    HttpClient client = getClient(domainName);
    PublicKey key = null;/*  w  ww.  j  av a 2  s  . c  o m*/
    String url = getIDCSBaseURL(domainName) + "/admin/v1/SigningCert/jwk";
    URI uri = new URI(url);
    HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    HttpGet httpGet = new HttpGet(uri);
    httpGet.addHeader("Authorization", "Bearer " + AccessTokenUtils.getAccessToken(domainName));
    HttpResponse response = client.execute(host, httpGet);
    try {
        HttpEntity entity2 = response.getEntity();
        String res = EntityUtils.toString(entity2);
        EntityUtils.consume(entity2);
        ObjectMapper mapper = new ObjectMapper();
        System.out.println("result is " + res);
        SigningKeys signingKey = mapper.readValue(res, SigningKeys.class);

        String base64Cert = signingKey.getKeys().get(0).getX5c().get(0);
        byte encodedCert[] = Base64.getDecoder().decode(base64Cert);
        ByteArrayInputStream inputStream = new ByteArrayInputStream(encodedCert);

        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(inputStream);
        key = cert.getPublicKey();
    } finally {
        if (response instanceof CloseableHttpResponse) {
            ((CloseableHttpResponse) response).close();
        }
    }
    return key;
}

From source file:com.ottogroup.bi.streaming.operator.json.decode.Base64ContentDecoder.java

/**
 * Decodes the provided {@link Base64} encoded string. Prior decoding a possibly existing prefix is removed from the encoded string.
 * The result which is received from {@link Decoder#decode(byte[])} as array of bytes is converted into a string representation which
 * follows the given encoding //  ww  w.  ja  v  a2  s  .c om
 * @param base64EncodedString
 *          The {@link Base64} encoded string
 * @param noValuePrefix
 *          An optional prefix attached to string after encoding (eg to mark it as base64 value) which must be removed prior decoding
 * @param encoding
 *          The encoding applied on converting the resulting byte array into a string representation  
 * @return
 */
protected String decodeBase64(final String base64EncodedString, final String noValuePrefix,
        final String encoding) throws UnsupportedEncodingException {

    // if the base64 encoded string is either empty or holds only the prefix that must be removed before decoding, the method returns an empty string
    if (StringUtils.isBlank(base64EncodedString)
            || StringUtils.equalsIgnoreCase(base64EncodedString, noValuePrefix))
        return "";

    // remove optional prefix and decode - if the prefix does not exist, simply decode the input
    byte[] result = null;
    if (StringUtils.startsWith(base64EncodedString, noValuePrefix))
        result = Base64.getDecoder().decode(StringUtils.substring(base64EncodedString, noValuePrefix.length()));
    else
        result = Base64.getDecoder().decode(base64EncodedString);

    // if the result array is either null or empty the method returns an empty string
    if (result == null || result.length < 1)
        return "";

    // otherwise: the method tries to convert the array into a proper string representation following the given encoding
    return new String(result, (StringUtils.isNotBlank(encoding) ? encoding : "UTF-8"));
}

From source file:org.codice.ddf.security.handler.basic.BasicAuthenticationHandler.java

/**
 * Extract the Authorization header and parse into a username/password token.
 *
 * @param authHeader the authHeader string from the HTTP request
 * @return the initialized BaseAuthenticationToken for this username and password combination (or
 *     null)/*ww  w  .  j a  va2s.  com*/
 */
protected BaseAuthenticationToken extractAuthInfo(String authHeader) {
    BaseAuthenticationToken token = null;
    authHeader = authHeader.trim();
    String[] parts = authHeader.split(" ");
    if (parts.length == 2) {
        String authType = parts[0];
        String authInfo = parts[1];

        if (authType.equalsIgnoreCase(AUTHENTICATION_SCHEME_BASIC)) {
            byte[] decode = Base64.getDecoder().decode(authInfo);
            if (decode != null) {
                String userPass = new String(decode, StandardCharsets.UTF_8);
                String[] authComponents = userPass.split(":");
                if (authComponents.length == 2) {
                    token = tokenFactory.fromUsernamePassword(authComponents[0], authComponents[1]);
                } else if ((authComponents.length == 1) && (userPass.endsWith(":"))) {
                    token = tokenFactory.fromUsernamePassword(authComponents[0], "");
                }
            }
        }
    }
    return token;
}

From source file:org.hawkular.listener.cache.InventoryHelper.java

@VisibleForTesting
static ExtendedInventoryStructure rebuildFromChunks(List<DataPoint<String>> datapoints)
        throws InvalidInventoryChunksException {
    if (datapoints.isEmpty()) {
        throw new InvalidInventoryChunksException("Missing inventory: no datapoint found. Did they expire?");
    }//  w w w  . ja  va 2 s .  c  o  m
    DataPoint<String> masterNode = datapoints.get(0);
    Decoder decoder = Base64.getDecoder();
    final byte[] all;
    if (masterNode.getTags().containsKey("chunks")) {
        int nbChunks = Integer.parseInt(masterNode.getTags().get("chunks"));
        int totalSize = Integer.parseInt(masterNode.getTags().get("size"));
        byte[] master = decoder.decode(masterNode.getValue().getBytes());
        if (master.length == 0) {
            throw new InvalidInventoryChunksException(
                    "Missing inventory: master datapoint exists but is empty");
        }
        if (nbChunks > datapoints.size()) {
            // Sanity check: missing chunks?
            throw new InvalidInventoryChunksException("Inventory sanity check failure: " + nbChunks
                    + " chunks expected, only " + datapoints.size() + " are available");
        }
        all = new byte[totalSize];
        int pos = 0;
        System.arraycopy(master, 0, all, pos, master.length);
        pos += master.length;
        for (int i = 1; i < nbChunks; i++) {
            DataPoint<String> slaveNode = datapoints.get(i);
            // Perform sanity check using timestamps; they should all be contiguous, in decreasing order
            if (slaveNode.getTimestamp() != masterNode.getTimestamp() - i) {
                throw new InvalidInventoryChunksException(
                        "Inventory sanity check failure: chunk n" + i + " timestamp is "
                                + slaveNode.getTimestamp() + ", expecting " + (masterNode.getTimestamp() - i));
            }
            byte[] slave = decoder.decode(slaveNode.getValue().getBytes());
            System.arraycopy(slave, 0, all, pos, slave.length);
            pos += slave.length;
        }
    } else {
        // Not chunked
        all = decoder.decode(masterNode.getValue().getBytes());
    }
    try {
        String decompressed = decompress(all);
        return MAPPER.readValue(decompressed, ExtendedInventoryStructure.class);
    } catch (IOException e) {
        throw new InvalidInventoryChunksException("Could not read assembled chunks", e);
    }
}