List of usage examples for java.util HashMap toString
public String toString()
From source file:de.fhg.fokus.odp.portal.managedatasets.utils.HashMapUtils.java
/** * Meta data to map.//from www . ja va 2s. co m * * @param metaData * the meta data * @return the hash map */ public static HashMap<String, String> metaDataToMap(MetaDataBean metaData) { HashMap<String, String> metaDataMap = new HashMap<String, String>(); HashMap<String, String> extrasMap = new HashMap<String, String>(); List<Map<String, String>> resourcesList = new ArrayList<Map<String, String>>(); extrasMap.put("temporal_coverage_from", metaData.getTemporal_coverage_from()); extrasMap.put("temporal_coverage_to", metaData.getTemporal_coverage_to()); extrasMap.put("temporal_granularity", metaData.getTemporal_granularity()); extrasMap.put("geographical_coverage", metaData.getGeographical_coverage()); extrasMap.put("geographical_granularity", metaData.getGeographical_granularity()); extrasMap.put("date_released", DateUtils.dateToStringTemporalCoverage(metaData.getDate_released())); extrasMap.put("others", metaData.getOthers()); for (Resource resource : metaData.getResources()) { Map<String, String> resourceMap = new HashMap<String, String>(); if (!resource.getUrl().isEmpty() && !resource.getFormat().isEmpty()) { resourceMap.put("url", resource.getUrl()); resourceMap.put("format", resource.getFormat().toUpperCase()); resourceMap.put("description", resource.getDescription()); resourceMap.put("language", resource.getLanguage()); resourcesList.add(resourceMap); } } metaDataMap.put("extras", JSONValue.toJSONString(extrasMap)); metaDataMap.put("resources", JSONValue.toJSONString(resourcesList)); if (metaData.getTags().isEmpty()) { metaDataMap.put("tags", "[]"); } else { StringBuilder tagsBuilder = new StringBuilder(); for (String tag : metaData.getTags().split(",")) { tagsBuilder.append("\"" + tag.trim() + "\","); } // remove trailing comma tagsBuilder = tagsBuilder.deleteCharAt(tagsBuilder.length() - 1); metaDataMap.put("tags", "[" + tagsBuilder.toString().trim() + "]"); } metaDataMap.put("groups", JSONValue.toJSONString(metaData.getGroups())); metaDataMap.put("title", "\"" + metaData.getTitle() + "\""); metaDataMap.put("name", "\"" + metaData.getName() + "\""); metaDataMap.put("author", "\"" + metaData.getAuthor() + "\""); metaDataMap.put("author_email", "\"" + metaData.getAuthor_email() + "\""); metaDataMap.put("url", "\"" + metaData.getUrl() + "\""); metaDataMap.put("notes", "\"" + metaData.getNotes() + "\""); metaDataMap.put("license_id", "\"" + metaData.getLicense_id() + "\""); metaDataMap.put("version", "\"" + metaData.getVersion() + "\""); metaDataMap.put("maintainer", "\"" + metaData.getMaintainer() + "\""); metaDataMap.put("maintainer_email", "\"" + metaData.getMaintainer_email() + "\""); metaDataMap.put("metadata_created", "\"" + DateUtils.dateToStringMetaDate(metaData.getMetadata_created()) + "\""); metaDataMap.put("metadata_modified", "\"" + metaData.getMetadata_modified() + "\""); log.info("JSON String for create metadata: " + metaDataMap.toString()); return metaDataMap; }
From source file:org.openecomp.sdnc.sli.aai.AAIDeclarations.java
@Override public QueryStatus query(String resource, boolean localOnly, String select, String key, String prefix, String orderBy, SvcLogicContext ctx) throws SvcLogicException { getLogger().debug("AAIService.query \tresource = " + resource); String vnfId = null;// www . jav a2s. co m String vnfName = null; HashMap<String, String> nameValues = keyToHashMap(key, ctx); getLogger().debug("key = " + nameValues.toString()); if (!checkOldFormat(resource, nameValues)) { ctx.setAttribute(String.format("%s.error.message", prefix), String .format("Resource %s is not supported. Key string contains invaid identifiers", resource)); return QueryStatus.FAILURE; } if (resource == null || resource.isEmpty() || AAIRequest.createRequest(resource, nameValues) == null) { ctx.setAttribute(String.format("%s.error.message", prefix), String.format("Resource %s is not supported", resource)); return QueryStatus.FAILURE; } // process data using new model boolean useNewModelProcessing = true; // process server query by name the old way if (("vserver".equals(resource) || "vserver2".equals(resource))) { if (nameValues.containsKey("vserver_name") || nameValues.containsKey("vserver-name") || nameValues.containsKey("vserver.vserver_name") || nameValues.containsKey("vserver.vserver-name")) useNewModelProcessing = false; } if ("generic-vnf".equals(resource)) { if (nameValues.containsKey("vnf_name") || nameValues.containsKey("vnf-name") || nameValues.containsKey("generic_vnf.vnf_name") || nameValues.containsKey("generic-vnf.vnf-name")) useNewModelProcessing = false; } // process data using new model if (useNewModelProcessing && AAIRequest.createRequest(resource, nameValues) != null) { try { return newModelQuery(resource, localOnly, select, key, prefix, orderBy, ctx); } catch (Exception exc) { getLogger().warn("Failed query - returning FAILURE", exc); return QueryStatus.FAILURE; } } ObjectMapper mapper = AAIService.getObjectMapper(); Map<String, Object> attributes = new HashMap<String, Object>(); String modifier = null; if (resource.contains(":")) { String[] tokens = resource.split(":"); resource = tokens[0]; if (tokens.length > 1) { modifier = tokens[1]; } } resource = resource.toLowerCase().replace("-", "_"); try { switch (resource) { case "generic_vnf": vnfId = nameValues.get("vnf_id"); if (nameValues.containsKey("vnf_id")) vnfId = nameValues.get("vnf_id"); else if (nameValues.containsKey("generic_vnf.vnf_name")) vnfId = nameValues.get("generic_vnf.vserver_name"); if (nameValues.containsKey("vnf_name")) vnfName = nameValues.get("vnf_name"); else if (nameValues.containsKey("generic_vnf.vnf_name")) vnfName = nameValues.get("generic_vnf.vnf_name"); if (vnfId != null && !vnfId.isEmpty()) { // at this point of the project this part should not be executed vnfId = vnfId.trim().replace("'", "").replace("$", "").replace("'", ""); GenericVnf vnf = this.requestGenericVnfData(vnfId); if (vnf == null) { return QueryStatus.NOT_FOUND; } attributes = mapper.convertValue(vnf, attributes.getClass()); } else if (vnfName != null && !vnfName.isEmpty()) { try { vnfName = vnfName.trim().replace("'", "").replace("$", "").replace("'", ""); GenericVnf vnf = this.requestGenericVnfeNodeQuery(vnfName); if (vnf == null) { return QueryStatus.NOT_FOUND; } vnfId = vnf.getVnfId(); nameValues.put("vnf_id", vnfId); attributes = mapper.convertValue(vnf, attributes.getClass()); } catch (AAIServiceException exc) { int errorCode = exc.getReturnCode(); switch (errorCode) { case 400: case 404: case 412: break; default: getLogger().warn("Caught exception trying to refresh generic VNF", exc); } ctx.setAttribute(prefix + ".error.message", exc.getMessage()); if (errorCode >= 300) { ctx.setAttribute(prefix + ".error.http.response-code", "" + exc.getReturnCode()); } return QueryStatus.FAILURE; } } else { getLogger().warn("No arguments are available to process generic VNF"); return QueryStatus.FAILURE; } break; case "vserver": case "vserver2": String vserverName = null; if (nameValues.containsKey("vserver_name")) vserverName = nameValues.get("vserver_name"); else if (nameValues.containsKey("vserver.vserver_name")) vserverName = nameValues.get("vserver.vserver_name"); String vserverId = null; if (nameValues.containsKey("vserver_id")) vserverId = nameValues.get("vserver_id"); if (nameValues.containsKey("vserver.vserver_id")) vserverId = nameValues.get("vserver.vserver_id"); String tenantId = nameValues.get("teannt_id"); if (vserverName != null) vserverName = vserverName.trim().replace("'", "").replace("$", "").replace("'", ""); if (vserverId != null) vserverId = vserverId.trim().replace("'", "").replace("$", "").replace("'", ""); if (tenantId != null) tenantId = tenantId.trim().replace("'", "").replace("$", "").replace("'", ""); if (vserverName != null) { URL vserverUrl = null; try { vserverUrl = this.requestVserverURLNodeQuery(vserverName); } catch (AAIServiceException aaiexc) { ctx.setAttribute(prefix + ".error.message", aaiexc.getMessage()); if (aaiexc.getReturnCode() >= 300) { ctx.setAttribute(prefix + ".error.http.response-code", "" + aaiexc.getReturnCode()); } if (aaiexc.getReturnCode() == 404) return QueryStatus.NOT_FOUND; else return QueryStatus.FAILURE; } if (vserverUrl == null) { return QueryStatus.NOT_FOUND; } tenantId = getTenantIdFromVserverUrl(vserverUrl); String cloudOwner = getCloudOwnerFromVserverUrl(vserverUrl); String cloudRegionId = getCloudRegionFromVserverUrl(vserverUrl); Vserver vserver = null; try { vserver = this.requestVServerDataByURL(vserverUrl); } catch (AAIServiceException aaiexc) { ctx.setAttribute(prefix + ".error.message", aaiexc.getMessage()); if (aaiexc.getReturnCode() >= 300) { ctx.setAttribute(prefix + ".error.http.response-code", "" + aaiexc.getReturnCode()); } if (aaiexc.getReturnCode() == 404) return QueryStatus.NOT_FOUND; else return QueryStatus.FAILURE; } if (vserver == null) { return QueryStatus.NOT_FOUND; } attributes = mapper.convertValue(vserver, attributes.getClass()); if (!attributes.containsKey("tenant-id") && tenantId != null) { attributes.put("tenant-id", tenantId); } if (!attributes.containsKey("cloud-owner") && cloudOwner != null) { attributes.put("cloud-owner", cloudOwner); } if (!attributes.containsKey("cloud-region-id") && cloudRegionId != null) { attributes.put("cloud-region-id", cloudRegionId); } } else if (vserverId != null && tenantId != null) { Vserver vserver = this.requestVServerData(tenantId, vserverId, "att-aic", "AAIAIC25"); if (vserver == null) { return QueryStatus.NOT_FOUND; } attributes = mapper.convertValue(vserver, attributes.getClass()); if (!attributes.containsKey("tenant-id") && tenantId != null) { attributes.put("tenant-id", tenantId); } } else { return QueryStatus.FAILURE; } break; default: return QueryStatus.FAILURE; } QueryStatus retval = QueryStatus.SUCCESS; if (attributes == null || attributes.isEmpty()) { retval = QueryStatus.NOT_FOUND; getLogger().debug("No data found"); } else { if (ctx != null) { if (prefix != null) { ArrayList<String> keys = new ArrayList<String>(attributes.keySet()); int numCols = keys.size(); for (int i = 0; i < numCols; i++) { String colValue = null; String colName = keys.get(i); Object object = attributes.get(colName); if (object != null && object instanceof String) { colValue = (String) object; if (prefix != null) { getLogger().debug("Setting " + prefix + "." + colName.replaceAll("_", "-") + " = " + colValue); ctx.setAttribute(prefix + "." + colName.replaceAll("_", "-"), colValue); } else { getLogger() .debug("Setting " + colValue.replaceAll("_", "-") + " = " + colValue); ctx.setAttribute(colValue.replaceAll("_", "-"), colValue); } } else if (object != null && object instanceof Map) { if (colName.equals(modifier) || colName.equals("relationship-list")) { String localNodifier = modifier; if (localNodifier == null) localNodifier = "relationship-list"; Map<String, Object> properties = (Map<String, Object>) object; writeMap(properties, prefix + "." + localNodifier, ctx); } } } } } } getLogger().debug("Query - returning " + retval); return (retval); } catch (Exception exc) { getLogger().warn("Failed query - returning FAILURE", exc); return QueryStatus.FAILURE; } // return QueryStatus.SUCCESS; }
From source file:org.restcomm.android.sdk.RCDevice.java
/** * Initialize RCDevice (if not already initialized) the RCDevice Service with parameters. Notice that this needs to happen after the service has been bound. Remember that * once the Service starts in continues to run in the background even if the App doesn't have any activity running * * @param activityContext Activity context * @param parameters Parameters for the Device entity (prefer using the string constants shown below, i.e. RCDevice.ParameterKeys.*, instead of * using strings like 'signaling-secure', etc. Possible keys: <br> * <b>RCDevice.ParameterKeys.SIGNALING_USERNAME</b>: Identity for the client, like <i>'bob'</i> (mandatory) <br> * <b>RCDevice.ParameterKeys.SIGNALING_PASSWORD</b>: Password for the client (optional for registrar-less scenarios). Be VERY careful to securely handle this inside your App. Never store it statically and in cleartext form in your App before submitting to Google Play Store as you run the risk of any of the folks downloading it figuring it out your credentials <br> * <b>RCDevice.ParameterKeys.SIGNALING_DOMAIN</b>: Restcomm endpoint to use, like <i>'cloud.restcomm.com'</i>. By default port 5060 will be used for cleartext signaling and 5061 for encrypted signaling. You can override the port by suffixing the domain; for example to use port 5080 instead, use the following: <i>'cloud.restcomm.com:5080'</i>. Don't pass this parameter (or leave empty) for registrar-less mode (optional) <br> * <b>RCDevice.ParameterKeys.MEDIA_ICE_SERVERS_DISCOVERY_TYPE</b>: Media ICE server discovery type, or how should SDK figure out which the actual set ICE servers to use internally. Use ICE_SERVERS_CONFIGURATION_URL_XIRSYS_V2 to utilize a V2 Xirsys configuration URL to retrieve the ICE servers. Use ICE_SERVERS_CONFIGURATION_URL_XIRSYS_V3 to utilize a V3 Xirsys configuration URL to retrieve the ICE servers. Use ICE_SERVERS_CUSTOM if you don't want to use a configuration URL, but instead provide the set of ICE servers youself to the SDK (i.e. the App needs to have logic to retrieve them and provide them) <br> * <b>RCDevice.ParameterKeys.MEDIA_ICE_URL</b>: ICE url to use when using a Xirsys configuration URL, like <i>'https://service.xirsys.com/ice'</i> for Xirsys V2 (i.e. ICE_SERVERS_CONFIGURATION_URL_XIRSYS_V2), and <i>https://es.xirsys.com/_turn/</i> for Xirsys V3 (i.e. ICE_SERVERS_CONFIGURATION_URL_XIRSYS_V3). If no Xirsys configuration URL is used (i.e. ICE_SERVERS_CUSTOM) then this key is not applicable shouldn't be passed (optional) <br> * <b>RCDevice.ParameterKeys.MEDIA_ICE_USERNAME</b>: ICE username for authentication when using a Xirsys configuration URL (optional) <br> * <b>RCDevice.ParameterKeys.MEDIA_ICE_PASSWORD</b>: ICE password for authentication when using a Xirsys configuration URL (optional). Be VERY careful to securely handle this inside your App. Never store it statically and in cleartext form in your App before submitting to Google Play Store as you run the risk of any of the folks downloading it figuring it out your credentials <br> * <b>RCDevice.ParameterKeys.MEDIA_ICE_DOMAIN</b>: ICE Domain to be used in the ICE configuration URL when using a Xirsys configuration URL. Notice that V2 Domains are called Channels in V3 organization, but we use this same key in both cases (optional) <br> * <b>RCDevice.ParameterKeys.SIGNALING_SECURE_ENABLED</b>: Should signaling traffic be encrypted? Always set this to true, unless you have a very good reason to use cleartext signaling (like debugging). If this is the case, then a key pair is generated when * signaling facilities are initialized and added to a custom keystore. Also, added to this custom keystore are all the trusted certificates from * the System Wide Android CA Store, so that we properly accept only legit server certificates. If not passed (or false) signaling is cleartext (optional) <br> * <b>RCDevice.ParameterKeys.MEDIA_TURN_ENABLED</b>: Should TURN be enabled for webrtc media? (optional) <br> * <b>RCDevice.ParameterKeys.SIGNALING_LOCAL_PORT</b>: Local port to use for signaling (optional) <br> * <b>RCDevice.ParameterKeys.RESOURCE_SOUND_CALLING</b>: The SDK provides the user with default sounds for calling, ringing, busy (declined) and message events, but the user can override them * by providing their own resource files (i.e. .wav, .mp3, etc) at res/raw passing them here with Resource IDs like R.raw.user_provided_calling_sound. This parameter * configures the sound you will hear when you make a call and until the call is either replied or you hang up<br> * <b>RCDevice.ParameterKeys.RESOURCE_SOUND_RINGING</b>: The sound you will hear when you receive a call <br> * <b>RCDevice.ParameterKeys.RESOURCE_SOUND_DECLINED</b>: The sound you will hear when your call is declined <br> * <b>RCDevice.ParameterKeys.RESOURCE_SOUND_MESSAGE</b>: The sound you will hear when you receive a message <br> * * //push notification keys * <b>RCDevice.ParameterKeys.PUSH_NOTIFICATIONS_APPLICATION_NAME</b>: name of the client application * <b>RCDevice.ParameterKeys.PUSH_NOTIFICATIONS_ACCOUNT_EMAIL</b>: account's email * <b>RCDevice.ParameterKeys.PUSH_NOTIFICATIONS_ACCOUNT_PASSWORD </b>: password for an account * <b>RCDevice.ParameterKeys.PUSH_NOTIFICATIONS_ENABLE_PUSH_FOR_ACCOUNT</b>: true if we want to enable push on server for the account, otherwise false * <b>RCDevice.ParameterKeys.PUSH_NOTIFICATIONS_PUSH_DOMAIN</b>: domain for the push notifications; for example: push.restcomm.com * <b>RCDevice.ParameterKeys.PUSH_NOTIFICATIONS_HTTP_DOMAIN</b>: Restcomm HTTP domain, like 'cloud.restcomm.com' * <b>RCDevice.ParameterKeys.PUSH_NOTIFICATIONS_FCM_SERVER_KEY</b>: server hash key for created application in firebase cloud messaging * <b>RCDevice.ParameterKeys.PUSH_NOTIFICATION_TIMEOUT_MESSAGING_SERVICE</b>: RCDevice will have timer introduced for closing because of the message background logic this is introduced in the design. The timer by default will be 5 seconds; It can be changed by sending parameter with value (in milliseconds) /*w ww. j a v a 2s. co m*/ * @param deviceListener The listener for upcoming RCDevice events * @return True always for now * @see RCDevice */ public boolean initialize(Context activityContext, HashMap<String, Object> parameters, RCDeviceListener deviceListener) throws RCException { try { if (!isServiceInitialized) { isServiceInitialized = true; //context = activityContext; state = DeviceState.OFFLINE; RCLogger.i(TAG, "RCDevice(): " + parameters.toString()); //this.updateCapabilityToken(capabilityToken); this.listener = deviceListener; RCUtils.validateDeviceParms(parameters); storageManagerPreferences = new StorageManagerPreferences(this); StorageUtils.saveParams(storageManagerPreferences, parameters); //because intents are saved as uri strings we need to check; do we have an //actual intent. If not, we must check is it a string and return an intent Object callObj = parameters.get(RCDevice.ParameterKeys.INTENT_INCOMING_CALL); Object messageObj = parameters.get(RCDevice.ParameterKeys.INTENT_INCOMING_MESSAGE); if (callObj instanceof String && messageObj instanceof String) { Intent intentCall; Intent intentMessage; try { intentCall = Intent.parseUri((String) callObj, Intent.URI_INTENT_SCHEME); } catch (URISyntaxException e) { throw new RCException(RCClient.ErrorCodes.ERROR_DEVICE_REGISTER_INTENT_CALL_MISSING); } try { intentMessage = Intent.parseUri((String) messageObj, Intent.URI_INTENT_SCHEME); } catch (URISyntaxException e) { throw new RCException(RCClient.ErrorCodes.ERROR_DEVICE_REGISTER_INTENT_MESSAGE_MISSING); } setIntents(intentCall, intentMessage); } else if (callObj instanceof Intent && messageObj instanceof Intent) { setIntents((Intent) callObj, (Intent) messageObj); } //set messages timer if (parameters.get(ParameterKeys.PUSH_NOTIFICATION_TIMEOUT_MESSAGING_SERVICE) != null) { messageTimeOutIntervalLimit = (long) parameters .get(ParameterKeys.PUSH_NOTIFICATION_TIMEOUT_MESSAGING_SERVICE); } connections = new HashMap<String, RCConnection>(); //if there is already data for registering to push, dont clear it (onOpenReply is using this parameter) // initialize JAIN SIP if we have connectivity this.parameters = parameters; // initialize registration FSM before we start signaling and push notification registrations // important: needs to happen *before* signaling and push registration startRegistrationFsm(); // check if TURN keys are there //params.put(RCDevice.ParameterKeys.MEDIA_TURN_ENABLED, prefs.getBoolean(RCDevice.ParameterKeys.MEDIA_TURN_ENABLED, true)); if (signalingClient == null) { signalingClient = new SignalingClient(); signalingClient.open(this, getApplicationContext(), parameters); } registerForPushNotifications(false); if (audioManager == null) { // Create and audio manager that will take care of audio routing, // audio modes, audio device enumeration etc. audioManager = AppRTCAudioManager.create(getApplicationContext(), new Runnable() { // This method will be called each time the audio state (number and // type of devices) has been changed. @Override public void run() { onAudioManagerChangedState(); } }); // Store existing audio settings and change audio mode to // MODE_IN_COMMUNICATION for best possible VoIP performance. RCLogger.d(TAG, "Initializing the audio manager..."); audioManager.init(parameters); } } else { throw new RCException(RCClient.ErrorCodes.ERROR_DEVICE_ALREADY_INITIALIZED); } return false; } catch (RCException e) { isServiceInitialized = false; throw e; } }
From source file:at.ac.tuwien.dsg.cloud.salsa.engine.smartdeployment.main.SmartDeploymentService.java
private String enrich_CAMF_CSAR_Process(String csarTmp, String serviceName) { String extractedFolder = csarTmp + ".extracted"; String toscaFile = extractedFolder + "/Definitions/Application.tosca"; String scriptDir = extractedFolder + "/Scripts/"; try {/*ww w .j a v a2 s . co m*/ // extract CSAR CSARParser.extractCsar(new File(csarTmp), extractedFolder); // enrich with QUELLE for String toscaXML = FileUtils.readFileToString(new File(toscaFile)); EngineLogger.logger.debug("Read tosca string done. 100 first characters: {}", toscaXML); EngineLogger.logger.debug("Now trying to enrich with QUELLE...."); //enrichCAMFToscaWithQuelle(toscaXML, serviceName, new String[]{EnrichFunctions.QuelleCloudServiceRecommendation.toString(), EnrichFunctions.SalsaInfoCompletion.toString()}); SmartDeploymentService sds = new SmartDeploymentService(); String result = sds.enrichCAMFToscaWithQuelle(toscaXML, serviceName, new String[] { EnrichFunctions.QuelleCloudServiceRecommendation.toString() }); EngineLogger.logger.debug("After enrich with QUELLE, the result is: {}", result); // write back to right place FileUtils.writeStringToFile(new File(toscaFile), result); // read software requirement in TOSCA for each node, put in a map + artifact // a map between node ID and full requirement in Tag Map<String, String> allRequirements = new HashMap<>(); TDefinitions def = ToscaXmlProcess.readToscaFile(toscaFile); for (TNodeTemplate node : ToscaStructureQuery.getNodeTemplateList(def)) { EngineLogger.logger.debug("Checking node: {}", node.getId()); String policiesStr = new String(); if (node.getPolicies() != null) { EngineLogger.logger.debug("Found policies of node: " + node.getId() + "/" + node.getName()); List<TPolicy> policies = node.getPolicies().getPolicy(); for (TPolicy p : policies) { if (p.getPolicyType().getLocalPart().equals("Requirement") && p.getPolicyType().getPrefix().equals("SmartDeployment")) { if (p.getName().startsWith("CONSTRAINT")) { // TODO: parse SYBL policies } else { policiesStr += p.getName().trim(); if (!p.getName().trim().endsWith(";")) { policiesStr += ";"; EngineLogger.logger.debug("polociesStr = {}", policiesStr); } } } } } EngineLogger.logger.debug("Collected policies for node {} is : {}", node.getId(), policiesStr); allRequirements.put(node.getId(), policiesStr); } EngineLogger.logger.debug("In total, we got following requirements: " + allRequirements.toString()); // Load dependency graph knowledge base String dependencyDataFile = SmartDeploymentService.class.getResource("/data/salsa.dependencygraph.xml") .getFile(); SalsaStackDependenciesGraph depGraph = SalsaStackDependenciesGraph .fromXML(FileUtils.readFileToString(new File(dependencyDataFile))); // ENRICH SCRIPT // extract all the requirement, put into the hashmap for (Map.Entry<String, String> entry : allRequirements.entrySet()) { EngineLogger.logger.debug("Analyzing node: {}. Full policies string is: *** {} ***", entry.getKey(), entry.getValue()); // extract CARL Strings CharStream stream = new ANTLRInputStream(entry.getValue()); CARLLexer lexer = new CARLLexer(stream); CommonTokenStream tokens = new CommonTokenStream(lexer); CARLParser parser = new CARLParser(tokens); RequirementsContext requirementsContext = parser.requirements(); ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker CARLProgramListener extractor = new CARLProgramListener(parser); walker.walk(extractor, requirementsContext); // initiate walk of tree with listener org.eclipse.camf.carl.model.Requirements requirements = extractor.getRequirements(); HashMap<String, String> allReqsOfNode = new HashMap<>(); ArrayList<String> checkList = new ArrayList<>(); // os=Ubuntu; os:ver=12.04; sw=jre:1.7 ==> os=Ubuntu, // here flat all the requirement of the node for (IRequirement req : requirements.getRequirements()) { EngineLogger.logger.debug("Irequirement: " + req.toString()); if (req.getCategory().equals(RequirementCategory.SOFTWARE)) { SoftwareRequirement swr = (SoftwareRequirement) req; allReqsOfNode.put("sw", removeQuote(swr.getName())); allReqsOfNode.put(removeQuote(swr.getName()) + ":ver", swr.getVersion().getVersion()); checkList.add(swr.getName()); } else { if (req.getCategory().equals(RequirementCategory.OPERATING_SYSTEM)) { // the system part is generated by quelle OSRequirement osReq = (OSRequirement) req; if (osReq.getName() != null) { allReqsOfNode.put("os", removeQuote(osReq.getName())); } if (osReq.getVersion() != null) { allReqsOfNode.put("os:ver", osReq.getVersion().getVersion()); } } } } // find all the deploymet script of all "sw" requirements LinkedList<String> listOfScripts = new LinkedList<>(); EngineLogger.logger.debug("The node {} will be enriched based-on the requirements: {}", entry.getKey(), checkList.toString()); for (String swReq : checkList) { EngineLogger.logger.debug("Searching deployment script for software req: {}", swReq); SalsaStackDependenciesGraph theNode = depGraph.findNodeByName(swReq); EngineLogger.logger.debug("Node found: {}", theNode.getName()); EngineLogger.logger.debug("All requirements: {}", allReqsOfNode.toString()); LinkedList<String> tmp = theNode.searchDeploymentScriptTemplate(allReqsOfNode); if (tmp != null) { listOfScripts.addAll(tmp); } } EngineLogger.logger.debug(listOfScripts.toString()); // create a script to solve all dependencies first String nodeID = entry.getKey(); String theDependencyScript = "#!/bin/bash \n\n######## Generated by the Decision Module to solve the software dependencies ######## \n\n"; for (String appendScript : listOfScripts) { String theAppend = SmartDeploymentService.class.getResource("/scriptRepo/" + appendScript) .getFile(); String stringToAppend = FileUtils.readFileToString(new File(theAppend)); theDependencyScript += stringToAppend + "\n"; } theDependencyScript += "######## End of generated script ########"; String tmpScriptFile = scriptDir + "/" + nodeID + ".salsatmp"; // read original script, remove the #!/bin/bash if having String originalScriptFile = null; TNodeTemplate node = ToscaStructureQuery.getNodetemplateById(nodeID, def); EngineLogger.logger.debug("Getting artifact template of node: {}", node.getId()); for (TDeploymentArtifact art : node.getDeploymentArtifacts().getDeploymentArtifact()) { EngineLogger.logger.debug("Checking art.Name: {}, type: {}", art.getName(), art.getArtifactType().getLocalPart()); if (art.getArtifactType().getLocalPart().equals("ScriptArtifactPropertiesType")) { String artTemplateID = art.getArtifactRef().getLocalPart(); TArtifactTemplate artTemplate = ToscaStructureQuery.getArtifactTemplateById(artTemplateID, def); if (artTemplate != null) { originalScriptFile = artTemplate.getArtifactReferences().getArtifactReference().get(0) .getReference(); originalScriptFile = extractedFolder + "/" + originalScriptFile; } } } if (originalScriptFile != null) { String originalScript = FileUtils.readFileToString(new File(originalScriptFile)); originalScript = originalScript.replace("#!/bin/bash", ""); originalScript = originalScript.replace("#!/bin/sh", ""); theDependencyScript += originalScript; FileUtils.writeStringToFile(new File(tmpScriptFile), theDependencyScript); EngineLogger.logger.debug("originalScript: {}, moveto: {}", originalScriptFile, originalScriptFile + ".original"); FileUtils.moveFile(FileUtils.getFile(originalScriptFile), FileUtils.getFile(originalScriptFile + ".original")); FileUtils.moveFile(FileUtils.getFile(tmpScriptFile), FileUtils.getFile(originalScriptFile)); } else { // TODO: there is no original script, just add new template, add tmpScript into that } } // end for each node in allRequirements analysis // repack the CSAR FileUtils.deleteQuietly(FileUtils.getFile(csarTmp)); File directory = new File(extractedFolder); File[] fList = directory.listFiles(); //CSARParser.buildCSAR(fList, csarTmp); String builtCSAR = SalsaConfiguration.getToscaTemplateStorage() + "/" + serviceName + ".csar"; CSARParser.buildCSAR(extractedFolder, builtCSAR); } catch (IOException ex) { EngineLogger.logger.error("Error when enriching CSAR: " + csarTmp, ex); return "Error"; } catch (JAXBException ex) { EngineLogger.logger.error("Cannot parse the Tosca definition in CSAR file: " + toscaFile, ex); return "Error"; } // return the link to the CSAR String csarURLReturn = SalsaConfiguration.getSalsaCenterEndpoint() + "/rest/smart/CAMFTosca/enrich/CSAR/" + serviceName; EngineLogger.logger.info("Enrich CSAR done. URL to download is: {}", csarURLReturn); return csarURLReturn; }
From source file:com.cabserver.handler.Driver.java
@POST @Path("login") @Produces(MediaType.TEXT_HTML)// w w w .ja va2s .co m public Response login(String jsonData) { // String data = ""; HashMap<String, String> responseMap = new HashMap<String, String>(); try { // log.info("Inside Driver >> login before decoding = " + jsonData); jsonData = (URLDecoder.decode(jsonData, "UTF-8")); // log.info("Inside Driver >> login >>" + jsonData); // jsonData = jsonData.split("=")[1]; if (jsonData.contains("=")) { jsonData = jsonData.split("=")[1]; // log.info("Inside Driver >> signup >> data=" + jsonData); } log.info("login >> data=" + jsonData); if (jsonData != null && jsonData.length() > 1) { // Gson gson = new Gson(); JSONParser parser = new JSONParser(); JSONObject obj = (JSONObject) parser.parse(jsonData); // LoginInfo result = new LoginInfo(); String phone = (String) obj.get("phone"); // String password = (String) obj.get("password"); // log.info("Driver Phone =" + phone); // log.info("password =" + password); if (phone != null) { DriverMaster driverMaster = DatabaseManager.validateDriver(phone); if (driverMaster != null) { // log.info("Inside Driver >> Login Successfull. HTTP bookingStatus code is 200."); responseMap.put("code", "200"); responseMap.put("msg", "Login Succesful."); responseMap.put("driverId", driverMaster.getDriverId()); responseMap.put("firstName", driverMaster.getFirstName()); responseMap.put("phoneNumber", driverMaster.getPhoneNumber()); responseMap.put("driverStatus", driverMaster.getDriverStatus()); responseMap.put("currAddr", driverMaster.getCurrAddr()); responseMap.put("currLongt", driverMaster.getCurrLongt()); responseMap.put("currLat", driverMaster.getCurrLat()); responseMap.put("bookingId", driverMaster.getBookingId()); log.info("login >> Login response = " + responseMap.toString()); } else { log.info("login >> Login Error. HTTP bookingStatus code is " + ConfigDetails.constants.get("BOOKING_FAILED_CODE") + "."); responseMap.put("code", ConfigDetails.constants.get("BOOKING_FAILED_CODE")); responseMap.put("msg", "Driver phone doesn't exists."); } } } } catch (Exception e) { e.printStackTrace(); } if (responseMap.size() < 1) { log.info("Login Error. HTTP bookingStatus code is " + ConfigDetails.constants.get("BOOKING_FAILED_CODE") + "."); responseMap.put("code", ConfigDetails.constants.get("BOOKING_FAILED_CODE")); responseMap.put("msg", "Server Error."); return Response.status(200).entity(jsonCreater(responseMap)).build(); } else { return Response.status(200).entity(jsonCreater(responseMap)).build(); } }
From source file:it.baywaylabs.jumpersumo.twitter.TwitterListener.java
/** * This method extract ordered commands list. * * @param ai//from ww w. j a v a2 s .c o m * @param statuses * @deprecated use {@link #extractCommandV2(Intelligence, List)} instead. */ private void extractCommand(Intelligence ai, List<twitter4j.Status> statuses) { publishProgress(false); HashMap<Integer, String> map = new HashMap<Integer, String>(); String twText = statuses.get(0).getText().toLowerCase(); for (String command : ai.getMoveOn()) { int lastIndex = 0; int count = 0; while (lastIndex != -1) { lastIndex = twText.indexOf(command, lastIndex); if (lastIndex != -1) { count++; map.put(lastIndex, "FORWARD"); lastIndex += command.length(); } } } for (String command : ai.getMoveBack()) { int lastIndex = 0; int count = 0; while (lastIndex != -1) { lastIndex = twText.indexOf(command, lastIndex); if (lastIndex != -1) { count++; map.put(lastIndex, "BACK"); lastIndex += command.length(); } } } for (String command : ai.getTurnLeft()) { int lastIndex = 0; int count = 0; while (lastIndex != -1) { lastIndex = twText.indexOf(command, lastIndex); if (lastIndex != -1) { count++; map.put(lastIndex, "LEFT"); lastIndex += command.length(); } } } for (String command : ai.getTurnRight()) { int lastIndex = 0; int count = 0; while (lastIndex != -1) { lastIndex = twText.indexOf(command, lastIndex); if (lastIndex != -1) { count++; map.put(lastIndex, "RIGHT"); lastIndex += command.length(); } } } for (String command : ai.getTakePhoto()) { int lastIndex = 0; int count = 0; while (lastIndex != -1) { lastIndex = twText.indexOf(command, lastIndex); if (lastIndex != -1) { count++; map.put(lastIndex, "PHOTO"); lastIndex += command.length(); } } } for (String command : ai.getExecuteCsv()) { int lastIndex = 0; int count = 0; while (lastIndex != -1) { lastIndex = twText.indexOf(command, lastIndex); if (lastIndex != -1) { count++; map.put(lastIndex, "EXECUTE"); lastIndex += command.length(); } } } Log.d(TAG, "MAP: " + map.toString()); List<String> ordered = f.getOrderedExtractedCommands(map); Log.d(TAG, "Lista Ordinata: " + ordered.toString()); execute = f.joinListCommands(ordered); Log.d(TAG, "LISTA FINALE: " + execute.toString()); editor.putLong(Constants.LAST_ID_MENTIONED, statuses.get(0).getId()); editor.apply(); }
From source file:com.emc.storageos.systemservices.impl.upgrade.CoordinatorClientExt.java
/** * Update system properties to zookeeper * //from w ww. ja va 2 s .c o m * @param currentProps * @throws CoordinatorClientException */ public void setTargetProperties(Map<String, String> currentProps) throws CoordinatorClientException { Map<String, PropertyMetadata> propsMetadata = PropertiesMetadata.getGlobalMetadata(); // split properties as global, or site specific HashMap<String, String> globalProps = new HashMap<String, String>(); HashMap<String, String> siteProps = new HashMap<String, String>(); for (Map.Entry<String, String> prop : currentProps.entrySet()) { String key = prop.getKey(); PropertyMetadata metadata = propsMetadata.get(key); if (metadata.getSiteSpecific()) { siteProps.put(key, prop.getValue()); } else { globalProps.put(key, prop.getValue()); } } // update properties to zk if (getTargetInfoLock()) { try { // check we are in stable state if checkState = true specified if (!isClusterUpgradable()) { throw APIException.serviceUnavailable.clusterStateNotStable(); } ConfigurationImpl globalCfg = new ConfigurationImpl(); globalCfg.setId(PropertyInfoExt.TARGET_PROPERTY_ID); globalCfg.setKind(PropertyInfoExt.TARGET_PROPERTY); PropertyInfoExt globalPropInfo = new PropertyInfoExt(globalProps); globalCfg.setConfig(TARGET_INFO, globalPropInfo.encodeAsString()); _coordinator.persistServiceConfiguration(globalCfg); _log.info("target properties changed successfully. target properties {}", globalPropInfo.toString()); if (siteProps.size() > 0) { setSiteSpecificProperties(siteProps, _coordinator.getSiteId()); _log.info("site scope target properties changed successfully. target properties {}", siteProps.toString()); } } catch (Exception e) { throw SyssvcException.syssvcExceptions .coordinatorClientError("Failed to set target info. " + e.getMessage()); } finally { releaseTargetVersionLock(); } } else { throw SyssvcException.syssvcExceptions .coordinatorClientError("Failed to set target state. Unable to obtain target lock"); } }
From source file:com.mirth.connect.server.migration.ServerMigrator.java
private void runConfigurationMigrator(ConfigurationMigrator configurationMigrator, PropertiesConfiguration mirthConfig, Version version) { configurationMigrator.updateConfiguration(mirthConfig); HashMap<String, Object> addedProperties = new LinkedHashMap<String, Object>(); Map<String, Object> propertiesToAdd = configurationMigrator.getConfigurationPropertiesToAdd(); if (propertiesToAdd != null) { for (Entry<String, Object> propertyToAdd : propertiesToAdd.entrySet()) { if (!mirthConfig.containsKey(propertyToAdd.getKey())) { PropertiesConfigurationLayout layout = mirthConfig.getLayout(); String key = propertyToAdd.getKey(); Object value;//w w w . j av a 2 s .c om String comment = ""; if (propertyToAdd.getValue() instanceof Pair) { // If a pair is used, get both the value and comment Pair<Object, String> pair = (Pair<Object, String>) propertyToAdd.getValue(); value = pair.getLeft(); comment = pair.getRight(); } else { // Only the value was specified value = propertyToAdd.getValue(); } mirthConfig.setProperty(key, value); // If this is the first added property, add a general comment about the added properties before it if (addedProperties.isEmpty()) { if (StringUtils.isNotEmpty(comment)) { comment = "\n\n" + comment; } comment = "The following properties were automatically added on startup for version " + version + comment; } if (StringUtils.isNotEmpty(comment)) { // When a comment is specified, always put a blank line before it layout.setBlancLinesBefore(key, 1); layout.setComment(key, comment); } addedProperties.put(key, value); } } } List<String> removedProperties = new ArrayList<String>(); String[] propertiesToRemove = configurationMigrator.getConfigurationPropertiesToRemove(); if (propertiesToRemove != null) { for (String propertyToRemove : propertiesToRemove) { if (mirthConfig.containsKey(propertyToRemove)) { mirthConfig.clearProperty(propertyToRemove); removedProperties.add(propertyToRemove); } } } if (!addedProperties.isEmpty() || !removedProperties.isEmpty()) { if (!addedProperties.isEmpty()) { logger.info("Adding properties in mirth.properties: " + addedProperties); } if (!removedProperties.isEmpty()) { logger.info("Removing properties in mirth.properties: " + removedProperties); } try { mirthConfig.save(); } catch (ConfigurationException e) { logger.error("There was an error updating mirth.properties.", e); if (!addedProperties.isEmpty()) { logger.error("The following properties should be added to mirth.properties manually: " + addedProperties.toString()); } if (!removedProperties.isEmpty()) { logger.error("The following properties should be removed from mirth.properties manually: " + removedProperties.toString()); } } } }
From source file:com.MainFiles.Functions.java
public HashMap getWeblogicMessageFromQueue(String JMSCorrelationID) { String url = AGENCY_ADAPTER_URL; String QUEUE = QUEUE_RESPONSE; Message msg = null;//from w w w . j av a2 s . co m Object ResponseMessage = null; HashMap fields = new HashMap(); int loops = 1; try { while (true) { if (loops > 5) { break; } DistributedWebLogicQueueBrowser distrWebLogic = new DistributedWebLogicQueueBrowser(); msg = distrWebLogic.browseWebLogicQueue(JMSCorrelationID, url, QUEUE); if (msg instanceof ObjectMessage) { ResponseMessage = ((ObjectMessage) msg).getObject(); fields = (HashMap) ResponseMessage; this.log("RESPONSE :: " + JMSCorrelationID + "\n" + fields.toString() + "\n\n", "ESB_Response"); break; } distrWebLogic = null; loops++; } } catch (JMSException ex) { this.log("Error getWeblogicMessageFromUDQueue() " + ex.getMessage() + "\n" + this.StackTraceWriter(ex), "error--"); } return fields; }
From source file:oscar.oscarRx.util.RxUtil.java
public static String findInterDrugStr(final UserPropertyDAO propDAO, String provider, final RxSessionBean bean) { //quiry mydrugref database to get a vector with all interacting drugs //if effect is not null or effect is not empty string //get a list of all pending prescriptions' ATC codes //compare if anyone match, //if yes, get it's randomId and set an session attribute //if not, do nothing UserProperty prop = propDAO.getProp(provider, UserProperty.MYDRUGREF_ID); String myDrugrefId = null;//from www . j a v a 2 s .co m if (prop != null) { myDrugrefId = prop.getValue(); MiscUtils.getLogger().debug("3myDrugrefId" + myDrugrefId); } RxPrescriptionData.Prescription[] rxs = bean.getStash(); //acd contains all atccodes in stash Vector<String> acd = new Vector<String>(); for (RxPrescriptionData.Prescription rxItem : rxs) { acd.add(rxItem.getAtcCode()); } logger.debug("3acd=" + acd); String[] str = new String[] { "warnings_byATC,bulletins_byATC,interactions_byATC,get_guidelines" }; //NEW more efficent way of sending multiple requests at the same time. Vector allInteractions = new Vector(); for (String command : str) { try { Vector v = getMyDrugrefInfo(command, acd, myDrugrefId); MiscUtils.getLogger().debug("2v in for loop: " + v); if (v != null && v.size() > 0) { allInteractions.addAll(v); } MiscUtils.getLogger().debug("3after all.addAll(v): " + allInteractions); } catch (Exception e) { log2.debug("3command :" + command + " " + e.getMessage()); MiscUtils.getLogger().error("Error", e); } } String retStr = ""; HashMap rethm = new HashMap(); for (RxPrescriptionData.Prescription rxItem : rxs) { MiscUtils.getLogger().debug("rxItem=" + rxItem.getDrugName()); Vector uniqueDrugNameList = new Vector(); for (int i = 0; i < allInteractions.size(); i++) { Hashtable hb = (Hashtable) allInteractions.get(i); String interactingAtc = (String) hb.get("atc"); String interactingDrugName = (String) hb.get("drug2"); String effectStr = (String) hb.get("effect"); String sigStr = (String) hb.get("significance"); MiscUtils.getLogger().debug("findInterDrugStr=" + hb); if (sigStr != null) { if (sigStr.equals("1")) { sigStr = "minor"; } else if (sigStr.equals("2")) { sigStr = "moderate"; } else if (sigStr.equals("3")) { sigStr = "major"; } else { sigStr = "unknown"; } } else { sigStr = "unknown"; } if (interactingAtc != null && interactingDrugName != null && rxItem.getAtcCode().equals(interactingAtc) && effectStr != null && effectStr.length() > 0 && !effectStr.equalsIgnoreCase("N") && !effectStr.equals(" ")) { MiscUtils.getLogger().debug("interactingDrugName=" + interactingDrugName); RxPrescriptionData.Prescription rrx = findRxFromDrugNameOrGN(rxs, interactingDrugName); if (rrx != null && !uniqueDrugNameList.contains(rrx.getDrugName())) { MiscUtils.getLogger().debug("rrx.getDrugName()=" + rrx.getDrugName()); uniqueDrugNameList.add(rrx.getDrugName()); String key = sigStr + "_" + rxItem.getRandomId(); if (rethm.containsKey(key)) { String val = (String) rethm.get(key); val += ";" + rrx.getDrugName(); rethm.put(key, val); } else { rethm.put(key, rrx.getDrugName()); } key = sigStr + "_" + rrx.getRandomId(); if (rethm.containsKey(key)) { String val = (String) rethm.get(key); val += ";" + rxItem.getDrugName(); rethm.put(key, val); } else { rethm.put(key, rxItem.getDrugName()); } } } } MiscUtils.getLogger().debug("***next rxItem***"); } MiscUtils.getLogger().debug("rethm=" + rethm); retStr = rethm.toString(); retStr = retStr.replace("}", ""); retStr = retStr.replace("{", ""); return retStr; }