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.xwiki.csrf.internal.DefaultCSRFToken.java

/**
 * {@inheritDoc}//from w ww. j  a  v a2  s .  co  m
 */
@Override
public String getToken() {
    String key = getTokenKey();
    String token = this.tokens.get(key);
    if (token != null) {
        return token;
    }

    // create fresh token if needed
    synchronized (this.tokens) {
        if (!this.tokens.containsKey(key)) {
            byte[] bytes = new byte[TOKEN_LENGTH];
            this.random.nextBytes(bytes);
            // Base64 encoded token can contain __ or -- which breaks the layout (see XWIKI-5996). Replacing them
            // with x reduces randomness a bit, but it seems that other special characters are either used in XWiki
            // syntax or not URL-safe
            token = Base64.encodeBase64URLSafeString(bytes).replaceAll("[_=+-]", "x");
            this.tokens.put(key, token);
        }
        return this.tokens.get(key);
    }
}

From source file:org.zaproxy.zap.extension.dynssl.SslCertificateUtils.java

/**
 * @param keystore//www . ja v a  2  s. c om
 * @return
 * @throws KeyStoreException
 * @throws IOException
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 */
public static final String keyStore2String(KeyStore keystore)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    keystore.store(baos, SslCertificateService.PASSPHRASE);
    final byte[] bytes = baos.toByteArray();
    baos.close();
    return Base64.encodeBase64URLSafeString(bytes);
}

From source file:org.zht.framework.uuid.Base64UuidGenerator.java

private static String base64Uuid(UUID uuid) {
    ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
    bb.putLong(uuid.getMostSignificantBits());
    bb.putLong(uuid.getLeastSignificantBits());
    return Base64.encodeBase64URLSafeString(bb.array());
}

From source file:poke.resources.JobResource.java

@Override
public Request process(Request request) {
    // TODO Auto-generated method stub

    Request reply = null;//  w w  w .  jav  a  2  s .c o m
    // get the leader node value
    int leaderNode = ElectionManager.getInstance().whoIsTheLeader();

    if (configFile.getNodeId() == leaderNode) {
        if (request.getBody().hasJobStatus()) {
            logger.info("Job Status received ");
            String jobId = request.getBody().getJobStatus().getJobId();
            logger.info("Job ID of Job Status " + jobId);
            if (reqMap.containsKey(jobId)) {
                reqMap.remove(jobId);
                Channel ch = channelMap.get(jobId);
                channelMap.remove(jobId);
                ch.writeAndFlush(request);
            }
        } else if (request.getBody().hasJobOp()) {
            logger.info("A new job request has been received by Leader");
            PhotoHeader photoHead = request.getHeader().getPhotoHeader();
            // Job proposal
            JobOperation jobOp = request.getBody().getJobOp();
            logger.info("Job Operation ID: " + jobOp.getJobId());
            reqMap.put(jobOp.getJobId(), request);

            PhotoPayload photoPay = request.getBody().getPhotoPayload();

            Management.Builder mb = Management.newBuilder();
            JobProposal.Builder jbr = JobProposal.newBuilder();
            PhotoPayload.Builder ppb = PhotoPayload.newBuilder();

            // setting mgmt header
            MgmtHeader.Builder mhb = MgmtHeader.newBuilder();
            mhb.setOriginator(configFile.getNodeId());
            mhb.setTime(System.currentTimeMillis());

            jbr.setJobId(jobOp.getJobId());
            jbr.setNameSpace(jobOp.getData().getNameSpace());
            jbr.setOwnerId(jobOp.getData().getOwnerId());
            jbr.setWeight(5);
            jbr.setOptions(jobOp.getData().getOptions());

            ppb.setName(photoPay.getName());
            ppb.setData(photoPay.getData());

            mb.setHeader(mhb.build());
            mb.setJobPropose(jbr.build());
            Management jobProposal = mb.build();
            String destHost = null;
            int destPort = 0;

            // TO-DO : need to update condition according to Team leads
            // communication standards
            if (photoHead.hasEntryNode()) {
                // Arraylist of IP addresses of leaders of other clusters
                List<String> leaderList = new ArrayList<String>();
                leaderList.add(new String("192.168.1.15:8080"));
                leaderList.add(new String("192.168.1.31:5573"));
                leaderList.add(new String("192.168.1.153:5570"));
                for (String destination : leaderList) {
                    String[] dest = destination.split(":");
                    destHost = dest[0];
                    destPort = Integer.parseInt(dest[1]);
                    logger.info("Job proposal forwarded to other cluster : " + destHost + ":" + destPort);
                    InetSocketAddress sa = new InetSocketAddress(destHost, destPort);
                    Channel ch = connectToManagement(sa);
                    ch.writeAndFlush(jobProposal);
                    logger.info("Job proposal has been sent to other cluster");
                }
            } else {
                for (NodeDesc nn : configFile.getAdjacent().getAdjacentNodes().values()) {
                    destHost = nn.getHost();
                    destPort = nn.getMgmtPort();
                    InetSocketAddress sa = new InetSocketAddress(destHost, destPort);
                    Channel ch = connectToManagement(sa);
                    ch.writeAndFlush(jobProposal);
                    logger.info("Job Proposal as been sent");
                }
            }
        }
    }

    else {
        String requestType = request.getHeader().getPhotoHeader().getRequestType().toString();
        logger.info("Job Operation received: " + requestType);
        // getting image name and content
        String imageName = request.getBody().getPhotoPayload().getName();

        try {
            // connecting to database
            DatabaseSharding dbShard = new DatabaseSharding();
            // add host of Database
            //To-Do Update IP address to Database IP
            dbShard.initManager("127.0.0.1", 27017, "test");

            if (requestType == "read") {

                logger.info("Server has read request for image: " + imageName);

                // call function to save image in DB
                File receiveImage;
                FileInputStream imageInFile = null;
                try {
                    receiveImage = dbShard.getImage(imageName);

                    imageInFile = new FileInputStream(receiveImage);
                    byte imageData[] = new byte[(int) receiveImage.length()];
                    imageInFile.read(imageData);

                    // Converting Image byte array into Base64 String
                    String imageDataString = Base64.encodeBase64URLSafeString(imageData);
                    imageDataStringReply = ByteString.copyFrom(imageData);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    imageInFile.close();
                }
                // set job status to true
                jobStatus = true;
            } else if (requestType == "write") {
                logger.info("Server has received image: " + imageName);

                ByteString imageByteString = request.getBody().getPhotoPayload().getData();
                FileOutputStream imageOutFile = null;
                byte[] encoded = imageByteString.toByteArray();
                // decoding to convert into image
                byte[] imageDataBytes = Base64.decodeBase64(encoded);

                // Write a image byte array into file system
                imageOutFile = new FileOutputStream(imageName);
                imageOutFile.write(imageDataBytes);

                // call function to save image in DB
                try {
                    newImageName = dbShard.saveImage(imageName);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    imageOutFile.close();
                }
                // set job status to true
                jobStatus = true;

            } else if (requestType == "delete") {
                logger.info("Server has been requested to delete image: " + imageName);
                // call function to save image in DB
                try {
                    jobStatus = dbShard.removeImage(imageName);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                logger.info("Client request can not be recognized");
                jobStatus = false;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Request.Builder rb = Request.newBuilder();
        // check for job status and prepare Header
        if (jobStatus) {
            // metadata
            rb.setHeader(ResourceUtil.buildHeaderFrom(request.getHeader(), PokeStatus.SUCCESS, null,
                    ResponseFlag.success));

        } else {
            // metadata
            rb.setHeader(ResourceUtil.buildHeaderFrom(request.getHeader(), PokeStatus.FAILURE, null,
                    ResponseFlag.failure));
        }

        // payload
        Payload.Builder pb = Payload.newBuilder();
        Ping.Builder fb = Ping.newBuilder();
        fb.setTag(request.getBody().getPing().getTag());
        fb.setNumber(request.getBody().getPing().getNumber());
        pb.setPing(fb.build());

        PhotoPayload.Builder ppb = PhotoPayload.newBuilder();
        if (imageDataStringReply != null) {
            ppb.setData(imageDataStringReply);
        }
        if (newImageName != null) {
            ppb.setName(newImageName);
        }
        pb.setPhotoPayload(ppb.build());
        rb.setBody(pb.build());
        reply = rb.build();
    }
    return reply;
}

From source file:ro.nextreports.server.web.dashboard.WidgetEmbedCodePanel.java

private String getCode(String widgetId, boolean error) {
    if (error) {//from ww w.java 2s . co  m
        return "";
    }
    StringBuilder sb = new StringBuilder();
    sb.append("&lt;iframe src=\"");

    String url = UrlUtil.getAppBaseUrl(storageService).append("widget?id=").append(widgetId).append("&width=")
            .append(String.valueOf(width)).append("&height=").append(String.valueOf(height)).toString();
    sb.append(url);

    if (!"".equals(parameters.trim())) {
        String password = storageService.getSettings().getIframe().getEncryptionKey();
        if ((password != null) && !password.trim().equals("")) {
            BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
            textEncryptor.setPassword(password);
            String myEncryptedText = textEncryptor.encrypt(parameters);
            myEncryptedText = Base64.encodeBase64URLSafeString(myEncryptedText.getBytes());
            sb.append("&P=").append(myEncryptedText);
        } else {
            sb.append("&").append(parameters);
        }
    }

    sb.append("\" ");

    sb.append("frameborder=0 ");
    sb.append("width=").append(width).append("px ");
    sb.append("height=").append(height).append("px");

    sb.append(">&lt;/iframe&gt;");
    return sb.toString();
}

From source file:ru.frostman.web.mongo.credentials.UsernamePasswordCredentials.java

public static String encodePassword(String password) {
    return Base64.encodeBase64URLSafeString(DigestUtils.sha384(password));
}

From source file:ru.frostman.web.util.Codec.java

public static String encodeBase64(byte[] bytes) {
    return Base64.encodeBase64URLSafeString(bytes);
}

From source file:se.vgregion.alfrescoclient.service.AlfrescoService.java

/**
 * Adds urls to the Alfresco share dashboard for each site.
 *
 * @param list/*from  w  w w.  j a v a2 s. c o  m*/
 * @return sites with dashboard URLs
 */
private List<Site> addAlfrescoShareDashboardURLs(List<Site> sites, String csIframPage, String portletInstance) {
    for (Site site : sites) {
        String shareLink = server + PAGE_SITES + site.getShortName() + DASHBOARD;

        String encodeUrl = Base64.encodeBase64URLSafeString(shareLink.getBytes());

        site.setShareUrl(csIframPage + "/-/autologin/" + portletInstance + "/" + encodeUrl);

    }
    return sites;
}

From source file:se.vgregion.portal.medcontrol.services.MedControlDeviationService.java

private void processUrl(List<DeviationCase> deviationCases) {
    if (deviationCases != null && StringUtils.isNotBlank(linkoutBase)) {
        for (DeviationCase deviation : deviationCases) {
            String correctedUrl = deviation.getUrl() + "&page=Context";
            String base64Url = Base64.encodeBase64URLSafeString(correctedUrl.getBytes());

            deviation.setUrl(linkoutBase + base64Url);
        }/* w w  w .j a v  a2  s  .com*/
    }
}

From source file:service.GoogleCalendarAuth.java

public GoogleCalendarAuth(String client_id, String key) {
    final long now = System.currentTimeMillis() / 1000L;
    final long exp = now + 3600;
    final char[] password = "notasecret".toCharArray();
    final String claim = "{\"iss\":\"" + client_id + "\"," + "\"scope\":\"" + SCOPE + "\","
            + "\"aud\":\"https://accounts.google.com/o/oauth2/token\"," + "\"exp\":" + exp + "," +
            // "\"prn\":\"some.user@somecorp.com\"," + // This require some.user to have their email served from a googlemail domain?
            "\"iat\":" + now + "}";
    try {//  w ww .j a va 2  s.  c  o  m
        final String jwt = Base64.encodeBase64URLSafeString(jwt_header.getBytes()) + "."
                + Base64.encodeBase64URLSafeString(claim.getBytes("UTF-8"));
        final byte[] jwt_data = jwt.getBytes("UTF8");
        final Signature sig = Signature.getInstance("SHA256WithRSA");

        final KeyStore ks = java.security.KeyStore.getInstance("PKCS12");
        ks.load(new FileInputStream(key), password);

        sig.initSign((PrivateKey) ks.getKey("privatekey", password));
        sig.update(jwt_data);
        final byte[] signatureBytes = sig.sign();
        final String b64sig = Base64.encodeBase64URLSafeString(signatureBytes);

        final String assertion = jwt + "." + b64sig;
        //System.out.println("Assertion: " + assertion);
        final String data = "grant_type=assertion" + "&assertion_type="
                + URLEncoder.encode("http://oauth.net/grant_type/jwt/1.0/bearer", "UTF-8") + "&assertion="
                + URLEncoder.encode(assertion, "UTF-8");

        // Make the Access Token Request
        URLConnection conn = null;
        try {
            final URL url = new URL("https://accounts.google.com/o/oauth2/token");
            conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();

            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                if (line.split(":").length > 0)
                    if (line.split(":")[0].trim().equals("\"access_token\""))
                        access_token = line.split(":")[1].trim().replace("\"", "").replace(",", "");
                System.out.println(line);
            }
            wr.close();
            rd.close();
        } catch (Exception ex) {
            final InputStream error = ((HttpURLConnection) conn).getErrorStream();
            final BufferedReader br = new BufferedReader(new InputStreamReader(error));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null)
                sb.append(line);
            System.out.println("Error: " + ex + "\n " + sb.toString());
        }
        System.out.println("access_token=" + access_token);
    } catch (Exception ex) {
        System.out.println("Error: " + ex);
    }
}