Example usage for org.apache.commons.ssl Base64 encodeBase64

List of usage examples for org.apache.commons.ssl Base64 encodeBase64

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:cl.nic.dte.util.XMLUtil.java

/**
 * Verifica si una firma XML embedida es válida según define
 * el est&aacute;ndar XML Signature (<a
 * href="http://www.w3.org/TR/xmldsig-core/#sec-CoreValidation">Core
 * Validation</a>), y si el certificado era v&aacute;lido en la fecha dada.
 * <p>/*from   w w w  .j a  v  a 2 s  .c  o m*/
 * 
 * Esta rutina <b>NO</b> verifica si el certificado embedido en
 * &lt;KeyInfo&gt; es v&aacute;lido (eso debe verificarlo con la autoridad
 * certificadora que emiti&oacute; el certificado), pero si verifica que la
 * llave utilizada para verificar corresponde a la contenida en el
 * certificado.
 * 
 * @param xml
 *            el nodo &lt;Signature&gt;
 * @param date
 *            una fecha en la que se verifica la validez del certificado
 * @return el resultado de la verificaci&oacute;n
 * 
 * @see javax.xml.crypto.dsig.XMLSignature#sign(javax.xml.crypto.dsig.XMLSignContext)
 * @see cl.nic.dte.VerifyResult
 * @see cl.nic.dte.extension.DTEDefTypeExtensionHandler
 * @see #getCertificate(XMLSignature)
 */
@SuppressWarnings("unchecked")
public static VerifyResult verifySignature(XMLSignature signature, DOMValidateContext valContext) {

    try {

        KeyValueKeySelector ksel = (KeyValueKeySelector) valContext.getKeySelector();
        X509Certificate x509 = getCertificate(signature);

        // Verifica que un certificado bien embedido
        if (x509 == null) {
            return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false,
                    Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_NO509")));
        }

        // Validate the XMLSignature
        boolean coreValidity = signature.validate(valContext);

        // Check core validation status
        if (coreValidity == false) {
            boolean sv = signature.getSignatureValue().validate(valContext);
            if (!sv)
                return new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false,
                        Utilities.verificationLabels.getString("XML_SIGNATURE_BAD_VALUE"));

            // check the validation status of each Reference
            String message = "";

            for (Reference ref : (List<Reference>) signature.getSignedInfo().getReferences()) {
                if (!ref.validate(valContext)) {
                    message += Utilities.verificationLabels.getString("XML_SIGNATURE_BAD_REFERENCE");
                    message = message.replaceAll("%1",
                            new String(Base64.encodeBase64(ref.getCalculatedDigestValue())));
                    message = message.replaceAll("%2", new String(Base64.encodeBase64(ref.getDigestValue())));
                    message += "\n";
                }
            }
            return new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false, message);
        }

        // Verifica que la llave del certificado corresponde a la usada para
        // la firma
        if (!ksel.getPk().equals(x509.getPublicKey())) {
            String message = Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_BADKEY");
            return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false, message));
        }

        return new VerifyResult(VerifyResult.XML_SIGNATURE_OK, true, null);
    } catch (XMLSignatureException e) {
        return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false,
                Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_UNKNOWN") + ": " + e.getMessage()));
    }

}

From source file:org.cloudfoundry.identity.uaa.mock.token.CheckTokenEndpointDocs.java

@Test
public void checkToken() throws Exception {
    String identityClientAuthorizationWithUaaResource = new String(
            Base64.encodeBase64("app:appclientsecret".getBytes()));

    String identityAccessToken = utils().getUserOAuthAccessToken(getMockMvc(), "app", "appclientsecret",
            UaaTestAccounts.DEFAULT_USERNAME, UaaTestAccounts.DEFAULT_PASSWORD, "", null, true);

    Snippet requestParameters = requestParameters(
            parameterWithName("token").description("The token").attributes(key("constraints").value("Required"),
                    key("type").value(STRING)),
            parameterWithName("scopes")
                    .description(/*  w w w .j av a 2  s. c o  m*/
                            "String of comma-separated scopes, for checking presence of scopes on the token")
                    .attributes(key("constraints").value("Optional"), key("type").value(ARRAY)));

    Snippet responseFields = responseFields(
            fieldWithPath("user_id").type(STRING).description("Only applicable for user tokens").optional(),
            fieldWithPath("user_name").type(STRING).description("Only applicable for user tokens").optional(),
            fieldWithPath("email").type(STRING).description("Only applicable for user tokens").optional(),
            fieldWithPath("client_id").description(
                    "A unique string representing the registration information provided by the client"),
            fieldWithPath("exp")
                    .description("[Expiration Time](https://tools.ietf.org/html/rfc7519#section-4.1.4) Claim"),
            fieldWithPath("authorities").type(ARRAY).description("Only applicable for client tokens")
                    .optional(),
            fieldWithPath("scope").description("List of scopes authorized by the user for this client"),
            fieldWithPath("jti")
                    .description("[JWT ID](https://tools.ietf.org/html/rfc7519#section-4.1.7) Claim"),
            fieldWithPath("aud")
                    .description("[Audience](https://tools.ietf.org/html/rfc7519#section-4.1.3) Claim"),
            fieldWithPath("sub")
                    .description("[Subject](https://tools.ietf.org/html/rfc7519#section-4.1.2) Claim"),
            fieldWithPath("iss")
                    .description("[Issuer](https://tools.ietf.org/html/rfc7519#section-4.1.1) Claim"),
            fieldWithPath("iat")
                    .description("[Issued At](https://tools.ietf.org/html/rfc7519#section-4.1.6) Claim"),
            fieldWithPath("cid").description("See `client_id`"),
            fieldWithPath("grant_type").description(
                    "The type of authentication being used to obtain the token, in this case `password`"),
            fieldWithPath("azp").description("Authorized party"),
            fieldWithPath("auth_time").type(NUMBER).description("Only applicable for user tokens").optional(),
            fieldWithPath("zid").description("Zone ID"),
            fieldWithPath("rev_sig").description(
                    "Revocation Signature - token revocation hash salted with at least client ID and client secret, and optionally various user values."),
            fieldWithPath("origin").type(STRING).description("Only applicable for user tokens").optional(),
            fieldWithPath("revocable").type(STRING).description("Set to true if this token is revocable")
                    .optional());

    getMockMvc()
            .perform(post("/check_token")
                    .header("Authorization", "Basic " + identityClientAuthorizationWithUaaResource)
                    .param("token", identityAccessToken).param("scopes", "password.write,scim.userids"))
            .andExpect(status().isOk())
            .andDo(document("{ClassName}/{methodName}", preprocessResponse(prettyPrint()),
                    requestHeaders(headerWithName("Authorization").description(
                            "Uses basic authorization with base64(resource_server:shared_secret) assuming the caller (a resource server) is actually also a registered client and has `uaa.resource` authority")),
                    requestParameters, responseFields));
}

From source file:org.opentestsystem.shared.security.oauth.client.grant.samlbearer.SamlAssertionAccessTokenProvider.java

public String getSamlAssertion() {
    String encodedStr = "";
    try {/*w ww .j a  v  a2 s.  co m*/
        final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        final SAMLCredential cred = (SAMLCredential) auth.getCredentials();
        final Assertion assertion = cred.getAuthenticationAssertion();

        final StringWriter output = new StringWriter();

        final Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.transform(new DOMSource(assertion.getDOM()), new StreamResult(output));

        String xml = output.toString();
        LOGGER.info("SAML ASSERTION:" + xml);
        byte[] bytesEncoded = Base64.encodeBase64(xml.getBytes());
        encodedStr = new String(bytesEncoded);

        LOGGER.info("SAML encoded:" + encodedStr);
    } catch (final TransformerException e) {
        LOGGER.error("There was an issue processing the SAML assertion", e);
    }
    return encodedStr;
}

From source file:org.wso2.carbon.appmgt.mdm.restconnector.utils.RestUtils.java

/**
 * If not exists generate new access key or return existing one.
 *
 * @param remoteServer bean that holds information about remote server
 * @param generateNewKey whether generate new access key or not
 * @return generated access key/*from w  w w.j  ava2s. c o  m*/
 */
public static String getAPIToken(RemoteServer remoteServer, boolean generateNewKey) {

    if (!generateNewKey) {
        if (!(AuthHandler.authKey == null || "null".equals(AuthHandler.authKey))) {
            return AuthHandler.authKey;
        }
    }

    HttpClient httpClient = AppManagerUtil.getHttpClient(remoteServer.getTokenApiURL());
    HttpPost postMethod = null;
    HttpResponse response = null;
    String responseString = "";
    try {
        List<NameValuePair> nameValuePairs = new ArrayList<>();
        nameValuePairs.add(
                new BasicNameValuePair(Constants.RestConstants.GRANT_TYPE, Constants.RestConstants.PASSWORD));
        nameValuePairs
                .add(new BasicNameValuePair(Constants.RestConstants.USERNAME, remoteServer.getAuthUser()));
        nameValuePairs
                .add(new BasicNameValuePair(Constants.RestConstants.PASSWORD, remoteServer.getAuthPass()));
        URIBuilder uriBuilder = new URIBuilder(remoteServer.getTokenApiURL());
        uriBuilder.addParameters(nameValuePairs);
        postMethod = new HttpPost(uriBuilder.build());

        postMethod.setHeader(Constants.RestConstants.AUTHORIZATION,
                Constants.RestConstants.BASIC + new String(Base64.encodeBase64((remoteServer.getClientKey()
                        + Constants.RestConstants.COLON + remoteServer.getClientSecret()).getBytes())));
        postMethod.setHeader(Constants.RestConstants.CONTENT_TYPE,
                Constants.RestConstants.APPLICATION_FORM_URL_ENCODED);
    } catch (URISyntaxException e) {
        String errorMessage = "Cannot construct the Httppost. Url Encoded error.";
        log.error(errorMessage, e);
        return null;
    }
    try {
        if (log.isDebugEnabled()) {
            log.debug("Sending POST request to API Token endpoint. Request path:  "
                    + remoteServer.getTokenApiURL());
        }

        response = httpClient.execute(postMethod);
        int statusCode = response.getStatusLine().getStatusCode();

        if (log.isDebugEnabled()) {
            log.debug("Status code " + statusCode + " received while accessing the API Token endpoint.");
        }

    } catch (IOException e) {
        String errorMessage = "Cannot connect to Token API Endpoint.";
        log.error(errorMessage, e);
        return null;
    }

    try {
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            responseString = EntityUtils.toString(entity, "UTF-8");
            EntityUtils.consume(entity);
        }

    } catch (IOException e) {
        String errorMessage = "Cannot get response body for auth.";
        log.error(errorMessage, e);
        return null;
    }
    JSONObject token = (JSONObject) new JSONValue().parse(responseString);

    AuthHandler.authKey = String.valueOf(token.get(Constants.RestConstants.ACCESS_TOKEN));
    return AuthHandler.authKey;
}

From source file:org.wso2.carbon.appmgt.mdm.wso2emm.ApplicationOperationsImpl.java

/**
 *
 * @param applicationOperationAction holds the information needs to perform an action on mdm
 *///from w w w  .  j ava  2s. co m

public String performAction(ApplicationOperationAction applicationOperationAction) {

    HashMap<String, String> configProperties = applicationOperationAction.getConfigParams();

    String serverURL = configProperties.get(Constants.PROPERTY_SERVER_URL);
    String authUser = configProperties.get(Constants.PROPERTY_AUTH_USER);
    String authPass = configProperties.get(Constants.PROPERTY_AUTH_PASS);

    String[] params = applicationOperationAction.getParams();
    JSONArray resources = new JSONArray();
    for (String param : params) {
        resources.add(param);
    }

    String action = applicationOperationAction.getAction();
    String type = applicationOperationAction.getType();
    int tenantId = applicationOperationAction.getTenantId();
    JSONObject requestObj = new JSONObject();
    requestObj.put("action", action);
    requestObj.put("to", type);
    requestObj.put("resources", resources);
    requestObj.put("tenantId", tenantId);

    JSONObject requestApp = new JSONObject();

    App app = applicationOperationAction.getApp();
    Method[] methods = app.getClass().getMethods();

    for (Method method : methods) {

        if (method.isAnnotationPresent(Property.class)) {
            try {
                Object value = method.invoke(app);
                if (value != null) {
                    requestApp.put(method.getAnnotation(Property.class).name(), value);
                }
            } catch (IllegalAccessException e) {
                String errorMessage = "Illegal Action";
                if (log.isDebugEnabled()) {
                    log.error(errorMessage, e);
                } else {
                    log.error(errorMessage);
                }

            } catch (InvocationTargetException e) {
                String errorMessage = "Target invocation failed";
                if (log.isDebugEnabled()) {
                    log.error(errorMessage, e);
                } else {
                    log.error(errorMessage);
                }
            }
        }

    }

    requestObj.put("app", requestApp);

    String requestURL = serverURL + String.format(Constants.API_OPERATION, tenantId);
    HttpClient httpClient = AppManagerUtil.getHttpClient(requestURL);
    StringEntity requestEntity = null;

    if (log.isDebugEnabled())
        log.debug("Request Payload for MDM: " + requestObj.toJSONString());

    try {
        requestEntity = new StringEntity(requestObj.toJSONString(), "UTF-8");
        requestEntity.setContentType(Constants.RestConstants.APPLICATION_JSON);
    } catch (UnsupportedEncodingException e) {
        String errorMessage = "JSON encoding not supported";
        if (log.isDebugEnabled()) {
            log.error(errorMessage, e);
        } else {
            log.error(errorMessage);
        }
    }

    HttpPost postMethod = new HttpPost(requestURL);
    postMethod.setEntity(requestEntity);
    postMethod.setHeader(Constants.RestConstants.AUTHORIZATION, Constants.RestConstants.BASIC
            + new String(Base64.encodeBase64((authUser + ":" + authPass).getBytes())));

    try {
        if (log.isDebugEnabled())
            log.debug("Sending POST request to perform operation on MDM. Request path:  " + requestURL);
        HttpResponse response = httpClient.execute(postMethod);
        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode == HttpStatus.SC_OK) {
            if (log.isDebugEnabled())
                log.debug(action + " operation on WSO2 EMM performed successfully");
        }

    } catch (IOException e) {
        String errorMessage = "Cannot connect to WSO2 EMM to perform operation";
        if (log.isDebugEnabled()) {
            log.error(errorMessage, e);
        } else {
            log.error(errorMessage);
        }
    }

    return null;

}

From source file:org.wso2.carbon.appmgt.mdm.wso2emm.ApplicationOperationsImpl.java

/**
 *
 * @param applicationOperationDevice holds the information needs to retrieve device list
 * @return List of devices/*w ww.j a v  a2  s  .  c  o  m*/
 */

public List<Device> getDevices(ApplicationOperationDevice applicationOperationDevice) {

    HashMap<String, String> configProperties = applicationOperationDevice.getConfigParams();

    String serverURL = configProperties.get(Constants.PROPERTY_SERVER_URL);
    String authUser = configProperties.get(Constants.PROPERTY_AUTH_USER);
    String authPass = configProperties.get(Constants.PROPERTY_AUTH_PASS);

    List<Device> devices = new ArrayList<>();

    HttpClient httpClient = AppManagerUtil.getHttpClient(serverURL);
    int tenantId = applicationOperationDevice.getTenantId();
    String[] params = applicationOperationDevice.getParams();
    HttpGet getMethod = new HttpGet(serverURL + String.format(Constants.API_DEVICE_LIST, tenantId, params[0]));
    getMethod.setHeader(Constants.RestConstants.AUTHORIZATION, Constants.RestConstants.BASIC
            + new String(Base64.encodeBase64((authUser + ":" + authPass).getBytes())));
    try {
        HttpResponse response = httpClient.execute(getMethod);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            String responseString = "";
            if (entity != null) {
                responseString = EntityUtils.toString(entity, "UTF-8");
                EntityUtils.consume(entity);
            }

            JSONArray devicesArray = (JSONArray) new JSONValue().parse(responseString);
            if (log.isDebugEnabled())
                log.debug("Devices Received" + devicesArray.toJSONString());
            Iterator<JSONObject> iterator = devicesArray.iterator();
            while (iterator.hasNext()) {
                JSONObject deviceObj = iterator.next();
                Device device = new Device();
                device.setId(deviceObj.get("id").toString());
                JSONObject properties = (JSONObject) new JSONValue()
                        .parse(deviceObj.get("properties").toString());
                device.setName(properties.get("device").toString());
                device.setModel(properties.get("model").toString());
                if ("1".equals(deviceObj.get("platform_id").toString())) {
                    device.setPlatform("android");
                } else if ("2".equals(deviceObj.get("platform_id").toString())) {
                    device.setPlatform("ios");
                } else if ("3".equals(deviceObj.get("platform_id").toString())) {
                    device.setPlatform("ios");
                } else if ("4".equals(deviceObj.get("platform_id").toString())) {
                    device.setPlatform("ios");
                }
                device.setImage(
                        String.format(configProperties.get("ImageURL"), properties.get("model").toString()));
                device.setType("mobileDevice");
                device.setPlatformVersion("0");
                devices.add(device);

            }
        }
    } catch (IOException e) {
        String errorMessage = "Error while getting the device list from WSO2 EMM";
        if (log.isDebugEnabled()) {
            log.error(errorMessage, e);
        } else {
            log.error(errorMessage);
        }
    }
    return devices;
}

From source file:org.wso2.carbon.appmgt.mdm.wso2emm.MDMOperationsImpl.java

/**
 * @param action action of the operation. Eg. install, uninstall, update
 * @param app application object/*w w w. ja v  a 2 s.  c  om*/
 * @param tenantId tenantId
 * @param type type of the resource. Eg: role, user, device
 * @param params ids of the resources which belong to type
 */

public void performAction(User currentUser, String action, App app, int tenantId, String type, String[] params,
        HashMap<String, String> configProperties) {

    String serverURL = configProperties.get(Constants.PROPERTY_SERVER_URL);
    String authUser = configProperties.get(Constants.PROPERTY_AUTH_USER);
    String authPass = configProperties.get(Constants.PROPERTY_AUTH_PASS);

    JSONArray resources = new JSONArray();
    for (String param : params) {
        resources.add(param);
    }

    JSONObject requestObj = new JSONObject();
    requestObj.put("action", action);
    requestObj.put("to", type);
    requestObj.put("resources", resources);
    requestObj.put("tenantId", tenantId);

    JSONObject requestApp = new JSONObject();

    Method[] methods = app.getClass().getMethods();

    for (Method method : methods) {

        if (method.isAnnotationPresent(Property.class)) {
            try {
                Object value = method.invoke(app);
                if (value != null) {
                    requestApp.put(method.getAnnotation(Property.class).name(), value);
                }
            } catch (IllegalAccessException e) {
                String errorMessage = "Illegal Action";
                if (log.isDebugEnabled()) {
                    log.error(errorMessage, e);
                } else {
                    log.error(errorMessage);
                }

            } catch (InvocationTargetException e) {
                String errorMessage = "Target invocation failed";
                if (log.isDebugEnabled()) {
                    log.error(errorMessage, e);
                } else {
                    log.error(errorMessage);
                }
            }
        }

    }

    requestObj.put("app", requestApp);

    HttpClient httpClient = new HttpClient();
    StringRequestEntity requestEntity = null;

    if (log.isDebugEnabled())
        log.debug("Request Payload for MDM: " + requestObj.toJSONString());

    try {
        requestEntity = new StringRequestEntity(requestObj.toJSONString(), "application/json", "UTF-8");
    } catch (UnsupportedEncodingException e) {
        String errorMessage = "JSON encoding not supported";
        if (log.isDebugEnabled()) {
            log.error(errorMessage, e);
        } else {
            log.error(errorMessage);
        }
    }

    String requestURL = serverURL + String.format(Constants.API_OPERATION, tenantId);

    PostMethod postMethod = new PostMethod(requestURL);
    postMethod.setRequestEntity(requestEntity);
    postMethod.setRequestHeader("Authorization",
            "Basic " + new String(Base64.encodeBase64((authUser + ":" + authPass).getBytes())));

    try {
        if (log.isDebugEnabled())
            log.debug("Sending POST request to perform operation on MDM. Request path:  " + requestURL);
        int statusCode = httpClient.executeMethod(postMethod);
        if (statusCode == HttpStatus.SC_OK) {
            if (log.isDebugEnabled())
                log.debug(action + " operation on WSO2 EMM performed successfully");
        }

    } catch (IOException e) {
        String errorMessage = "Cannot connect to WSO2 EMM to perform operation";
        if (log.isDebugEnabled()) {
            log.error(errorMessage, e);
        } else {
            log.error(errorMessage);
        }
    }

}

From source file:org.wso2.carbon.appmgt.mdm.wso2emm.MDMOperationsImpl.java

/**
 *
 * @param tenantId tenantId/*from   w w  w .j a  v a 2s  .c om*/
 * @param type type of the resource. Eg: role, user, device
 * @param params ids of the resources which belong to type
 * @param platform platform of the devices
 * @param platformVersion platform version of the devices
 * @param isSampleDevicesEnabled if MDM is not connected, enable this to display sample devices.
 * @return
 */

public List<Device> getDevices(User currentUser, int tenantId, String type, String[] params, String platform,
        String platformVersion, boolean isSampleDevicesEnabled, HashMap<String, String> configProperties) {

    String serverURL = configProperties.get(Constants.PROPERTY_SERVER_URL);
    String authUser = configProperties.get(Constants.PROPERTY_AUTH_USER);
    String authPass = configProperties.get(Constants.PROPERTY_AUTH_PASS);

    List<Device> devices = new ArrayList<Device>();

    if (isSampleDevicesEnabled) {
        return Sample.getSampleDevices();
    } else {

        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(
                serverURL + String.format(Constants.API_DEVICE_LIST, tenantId, params[0]));
        getMethod.setRequestHeader("Authorization",
                "Basic " + new String(Base64.encodeBase64((authUser + ":" + authPass).getBytes())));
        try {
            int statusCode = httpClient.executeMethod(getMethod);
            if (statusCode == 200) {
                String response = getMethod.getResponseBodyAsString();
                JSONArray devicesArray = (JSONArray) new JSONValue().parse(response);
                if (log.isDebugEnabled())
                    log.debug("Devices Received" + devicesArray.toJSONString());
                Iterator<JSONObject> iterator = devicesArray.iterator();
                while (iterator.hasNext()) {
                    JSONObject deviceObj = iterator.next();
                    Device device = new Device();
                    device.setId(deviceObj.get("id").toString());
                    JSONObject properties = (JSONObject) new JSONValue()
                            .parse(deviceObj.get("properties").toString());
                    device.setName(properties.get("device").toString());
                    device.setModel(properties.get("model").toString());
                    if ("1".equals(deviceObj.get("platform_id").toString())) {
                        device.setPlatform("android");
                    } else if ("2".equals(deviceObj.get("platform_id").toString())) {
                        device.setPlatform("ios");
                    } else if ("3".equals(deviceObj.get("platform_id").toString())) {
                        device.setPlatform("ios");
                    } else if ("4".equals(deviceObj.get("platform_id").toString())) {
                        device.setPlatform("ios");
                    }
                    device.setImage(String.format(configProperties.get("ImageURL"),
                            properties.get("model").toString()));
                    device.setType("mobileDevice");
                    device.setPlatformVersion("0");
                    devices.add(device);

                }
            }
        } catch (IOException e) {
            String errorMessage = "Error while getting the device list from WSO2 EMM";
            if (log.isDebugEnabled()) {
                log.error(errorMessage, e);
            } else {
                log.error(errorMessage);
            }
        }
        return devices;
    }
}

From source file:org.wso2.carbon.appmgt.mdm.wso2mdm.MDMOperationsImpl.java

private String getAPIToken(String tokenApiURL, String clientKey, String clientSecret, String authUser,
        String authPass, boolean generateNewKey) {

    if (!generateNewKey) {
        if (!(AuthHandler.authKey == null || "null".equals(AuthHandler.authKey))) {
            return AuthHandler.authKey;
        }//w  ww . ja  v a2 s  .c om
    }

    HttpClient httpClient = new HttpClient();
    PostMethod postMethod = new PostMethod(tokenApiURL);

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new NameValuePair("grant_type", "password"));
    nameValuePairs.add(new NameValuePair("username", authUser));
    nameValuePairs.add(new NameValuePair("password", authPass));
    postMethod
            .setQueryString((NameValuePair[]) nameValuePairs.toArray(new NameValuePair[nameValuePairs.size()]));
    postMethod.addRequestHeader("Authorization",
            "Basic " + new String(Base64.encodeBase64((clientKey + ":" + clientSecret).getBytes())));
    postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    try {
        if (log.isDebugEnabled())
            log.debug("Sending POST request to API Token endpoint. Request path:  " + tokenApiURL);
        int statusCode = httpClient.executeMethod(postMethod);
        if (log.isDebugEnabled())
            log.debug("Status code " + statusCode + " received while accessing the API Token endpoint.");
    } catch (IOException e) {
        String errorMessage = "Cannot connect to Token API Endpoint";
        if (log.isDebugEnabled()) {
            log.error(errorMessage, e);
        } else {
            log.error(errorMessage);
        }
        return null;
    }

    String response = null;
    try {
        response = postMethod.getResponseBodyAsString();
    } catch (IOException e) {
        String errorMessage = "Cannot get response body for auth";
        if (log.isDebugEnabled()) {
            log.error(errorMessage, e);
        } else {
            log.error(errorMessage);
        }
        return null;
    }

    JSONObject token = (JSONObject) new JSONValue().parse(response);

    AuthHandler.authKey = String.valueOf(token.get("access_token"));
    return AuthHandler.authKey;
}

From source file:org.wso2.carbon.device.mgt.output.adapter.mqtt.util.MQTTAdapterPublisher.java

private String getBase64Encode(String key, String value) {
    return new String(Base64.encodeBase64((key + ":" + value).getBytes()));
}