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.jaqpot.algorithms.resource.Standarization.java

@POST
@Path("training")
public Response training(TrainingRequest request) {
    try {//from www .  j a v a2 s. c om
        if (request.getDataset().getDataEntry().isEmpty()
                || request.getDataset().getDataEntry().get(0).getValues().isEmpty()) {
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity("Dataset is empty. Cannot train model on empty dataset.").build();
        }
        List<String> features = request.getDataset().getDataEntry().stream().findFirst().get().getValues()
                .keySet().stream().filter(feature -> !feature.equals(request.getPredictionFeature()))
                .collect(Collectors.toList());

        LinkedHashMap<String, Double> maxValues = new LinkedHashMap<>();
        LinkedHashMap<String, Double> minValues = new LinkedHashMap<>();

        features.stream().forEach(feature -> {
            List<Double> values = request.getDataset().getDataEntry().stream().map(dataEntry -> {
                return Double.parseDouble(dataEntry.getValues().get(feature).toString());
            }).collect(Collectors.toList());
            double[] doubleValues = values.stream().mapToDouble(Double::doubleValue).toArray();

            Double mean = StatUtils.mean(doubleValues);
            Double stddev = Math.sqrt(StatUtils.variance(doubleValues));

            maxValues.put(feature, stddev);
            minValues.put(feature, mean);
        });
        ScalingModel model = new ScalingModel();
        model.setMaxValues(maxValues);
        model.setMinValues(minValues);

        TrainingResponse response = new TrainingResponse();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(baos);
        out.writeObject(model);
        String base64Model = Base64.getEncoder().encodeToString(baos.toByteArray());
        response.setRawModel(base64Model);
        response.setIndependentFeatures(features);
        response.setPredictedFeatures(features.stream().map(feature -> {
            return "Standarized " + feature;
        }).collect(Collectors.toList()));
        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.eclipse.smarthome.binding.homematic.internal.communicator.message.XmlRpcRequest.java

/**
 * Generates a value tag based on the type of the value.
 *//* w ww .  j  av a  2 s .  c o  m*/
private void generateValue(Object value) {
    if (value == null) {
        tag("string", "void");
    } else {
        Class<?> clazz = value.getClass();
        if (clazz == String.class || clazz == Character.class) {
            sb.append(StringEscapeUtils.escapeXml(value.toString()));
        } else if (clazz == Long.class || clazz == Integer.class || clazz == Short.class
                || clazz == Byte.class) {
            tag("int", value.toString());
        } else if (clazz == Double.class) {
            tag("double", String.valueOf(((Double) value).doubleValue()));
        } else if (clazz == Float.class) {
            BigDecimal bd = new BigDecimal((Float) value);
            generateValue(bd.setScale(6, RoundingMode.HALF_DOWN).doubleValue());
        } else if (clazz == BigDecimal.class) {
            generateValue(((BigDecimal) value).setScale(6, RoundingMode.HALF_DOWN).doubleValue());
        } else if (clazz == Boolean.class) {
            tag("boolean", ((Boolean) value).booleanValue() ? "1" : "0");
        } else if (clazz == Date.class) {
            tag("dateTime.iso8601", xmlRpcDateFormat.format(((Date) value)));
        } else if (value instanceof Calendar) {
            generateValue(((Calendar) value).getTime());
        } else if (value instanceof byte[]) {
            tag("base64", Base64.getEncoder().encodeToString((byte[]) value));
        } else if (clazz.isArray() || value instanceof List) {
            sb.append("<array><data>");

            Object[] array = null;
            if (value instanceof List) {
                array = ((List<?>) value).toArray();
            } else {
                array = (Object[]) value;
            }
            for (Object arrayObject : array) {
                sb.append("<value>");
                generateValue(arrayObject);
                sb.append("</value>");
            }

            sb.append("</data></array>");
        } else if (value instanceof Map) {
            sb.append("<struct>");

            for (Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
                sb.append("<member>");
                sb.append("<name>").append(entry.getKey()).append("</name>");
                sb.append("<value>");
                generateValue(entry.getValue());
                sb.append("</value>");
                sb.append("</member>");
            }

            sb.append("</struct>");
        } else {
            throw new RuntimeException("Unsupported XML-RPC Type: " + value.getClass());
        }
    }
}

From source file:com.nike.cerberus.service.Ec2UserDataService.java

private String encodeUserData(String userData) {
    return Base64.getEncoder().encodeToString(userData.getBytes(Charset.forName("UTF-8")));
}

From source file:SdkUnitTests.java

@Test
public void RequestASignatureTest() {

    byte[] fileBytes = null;
    try {//from   ww w .jav a 2  s . c om
        //  String currentDir = new java.io.File(".").getCononicalPath();

        String currentDir = System.getProperty("user.dir");

        Path path = Paths.get(currentDir + SignTest1File);
        fileBytes = Files.readAllBytes(path);
    } catch (IOException ioExcp) {
        Assert.assertEquals(null, ioExcp);
    }

    // create an envelope to be signed
    EnvelopeDefinition envDef = new EnvelopeDefinition();
    envDef.setEmailSubject("Please Sign my Java SDK Envelope");
    envDef.setEmailBlurb("Hello, Please sign my Java SDK Envelope.");

    // add a document to the envelope
    Document doc = new Document();
    String base64Doc = Base64.getEncoder().encodeToString(fileBytes);
    doc.setDocumentBase64(base64Doc);
    doc.setName("TestFile.pdf");
    doc.setDocumentId("1");

    List<Document> docs = new ArrayList<Document>();
    docs.add(doc);
    envDef.setDocuments(docs);

    // Add a recipient to sign the document
    Signer signer = new Signer();
    signer.setEmail(UserName);
    signer.setName("Pat Developer");
    signer.setRecipientId("1");

    // Create a SignHere tab somewhere on the document for the signer to sign
    SignHere signHere = new SignHere();
    signHere.setDocumentId("1");
    signHere.setPageNumber("1");
    signHere.setRecipientId("1");
    signHere.setXPosition("100");
    signHere.setYPosition("100");

    List<SignHere> signHereTabs = new ArrayList<SignHere>();
    signHereTabs.add(signHere);
    Tabs tabs = new Tabs();
    tabs.setSignHereTabs(signHereTabs);
    signer.setTabs(tabs);

    // Above causes issue
    envDef.setRecipients(new Recipients());
    envDef.getRecipients().setSigners(new ArrayList<Signer>());
    envDef.getRecipients().getSigners().add(signer);

    // send the envelope (otherwise it will be "created" in the Draft folder
    envDef.setStatus("sent");

    try {

        ApiClient apiClient = new ApiClient();
        apiClient.setBasePath(BaseUrl);

        String creds = createAuthHeaderCreds(UserName, Password, IntegratorKey);
        apiClient.addDefaultHeader("X-DocuSign-Authentication", creds);
        Configuration.setDefaultApiClient(apiClient);

        AuthenticationApi authApi = new AuthenticationApi();

        AuthenticationApi.LoginOptions loginOptions = authApi.new LoginOptions();
        loginOptions.setApiPassword("true");
        loginOptions.setIncludeAccountIdGuid("true");
        LoginInformation loginInfo = authApi.login(loginOptions);

        Assert.assertNotNull(loginInfo);
        Assert.assertNotNull(loginInfo.getLoginAccounts());
        Assert.assertTrue(loginInfo.getLoginAccounts().size() > 0);
        List<LoginAccount> loginAccounts = loginInfo.getLoginAccounts();
        Assert.assertNotNull(loginAccounts.get(0).getAccountId());

        String accountId = loginInfo.getLoginAccounts().get(0).getAccountId();

        EnvelopesApi envelopesApi = new EnvelopesApi();

        EnvelopeSummary envelopeSummary = envelopesApi.createEnvelope(accountId, envDef);

        Assert.assertNotNull(envelopeSummary);
        Assert.assertNotNull(envelopeSummary.getEnvelopeId());
        Assert.assertEquals("sent", envelopeSummary.getStatus());

        System.out.println("EnvelopeSummary: " + envelopeSummary);

    } catch (ApiException ex) {
        System.out.println("Exception: " + ex);
        Assert.assertEquals(null, ex);
    }
}

From source file:vazkii.psi.client.core.helper.SharingHelper.java

public static String takeScreenshot() throws Exception {
    Minecraft mc = Minecraft.getMinecraft();

    ScaledResolution res = new ScaledResolution(mc);
    int screenWidth = mc.displayWidth;
    int screenHeight = mc.displayHeight;

    int scale = res.getScaleFactor();
    int width = 380 * scale;
    int height = 200 * scale;

    int left = screenWidth / 2 - width / 2;
    int top = screenHeight / 2 - height / 2;

    int i = width * height;

    if (pixelBuffer == null || pixelBuffer.capacity() < i) {
        pixelBuffer = BufferUtils.createIntBuffer(i);
        pixelValues = new int[i];
    }/*from  w w w  .  jav a2 s  . com*/

    GL11.glPixelStorei(GL11.GL_PACK_ALIGNMENT, 1);
    GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1);
    pixelBuffer.clear();

    GL11.glReadPixels(left, top, width, height, GL12.GL_BGRA, GL12.GL_UNSIGNED_INT_8_8_8_8_REV,
            (IntBuffer) pixelBuffer);

    pixelBuffer.get(pixelValues);
    TextureUtil.processPixelValues(pixelValues, width, height);
    BufferedImage bufferedimage = null;

    bufferedimage = new BufferedImage(width, height, 1);
    bufferedimage.setRGB(0, 0, width, height, pixelValues, 0, width);

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    ImageIO.write(bufferedimage, "png", stream);
    byte[] bArray = stream.toByteArray();
    String base64 = Base64.getEncoder().encodeToString(bArray);
    return base64;
}

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

@POST
@Path("training")
public Response training(TrainingRequest request) {
    try {// ww  w.j  a v  a2  s . c om
        if (request.getDataset().getDataEntry().isEmpty()
                || request.getDataset().getDataEntry().get(0).getValues().isEmpty()) {
            return Response.status(Response.Status.BAD_REQUEST).entity(
                    ErrorReportFactory.badRequest("Dataset is empty", "Cannot train model on empty dataset"))
                    .build();
        }
        List<String> features = request.getDataset().getDataEntry().stream().findFirst().get().getValues()
                .keySet().stream().filter(feature -> !feature.equals(request.getPredictionFeature()))
                .collect(Collectors.toList());

        LinkedHashMap<String, Double> maxValues = new LinkedHashMap<>();
        LinkedHashMap<String, Double> minValues = new LinkedHashMap<>();

        features.stream().forEach(feature -> {
            List<Double> values = request.getDataset().getDataEntry().stream().map(dataEntry -> {
                return Double.parseDouble(dataEntry.getValues().get(feature).toString());
            }).collect(Collectors.toList());
            double[] doubleValues = values.stream().mapToDouble(Double::doubleValue).toArray();

            Double mean = StatUtils.mean(doubleValues);
            Double stddev = Math.sqrt(StatUtils.variance(doubleValues));

            maxValues.put(feature, stddev);
            minValues.put(feature, mean);
        });
        ScalingModel model = new ScalingModel();
        model.setMaxValues(maxValues);
        model.setMinValues(minValues);

        TrainingResponse response = new TrainingResponse();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(baos);
        out.writeObject(model);
        String base64Model = Base64.getEncoder().encodeToString(baos.toByteArray());
        response.setRawModel(base64Model);
        response.setIndependentFeatures(features);
        response.setPredictedFeatures(features.stream().map(feature -> {
            return "Standarized " + feature;
        }).collect(Collectors.toList()));
        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.codice.ddf.branding.impl.DdfBrandingPlugin.java

@Override
public String getBase64FavIcon() throws IOException {
    try (InputStream inputStream = DdfBrandingPlugin.class.getResourceAsStream(getFavIcon())) {
        byte[] favIconAsBytes = IOUtils.toByteArray(inputStream);
        if (favIconAsBytes.length > 0) {
            return Base64.getEncoder().encodeToString(favIconAsBytes);
        }//w ww.j  av  a  2  s . c  om
    }
    return "";
}

From source file:jp.primecloud.auto.sdk.Requester.java

protected String createQueryString(String endpointPath, Map<String, String> parameters) {
    StringBuilder param = new StringBuilder();
    param.append("AccessId=").append(accessId);
    param.append("&Timestamp=").append(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()));

    if (parameters != null && !parameters.isEmpty()) {
        for (Map.Entry<String, String> parameter : parameters.entrySet()) {
            param.append("&").append(parameter.getKey()).append("=").append(parameter.getValue());
        }//from  ww w .  j  a v  a  2s  .  c o m
    }

    String signature = HmacUtils.hmacSha256Hex(accessKey, endpointPath + "?" + param.toString());

    param.append("&Signature=").append(signature);

    String queryString = Base64.getEncoder().encodeToString(param.toString().getBytes(StandardCharsets.UTF_8));

    return queryString;
}

From source file:ste.web.http.BugFreeHttpUtils.java

@Test
public void parse_basic_auth_ok() throws Exception {
    final Pair<String, String>[] PAIRS = new Pair[] { new ImmutablePair<>("abcd", "1234"),
            new ImmutablePair<>("defg", "5678"), new ImmutablePair<>("hij", ""), };

    Encoder b64 = Base64.getEncoder();

    for (Pair<String, String> p : PAIRS) {
        then(HttpUtils.parseBasicAuth(new BasicHeader(HttpHeaders.AUTHORIZATION,
                "Basic " + b64.encodeToString((p.getLeft() + ':' + p.getRight()).getBytes("UTF-8")))))
                        .isEqualTo(p);/*from  w w w.  j a  v  a 2  s.c  o  m*/
    }

    Pair<String, String> p = new ImmutablePair<>("klm", null);
    then(HttpUtils.parseBasicAuth(new BasicHeader(HttpHeaders.AUTHORIZATION,
            "Basic " + b64.encodeToString(p.getLeft().getBytes("UTF-8"))))).isEqualTo(p);
}

From source file:org.hawkular.openshift.auth.BasicAuthentication.java

private boolean verifySHA1Password(String storedPassword, String passedPassword) {
    //Remove the SHA_PREFIX from the password string
    storedPassword = storedPassword.substring(SHA_PREFIX.length());

    //Get the SHA digest and encode it in Base64
    byte[] digestedPasswordBytes = DigestUtils.sha1(passedPassword);
    String digestedPassword = Base64.getEncoder().encodeToString(digestedPasswordBytes);

    //Check if the stored password matches the passed one
    if (digestedPassword.equals(storedPassword)) {
        return true;
    } else {/*  w w w .  j  a  va  2s  .  c o  m*/
        return false;
    }
}