Java Code Examples for org.codehaus.jackson.map.ObjectMapper#convertValue()

The following examples show how to use org.codehaus.jackson.map.ObjectMapper#convertValue() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: KubernetesBackUpTask.java    From kardio with Apache License 2.0 5 votes vote down vote up
/**
 * This function returns a Map with key as service name and value as Map with all selector values
 * @param authToken
 * @param eVo
 * @return
 * @throws Exception
 */
private static Map<String, Map<String, String>> getServiceLabelValues(String authToken, EnvironmentVO eVo) throws Exception {
	// TODO Auto-generated method stub
	String serviceApiUrl = eVo.getK8sUrl() + PropertyUtil.getInstance().getValue(SurveillerConstants.K8S_API_SERVICE_PATH);
	String serviceJson = RestCommunicationHandler.getResponse(serviceApiUrl, true, SurveillerConstants.BEARER_TOKEN, authToken);
	ObjectMapper mapper = new ObjectMapper();
	JsonNode rootNodeServ = mapper.readTree(serviceJson);
	ArrayNode serviceNode = (ArrayNode) rootNodeServ.get("items");
	if(serviceNode == null || serviceNode.size() == 0){
		logger.info("No Service is available for the environment : "+eVo.getEnvironmentName());
		return null;
	}
	Map<String, Map<String, String>> serviceLabelMap = new HashMap<String, Map<String, String>>(); 
	Iterator<JsonNode> serviceIterator = serviceNode.getElements();
	while (serviceIterator.hasNext()) {
		JsonNode appsInNode = serviceIterator.next();
		JsonNode servMetadataNode = appsInNode.get("metadata");
		JsonNode servNameNode = servMetadataNode.get("name");
		String serviceName = servNameNode.getValueAsText();
		JsonNode namespaceNode = servMetadataNode.get("namespace");
		String namespace = namespaceNode.getValueAsText();
		JsonNode specNode = appsInNode.get("spec");
		JsonNode selectorNode = specNode.get("selector");
		if (namespace.equals("default") || !namespace.contains("-")) {
			logger.info("Excluding service - " + serviceName + " in the namespace - " + namespace);
			continue;
		}
		Map<String, String> selectorMap = mapper.convertValue(selectorNode, Map.class);
		serviceLabelMap.put(namespace+"/"+serviceName, selectorMap);
	}
	return serviceLabelMap;
}
 
Example 2
Source File: MetricsResourceTest.java    From metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void testListMetrics() {
    MetricManager.getIMetricManager().clear();
    MetricManager.getCounter("product", MetricName.build("middleware.product.provider"));
    MetricManager.getMeter("test", MetricName.build("shared.carts.my_cart").level(MetricLevel.CRITICAL)).mark();
    MetricManager.getMeter("test", MetricName.build("shared.carts.my_cart")
            .level(MetricLevel.CRITICAL).tagged("source", "taobao")).mark();

    GenericType<Map<String, Object>> genericType = new GenericType<Map<String, Object>>(){};
    Map<String, Object> result = target("metrics/list").request()
            .accept(MediaType.APPLICATION_JSON_TYPE).get(genericType);

    Assert.assertEquals("success should be true", true, result.get("success"));
    Assert.assertTrue("data should be a map", result.get("data") instanceof Map);

    ObjectMapper mapper = new ObjectMapper();
    Map<String, Set<MetricObject>> data =
            mapper.convertValue(result.get("data"), new TypeReference<Map<String, Set<MetricObject>>>(){});
    Assert.assertTrue(data.get("product").contains(MetricObject.named("middleware.product.provider.count")
            .withType(MetricObject.MetricType.COUNTER).withLevel(MetricLevel.NORMAL).build()));
    Assert.assertEquals(".count/.m1/.m5/.m15/.bucket_count/qps * 2 = 12", 12, data.get("test").size());
    Assert.assertTrue("shared.carts.my_cart.m1 should be CRITICAL level",
            data.get("test").contains(MetricObject.named("shared.carts.my_cart.m1")
            .withLevel(MetricLevel.CRITICAL).withType(MetricObject.MetricType.GAUGE).build()));
    Map<String, String> tags = new HashMap<String, String>();
    tags.put("source", "taobao");
    Assert.assertTrue(data.get("test").contains(MetricObject.named("shared.carts.my_cart.m1").withTags(tags)
            .withLevel(MetricLevel.CRITICAL).withType(MetricObject.MetricType.GAUGE).build()));
}
 
Example 3
Source File: MediaServiceImpl.java    From jwala with Apache License 2.0 5 votes vote down vote up
@Override
@Transactional
public JpaMedia create(final Map<String, String> mediaDataMap, final Map<String, Object> mediaFileDataMap) {
    final ObjectMapper objectMapper = new ObjectMapper();
    final JpaMedia media = objectMapper.convertValue(mediaDataMap, JpaMedia.class);

    // filename can be the full path or just the name that is why we need to convert it to Paths
    // to extract the base name e.g. c:/jdk.zip -> jdk.zip or jdk.zip -> jdk.zip
    final String filename = FilenameUtils.getName((String) mediaFileDataMap.get("filename"));

    try {
        mediaDao.findByNameAndType(media.getName(), media.getType());
        final String msg = MessageFormat.format("Media already exists with name {0} and type {1}", media.getName(), media.getType());
        LOGGER.error(msg);
        throw new MediaServiceException(msg);
    } catch (NoResultException e) {
        LOGGER.debug("No Media name conflict, ignoring not found exception for creating media ", e);
    }

    final String uploadedFilePath = repositoryService.upload(filename, (BufferedInputStream) mediaFileDataMap.get("content"));
    final List<String> binariesByBasename = repositoryService.getBinariesByBasename(FilenameUtils.removeExtension(filename));
    final String dest = getPathForExistingBinary(uploadedFilePath, binariesByBasename);

    final Set<String> zipRootDirSet = fileUtility.getZipRootDirs(dest);
    if (!zipRootDirSet.isEmpty()) {
        media.setRootDir(Paths.get(StringUtils.join(zipRootDirSet, ",")));
        media.setLocalPath(Paths.get(dest));
        return mediaDao.create(media);
    }
    repositoryService.delete(dest);
    throw new MediaServiceException(MessageFormat.
            format("{0} does not have any root directories! It may not be a valid media file.", filename));
}
 
Example 4
Source File: K8sAPIDashboardTask.java    From kardio with Apache License 2.0 4 votes vote down vote up
/**
 * Method to get all Pods and Containers associated to the deployment.
 * 
 * @param authToken
 * @param eVo
 * @param depLabelMap
 * @param externalPodsMap
 *
 */
private static void getPodsAndContainersOfDeployments(String authToken, EnvironmentVO eVo,
		Map<String, List<ServiceLabelVO>> depLabelMap, Map<String, ArrayList<Integer>> externalPodsMap) throws IOException {
	String podApiUrl = eVo.getK8sUrl() + PropertyUtil.getInstance().getValue(SurveillerConstants.K8S_API_PODS_PATH);
	/* Call - the Kube Pod api to get all the Pods in the Cluster */
	String podJson = RestCommunicationHandler.getResponse(podApiUrl, true, SurveillerConstants.BEARER_TOKEN, authToken);
	ObjectMapper mapper = new ObjectMapper();
	JsonNode podRootNode = mapper.readTree(podJson);
	ArrayNode appsNode = (ArrayNode) podRootNode.get("items");
	Iterator<JsonNode> podsIterator = appsNode.getElements();
	while (podsIterator.hasNext()) {
		JsonNode appsInNode = podsIterator.next();
		JsonNode metadataNode = appsInNode.get("metadata");
		JsonNode nameNode = metadataNode.get("name");
		String podName = nameNode.getValueAsText();
		JsonNode namespaceNode = metadataNode.get("namespace");
		String namespace = namespaceNode.getValueAsText();
		if (namespace.equals("default") || !namespace.contains("-")) {
			logger.info("Excluding Pods - " + podName + " in the namespace - " + namespace);
			continue;
		}
		JsonNode specNode = appsInNode.get("spec");
		ArrayNode contArrayNode = (ArrayNode) specNode.get("containers");
		/* Number of containers in Pod */
		int numCount = contArrayNode.size();
		//JsonNode ownerReferencesNode = 
		ArrayNode ownerReferencesArray = (ArrayNode) metadataNode.get("ownerReferences");
		if(ownerReferencesArray == null){
			loadPodsAndContainer("Kube-Systems",namespace, externalPodsMap, numCount);
			continue;
		}
		JsonNode ownerReferencesNode = ownerReferencesArray.get(0);
		JsonNode kindNode = ownerReferencesNode.get("kind");
		String kind = kindNode.getTextValue();
		if(!kind.equalsIgnoreCase("ReplicaSet")){
			loadPodsAndContainer(kind,namespace , externalPodsMap, numCount);
			continue;
		}
		
		JsonNode labelsNode = metadataNode.get("labels");
		if (labelsNode == null) {
			logger.info("The labelsNode is null for the pod - " + podName + " in the namespace - " + namespace);
			continue;
		}
		Map<String, String> podLabelMap = mapper.convertValue(labelsNode, Map.class);
		List<ServiceLabelVO> servLblList = depLabelMap.get(namespace);
		if(servLblList == null){
			continue;
		}
		serviceLabelLoop: for (ServiceLabelVO servLabelVo : servLblList) {
			int labelCount = 0;
			for (Entry<String, String> labelInfo : servLabelVo.getLabel().entrySet()) {
				if (podLabelMap.containsKey(labelInfo.getKey())) {
					if (podLabelMap.get(labelInfo.getKey()).equals(labelInfo.getValue())) {
						labelCount = labelCount + 1;
					} else {
						continue serviceLabelLoop;
					}
				} else {
					continue serviceLabelLoop;
				}
			}
			if (servLabelVo.getLabel().size() == labelCount) {
				
				servLabelVo.setNumOfContainers(servLabelVo.getNumOfContainers() + numCount);
				servLabelVo.setNumOfPods(servLabelVo.getNumOfPods() + 1);
				break;
			}
		}
	}
	
}
 
Example 5
Source File: K8sAPIDashboardTask.java    From kardio with Apache License 2.0 4 votes vote down vote up
/**
 * Method to get all Deployment and MatchLabels of the given cluster
 * 
 * @param authToken
 * @param eVo
 * @param depLabelMap
 *
 */
private static void getDeploymentAndMatchLabels(String authToken, EnvironmentVO eVo, Map<String, List<ServiceLabelVO>> depLabelMap) throws IOException {

	String deployementApiUrl = eVo.getK8sUrl() + PropertyUtil.getInstance().getValue(SurveillerConstants.K8S_API_DEPLOYMENT_PATH);
	String deploymentJson = RestCommunicationHandler.getResponse(deployementApiUrl, true, SurveillerConstants.BEARER_TOKEN, authToken);
	ObjectMapper mapper = new ObjectMapper();
	JsonNode rootNode = mapper.readTree(deploymentJson);
	ArrayNode deploymentNode = (ArrayNode) rootNode.get("items");
	if (deploymentNode.size() == 0) {
		String errorString = "Surveiller task DOK8SAPIDASHBOARDTASK - FAILED : Enviroment -"
				+ eVo.getEnvironmentName() + " Deployment JSON Cannot be empty";
		logger.error(errorString);
		throw new GeneralException(errorString);
	}
	
	Iterator<JsonNode> deploymentIterator = deploymentNode.getElements();
	while (deploymentIterator.hasNext()) {
		JsonNode appsInNode = deploymentIterator.next();
		JsonNode depMetadataNode = appsInNode.get("metadata");
		JsonNode depNameNode = depMetadataNode.get("name");
		String depName = depNameNode.getValueAsText();
		JsonNode namespaceNode = depMetadataNode.get("namespace");
		String namespace = namespaceNode.getValueAsText();
		JsonNode specNode = appsInNode.get("spec");
		JsonNode selectorNode = specNode.get("selector");
		if (namespace.equals("default") || !namespace.contains("-")) {
			logger.info("Excluding deployment - " + depName + " in the namespace - " + namespace);
			continue;
		}
		JsonNode matchLabelsNode = selectorNode.get("matchLabels");
		if (matchLabelsNode == null) {
			logger.info("The matchLabelsNode is null for the deployment - " + depName + " in the namespace - "
					+ namespace);
			continue;
		}
		Map<String, String> labelMap = mapper.convertValue(matchLabelsNode, Map.class);
		ServiceLabelVO slVo = new ServiceLabelVO();
		slVo.setLabel(labelMap);
		String serviceName = namespace + "/" + depName;
		slVo.setServiceName(serviceName);
		String appName = namespace.substring(0, namespace.indexOf("-"));
		slVo.setAppName(appName);
		List<ServiceLabelVO> servLblList = null;
		if (depLabelMap.containsKey(namespace)) {
			servLblList = depLabelMap.get(namespace);
		} else {
			servLblList = new ArrayList<ServiceLabelVO>();
		}
		servLblList.add(slVo);
		depLabelMap.put(namespace, servLblList);
		
	}
}
 
Example 6
Source File: TPSLookupTask.java    From kardio with Apache License 2.0 4 votes vote down vote up
private static Map<String, String> getAppService(EnvironmentVO eVo, String authToken) throws Exception {
	// TODO Auto-generated method stub
	
    /*Method to get All the deployment and the match label associated to each deployment.
     * The method will return a Map with namespace as key and value List<ServiceLabelVO>
     * */
	Map<String, List<ServiceLabelVO>> depLabelMap = getDepServiceLabel(eVo, authToken);
	/*Service Lookup Code*/
	
	String serviceApiUrl = eVo.getK8sUrl() + PropertyUtil.getInstance().getValue(SurveillerConstants.K8S_API_SERVICE_PATH);
	String serviceJson = RestCommunicationHandler.getResponse(serviceApiUrl, true, SurveillerConstants.BEARER_TOKEN, authToken);
	ObjectMapper mapper = new ObjectMapper();
	JsonNode rootNodeServ = mapper.readTree(serviceJson);
	ArrayNode serviceNode = (ArrayNode) rootNodeServ.get("items");
	if (serviceNode.size() == 0) {
		String errorString = "Surveiller task DOK8STPSLOOKUPLOADTASK - FAILED : Enviroment -"
				+ eVo.getEnvironmentName() + " Service JSON Cannot be empty";
		logger.error(errorString);
		throw new GeneralException(errorString);
	}
	Map<String, String> appServiceMap = new HashMap<String, String>(); 
	Iterator<JsonNode> serviceIterator = serviceNode.getElements();
	while (serviceIterator.hasNext()) {
		JsonNode appsInNode = serviceIterator.next();
		JsonNode servMetadataNode = appsInNode.get("metadata");
		JsonNode servNameNode = servMetadataNode.get("name");
		String serviceName = servNameNode.getValueAsText();
		JsonNode namespaceNode = servMetadataNode.get("namespace");
		String namespace = namespaceNode.getValueAsText();
		JsonNode specNode = appsInNode.get("spec");
		JsonNode selectorNode = specNode.get("selector");
		if (namespace.equals("default") || !namespace.contains("-")) {
			logger.info("Excluding service - " + serviceName + " in the namespace - " + namespace);
			continue;
		}
		Map<String, String> selectorMap = mapper.convertValue(selectorNode, Map.class);
		List<ServiceLabelVO> servLblList = depLabelMap.get(namespace);
		if(servLblList == null){
			continue;
		}
		for(ServiceLabelVO servLabelVo : servLblList){
			if(servLabelVo.getLabel() == null){
				continue;
			}
			if(servLabelVo.getLabel().equals(selectorMap)){
				appServiceMap.put(serviceName, servLabelVo.getServiceName());
			}
		}
	}	
	return appServiceMap;
}
 
Example 7
Source File: TPSLookupTask.java    From kardio with Apache License 2.0 4 votes vote down vote up
/**Method to get All the deployment and the match label associated to each deployment.
 * @param eVo
 * @param authToken
 * @return
 * @throws Exception
 */
private static Map<String, List<ServiceLabelVO>> getDepServiceLabel(EnvironmentVO eVo, String authToken) throws Exception {
	String deployementApiUrl = eVo.getK8sUrl() + PropertyUtil.getInstance().getValue(SurveillerConstants.K8S_API_DEPLOYMENT_PATH);
	String deploymentJson = RestCommunicationHandler.getResponse(deployementApiUrl, true, SurveillerConstants.BEARER_TOKEN, authToken);
	ObjectMapper mapper = new ObjectMapper();
	JsonNode rootNode = mapper.readTree(deploymentJson);
	ArrayNode deploymentNode = (ArrayNode) rootNode.get("items");
	if (deploymentNode.size() == 0) {
		String errorString = "Surveiller task DOK8STPSLOOKUPLOADTASK - FAILED : Enviroment -"
				+ eVo.getEnvironmentName() + " Deployment JSON Cannot be empty";
		logger.error(errorString);
		throw new GeneralException(errorString);
	}
	Map<String, List<ServiceLabelVO>> depLabelMap = new HashMap<String, List<ServiceLabelVO>>();
	Iterator<JsonNode> deploymentIterator = deploymentNode.getElements();
	while (deploymentIterator.hasNext()) {
		JsonNode appsInNode = deploymentIterator.next();
		JsonNode depMetadataNode = appsInNode.get("metadata");
		JsonNode depNameNode = depMetadataNode.get("name");
		String depName = depNameNode.getValueAsText();
		JsonNode namespaceNode = depMetadataNode.get("namespace");
		String namespace = namespaceNode.getValueAsText();
		JsonNode specNode = appsInNode.get("spec");
		JsonNode selectorNode = specNode.get("selector");
		if (namespace.equals("default") || !namespace.contains("-")) {
			logger.info("Excluding deployment - " + depName + " in the namespace - " + namespace);
			continue;
		}
		JsonNode matchLabelsNode = selectorNode.get("matchLabels");
		if(matchLabelsNode == null) {
			logger.info("The matchLabelsNode is null for the deployment - " + depName + " in the namespace - "
					+ namespace);
			continue;
		}
		Map<String, String> labelMap = mapper.convertValue(matchLabelsNode, Map.class);
		ServiceLabelVO slVo = new ServiceLabelVO();
		slVo.setLabel(labelMap);
		String serviceName = namespace + "/" + depName;
		slVo.setServiceName(serviceName);
		String appName = namespace.substring(0, namespace.indexOf("-"));
		slVo.setAppName(appName);
		List<ServiceLabelVO> servLblList = null;
		if (depLabelMap.containsKey(namespace)) {
			servLblList = depLabelMap.get(namespace);
		} else {
			servLblList = new ArrayList<ServiceLabelVO>();
		}
		servLblList.add(slVo);
		depLabelMap.put(namespace, servLblList);
	}
	return depLabelMap;
}
 
Example 8
Source File: SamlFederationResource.java    From secure-data-service with Apache License 2.0 4 votes vote down vote up
private void auditSuccessfulLogin(SLIPrincipal principal, Entity session, URI requestUri, String authorizationCode, Entity realm, Map<String, Object> appSession, String tenant) {
    TenantContext.setIsSystemCall(true);

    ObjectMapper jsoner = new ObjectMapper();
    Map<String, Object> mapForm = jsoner.convertValue(principal, Map.class);
    mapForm.remove("entity");
    if (!mapForm.containsKey("userType")) {
        mapForm.put("userType", EntityNames.STAFF);
    }
    session.getBody().put("principal", mapForm);
    sessionManager.updateSession(session);

    SecurityEvent successfulLogin = securityEventBuilder.createSecurityEvent(this.getClass().getName(), requestUri, "", principal, null, realm, null, true);
    successfulLogin.setOrigin(httpServletRequest.getRemoteHost()+ ":" + httpServletRequest.getRemotePort());
    successfulLogin.setCredential(authorizationCode);
    successfulLogin.setUserOrigin(httpServletRequest.getRemoteHost()+ ":" + httpServletRequest.getRemotePort());
    successfulLogin.setLogLevel(LogLevelType.TYPE_INFO);
    successfulLogin.setRoles(principal.getRoles());

    String applicationDetails = null;
    if (appSession != null){
        String clientId = (String) appSession.get("clientId");
        if (clientId != null) {
            NeutralQuery appQuery = new NeutralQuery();
            appQuery.setOffset(0);
            appQuery.setLimit(1);
            appQuery.addCriteria(new NeutralCriteria("client_id", "=", clientId));
            Entity application = repo.findOne("application", appQuery);
            if (application != null) {
                Map<String, Object> body = application.getBody();
                if (body != null) {
                    String name                = (String) body.get("name");
                    String createdBy           = (String) body.get("created_by");
                    successfulLogin.setAppId(name+"," + clientId);
                    applicationDetails         = String.format("%s by %s", name, createdBy);
                }
            }
        }
    }
    successfulLogin.setUser(principal.getExternalId());
    successfulLogin.setLogMessage(principal.getExternalId() + " from tenant " + tenant + " logged successfully into " + applicationDetails + ".");

    auditLogger.audit(successfulLogin);
}
 
Example 9
Source File: JsonMapperUtil.java    From ankush with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * Method to get Map from the object.
 * 
 * @param obj
 *            the obj
 * @return the map
 * @throws Exception
 *             the exception
 */
public static Map<String, Object> mapFromObject(Object obj)
		throws Exception {
	ObjectMapper mapper = new ObjectMapper();
	return mapper.convertValue(obj, HashMap.class);
}
 
Example 10
Source File: JsonMapperUtil.java    From ankush with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * Map from object.
 * 
 * @param <S>
 *            the generic type
 * @param obj
 *            the obj
 * @param className
 *            the class name
 * @return the s
 * @throws Exception
 *             the exception
 */
public static <S> S objectFromObject(Object obj, Class<S> className)
		throws Exception {
	ObjectMapper mapper = new ObjectMapper();
	return mapper.convertValue(obj, className);
}