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

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

Introduction

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

Prototype

public static byte[] encodeBase64(final byte[] binaryData) 

Source Link

Document

Encodes binary data using the base64 algorithm but does not chunk the output.

Usage

From source file:cz.muni.fi.mushroomhunter.restclient.LocationDeleteSwingWorker.java

@Override
protected Integer doInBackground() throws Exception {
    int selectedRow = restClient.getTblLocation().getSelectedRow();
    RestTemplate restTemplate = new RestTemplate();

    String plainCreds = RestClient.USER_NAME + ":" + RestClient.PASSWORD;
    byte[] plainCredsBytes = plainCreds.getBytes();
    byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
    String base64Creds = new String(base64CredsBytes);

    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Basic " + base64Creds);

    HttpEntity<String> request = new HttpEntity<>(headers);

    restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory() {
        @Override//from   www .  j a va2  s . c om
        protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
            if (HttpMethod.DELETE == httpMethod) {
                return new HttpEntityEnclosingDeleteRequest(uri);
            }
            return super.createHttpUriRequest(httpMethod, uri);
        }
    });

    restTemplate.exchange(
            RestClient.SERVER_URL + "pa165/rest/location/" + RestClient.getLocationIDs().get(selectedRow),
            HttpMethod.DELETE, request, LocationDto.class);

    RestClient.getLocationIDs().remove(selectedRow);
    return selectedRow;
}

From source file:com.dv.sharer.ws.controller.ImageController.java

public String download(String id) {
    Integer idInt = Integer.valueOf(id);
    Image binaryData = imageDao.find(idInt);
    byte[] data = Base64.encodeBase64(binaryData.getData());
    return new String(data);
}

From source file:com.andiandy.m101j.week4.course.SessionDAO.java

public String getSessionID() {
    // get 32 byte random number. that's a lot of bits.
    SecureRandom generator = new SecureRandom();
    byte randomBytes[] = new byte[32];
    generator.nextBytes(randomBytes);//  w w  w.jav  a2s  .com

    byte[] idBytes = Base64.encodeBase64(randomBytes);
    String sessionID = new String(idBytes);

    return sessionID;
}

From source file:com.woooha.web.tag.StaticTag.java

private String toBase64(String str) throws UnsupportedEncodingException {
    return new String(Base64.encodeBase64(str.getBytes("UTF-8")));
}

From source file:br.ufsm.csi.hotelmanagementats.controller.AcessoController.java

@RequestMapping(value = "realizarLogin.html", method = RequestMethod.POST)
public ModelAndView realizarLogin(HttpServletRequest rq, HttpSession session)
        throws NoSuchAlgorithmException, UnsupportedEncodingException {
    System.out.println("-------------------------------");
    System.out.println("Submit Formulrio de Login...");

    String login = rq.getParameter("login");
    String senha = rq.getParameter("senha");
    ModelAndView mv = new ModelAndView("/WEB-INF/views/paginaInicial");

    if (login != null && senha != null) {
        int verificador = login.indexOf("@");

        byte[] senhaByte = senha.getBytes();

        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] hashSenha = md.digest(senhaByte);

        byte[] hashSenhaBase = Base64.encodeBase64(hashSenha);
        String valorSenha = new String(hashSenhaBase, "ISO-8859-1");

        if (verificador != -1) {
            UsuarioAdministrador u = new UsuarioAdministrador();
            u.setEmail(login);/*from   ww w .j  av  a2 s. c o m*/

            u.setSenha(valorSenha);

            UsuarioAdmDao uD = new UsuarioAdmDao();

            u = uD.logar(u);

            if (u == null) {
                mv.addObject("mensagem", "<Strong> Erro</Strong> Dados invlidos!");
                mv.addObject("tipo", "danger");
                System.out.println("Erro de Login - Administrador!");
            } else {
                session.setAttribute("administrador", u);

                mv = new ModelAndView("/WEB-INF/views/ambienteAdministrador/paginaPrincipalAdm");

                System.out.println("Login feito com sucesso - Administrador!");
            }

        } else {
            UsuarioOperador u = new UsuarioOperador();
            u.setNickname(login);
            u.setSenha(valorSenha);

            UsuarioOpDao uD = new UsuarioOpDao();

            u = uD.logar(u);

            if (u == null) {
                mv.addObject("mensagem",
                        "<Strong>Erro</Strong> Dados invlidos ou usurio sem acesso ao Sistema!");
                mv.addObject("tipo", "danger");
                System.out.println("Erro de Login - Operador!");
            } else {
                mv = new ModelAndView("/WEB-INF/views/ambienteEstabelecimento/paginaPrincipalEstabelecimento");
                // mv.addObject("mensagem", "<Strong> Sucesso!</Strong> Dados vlidos!");
                // mv.addObject("tipo", "success");
                session.setAttribute("operador", u);
                session.setAttribute("estabelecimentoEscolhido", u.getEstabelecimento());

                System.out.println("Login feito com sucesso - Operador!");
            }
        }
    }

    System.out.println("\n-------------------------------\n");

    return mv;
}

From source file:com.andiandy.m101j.week3.hw2_3.SessionDAO.java

public String generateSessionID() {
    // get 32 byte random number. that's a lot of bits.
    SecureRandom generator = new SecureRandom();
    byte randomBytes[] = new byte[32];
    generator.nextBytes(randomBytes);/*from   www .j  av a 2  s  . c  o m*/

    byte[] idBytes = Base64.encodeBase64(randomBytes);
    String sessionID = new String(idBytes);

    return sessionID;
}

From source file:it.avalz.opendaylight.controller.Controller.java

private String callControllerApi(String partialUrl) {
    String authString = this.username + ":" + this.password;

    StringBuilder responseString = new StringBuilder();
    try {/*from www .j  av a  2 s . c om*/
        URL url = new URL(this.baseUrl + partialUrl);
        byte[] authEncoded = Base64.encodeBase64(authString.getBytes());
        String authEncodedString = new String(authEncoded);

        URLConnection connection = url.openConnection();
        connection.setRequestProperty("Authorization", "Basic " + authEncodedString);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");

        InputStream is = connection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = br.readLine()) != null) {
            responseString.append(line);
        }
        br.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return responseString.toString();
}

From source file:com.basho.riak.presto.SplitTask.java

public String toString() {
    byte[] binary = term2binary(task);
    byte[] b = Base64.encodeBase64(binary);
    return Hex.encodeHexString(b);
}

From source file:com.nautestech.VERDE.controller.HomeController.java

/**
 * Simply selects the home view to render by returning its name.
 *///from   w  w w .  j  a v a 2  s.c o  m
//   @RequestMapping(value = "/", method = RequestMethod.GET)
//   public String home(Locale locale, Model model) {
//      logger.info("Welcome home! The client locale is {}.", locale);
//      
//      Date date = new Date();
//      DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
//      
//      String formattedDate = dateFormat.format(date);
//      
//      model.addAttribute("serverTime", formattedDate );
//      
//      return "home1";
//   }

@RequestMapping(value = "/verdeLicense")
public String RestVerdeLicense(Model model) throws URISyntaxException {

    RestTemplate restTemplate = new RestTemplate();

    String plainCreds = "mcadmin1:pass_1234";
    byte[] plainCredsBytes = plainCreds.getBytes();
    byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
    String base64Creds = new String(base64CredsBytes);

    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Basic " + base64Creds);
    //      headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    HttpEntity<String> request = new HttpEntity<String>(headers);
    URI url = new URI("http://netseason.iptime.org/mc/rest/verdeLicense");
    ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, request, String.class);

    logger.info(response.getHeaders().toString());

    model.addAttribute("result", response.getBody());

    return "rest";
}

From source file:com.qut.middleware.esoe.sso.plugins.artifact.data.impl.ArtifactDaoBase.java

public void resolveArtifact(Artifact artifact) throws ArtifactBindingException {
    try {/*ww  w. j av a2s  .  c  o m*/
        byte[] base64MessageHandle = Base64.encodeBase64(artifact.getMessageHandle());
        String messageHandle = new String(base64MessageHandle, "UTF-8");

        Artifact retrieved = this.resolveArtifact(messageHandle);
        artifact.setDocument(retrieved.getDocument());
        artifact.setAudience(retrieved.getAudience());
    } catch (UnsupportedEncodingException e) {
        throw new ArtifactBindingException(
                "Unable to create message handle base64 string, the required encoding is not supported. Error: "
                        + e.getMessage(),
                e);
    }
}