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:gov.nih.nci.system.web.client.RESTfulReadClient.java

public Response read(String url, String userName, String password) {
    try {/*from w  w  w  .j av a2  s  . c o  m*/
        if (url == null) {
            ResponseBuilder builder = Response.status(Status.BAD_REQUEST);
            builder.type("application/xml");
            StringBuffer buffer = new StringBuffer();
            buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            buffer.append("<response>");
            buffer.append("<type>ERROR</type>");
            buffer.append("<code>INVALID_URL</code>");
            buffer.append("<message>Invalid URL: " + url + "</message>");
            buffer.append("</response>");
            builder.entity(buffer.toString());
            return builder.build();
        }
        WebClient client = WebClient.create(url);
        client.type("application/xml").accept("application/xml");
        String base64encodedUsernameAndPassword = new String(
                Base64.encodeBase64((userName + ":" + password).getBytes()));
        client.header("Authorization", "Basic " + base64encodedUsernameAndPassword);

        return client.get();

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

From source file:com.inmobi.databus.partition.TestCurrentFile.java

private void writeMessages(FSDataOutputStream out, int num) throws IOException {
    for (int i = 0; i < num; i++) {
        out.write(Base64.encodeBase64(MessageUtil.constructMessage(msgIndex).getBytes()));
        out.write('\n');
        msgIndex++;/*from   ww w  . j  a va  2  s  .  com*/
    }
    out.sync();
}

From source file:com.amazonaws.tvm.Utilities.java

public static String base64(String data) throws UnsupportedEncodingException {
    byte[] signature = Base64.encodeBase64(data.getBytes(Constants.ENCODING_FORMAT));
    return new String(signature, Constants.ENCODING_FORMAT);
}

From source file:com.dss886.nForumSDK.NForumSDK.java

/**
 * ?appkey//from  ww  w.  j  av  a  2  s  .  c  o  m
 * @param host ????http://api.byr.cn/
 *           Host.HOST_* ?
 * @param appkey ?????"?appkey=""&"
 * @param username ??
 * @param password ?
 */
public NForumSDK(String host, String appkey, String username, String password) {
    httpClient = new DefaultHttpClient();
    HttpParams param = httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(param, timeout);
    HttpConnectionParams.setSoTimeout(param, timeout);
    httpClient = new DefaultHttpClient(param);

    auth = new String(Base64.encodeBase64((username + ":" + password).getBytes()));
    this.host = host;
    this.returnFormat = returnFormat + "?";
    this.appkey = "&appkey=" + appkey;
}

From source file:com.sirius.utils.encrypt.DESEncryptor.java

@Override
public String encryptBase64(Object key, String data) throws EncryptException {
    byte[] result = encrypt(key, data.getBytes());
    return new String(Base64.encodeBase64(result));
}

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

@Override
protected Void doInBackground() throws Exception {
    MushroomDto mushroomDto = new MushroomDto();
    mushroomDto.setName(restClient.getTfMushroomName().getText());

    mushroomDto.setType(cz.fi.muni.pa165.mushroomhunter.api.Type
            .valueOf(restClient.getComboBoxMushroomType().getSelectedItem().toString()));

    //to create date object only month is used, day and year are fixed values
    String dateInString = restClient.getComboBoxMushroomStartOfOccurence().getSelectedItem().toString()
            + " 1, 2000";

    SimpleDateFormat formatter = new SimpleDateFormat("MMMM d, yyyy", new Locale("en_US"));

    mushroomDto.setStartOfOccurence(formatter.parse(dateInString));

    //to create date object only month is used, day and year are fixed values
    dateInString = restClient.getComboBoxMushroomEndOfOccurence().getSelectedItem().toString() + " 1, 2000";
    mushroomDto.setEndOfOccurence(formatter.parse(dateInString));

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    List<MediaType> mediaTypeList = new ArrayList<>();
    mediaTypeList.add(MediaType.ALL);//from   w ww.j  a  va2s .  c o  m
    headers.setAccept(mediaTypeList);

    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    String json = ow.writeValueAsString(mushroomDto);

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

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

    HttpEntity request = new HttpEntity(json, headers);

    RestTemplate restTemplate = new RestTemplate();
    Long[] result = restTemplate.postForObject(RestClient.SERVER_URL + "pa165/rest/mushroom", request,
            Long[].class);

    System.out.println("Id of the created mushroom: " + result[0]);
    RestClient.getMushroomIDs().add(result[0]);
    return null;
}

From source file:de.cynapsys.homeautomation.ddns.NoIP.java

private boolean submitIpUpdate(String newIP, String hostname) {
    String host = "http://dynupdate.no-ip.com/nic/update?hostname=" + hostname + "&myip=" + newIP;
    try {/* ww  w  .jav a2 s.c  o  m*/
        URL url = new URL(host);
        HttpURLConnection http = (HttpURLConnection) url.openConnection();
        String auth = new String(Base64.encodeBase64((username + ":" + password).getBytes()));
        http.setRequestProperty("Authorization", "Basic " + auth);
        http.setRequestProperty("User-Agent", "Java NoIP Updated 1.0");
        BufferedReader br = new BufferedReader(new InputStreamReader(http.getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            if (line.startsWith("good")) {
                System.out.println("IP Update Successful: " + line.substring(5));
                return true;
            } else if (line.startsWith("nochg")) {
                return true;
            } else if (line.startsWith("badauth")) {
                System.out.println("Invalid Login Details");
            } else if (line.startsWith("badagent")) {
                System.out.println("Bad user agent supplied");
            } else if (line.startsWith("abuse")) {
                System.out.println("Account hs been disabled");
            } else if (line.startsWith("911")) {
                System.out.println("Server fallover");
            } else if (line.startsWith("!donator")) {
                System.out.println("You cannot use donator features");
                return true;
            }
        }
        br.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return false;
}

From source file:com.parleys.io.amf.client.AMFClientProxy.java

/**
 * Invoke the proxy.//from  w w w  .  j  ava2  s .co m
 *
 * @param proxy The proxy.
 * @param method The method to invoke.
 * @param args The method arguments.
 * @return The return value of the method.
 * @throws ClientStatusException If an error occurs on the client during the service call.
 * @throws ServerStatusException If an error occurs on the server during the service call.
 */
public Object invoke(final Object proxy, final Method method, final Object[] args)
        throws ClientStatusException, ServerStatusException {
    AMFConnection connection = new AMFConnection();

    if (username != null) {
        final String userpasswd = username + ":" + password;
        final String encoding = new String(Base64.encodeBase64(userpasswd.getBytes()));
        connection.addHttpRequestHeader("Authorization", "Basic " + encoding);
    }

    connection.connect(serviceUrl);

    Object[] params = args;
    if (null == params) {
        params = new Object[0];
    }

    Object callResult = null;
    try {
        callResult = connection.call(serviceName + "." + method.getName(), params);
    } catch (ServerStatusException e) {
        ASObject asObject = (ASObject) e.getData();
        Object cause = asObject.get("rootCause");
        if (cause instanceof AuthorizationException) {
            throw (AuthorizationException) cause;
        } else {
            throw e;
        }
    } finally {
        connection.close();
    }

    if ((method.getReturnType() != null) && method.getReturnType().equals(int.class)) {
        callResult = ((Double) callResult).intValue();
    } else if ((method.getReturnType() != null) && method.getReturnType().equals(Long.class)) {
        callResult = ((Double) callResult).longValue();
    } else if (method.getReturnType().isArray()) {
        callResult = convertReturnValueToArray(method, callResult);
    }

    return callResult;
}

From source file:jp.co.yahoo.yconnect.core.oauth2.TokenClient.java

@Override
public void fetch() throws TokenException, Exception {

    HttpParameters parameters = new HttpParameters();
    parameters.put("grant_type", OAuth2GrantType.AUTHORIZATION_CODE);
    parameters.put("code", authorizationCode);
    parameters.put("redirect_uri", redirectUri);

    String credential = clientId + ":" + clientSecret;
    String basic = new String(Base64.encodeBase64(credential.getBytes()));

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.put("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    requestHeaders.put("Authorization", "Basic " + basic);

    client = new YHttpClient();
    client.requestPost(endpointUrl, parameters, requestHeaders);

    YConnectLogger.debug(TAG, client.getResponseHeaders().toString());
    YConnectLogger.debug(TAG, client.getResponseBody().toString());

    String json = client.getResponseBody();
    JsonReader jsonReader = Json.createReader(new StringReader(json));

    JsonObject jsonObject = jsonReader.readObject();
    jsonReader.close();/* w  w w.  ja v a  2  s . c  o m*/

    int statusCode = client.getStatusCode();

    checkErrorResponse(statusCode, jsonObject);

    String accessTokenString = (String) jsonObject.getString("access_token");
    long expiresIn = Long.parseLong((String) jsonObject.getString("expires_in"));
    String refreshToken = (String) jsonObject.getString("refresh_token");
    accessToken = new BearerToken(accessTokenString, expiresIn, refreshToken);
    idToken = (String) jsonObject.getString("id_token");

}

From source file:com.twilio.sdk.TwilioRestClient.java

@Override
public TwilioRestResponse request(String path, String method, Map<String, String> vars)
        throws TwilioRestException {

    String encoded = "";
    if (vars != null && !vars.isEmpty()) {
        for (String key : vars.keySet()) {
            try {
                encoded += "&" + key + "=" + URLEncoder.encode(vars.get(key), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new TwilioRestException(e);
            }/*  w w w.j  a  v  a 2  s .  c  o m*/
        }
        encoded = encoded.substring(1);
    }

    // construct full url
    String url = this.endpoint + path;

    // if GET and vars, append them
    if (method.toUpperCase().equals("GET"))
        url += ((path.indexOf('?') == -1) ? "?" : "&") + encoded;

    try {
        HttpURLConnection con = openConnection(url);
        String userpass = this.accountSid + ":" + this.authToken;
        String encodeuserpass = new String(Base64.encodeBase64(userpass.getBytes()));

        con.setRequestProperty("Authorization", "Basic " + encodeuserpass);

        con.setDoOutput(true);

        // initialize a new curl object            
        if (method.toUpperCase().equals("GET")) {
            con.setRequestMethod("GET");
        } else if (method.toUpperCase().equals("POST")) {
            con.setRequestMethod("POST");
            OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
            out.write(encoded);
            out.close();
        } else if (method.toUpperCase().equals("PUT")) {
            con.setRequestMethod("PUT");
            OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
            out.write(encoded);
            out.close();
        } else if (method.toUpperCase().equals("DELETE")) {
            con.setRequestMethod("DELETE");
        } else {
            throw new TwilioRestException("Unknown method " + method);
        }

        BufferedReader in = null;
        try {
            if (con.getInputStream() != null) {
                in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            }
        } catch (IOException e) {
            if (con.getErrorStream() != null) {
                in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
            }
        }

        if (in == null) {
            throw new TwilioRestException("Unable to read response from server");
        }

        StringBuilder decodedString = new StringBuilder();
        String line;
        while ((line = in.readLine()) != null) {
            decodedString.append(line);
        }
        in.close();

        // get result code
        int responseCode = con.getResponseCode();

        return new TwilioRestResponse(url, decodedString.toString(), responseCode);
    } catch (MalformedURLException e) {
        throw new TwilioRestException(e);
    } catch (IOException e) {
        throw new TwilioRestException(e);
    }
}