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

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

Introduction

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

Prototype

public static String encodeBase64URLSafeString(final byte[] binaryData) 

Source Link

Document

Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output.

Usage

From source file:org.panbox.desktop.common.urihandler.PanboxURICmdImportIdentity.java

public static URI getPanboxLink(URI uri) {
    StringBuilder b = new StringBuilder();
    b.append(NAME);//from w  w  w  .ja va2  s .  c  o m
    b.append("?");
    b.append(Base64.encodeBase64URLSafeString(
            uri.toString().getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET))));
    return URI.create(PanboxConstants.PANBOX_URL_PREFIX + b.toString());
}

From source file:org.panbox.desktop.common.urihandler.PanboxURICmdShareInvitation.java

public static URI getPanboxLink(String sid, String stype) {
    StringBuilder b = new StringBuilder();
    b.append(NAME);/* ww w.ja  v a2 s . c om*/
    b.append("?");

    b.append(Base64.encodeBase64URLSafeString(sid.getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET))));
    b.append(":");
    b.append(Base64
            .encodeBase64URLSafeString(stype.getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET))));

    return URI.create(PanboxConstants.PANBOX_URL_PREFIX + b.toString());
}

From source file:org.pig.oink.commons.PigUtils.java

public static void writeStatsFile(Path filePath, PigRequestStats stats) throws Exception {
    Gson gson = new GsonBuilder().setPrettyPrinting().setDateFormat("yyyy/MM/dd-HH:mm").create();

    String encodedStats = new String(
            Base64.encodeBase64URLSafeString(gson.toJson(stats, PigRequestStats.class).getBytes()));

    try {/* ww w  .  j a v  a 2  s.c o m*/
        Configuration conf = new Configuration();
        conf = new Configuration();
        conf.set(Constants.DEFAULT_HDFS_NAME,
                PropertyLoader.getInstance().getProperty(Constants.DEFAULT_HDFS_NAME));
        FileSystem fileSystem = FileSystem.get(conf);
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fileSystem.create(filePath, true)));
        writer.write(encodedStats);
        writer.close();
    } catch (Exception e) {
        logger.log(Level.ERROR, "Unable to write input file", e);
        throw new IOException("Unable to write input file", e);
    }
}

From source file:org.pig.oink.operation.impl.PigEventListener.java

@Override
public void progressUpdatedNotification(String scriptId, int progress) {
    logger.info(progress + "% completed for request " + requestId);
    requestStats.setStatus(Status.SUBMITTED.toString());
    requestStats.setProgress(progress);/*  ww  w  .  j  a v a2  s.com*/

    try {
        PigUtils.writeStatsFile(new Path(requestPath + "/stats"), requestStats);
    } catch (Exception e) {
        logger.error("Unable to write stats file for path: " + requestPath);
    }

    if (httpUrl != null) {
        String encodedStats = new String(
                Base64.encodeBase64URLSafeString(gson.toJson(requestStats).getBytes()));
        Map<String, String> parameters = new HashMap<String, String>();
        parameters.put("$stats", encodedStats);
        parameters.put("$id", requestId);
        parameters.put("$status", Status.SUBMITTED.toString());
        EndNotificationServiceImpl.getService().sendHttpNotification(httpUrl, parameters);
    }

}

From source file:org.pig.oink.operation.impl.SubmitTask.java

@Override
public void run() {
    Gson gson = new GsonBuilder().setPrettyPrinting().setDateFormat("yyyy/MM/dd-HH:mm").create();

    List<String> parameters = new ArrayList<String>();
    Map<String, String> inputParams = params.getInputParameters();
    String httpCallBack = params.getHttpCallback();

    String defaultHdfsName = PropertyLoader.getInstance().getProperty(Constants.DEFAULT_HDFS_NAME);
    Configuration conf = new Configuration();
    conf.set(Constants.DEFAULT_HDFS_NAME, defaultHdfsName);
    FileSystem fileSystem = null;
    try {/* ww w  .java  2  s .  co m*/
        fileSystem = FileSystem.get(conf);
    } catch (Exception e) {
        logger.error("Unable to create filesystem object to write input file", e);
        return;
    }

    String requestPath = PropertyLoader.getInstance().getProperty(Constants.REQUEST_PATH);
    String scriptPath = PropertyLoader.getInstance().getProperty(Constants.SCRIPTS_PATH);

    String log4jPath = getClass().getResource("/log4j.xml").getPath();
    Path inputPath = new Path(requestPath + requestId + "/input");
    String jsonStr = gson.toJson(params);
    String encodedParams = new String(Base64.encodeBase64URLSafeString(jsonStr.getBytes()));
    try {
        if (!fileSystem.exists(inputPath)) {
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(fileSystem.create(inputPath, false)));
            writer.write(encodedParams);
            writer.close();
        } else {
            logger.error("Input file already exists");
        }
    } catch (IOException e) {
        logger.error("Unable to write input file", e);
    }

    for (Map.Entry<String, String> entry : inputParams.entrySet()) {
        parameters.add("-p");
        parameters.add(entry.getKey() + "=" + entry.getValue());
    }

    String outputPath = requestPath + requestId + "/output";
    parameters.add("-p");
    parameters.add("output=" + outputPath);

    parameters.add("-4");
    parameters.add(log4jPath);

    parameters.add("-f");
    parameters.add(scriptPath + scriptName);

    String args[] = new String[parameters.size()];
    PigEventListener listener = new PigEventListener(httpCallBack, requestId);
    PigRequestStats requestStats = listener.getStats();
    Path statsPath = new Path(requestPath + requestId + "/stats");

    try {
        PigUtils.writeStatsFile(statsPath, requestStats);
    } catch (Exception e) {
        logger.error("Unable to write stats file", e);
    }

    PigStats pigStats = PigRunner.run(parameters.toArray(args), listener);

    requestStats = listener.getStats();
    requestStats.setBytesWritten(pigStats.getBytesWritten());
    requestStats.setDuration(pigStats.getDuration());
    Map<String, String> outputParams = new HashMap<String, String>();
    if (pigStats.isSuccessful()) {
        outputParams.put("$status", Status.SUCCEEDED.toString());
        requestStats.setStatus(Status.SUCCEEDED.toString());
    } else {
        outputParams.put("$status", Status.FAILED.toString());
        requestStats.setStatus(Status.FAILED.toString());
    }

    if (requestStats.getErrorMessage() == null) {
        requestStats.setErrorMessage(pigStats.getErrorMessage());
    }

    requestStats.setProgress(100);

    String encodedStats = new String(
            Base64.encodeBase64URLSafeString(gson.toJson(requestStats, PigRequestStats.class).getBytes()));

    try {
        PigUtils.writeStatsFile(statsPath, requestStats);
    } catch (Exception e) {
        logger.error("Unable to write stats file", e);
    }

    outputParams.put("$stats", encodedStats);
    outputParams.put("$id", requestId);
    if (httpCallBack != null) {
        EndNotificationServiceImpl.getService().sendHttpNotification(httpCallBack, outputParams);
    }
}

From source file:org.pig.oink.rest.TestPigResource.java

@Test
public void testGetRequest() throws Exception {
    PigResource resource = new PigResource();
    PigRequestParameters input = new PigRequestParameters();
    input.setHttpCallback("123");
    input.setPigScript("abc.pig");
    input.setRequestStartTime(new Date());

    String requestId = UUID.randomUUID().toString();
    Gson gson = new GsonBuilder().setPrettyPrinting().setDateFormat("yyyy/MM/dd-HH:mm").create();
    String inputString = Base64.encodeBase64URLSafeString(gson.toJson(input).getBytes());
    String path = PropertyLoader.getInstance().getProperty("requests.basepath") + requestId + "/input";

    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(fileSystem.create(new Path(path), false)));
    writer.write(inputString);//from   w  w w . j  a va2 s.  c  o m
    writer.close();

    Response resp = resource.getInput(requestId);
    Assert.assertEquals(resp.getStatus(), 200);

    requestId = "abc";
    try {
        resp = resource.getInput(requestId);
    } catch (Exception e) {
        Assert.assertNotNull(e);
    }

    requestId = UUID.randomUUID().toString();
    fileSystem.mkdirs(new Path(PropertyLoader.getInstance().getProperty("requests.basepath") + requestId));
    try {
        resp = resource.getInput(requestId);
    } catch (Exception e) {
        Assert.assertNotNull(e);
    }
}

From source file:org.plasma.sdo.core.CoreDataObject.java

public String uuidToBase64(String str) {
    ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
    bb.putLong(this.uuid.getMostSignificantBits());
    bb.putLong(this.uuid.getLeastSignificantBits());
    return Base64.encodeBase64URLSafeString(bb.array());
}

From source file:org.projectforge.common.Crypt.java

/**
 * Encrypts the given str with AES. The password is first converted using SHA-256.
 * @param password/*from www  . j  a  v  a2s .co  m*/
 * @param str
 * @return The base64 encoded result (url safe).
 */
public static String encrypt(final String password, final String data) {
    initialize();
    try {
        // AES is sometimes not part of Java, therefore use bouncy castle provider:
        final Cipher cipher = Cipher.getInstance(CRYPTO_ALGORITHM);
        final byte[] keyValue = getPassword(password);
        final Key key = new SecretKeySpec(keyValue, "AES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        final byte[] encVal = cipher.doFinal(data.getBytes("UTF-8"));
        final String encryptedValue = Base64.encodeBase64URLSafeString(encVal);
        return encryptedValue;
    } catch (final Exception ex) {
        log.error("Exception encountered while trying to encrypt with Algorithm 'AES' and the given password: "
                + ex.getMessage(), ex);
        return null;
    }
}

From source file:org.projectforge.common.NumberHelper.java

/**
 * Generates secure random bytes of the given length and return base 64 encoded bytes as url safe String. This is not the length of the
 * resulting string!/*ww w  .jav  a 2s .c  o m*/
 * @param numberOfBytes
 * @return
 */
public static String getSecureRandomUrlSaveString(final int numberOfBytes) {
    final SecureRandom random = new SecureRandom();
    final byte[] bytes = new byte[numberOfBytes];
    random.nextBytes(bytes);
    return Base64.encodeBase64URLSafeString(bytes);
}

From source file:org.psl.fidouaf.core.ops.AuthenticationResponseProcessing.java

private AuthenticatorRecord processAssertions(AuthenticatorSignAssertion authenticatorSignAssertion,
        StorageInterface storage) throws DataRecordNotFoundException {
    TlvAssertionParser parser = new TlvAssertionParser();
    AuthenticatorRecord authRecord = new AuthenticatorRecord();
    RegistrationRecord registrationRecord = null;

    try {//ww w.j  a v a 2  s .  c  om
        Tags tags = parser.parse(authenticatorSignAssertion.assertion);
        authRecord.AAID = new String(tags.getTags().get(TagsEnum.TAG_AAID.id).value);
        authRecord.KeyID = Base64.encodeBase64URLSafeString(tags.getTags().get(TagsEnum.TAG_KEYID.id).value);
        // authRecord.KeyID = new String(
        // tags.getTags().get(TagsEnum.TAG_KEYID.id).value);

        registrationRecord = getRegistrationRecordFrmDB(authRecord, storage);
        Tag signnedData = tags.getTags().get(TagsEnum.TAG_UAFV1_SIGNED_DATA.id);
        Tag signature = tags.getTags().get(TagsEnum.TAG_SIGNATURE.id);
        Tag info = tags.getTags().get(TagsEnum.TAG_ASSERTION_INFO.id);
        AlgAndEncodingEnum algAndEncoding = getAlgAndEncoding(info);
        String pubKey = registrationRecord.PublicKey;
        try {
            if (!verifySignature(signnedData, signature, pubKey, algAndEncoding)) {
                logger.log(Level.INFO,
                        "Signature verification failed for authenticator: " + authRecord.toString());
                authRecord.status = "FAILED_SIGNATURE_NOT_VALID";
                return authRecord;
            }
        } catch (Exception e) {
            logger.log(Level.INFO, "Signature verification failed for authenticator: " + authRecord.toString(),
                    e);
            authRecord.status = "FAILED_SIGNATURE_VERIFICATION";
            return authRecord;
        }
        authRecord.username = registrationRecord.username;
        authRecord.deviceId = registrationRecord.deviceId;
        authRecord.status = "SUCCESS";
        return authRecord;
    } catch (IOException e) {
        logger.log(Level.INFO, "Fail to parse assertion: " + authenticatorSignAssertion.assertion, e);
        authRecord.status = "FAILED_ASSERTION_VERIFICATION";
        return authRecord;
    }
}