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

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

Introduction

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

Prototype

public Base64(final int lineLength) 

Source Link

Document

Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.

Usage

From source file:com.buddycloud.mediaserver.download.DownloadAvatarTest.java

@Test
public void anonymousPreviewSuccessfulDownloadParamAuth() throws Exception {
    int height = 50;
    int width = 50;

    Base64 encoder = new Base64(true);
    String authStr = BASE_USER + ":" + BASE_TOKEN;

    String completeUrl = URL + "?maxheight=" + height + "&maxwidth=" + width + "?auth="
            + new String(encoder.encode(authStr.getBytes()));

    ClientResource client = new ClientResource(completeUrl);
    client.setChallengeResponse(ChallengeScheme.HTTP_BASIC, BASE_USER, BASE_TOKEN);

    File file = new File(TEST_OUTPUT_DIR + File.separator + "avatarPreview.jpg");
    FileOutputStream outputStream = FileUtils.openOutputStream(file);
    client.get().write(outputStream);//from  www  .j  av a  2 s.com

    Assert.assertTrue(file.exists());

    // Delete downloaded file
    FileUtils.deleteDirectory(new File(TEST_OUTPUT_DIR));
    outputStream.close();

    // Delete previews table row
    final String previewId = dataSource.getPreviewId(MEDIA_ID, height, width);
    dataSource.deletePreview(previewId);
}

From source file:com.cloudera.alfredo.client.KerberosAuthenticator.java

/**
 * Performs SPNEGO authentication against the specified URL.
 * <p/>/*from www .j a  v  a  2 s  .c  o  m*/
 * If a token is given if does a NOP and returns the given token.
 * <p/>
 * If no token is given, it will perform the SPNEGO authentication sequency using a
 *  HTTP <code>OPTIONS</code> request.
 *
 * @param url the URl to authenticate against.
 * @param token the authencation token being used for the user.
 * @throws IOException if an IO error occurred.
 * @throws AuthenticationException if an authentication error occurred.
 */
@Override
public void authenticate(URL url, AuthenticatedURL.Token token) throws IOException, AuthenticationException {
    if (!token.isSet()) {
        this.url = url;
        base64 = new Base64(0);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(AUTH_HTTP_METHOD);
        conn.connect();
        if (isNegotiate()) {
            doSpnegoSequence(token);
        } else {
            getFallBackAuthenticator().authenticate(url, token);
        }
    }
}

From source file:com.aquest.emailmarketing.web.controllers.TrackingController.java

/**
 * Gets the tracking link./*from   w w w  .ja  va  2 s  . c  o  m*/
 *
 * @param request the request
 * @param response the response
 * @param id the id
 * @return the tracking link
 * @throws IOException Signals that an I/O exception has occurred.
 */
@RequestMapping(value = "/tracking", method = RequestMethod.GET)
public void getTrackingLink(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("id") String id) throws IOException {
    Base64 base64 = new Base64(true);
    String decriptedText = new String(base64.decode(id.getBytes()));
    String unique_id = decriptedText.substring(decriptedText.indexOf("trackingId=") + 11);
    String url = decriptedText.substring(0, decriptedText.indexOf("trackingId=") - 1);
    System.out.println(url);
    response.sendRedirect(url);

    Timestamp curTimestamp = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime());

    EmailList emailList = emailListService.getEmailListById(unique_id);
    TrackingResponse trackingResponse = new TrackingResponse();
    trackingResponse.setBroadcast_id(emailList.getBroadcast_id());
    trackingResponse.setEmail(emailList.getEmail());
    trackingResponse.setResponse_type("Click");
    trackingResponse.setUnique_id(emailList.getId());
    trackingResponse.setResponse_source("Internal Tracking");
    trackingResponse.setResponse_url(url);
    trackingResponse.setResponse_time(curTimestamp);
    trackingResponse.setProcessed_dttm(curTimestamp);
    trackingResponseService.SaveOrUpdate(trackingResponse);
}

From source file:com.aquest.emailmarketing.web.service.SendEmail.java

/**
 * Send email./*from   w  ww.  j  av  a  2  s . c om*/
 *
 * @param broadcast the broadcast
 * @param emailConfig the email config
 * @param emailList the email list
 * @throws EmailException the email exception
 * @throws MalformedURLException the malformed url exception
 * @throws InterruptedException the interrupted exception
 */
@Async
public void sendEmail(Broadcast broadcast, EmailConfig emailConfig, EmailList emailList)
        throws EmailException, MalformedURLException, InterruptedException {

    Timestamp curTimestamp = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime());
    // email configuration part
    HtmlEmail email = new HtmlEmail();
    email.setSmtpPort(emailConfig.getPort());
    email.setHostName(emailConfig.getHostname());
    email.setAuthenticator(new DefaultAuthenticator(emailConfig.getUsername(), emailConfig.getPassword()));
    email.setSSLOnConnect(emailConfig.isSslonconnect());
    email.setDebug(emailConfig.isDebug());
    email.setFrom(emailConfig.getFrom_address()); //ovde dodati i email from description

    System.out.println(emailList);
    HashMap<String, String> variables = processVariableService.ProcessVariable(emailList);

    for (String keys : variables.keySet()) {
        System.out.println("key:" + keys + ", value:" + variables.get(keys));
    }

    String processSubject = broadcast.getSubject();
    String newHtml = broadcast.getHtmlbody_embed();
    String newPlainText = broadcast.getPlaintext();

    for (String key : variables.keySet()) {
        processSubject = processSubject.replace("[" + key + "]", variables.get(key));
        System.out.println(key + "-" + variables.get(key));
        newHtml = newHtml.replace("[" + key + "]", variables.get(key));
        newPlainText = newPlainText.replace("[" + key + "]", variables.get(key));
    }
    System.out.println(processSubject);
    email.setSubject(processSubject);
    email.addTo(emailList.getEmail());

    String image = embeddedImageService.getEmbeddedImages(broadcast.getBroadcast_id()).getUrl();
    List<String> images = Arrays.asList(image.split(";"));
    for (int j = 0; j < images.size(); j++) {
        System.out.println(images.get(j));
    }
    for (int i = 0; i < images.size(); i++) {
        String id = email.embed(images.get(i), "Slika" + i);
        newHtml = newHtml.replace("[IMAGE:" + i + "]", "cid:" + id);
    }

    Config config = configService.getConfig("trackingurl");
    //DONE: Create jsp page for tracking server url
    String serverUrl = config.getValue();
    System.out.println(serverUrl);
    Base64 base64 = new Base64(true);

    Pattern pattern = Pattern.compile("<%tracking=(.*?)=tracking%>");
    Matcher matcher = pattern.matcher(newHtml);
    while (matcher.find()) {
        String url = matcher.group(1);
        System.out.println(url);
        logger.debug(url);
        String myEncryptedUrl = new String(base64.encode(url.getBytes()));

        String oldurl = "<%tracking=" + url + "=tracking%>";
        logger.debug(oldurl);
        System.out.println(oldurl);
        String newurl = serverUrl + "tracking?id=" + myEncryptedUrl;
        logger.debug(newurl);
        System.out.println(newurl);
        newHtml = newHtml.replace(oldurl, newurl);
    }
    //        System.out.println(newHtml);

    email.setHtmlMsg(newHtml);
    email.setTextMsg(newPlainText);
    try {
        System.out.println("A ovo ovde?");
        email.send();
        emailList.setStatus("SENT");
        emailList.setProcess_dttm(curTimestamp);
        emailListService.SaveOrUpdate(emailList);
    } catch (Exception e) {
        logger.error(e);
    }
    // time in seconds to wait between 2 mails
    TimeUnit.SECONDS.sleep(emailConfig.getWait());
}

From source file:de.anycook.social.facebook.FacebookHandler.java

private static String decodeBase64(String input) {
    return new String(new Base64(true).decode(input));
}

From source file:com.buddycloud.mediaserver.upload.UploadMediaTest.java

@Test
public void uploadWebFormImageParamAuth() throws Exception {
    // file fields
    String title = "Test Image";
    String description = "My Test Image";

    Base64 encoder = new Base64(true);
    String authStr = BASE_USER + ":" + BASE_TOKEN;

    ClientResource client = new ClientResource(
            BASE_URL + "/" + BASE_CHANNEL + "?auth=" + new String(encoder.encode(authStr.getBytes())));

    Form form = createWebForm(TEST_IMAGE_NAME, title, description, TEST_FILE_PATH + TEST_IMAGE_NAME,
            TEST_IMAGE_CONTENT_TYPE);/*from   ww w  . jav  a2s  . c om*/

    Representation result = client.post(form);
    Media media = gson.fromJson(result.getText(), Media.class);

    // verify if resultant media has the passed attributes
    assertEquals(TEST_IMAGE_NAME, media.getFileName());
    assertEquals(title, media.getTitle());
    assertEquals(description, media.getDescription());
    assertEquals(BASE_USER, media.getAuthor());

    // delete metadata
    dataSource.deleteMedia(media.getId());
}

From source file:com.buddycloud.mediaserver.upload.UploadAvatarTest.java

@Test
public void uploadAvatarWebFormDataParamAuth() throws Exception {
    // file fields
    String title = "Test Avatar";
    String description = "My Test Avatar";

    Base64 encoder = new Base64(true);
    String authStr = BASE_USER + ":" + BASE_TOKEN;

    ClientResource client = new ClientResource(BASE_URL + "/" + BASE_CHANNEL + "/avatar" + "?auth="
            + new String(encoder.encode(authStr.getBytes())));

    Form form = createWebForm(TEST_AVATAR_NAME, title, description, TEST_FILE_PATH + TEST_AVATAR_NAME,
            TEST_AVATAR_CONTENT_TYPE);//from  w w w  .j  a  v  a  2s . c  o  m

    Representation result = client.put(form);
    Media media = gson.fromJson(result.getText(), Media.class);

    // verify if resultant media has the passed attributes
    assertEquals(TEST_AVATAR_NAME, media.getFileName());
    assertEquals(title, media.getTitle());
    assertEquals(description, media.getDescription());
    assertEquals(BASE_USER, media.getAuthor());

    // delete metadata
    dataSource.deleteEntityAvatar(media.getEntityId());
    dataSource.deleteMedia(media.getId());
}

From source file:com.floreantpos.ui.dialog.LicenseDialog.java

private void saveBtnActionPerformed(java.awt.event.ActionEvent evt) {

    try {//from  w ww.j  av  a  2  s . c o m

        AppConfig.setMachineId(idTF.getText());

        MessageDigest md = MessageDigest.getInstance("SHA");

        md.update(idTF.getText().getBytes("UTF-8"));

        String key = new String(md.digest(), "UTF-8");

        Base64 base64 = new Base64(true);

        key = base64.encodeAsString(key.getBytes("UTF-8")).trim().toUpperCase();

        key = key.replaceAll("_", "").replaceAll("-", "");

        if (key.equalsIgnoreCase(keyTF.getText())) {
            AppConfig.setLicenceKey(key);
            System.exit(0);
        } else {
            MessageDialog.showError("License Key tidak valid");
        }

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

}

From source file:mx.bigdata.sat.cfdi.CFDv33.java

@Override
public void sellar(PrivateKey key, X509Certificate cert) throws Exception {
    String nc = new String(cert.getSerialNumber().toByteArray());
    cert.checkValidity();/*from  www.  j av a 2  s .  c o  m*/
    byte[] bytes = cert.getEncoded();
    Base64 b64 = new Base64(-1);
    String certStr = b64.encodeToString(bytes);
    document.setCertificado(certStr);
    document.setNoCertificado(nc);
    String signature = getSignature(key);
    document.setSello(signature);
}

From source file:mx.bigdata.cfdi.CFDv3.java

String getSignature(PrivateKey key) throws Exception {
    byte[] bytes = getOriginalBytes();
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initSign(key);// www . j  a va 2 s .c  om
    sig.update(bytes);
    byte[] signed = sig.sign();
    Base64 b64 = new Base64(-1);
    return b64.encodeToString(signed);
}