Java Code Examples for org.json.simple.JSONObject#isEmpty()

The following examples show how to use org.json.simple.JSONObject#isEmpty() . 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: RssFeedWorker.java    From sepia-assist-server with MIT License 7 votes vote down vote up
private boolean workerAction(long tic){
	
	//get new reader
	RssFeedReader newRssReader = new RssFeedReader();
   	
   	//get feeds
   	int goodFeeds = 0;
   	for (String feedName : refreshFeeds){
		String url = NewsRssFeeds.feedUrls.get(feedName);
        JSONObject feed = newRssReader.getFeed(url, feedName, maxHeadlinesPerFeed, true);
        if (!feed.isEmpty()){
        	goodFeeds++;
        	//Debugger.println("NEWS-API: feed refreshed: " + feedName, 3);
        }
	}
   	//overwrite old feeds
   	Config.rssReader = newRssReader;
   	lastUpdated = System.currentTimeMillis();
   	
   	executedRefreshs++;
   	Debugger.println(name + ": " + goodFeeds + " feeds have been updated! (" + executedRefreshs + " time(s)) It took (ms): " 
   			+ (System.currentTimeMillis()-tic) + ", average (ms): " + averageRefreshTime, 3);
	
	return true;
}
 
Example 2
Source File: SchemaSerialization.java    From sqoop-on-spark with Apache License 2.0 7 votes vote down vote up
public static Schema restoreSchema(JSONObject jsonObject) {
  // if the object is empty return a empty schema
  if (jsonObject == null || jsonObject.isEmpty()) {
    return NullSchema.getInstance();
  }
  String name = (String) jsonObject.get(NAME);
  String note = (String) jsonObject.get(NOTE);
  java.util.Date date = new java.util.Date((Long) jsonObject.get(CREATION_DATE));

  Schema schema = new Schema(name).setNote(note).setCreationDate(date);
  JSONArray columnsArray = (JSONArray) jsonObject.get(COLUMNS);
  for (Object obj : columnsArray) {
    schema.addColumn(restoreColumn((JSONObject) obj));
  }
  return schema;
}
 
Example 3
Source File: Card.java    From sepia-assist-server with MIT License 6 votes vote down vote up
/**
 * Add an element to the card. Elements can be considered sub-cards of the service and might or might not be displayed 
 * as separate cards depending on cardType and client.
 * @param type - (optional) set an element type other than default 
 * @param data - (required) JSON string holding all required data for card type
 * @param details - (optional) JSON string holding details for an extended view
 * @param detailsHTML - (optional) HTML block holding details for an extended view  
 * @param text - (optional) text info (description or short summary)
 * @param redirectURL - (optional) link to element (e.g. to wikipedia, to homepage, etc.)
 * @param imageURL - (optional) image to element
 * @param actionInfo - (optional) JSON array with actions (see assistant.ACTIONS)
 * @param customHTML - (optional) custom HTML data block that can be used to replace JSON + details + template
 * @return the JSONObject that has been added to cards
 */
@SuppressWarnings("unchecked")
public JSONObject addElement(ElementType type, JSONObject data, JSONObject details, String detailsHTML,
				String text, String redirectURL, String imageURL, JSONArray actionInfo, String customHTML){
	JSONObject element = new JSONObject();
	element.put("data", data);
	if (type != null && !type.name().isEmpty()) 		element.put("type", type.name());
	if (details != null && !details.isEmpty()) 			element.put("details", details);
	if (detailsHTML != null && !detailsHTML.isEmpty())	element.put("detailsHTML", detailsHTML);
	if (text != null && !text.isEmpty()) 				element.put("text", text);
	if (redirectURL != null && !redirectURL.isEmpty())	element.put("url", redirectURL);
	if (imageURL != null && !imageURL.isEmpty())		element.put("image", imageURL);
	if (actionInfo != null && !actionInfo.isEmpty())	element.put("action", actionInfo);
	if (customHTML != null && !customHTML.isEmpty())	element.put("customHTML", customHTML);
	//add it
	cardInfo.add(element);
	number_of_elements++;
	return element;
}
 
Example 4
Source File: RssFeedReader.java    From sepia-assist-server with MIT License 6 votes vote down vote up
/**
 * Load the backup and return the last-modified timestamp of it or -1 if there was none.
 * @return timestamp or -1
 */
public long loadBackup(){
	//check file
	File file = new File(Workers.rssFeedsData_BackupFile);
	if (!file.exists()){
		Debugger.println("RssFeedReader - no backup file found! This is ok if you start for the first time or cleaned the backup.", 1);
		return -1l;
	}
	JSONObject backup = JSON.readJsonFromFile(Workers.rssFeedsData_BackupFile);
	if (backup != null && !backup.isEmpty()){
		long lastMod = file.lastModified();
		this.feedCache = backup;
		Debugger.println("RssFeedReader - backup restored with " + feedCache.size() + " feeds. Last modified: " + (new SimpleDateFormat(Config.defaultSdf)).format(lastMod), 3);
		return lastMod;
	}else{
		Debugger.println("RssFeedReader - backup was corrupted! Please check or remove the file at: " + Workers.rssFeedsData_BackupFile, 1);
		return -1l;
	}
}
 
Example 5
Source File: DynamoDB.java    From sepia-assist-server with MIT License 5 votes vote down vote up
/**
 * Get an item inside a table by using the primaryKey to search.
 * @param tableName - name of the table to check, usually "users"
 * @param primaryKey - primary key to search for, e.g. "Guuid"
 * @param keyValue - value of the primary key to check, e.g. "[email protected]"
 * @param lookUp - array of strings to look up in the item
 * @return JSONObject result (needs to be checked manually for success)
 */
public static JSONObject getItem(String tableName, String primaryKey, String keyValue, String... lookUp){
	if (lookUp == null || lookUp.length <= 0){
		JSONObject result =	new JSONObject();
		JSON.add(result, Connectors.HTTP_REST_SUCCESS, Boolean.FALSE);
		JSON.add(result, "error", "no data to lookup!");
		return result;
	}
	
	//operation:
	String operation = "GetItem";
	
	JSONObject expressionAttributeNames = new JSONObject();
	
	//get password, key token, basic info etc ... :
	String lookFor = "";
	for (String s : lookUp){
		lookFor += makeExpressionAttributeName(s, expressionAttributeNames) + ", ";
	}
	lookFor = lookFor.trim().replaceFirst(",$", "");
	
	//JSON request:
	JSONObject request = new JSONObject();
	JSON.add(request, "TableName", tableName);
	JSON.add(request, "Key", getSearchKey(primaryKey, keyValue.toLowerCase().trim())); 		//IDs are always lowerCase
	JSON.add(request, "ConsistentRead", Boolean.FALSE);	//eventually consistent should be enough
	JSON.add(request, "ReturnConsumedCapacity", "NONE");		//we don't need that info here .. yet
	JSON.add(request, "ProjectionExpression", lookFor);
	if (!expressionAttributeNames.isEmpty()){
		JSON.add(request, "ExpressionAttributeNames", expressionAttributeNames);
	}
	
	return request(operation, request.toJSONString());
}
 
Example 6
Source File: AccountElasticsearch.java    From sepia-assist-server with MIT License 5 votes vote down vote up
@Override
public int setInfos(User user, ServiceAccessManager api, JSONObject data) {
	long tic = System.currentTimeMillis();
	if (data.isEmpty()){
		Debugger.println("setInfo - No data was given. This will not return an error but it should not happen!", 1);	//debug
		return 0;
	}
	
	//check if the user is authorized to access the database
	if (!user.getToken().authenticated() || !api.isSigned()){
		return 2;
	}
	
	//filter the fields that are not allowed to be accessed - Note: applies to top level and some partially accessible direct children!
	JSONObject filteredData = ACCOUNT.filterServiceWriteData(api, data);
	if (filteredData.isEmpty()){
		Debugger.println("setInfo - Failed due to empty (allowed) data!", 1);			//debug
		return 2;
	}
	
	//Connect
	int code = getDB().updateDocument(DB.USERS, "all", user.getUserID(), filteredData);
	//System.out.println("Time needed: " + Debugger.toc(tic) + "ms");		//debug
	
	//Status?
	if (code != 0){
		Debugger.println("setInfo - Failed due to 'some' error!", 1);			//debug
		return 4;
	}else{
		//save statistics on successful data transfer
		Statistics.add_DB_hit();
		Statistics.save_DB_total_time(tic);			
		return 0;
	}
}
 
Example 7
Source File: Setup.java    From sepia-assist-server with MIT License 5 votes vote down vote up
/**
 * Test if Elasticsearch index exists and (optionally) create when missing.
 * @param createWhenMissing - true/false
 * @throws Exception
 */
public static void testAndUpdateElasticsearchMapping(boolean createWhenMissing) throws Exception{
	Elasticsearch db = new Elasticsearch();
	List<File> mappingFiles = FilesAndStreams.directoryToFileList(Config.dbSetupFolder + "ElasticsearchMappings/", null, false);
	//Test mappings
	JSONObject mappings = db.getMappings();
	if (mappings == null){
		throw new RuntimeException("ElasticSearch - Failed to check mappings! Is ES running and reachable?");
	}else if (mappings.isEmpty()){
		throw new RuntimeException("ElasticSearch - Failed to check mappings! Did you already run SEPIA setup?");
	}
	int mr = 0;
	int mf = 0;
	for (File f : mappingFiles){
		if (!f.getName().contains(".json")){
			//File has to be a .json map
			continue;
		}
		mr++;
		String index = f.getName().replaceFirst("\\.json$", "").trim();
		if (!mappings.containsKey(index)){
			//missing index
			Debugger.println("Elasticsearch - Missing index: " + index, 1);
			if (createWhenMissing){
				Debugger.println("Elasticsearch - Trying to create missing index: " + index, 3);
				writeElasticsearchMapping(index, true);
				mf++;
			}
		}else{
			mf++;
		}
	}
	if (mr == mf){
		Debugger.println("Elasticsearch: found " + mf + " of " + mr + " mapped indices. All good.", 3);
	}else{
		throw new RuntimeException("Elasticsearch: missing " + (mr-mf) + " of " + mr + " mapped indices. Please check database setup.");
	}
}
 
Example 8
Source File: EnrichmentUtils.java    From metron with Apache License 2.0 5 votes vote down vote up
public static JSONObject adjustKeys(JSONObject enrichedMessage, JSONObject enrichedField, String field, String prefix) {
  if ( !enrichedField.isEmpty()) {
    for (Object enrichedKey : enrichedField.keySet()) {
      if(!StringUtils.isEmpty(prefix)) {
        enrichedMessage.put(field + "." + enrichedKey, enrichedField.get(enrichedKey));
      }
      else {
        enrichedMessage.put(enrichedKey, enrichedField.get(enrichedKey));
      }
    }
  }
  return enrichedMessage;
}
 
Example 9
Source File: DynamoDB.java    From sepia-assist-server with MIT License 4 votes vote down vote up
/**
 * Get item inside table by using secondary indices. Note that indexName must be attributName here.  
 * @param tableName - name of the table to check, usually "users"
 * @param indexName - indexName aka attributName to search for, e.g. "Guuid"
 * @param indexValue - value of the attribute to check, e.g. "[email protected]"
 * @param lookUp - array of strings to look up in the item
 * @return JSONObject result (needs to be checked manually for success)
 */
public static JSONObject queryIndex(String tableName, String indexName, String indexValue, String... lookUp){
	//note: in this case indexName must be identical to attribute name. 
	//IndexName could also be the header for multiple attributes or independent from attribute name, but this is not supported here.
	if (lookUp == null || lookUp.length <= 0){
		JSONObject result =	new JSONObject();
		JSON.add(result, Connectors.HTTP_REST_SUCCESS, Boolean.FALSE);
		JSON.add(result, "error", "no data to lookup!");
		return result;
	}
	
	//operation:
	String operation = "Query";
	
	JSONObject expressionAttributeNames = new JSONObject();
	
	//get password, key token, basic info etc ... :
	String lookFor = "";
	for (String s : lookUp){
		lookFor += makeExpressionAttributeName(s, expressionAttributeNames) + ", ";
	}
	lookFor = lookFor.trim().replaceFirst(",$", "");
	
	//JSON request:
	JSONObject request = new JSONObject();
	JSON.add(request, "TableName", tableName);
	JSON.add(request, "IndexName", indexName); 
	JSON.add(request, "KeyConditionExpression", indexName + "= :ival");
		JSONObject expAttVal = new JSONObject();
			JSONObject ival = JSON.add(new JSONObject(), "S", indexValue.toLowerCase().trim()); 	//IDs are always lowerCase
		JSON.add(expAttVal, ":ival", ival);
	JSON.add(request, "ExpressionAttributeValues", expAttVal);
	JSON.add(request, "Limit", 1);
	JSON.add(request, "ConsistentRead", Boolean.FALSE);	//eventually consistent should be enough
	JSON.add(request, "ReturnConsumedCapacity", "NONE");		//we don't need that info here .. yet
	JSON.add(request, "ProjectionExpression", lookFor);
	if (!expressionAttributeNames.isEmpty()){
		JSON.add(request, "ExpressionAttributeNames", expressionAttributeNames);
	}
	
	return request(operation, request.toJSONString());
}
 
Example 10
Source File: DynamoDB.java    From sepia-assist-server with MIT License 4 votes vote down vote up
/**
 * Write a protected account attribute. For server operations only!!!
 * @param primaryKey - primaryKey of item in table
 * @param keyValue - value of primaryKey to match
 * @param keys - keys to write
 * @param objects - values to put at key positions
 * @return error code: 0 - all good, 2 - wrong or invalid keys, 3 - DB connection error
 */
public static int writeAny(String tableName, String primaryKey, String keyValue, String[] keys, Object[] objects){
	
	long tic = System.currentTimeMillis();
	int errorCode = 0;
	
	if (keys == null || keys.length <= 0){
		return 2;
	}
	
	//operation:
	String operation = "UpdateItem";
	
	//add this
	String updateExpressionSet = "SET ";
	String updateExpressionRemove = "REMOVE ";
	
	JSONObject expressionAttributeValues = new JSONObject();
	JSONObject expressionAttributeNames = new JSONObject();
	
	for (int i=0; i<keys.length; i++){
		if (objects[i].toString().isEmpty()){
			updateExpressionRemove += makeExpressionAttributeName(keys[i], expressionAttributeNames) + ", ";
		}else{
			updateExpressionSet += makeExpressionAttributeName(keys[i], expressionAttributeNames) + "=" + ":val"+i + ", ";
			//System.out.println("type: " + objects[i].getClass()); 		//debug
			if (objects[i].getClass().equals(JSONObject.class)){
				JSON.add(expressionAttributeValues, ":val"+i, objects[i]);
			}else{
				JSONObject jo = typeConversionDynamoDB(objects[i]);
				JSON.add(expressionAttributeValues, ":val"+i, jo);
			}
		}
	}
	//clean up:
	if (updateExpressionSet.trim().equals("SET")){
		updateExpressionSet = "";
	}
	if (updateExpressionRemove.trim().equals("REMOVE")){
		updateExpressionRemove = "";
	}
	//check if valid keys are left
	if (updateExpressionSet.isEmpty() && updateExpressionRemove.isEmpty()){
		//access to all requested keys was denied 
		return 2;
	}
	String updateExpression = (updateExpressionSet.trim().replaceFirst(",$", "") + " " +
							updateExpressionRemove.trim().replaceFirst(",$", "")).trim();
	
	//JSON request:
	JSONObject request = new JSONObject();
	JSON.add(request, "TableName", tableName);
	JSON.add(request, "Key", getSearchKey(primaryKey, keyValue.toLowerCase().trim())); 	//IDs are always lowerCase
	JSON.add(request, "UpdateExpression", updateExpression);
	if (!expressionAttributeNames.isEmpty()){
		JSON.add(request, "ExpressionAttributeNames", expressionAttributeNames);
	}
	if (!expressionAttributeValues.isEmpty()){
		JSON.add(request, "ExpressionAttributeValues", expressionAttributeValues);
	}
	JSON.add(request, "ReturnValues", "NONE");		//we don't need that info here .. yet
	
	//System.out.println("REQUEST: " + request.toJSONString());		//debug
	
	//Connect
	JSONObject response = request(operation, request.toJSONString());
	//System.out.println("RESPONSE: " + response.toJSONString());			//debug
	
	if (!Connectors.httpSuccess(response)){
		errorCode = 3;
		return errorCode;
	}else{
		//save statistics on successful data transfer
		Statistics.add_DB_hit();
		Statistics.save_DB_total_time(tic);
		
		errorCode = 0;
		return errorCode;
	}	
}
 
Example 11
Source File: AccountElasticsearch.java    From sepia-assist-server with MIT License 4 votes vote down vote up
@Override
public int getInfos(User user, ServiceAccessManager api, String... keys) {
	
	long tic = System.currentTimeMillis();
	
	//check if the user and api are valid and authorized to access the database
	if (!user.getToken().authenticated() || !api.isSigned()){
		return 2;
	}
	
	String userId = user.getUserID();
	
	//filter keys to make sure we only read what we are allowed to
	ArrayList<String> checkedFields = ACCOUNT.filterServiceReadData(api, keys);
	
	//make sure we have filters
	if (checkedFields.isEmpty()){
		return 2;
	}
	
	//Connect
	JSONObject response = getDB().getItemFiltered(DB.USERS, "all", userId, checkedFields.toArray(new String[]{}));
	//System.out.println("RESPONSE: " + response.toJSONString());			//debug
	//System.out.println("Time needed: " + Debugger.toc(tic) + "ms");		//debug
	
	//Status?
	if (!Connectors.httpSuccess(response)){
		//no access, no connection, wrong search keys or unknown error
		return 4;
	}else{
		JSONObject item = (JSONObject) response.get("_source");
		if (item == null || item.isEmpty()){
			//best guess: no account found?
			return 3;
		}else{
			//all clear! get the stuff:
			
			//Run through all keys and save them
			for (String k : checkedFields){
				
				//we strictly use maps as containers! So we can split strings at "." to get attributes
				String[] levels = k.split("\\.");
				Object found = JSON.getObject(item, levels);
				if (found != null){
					//name
					if (k.equals(ACCOUNT.USER_NAME)){
						user.userName = new Name(Converters.object2HashMapStrObj(found));
						user.info.put(k, user.userName);
					
					//user_home - this is not officially part of the account anymore, 
					//but its all in user-data
					/*
					}else if (k.equals(ACCOUNT.USER_HOME)){
						user.userHome = new Address((JSONObject) found);
						user.info.put(k, user.userHome);

					//user_work
					}else if (k.equals(ACCOUNT.USER_WORK)){
						user.userWork = new Address((JSONObject) found);
						user.info.put(k, user.userWork);
					*/
					
					//add to info as is
					}else{
						user.info.put(k, found);
					}
					
					//TODO: add more specials?
				}
			}
			//save statistics on successful data transfer
			Statistics.add_DB_hit();
			Statistics.save_DB_total_time(tic);
			
			return 0;
		}
	}
}
 
Example 12
Source File: AccountDynamoDB.java    From sepia-assist-server with MIT License 4 votes vote down vote up
public int setInfos(User user, ServiceAccessManager api, JSONObject data) {
	long tic = System.currentTimeMillis();
	if (data.isEmpty()){
		Debugger.println("setInfo - No data was given. This will not return an error but it should not happen!", 1);	//debug
		return 0;
	}
	
	//check if the user is authorized to access the database
	if (!user.getToken().authenticated() || !api.isSigned()){
		return 2;
	}
	
	//Convert it back to the old format - we need this because we don't know if the user/system uses/requires keys with dots (e.g. uname.first). 
	//TODO: this is probably computational "heavy", but it was my best idea to restore compatibility 
	JSONObject flatJson = JSON.makeFlat(data, "", null);
	
	//Filter the fields that are not allowed to be accessed - Note: applies to top level and some partially accessible direct children!
	//TODO: we should test this again before considering DynamoDB as database (I'm 'almost' sure it works).
	JSONObject filteredData = ACCOUNT.filterServiceWriteData(api, flatJson);
	
	//Convert again to separate key-value pairs
	ArrayList<String> keys = new ArrayList<>();
	ArrayList<Object> objects = new ArrayList<>();
	for (Object kO : filteredData.keySet()){
		String k = kO.toString();
		keys.add(k);
		objects.add(flatJson.get(k));
	}
	if (keys.isEmpty()){
		Debugger.println("setInfo - no valid keys (left)!", 1);
		return 2;
	}
	
	//Connect
	int code = DynamoDB.writeAny(tableName, DynamoDB.PRIMARY_USER_KEY, user.getUserID(), 
			keys.toArray(new String[0]), objects.toArray(new Object[0]));
	
	if (code == 3){
		Debugger.println("setInfo - DynamoDB connection error!", 1);		//debug
		return 1;
	}else if (code != 0){
		Debugger.println("setInfo - DynamoDB 'some' error!", 1);			//debug
		return 4;
	}else{
		//save statistics on successful data transfer
		Statistics.add_DB_hit();
		Statistics.save_DB_total_time(tic);
		
		return 0;
	}
}
 
Example 13
Source File: AccountDynamoDB.java    From sepia-assist-server with MIT License 4 votes vote down vote up
public boolean writeBasicStatistics(String userID){
	
	long tic = System.currentTimeMillis();
	
	//operation:
	String operation = "UpdateItem";
	
	//add this
	JSONObject expressionAttributeValues = new JSONObject();

	String updateExpressionSet = "ADD ";
	updateExpressionSet += "statistics.totalCalls :val1";	// + ", ";
	JSON.add(expressionAttributeValues, ":val1", DynamoDB.typeConversionDynamoDB(Integer.valueOf(1)));
	
	updateExpressionSet += " SET ";
	updateExpressionSet += "statistics.lastLogin = :val2";  // + ", ";
	JSON.add(expressionAttributeValues, ":val2", DynamoDB.typeConversionDynamoDB(String.valueOf(System.currentTimeMillis())));

	//clean up:
	String updateExpression = updateExpressionSet.trim();
	
	//primaryKey:
	JSONObject prime = DynamoDB.getPrimaryUserKey(userID);
	
	//JSON request:
	JSONObject request = new JSONObject();
	JSON.add(request, "TableName", tableName);
	JSON.add(request, "Key", prime);
	JSON.add(request, "UpdateExpression", updateExpression);
	if (!expressionAttributeValues.isEmpty()){
		JSON.add(request, "ExpressionAttributeValues", expressionAttributeValues);
	}
	JSON.add(request, "ReturnValues", "NONE");		//we don't need that info here .. yet
	
	//System.out.println("REQUEST: " + request.toJSONString());		//debug
	
	//Connect
	JSONObject response = DynamoDB.request(operation, request.toJSONString());
	//System.out.println("RESPONSE: " + response.toJSONString());			//debug
	//System.out.println("Time needed: " + Debugger.toc(tic) + "ms");		//debug
	
	if (!Connectors.httpSuccess(response)){
		//errorCode = 3;
		Debugger.println("writeBasicStatistics - DynamoDB Response: " + response.toJSONString(), 1);			//debug
		return false;
	}else{
		//save statistics on successful data transfer
		Statistics.add_DB_hit();
		Statistics.save_DB_total_time(tic);
		
		//errorCode = 0;
		return true;
	}	
}
 
Example 14
Source File: DockerAction.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public DockerContainerDetail getDetail(DockerContainer container) throws DockerException {
    JSONObject value = getRawDetails(DockerEntityType.Container, container.getId());
    String name = (String) value.get("Name");
    DockerContainer.Status status = DockerContainer.Status.STOPPED;
    JSONObject state = (JSONObject) value.get("State");
    if (state != null) {
        boolean paused = (Boolean) getOrDefault(state, "Paused", false);
        if (paused) {
            status = DockerContainer.Status.PAUSED;
        } else {
            boolean running = (Boolean) getOrDefault(state, "Running", false);
            if (running) {
                status = DockerContainer.Status.RUNNING;
            }
        }
    }

    boolean tty = false;
    boolean stdin = false;
    JSONObject config = (JSONObject) value.get("Config");
    if (config != null) {
        tty = (boolean) getOrDefault(config, "Tty", false);
        stdin = (boolean) getOrDefault(config, "OpenStdin", false);
    }
    JSONObject ports = (JSONObject) ((JSONObject) value.get("NetworkSettings")).get("Ports");
    if (ports == null || ports.isEmpty()) {
        return new DockerContainerDetail(name, status, stdin, tty);
    } else {
        List<PortMapping> portMapping = new ArrayList<>();
        for (String containerPortData : (Set<String>) ports.keySet()) {
            JSONArray hostPortsArray = (JSONArray) ports.get(containerPortData);
            if (hostPortsArray != null && !hostPortsArray.isEmpty()) {
                Matcher m = PORT_PATTERN.matcher(containerPortData);
                if (m.matches()) {
                    int containerPort = Integer.parseInt(m.group(1));
                    String type = m.group(2).toUpperCase(Locale.ENGLISH);
                    int hostPort = Integer.parseInt((String) ((JSONObject) hostPortsArray.get(0)).get("HostPort"));
                    String hostIp = (String) ((JSONObject) hostPortsArray.get(0)).get("HostIp");
                    portMapping.add(new PortMapping(ExposedPort.Type.valueOf(type), containerPort, hostPort, hostIp));
                } else {
                    LOGGER.log(Level.FINE, "Unparsable port: {0}", containerPortData);
                }
            }
        }
        return new DockerContainerDetail(name, status, stdin, tty, portMapping);
    }
}
 
Example 15
Source File: APIManagerConfiguration.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * To populate deployment environments based configurations
 *
 * @param omElement
 */
public void setContainerMgtConfigurations(OMElement omElement) {
    JSONObject containerMgt = new JSONObject();
    Iterator containerMgtElements = omElement.getChildElements();
    JSONArray containerMgtInfo = new JSONArray();
    Map<String, String> deploymentEnvs = new HashMap<>();
    while (containerMgtElements.hasNext()) {
        OMElement containerMgtElement = (OMElement) containerMgtElements.next();

        //Get Deployment Environments
        if (containerMgtElement.getLocalName().equals(ContainerBasedConstants.DEPLOYMENT_ENVIRONMENTS)) {
            Iterator environmentsIterator = containerMgtElement.getChildElements();
            while (environmentsIterator.hasNext()) {
                //read default values for class name and put into a map
                OMElement environmentElement = (OMElement) environmentsIterator.next();
                deploymentEnvs.put(environmentElement.getAttributeValue(new QName("name")).toLowerCase(),
                        environmentElement.getText());
            }
        } else if (containerMgtElement.getLocalName().equals(ContainerBasedConstants.CONTAINER_MANAGEMENT_INFO)) {
            //if configurations defined put them into JSON array
            Iterator containerMgtInfoElements = containerMgtElement.getChildElements();
            JSONObject containerMgtInfoObj = new JSONObject();
            while (containerMgtInfoElements.hasNext()) {
                OMElement containerMgtInfoElement = (OMElement) containerMgtInfoElements.next();
                if (containerMgtInfoElement.getLocalName().equals(ContainerBasedConstants.TYPE)) {
                    containerMgt.put(ContainerBasedConstants.TYPE, containerMgtInfoElement.getText().toLowerCase());
                } else if (containerMgtInfoElement.getLocalName().equals(ContainerBasedConstants.CLASS_NAME)) {
                    if (containerMgtInfoElement.getText() != null && containerMgtInfoElement.getText() != "") {
                        containerMgt.put(ContainerBasedConstants.CLASS_NAME, containerMgtInfoElement.getText().toLowerCase());
                    } else {
                        containerMgt.put(ContainerBasedConstants.CLASS_NAME,
                                deploymentEnvs.get(containerMgt.get(ContainerBasedConstants.TYPE)));
                    }
                } else if (containerMgtInfoElement.getLocalName().equals(ContainerBasedConstants.CLUSTER_NAME)) {
                    containerMgtInfoObj.put(ContainerBasedConstants.CLUSTER_NAME, containerMgtInfoElement.getText());
                } else if (containerMgtInfoElement.getLocalName().equals(ContainerBasedConstants.DISPLAY_NAME)) {
                    containerMgtInfoObj.put(ContainerBasedConstants.DISPLAY_NAME, containerMgtInfoElement.getText());
                } else if (containerMgtInfoElement.getLocalName().equals(ContainerBasedConstants.PROPERTIES)) {
                    Iterator clusterPropertiesIterator =
                            containerMgtInfoElement.getChildElements();
                    JSONObject propertyObj = new JSONObject();
                    while (clusterPropertiesIterator.hasNext()) {
                        OMElement propertyElement = (OMElement) clusterPropertiesIterator.next();
                        propertyObj.put(propertyElement.getAttributeValue(new QName("name")), propertyElement.getText());
                    }
                    containerMgtInfoObj.put(ContainerBasedConstants.PROPERTIES, propertyObj);
                }
            }
            containerMgtInfo.add(containerMgtInfoObj);
        }
    }
    if (!containerMgtInfo.isEmpty()) {
        containerMgt.put(ContainerBasedConstants.CONTAINER_MANAGEMENT_INFO, containerMgtInfo);
    }
    if (!containerMgt.isEmpty()) {
        containerMgtAttributes.add(containerMgt);
    }
}