Java tutorial
/* * * Copyright (c) 2016 SERENA Software, Inc. All Rights Reserved. * * This software is proprietary information of SERENA Software, Inc. * Use is subject to license terms. * * @author Kevin Lee */ package com.serena.rlc.provider.servicenow; import com.serena.rlc.provider.annotations.ConfigProperty; import com.serena.rlc.provider.annotations.Getter; import com.serena.rlc.provider.annotations.Param; import com.serena.rlc.provider.annotations.Params; import com.serena.rlc.provider.domain.*; import com.serena.rlc.provider.exceptions.ProviderException; import com.serena.rlc.provider.spi.IBaseServiceProvider; import com.serena.rlc.provider.servicenow.client.ServiceNowClient; import com.serena.rlc.provider.servicenow.domain.*; import com.serena.rlc.provider.servicenow.exception.ServiceNowClientException; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * ServiceNow Base Service Provider * @author klee@serena.com */ public abstract class ServiceNowBaseServiceProvider implements IBaseServiceProvider { final static Logger logger = LoggerFactory.getLogger(ServiceNowBaseServiceProvider.class); final static String REQUEST_TYPE = "requestType"; final static String REQUEST_STATUS_VALUES = "requestStatusValues"; final static String CHANGE_TYPE_VALUES = "changeTypeValues"; final static String CHANGE_STATUS_VALUES = "changeStatusValues"; final static String TASK_STATUS_VALUES = "taskStatusValues"; final static String INCIDENT_STATUS_VALUES = "incidentStatusValues"; final static String REQUEST_CATEGORY_VALUES = "requestCategoryValues"; final static String INCIDENT_CATEGORY_VALUES = "incidentCategoryValues"; final static String REQUEST_PRIORITY_VALUES = "requestPriorityValues"; final static String REQUEST_RISK_VALUES = "requestRiskValues"; final static String REQUEST_IMPACT_VALUES = "requestImpactValues"; final static String REQUEST_URGENCY_VALUES = "requestUrgencyValues"; final static String TITLE_FILTER = "titleFilter"; final static String CHANGE_REQUEST = "changeRequest"; final static String CHANGE_TASK = "changeTask"; final static String INCIDENT = "incident"; final static String TITLE = "title"; final static String DESCRIPTION = "description"; final static String UPDATED_CHANGE_STATUS = "updatedChangeStatus"; final static String UPDATED_TASK_STATUS = "updatedTaskStatus"; final static String NOTES = "notes"; private Integer resultLimit; //================================================================================ // Configuration Properties // ------------------------------------------------------------------------------- // The configuration properties are marked with the @ConfigProperty annotaion // and will be displayed in the provider administration page when creating a // configuration of this plugin for use. //================================================================================ @ConfigProperty(name = "snow_url", displayName = "ServiceNow URL", description = "ServiceNow Server URL.", defaultValue = "http://<servername>", dataType = DataType.TEXT) private String snowUrl; @ConfigProperty(name = "snow_api_version", displayName = "ServiceNow API Version", description = "ServiceNow API Version.", defaultValue = "v1", dataType = DataType.TEXT) private String snowApiVersion; @ConfigProperty(name = "snow_serviceuser", displayName = "User Name", description = "ServiceNow service username.", defaultValue = "", dataType = DataType.TEXT) private String serviceUser; @ConfigProperty(name = "snow_servicepassword", displayName = "Password/Token", description = "ServiceNow service password/token", defaultValue = "", dataType = DataType.PASSWORD) private String servicePassword; @ConfigProperty(name = "request_type_values", displayName = "Change Request Type Values", description = "change request type filter selection values separated by commas", defaultValue = "Routine,Normal,Standard,Emergency", dataType = DataType.TEXT) private String requestTypeValues; @ConfigProperty(name = "change_status_values", displayName = "Change Request Status Values", description = "change request status filter selection values separated by commas", defaultValue = "New,Assess,Authorize,Scheduled,Implement,Review,Closed,Canceled", dataType = DataType.TEXT) private String changeStatusValues; @ConfigProperty(name = "task_status_values", displayName = "Change Task Status Values", description = "change task status filter selection values separated by commas", defaultValue = "Pending,Open,Work in Progress,Closed Complete,Closed Incomplete,Closed Skipped", dataType = DataType.TEXT) private String taskStatusValues; @ConfigProperty(name = "incident_status_values", displayName = "Incident Status Values", description = "incident status filter selection values separated by commas", defaultValue = "New,Active,Awaiting Problem,Awaiting User Info,Awaiting Evidence,Resolved", dataType = DataType.TEXT) private String incidentStatusValues; @ConfigProperty(name = "request_category_values", displayName = "Change Request Category Values", description = "change request category selection values separated by commas", defaultValue = "Hardware,Software,Business Service,System Software,Applications Software,Network,Telecom,Documentation,Other,Virtual Provisioning", dataType = DataType.TEXT) private String requestCategoryValues; @ConfigProperty(name = "incident_category_values", displayName = "Incident Category Values", description = "incident category selection values separated by commas", defaultValue = "Access & Identity Management,Datacenter Automation,IT Service Management,Request,Inquiry,Help,Software,Hardware,Network,Database", dataType = DataType.TEXT) private String incidentCategoryValues; @ConfigProperty(name = "request_priority_values", displayName = "Priority Selection Values", description = "change request priority selection values separated by commas", defaultValue = "1 - Critical,2 - High,3 - Moderate,4 - Low", dataType = DataType.TEXT) private String requestPriorityValues; @ConfigProperty(name = "request_risk_values", displayName = "Risk Selection Values", description = "change request risk selection values separated by commas", defaultValue = "Very High,High,Moderate,Low,None", dataType = DataType.TEXT) private String requestRiskValues; @ConfigProperty(name = "request_impact_values", displayName = "Impact Selection Values", description = "change request / incident impact selection values separated by commas", defaultValue = "1 - High,2 - Medium,3 - Low", dataType = DataType.TEXT) private String requestImpactValues; @ConfigProperty(name = "request_urgency_values", displayName = "Urgency Selection Values", description = "change request / incident urgency selection values separated by commas", defaultValue = "1 - High,2 - Medium,3 - Low", dataType = DataType.TEXT) private String requestUrgencyValues; @ConfigProperty(name = "request_result_limit", displayName = "Result Limit", description = "Result limit for find requests action", defaultValue = "200", dataType = DataType.TEXT) private String requestResultLimit; private SessionData session; private Long providerId; private String providerUuid; private String providerNamespaceId; @Autowired ServiceNowClient serviceNowClient; public SessionData getSession() { return session; } @Override public void setSession(SessionData session) { this.session = null; } @Override public Long getProviderId() { return providerId; } @Override public void setProviderId(Long providerId) { this.providerId = providerId; } @Override public String getProviderNamespaceId() { return providerNamespaceId; } @Override public void setProviderNamespaceId(String providerNamespaceId) { this.providerNamespaceId = providerNamespaceId; } @Override public String getProviderUuid() { return providerUuid; } @Override public void setProviderUuid(String providerUuid) { this.providerUuid = providerUuid; } public String getSnowUrl() { return snowUrl; } @Autowired(required = false) public void setSnowUrl(String snowUrl) { if (StringUtils.isNotEmpty(snowUrl)) { this.snowUrl = snowUrl.replaceAll("^\\s+", ""); } else { this.snowUrl = "https://demo002.service-now.com"; } } public String getSnowApiVersion() { return snowApiVersion; } @Autowired(required = false) public void setSnowApiVersion(String snowApiVersion) { if (!StringUtils.isEmpty(snowApiVersion)) { snowApiVersion = snowApiVersion.trim(); } else { this.snowApiVersion = "v1"; } this.snowApiVersion = snowApiVersion; } public String getServiceUser() { return serviceUser; } @Autowired(required = false) public void setServiceUser(String serviceUser) { if (!StringUtils.isEmpty(serviceUser)) { this.serviceUser = serviceUser.replaceAll("^\\s+", ""); } } public String getServicePassword() { return servicePassword; } @Autowired(required = false) public void setServicePassword(String servicePassword) { if (!StringUtils.isEmpty(servicePassword)) { this.servicePassword = servicePassword.replaceAll("^\\s+", ""); } } public String getRequestTypeValues() { return requestTypeValues; } @Autowired(required = false) public void setRequestTypeValues(String requestTypeValues) { if (!StringUtils.isEmpty(requestTypeValues)) { requestTypeValues = requestTypeValues.trim(); } this.requestTypeValues = requestTypeValues; } public String getChangeStatusValues() { return changeStatusValues; } @Autowired(required = false) public void setChangeStatusValues(String changeStatusValues) { if (!StringUtils.isEmpty(changeStatusValues)) { changeStatusValues = changeStatusValues.trim(); } this.changeStatusValues = changeStatusValues; } public String getTaskStatusValues() { return taskStatusValues; } @Autowired(required = false) public void setTaskStatusValues(String taskStatusValues) { if (!StringUtils.isEmpty(taskStatusValues)) { taskStatusValues = taskStatusValues.trim(); } this.taskStatusValues = taskStatusValues; } public String getIncidentStatusValues() { return incidentStatusValues; } @Autowired(required = false) public void setIncidentStatusValues(String incidentStatusValues) { if (!StringUtils.isEmpty(incidentStatusValues)) { incidentStatusValues = incidentStatusValues.trim(); } this.incidentStatusValues = incidentStatusValues; } public String getRequestCategoryValues() { return requestCategoryValues; } @Autowired(required = false) public void setRequestCategoryValues(String requestCategoryValues) { if (!StringUtils.isEmpty(requestCategoryValues)) { requestCategoryValues = requestCategoryValues.trim(); } this.requestCategoryValues = requestCategoryValues; } public String getIncidentCategoryValues() { return incidentCategoryValues; } @Autowired(required = false) public void setIncidentCategoryValues(String incidentCategoryValues) { if (!StringUtils.isEmpty(incidentCategoryValues)) { incidentCategoryValues = incidentCategoryValues.trim(); } this.incidentCategoryValues = incidentCategoryValues; } public String getRequestPriorityValues() { return requestPriorityValues; } @Autowired(required = false) public void setRequestPriorityValues(String requestPriorityValues) { if (!StringUtils.isEmpty(requestPriorityValues)) { requestPriorityValues = requestPriorityValues.trim(); } this.requestPriorityValues = requestPriorityValues; } public String getRequestRiskValues() { return requestRiskValues; } @Autowired(required = false) public void setRequestRiskValues(String requestRiskValues) { if (!StringUtils.isEmpty(requestRiskValues)) { requestRiskValues = requestRiskValues.trim(); } this.requestRiskValues = requestRiskValues; } public String getRequestImpactValues() { return requestImpactValues; } @Autowired(required = false) public void setRequestImpactValues(String requestImpactValues) { if (!StringUtils.isEmpty(requestImpactValues)) { requestImpactValues = requestImpactValues.trim(); } this.requestImpactValues = requestImpactValues; } public String getRequestUrgencyValues() { return requestUrgencyValues; } @Autowired(required = false) public void setRequestUrgencyValues(String requestUrgencyValues) { if (!StringUtils.isEmpty(requestUrgencyValues)) { requestUrgencyValues = requestUrgencyValues.trim(); } this.requestUrgencyValues = requestUrgencyValues; } public String getRequestResultLimit() { return requestResultLimit; } @Autowired(required = false) public void setRequestResultLimit(String requestResultLimit) { this.requestResultLimit = requestResultLimit; } //================================================================================ // Getter Methods // ------------------------------------------------------------------------------- // These methods are used to get the field values. The @Getter annotation is used // by the system to generate a user interface and pass the correct parameters to // to the provider //================================================================================ @Getter(name = REQUEST_TYPE, displayName = "Request Type", description = "Get ServiceNow Request Type.") public FieldInfo getRequestTypeFieldValues(String fieldName, List<Field> properties) throws ProviderException { FieldInfo fieldInfo = new FieldInfo(fieldName); setServiceNowClientConnectionDetails(); List<FieldValueInfo> values = new ArrayList<>(); FieldValueInfo value = new FieldValueInfo("change_request", "Change Request"); values.add(value); value = new FieldValueInfo("change_task", "Change Task"); values.add(value); value = new FieldValueInfo("incident", "Incident"); values.add(value); fieldInfo.setValues(values); return fieldInfo; } @Getter(name = REQUEST_STATUS_VALUES, displayName = "Status Filter", description = "Get ServiceNow Status Filters.") @Params(params = { @Param(fieldName = REQUEST_TYPE, displayName = "Request Type", description = "ServiceNow Request Type", required = true, dataType = DataType.SELECT), }) public FieldInfo getStatusFiltersFieldValues(String fieldName, List<Field> properties) throws ProviderException { String statusValues = ""; Field field = Field.getFieldByName(properties, REQUEST_TYPE); if (field == null) { throw new ProviderException("Missing required property: " + REQUEST_TYPE); } String requestType = field.getValue(); if (requestType.equals("change_request")) { statusValues = getChangeStatusValues(); } else if (requestType.equals("change_task")) { statusValues = getTaskStatusValues(); } else if (requestType.equals("incident")) { statusValues = getIncidentStatusValues(); } else { throw new ProviderException("Invalid request type: " + requestType); } if (StringUtils.isEmpty(statusValues)) { return null; } return createSelectionList(fieldName, statusValues); } @Getter(name = CHANGE_STATUS_VALUES, displayName = "Status Filter", description = "Change Request Status Filter Values.") public FieldInfo getChangeStatusValuesFieldValues(String fieldName, List<Field> properties) throws ProviderException { if (StringUtils.isEmpty(getChangeStatusValues())) { return null; } return createSelectionList(fieldName, getChangeStatusValues()); } @Getter(name = UPDATED_CHANGE_STATUS, displayName = "Status", description = "Change Request Status.") public FieldInfo getUpdatedChangeStatusFieldValues(String fieldName, List<Field> properties) throws ProviderException { if (StringUtils.isEmpty(getChangeStatusValues())) { return null; } return createSelectionList(fieldName, getChangeStatusValues()); } @Getter(name = TASK_STATUS_VALUES, displayName = "Status Filter", description = "Change Task Status Filter Values.") public FieldInfo getTaskStatusValuesFieldValues(String fieldName, List<Field> properties) throws ProviderException { if (StringUtils.isEmpty(getTaskStatusValues())) { return null; } return createSelectionList(fieldName, getTaskStatusValues()); } @Getter(name = UPDATED_TASK_STATUS, displayName = "Status", description = "Change Task Status.") public FieldInfo getUpdatedTaskStatusFieldValues(String fieldName, List<Field> properties) throws ProviderException { if (StringUtils.isEmpty(getTaskStatusValues())) { return null; } return createSelectionList(fieldName, getTaskStatusValues()); } @Getter(name = INCIDENT_STATUS_VALUES, displayName = "Status Filter", description = "Incident Status Filter Values.") public FieldInfo getIncidentStatusValuesFieldValues(String fieldName, List<Field> properties) throws ProviderException { if (StringUtils.isEmpty(getIncidentStatusValues())) { return null; } return createSelectionList(fieldName, getIncidentStatusValues()); } @Getter(name = CHANGE_TYPE_VALUES, displayName = "Type", description = "Change Request Type Values.") public FieldInfo getChangeTypeValuesFieldValues(String fieldName, List<Field> properties) throws ProviderException { if (StringUtils.isEmpty(getRequestTypeValues())) { return null; } return createSelectionList(fieldName, getRequestTypeValues()); } @Getter(name = REQUEST_CATEGORY_VALUES, displayName = "Category", description = "Change Request Category Values.") public FieldInfo getRequestCategoryFieldValues(String fieldName, List<Field> properties) throws ProviderException { if (StringUtils.isEmpty(getRequestCategoryValues())) { return null; } return createSelectionList(fieldName, getRequestCategoryValues()); } @Getter(name = INCIDENT_CATEGORY_VALUES, displayName = "Category", description = "Incident Category Values.") public FieldInfo getIncidentCategoryFieldValues(String fieldName, List<Field> properties) throws ProviderException { if (StringUtils.isEmpty(getIncidentCategoryValues())) { return null; } return createSelectionList(fieldName, getIncidentCategoryValues()); } @Getter(name = REQUEST_PRIORITY_VALUES, displayName = "Priority", description = "Change Request Priority Values.") public FieldInfo getRequestPriorityFieldValues(String fieldName, List<Field> properties) throws ProviderException { if (StringUtils.isEmpty(getRequestPriorityValues())) { return null; } return createSelectionList(fieldName, getRequestPriorityValues()); } @Getter(name = REQUEST_RISK_VALUES, displayName = "Risk", description = "Change Request Risk Values.") public FieldInfo getRequestRiskFieldValues(String fieldName, List<Field> properties) throws ProviderException { if (StringUtils.isEmpty(getRequestRiskValues())) { return null; } return createSelectionList(fieldName, getRequestRiskValues()); } @Getter(name = REQUEST_IMPACT_VALUES, displayName = "Risk", description = "Change Request Impact Values.") public FieldInfo getRequestImpactFieldValues(String fieldName, List<Field> properties) throws ProviderException { if (StringUtils.isEmpty(getRequestImpactValues())) { return null; } return createSelectionList(fieldName, getRequestImpactValues()); } @Getter(name = REQUEST_URGENCY_VALUES, displayName = "Risk", description = "Change Request Urgency Values.") public FieldInfo getRequestUrgencyFieldValues(String fieldName, List<Field> properties) throws ProviderException { if (StringUtils.isEmpty(getRequestUrgencyValues())) { return null; } return createSelectionList(fieldName, getRequestUrgencyValues()); } @Getter(name = CHANGE_REQUEST, displayName = "Change Request", description = "Get ServiceNow Change Request.") @Params(params = { @Param(fieldName = CHANGE_STATUS_VALUES, displayName = "Status Filters", description = "ServiceNow Status filters.", dataType = DataType.SELECT, required = false), }) public FieldInfo getChangeRequestFieldValues(String fieldName, List<Field> properties) throws ProviderException { FieldInfo fieldInfo = new FieldInfo(fieldName); setServiceNowClientConnectionDetails(); String requestStatusFilter = null; Field field = Field.getFieldByName(properties, REQUEST_STATUS_VALUES); if (field != null) { requestStatusFilter = field.getValue(); } String query = ""; /*field = Field.getFieldByName(properties, TITLE_FILTER); String titleFilter = field.getValue(); String query = "short_descriptionLIKE" + titleFilter + "^ORdescriptionLIKE" + titleFilter + "^ORnumberLIKE" + titleFilter;*/ try { List<ChangeRequest> changeRequests = getServiceNowClient().getChangeRequests(query, requestStatusFilter, getResultLimit()); if (changeRequests == null || changeRequests.size() < 1) { return null; } List<FieldValueInfo> values = new ArrayList<>(); FieldValueInfo value; for (ChangeRequest cr : changeRequests) { value = new FieldValueInfo(cr.getId(), cr.getNumber() + " - " + cr.getTitle()); value.setDescription(cr.getNumber() + " - " + cr.getTitle()); values.add(value); } fieldInfo.setValues(values); return fieldInfo; } catch (ServiceNowClientException ex) { logger.error("Unable to retrieve ServiceNow Change Requests: {}", ex.getLocalizedMessage()); throw new ProviderException(ex.getLocalizedMessage()); } } @Getter(name = CHANGE_TASK, displayName = "Change Task", description = "Get ServiceNow Change Task.") @Params(params = { @Param(fieldName = CHANGE_REQUEST, displayName = "Change Request", description = "ServiceNow Change Request.", dataType = DataType.SELECT, required = true), }) public FieldInfo getChangeTaskFieldValues(String fieldName, List<Field> properties) throws ProviderException { FieldInfo fieldInfo = new FieldInfo(fieldName); setServiceNowClientConnectionDetails(); String crId = ""; String crNumber = ""; Field field = Field.getFieldByName(properties, CHANGE_REQUEST); if (field != null) { crId = field.getValue(); crNumber = field.getDisplayValue(); } try { List<ChangeTask> changeTasks = getServiceNowClient().getChangeTasks("", crNumber, "", getResultLimit()); if (changeTasks == null || changeTasks.size() < 1) { return null; } List<FieldValueInfo> values = new ArrayList<>(); FieldValueInfo value; for (ChangeTask ct : changeTasks) { value = new FieldValueInfo(ct.getId(), ct.getNumber() + " - " + ct.getTitle()); values.add(value); } fieldInfo.setValues(values); return fieldInfo; } catch (ServiceNowClientException ex) { logger.error("Unable to retrieve ServiceNow Change Tasks: {}", ex.getLocalizedMessage()); throw new ProviderException(ex.getLocalizedMessage()); } } //================================================================================ // Additional Public Methods //================================================================================ public ServiceNowClient getServiceNowClient() { if (serviceNowClient == null) { serviceNowClient = new ServiceNowClient(); } return serviceNowClient; } public int getResultLimit() { if (resultLimit == null) { resultLimit = 200; if (StringUtils.isNotBlank(requestResultLimit)) { try { resultLimit = Integer.parseInt(requestResultLimit); } catch (Throwable e) { logger.warn(e.getMessage(), e); } } } return resultLimit; } public void addField(List<Field> fieldCollection, String fieldName, String fieldDisplayName, String fieldValue) { if (StringUtils.isNotEmpty(fieldValue)) { Field field = new Field(fieldName, fieldDisplayName); field.setValue(fieldValue); fieldCollection.add(field); } } public void setServiceNowClientConnectionDetails() { getServiceNowClient().createConnection(getSession(), getSnowUrl(), getSnowApiVersion(), getServiceUser(), getServicePassword()); } //================================================================================ // Private Methods //================================================================================ private FieldInfo createSelectionList(String fieldName, String selectionValues) { logger.debug("Creating selection list from: {} - {}", fieldName, selectionValues); StringTokenizer st = new StringTokenizer(selectionValues, ",;"); FieldInfo fieldInfo = new FieldInfo(fieldName); List<FieldValueInfo> values = new ArrayList<>(); FieldValueInfo value; String status; while (st.hasMoreElements()) { status = (String) st.nextElement(); status = status.trim(); value = new FieldValueInfo(status, status); values.add(value); } fieldInfo.setValues(values); return fieldInfo; } }