Focusing on easy try-with-resources changes. Plus some other minor items.
I did not get all of them yet, as some have some heavy refactoring. These
try-with-resources seem to be fairly harmless.
* Utilize try-with-resources
* Remove unnecessary parenthesis
* Merging simple if statements
* Remove useless assignment
* Moving string literals to left hand side
Issue-ID: POLICY-482
Change-Id: If519ec8ea96f6b90bf82ac2676ffea9cd0cd2daf
Signed-off-by: Pamela Dragosh <pdragosh@research.att.com>
}
private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) {
- Set<String> scopes = null;
- List<String> roles = null;
+ Set<String> scopes;
+ List<String> roles;
List<Object> policyData = new ArrayList<>();
JSONArray policyList = null;
if(params.has("policyList")){
policyName = removeExtension.substring(0, removeExtension.lastIndexOf('.'));
}
- String activePolicy = null;
+ String activePolicy;
PolicyController controller = getPolicyControllerInstance();
if(params.toString().contains("activeVersion")){
String activeVersion = params.getString("activeVersion");
}
private List<Object> queryPolicyEditorScopes(String scopeName){
- String scopeNamequery = "";
+ String scopeNamequery;
SimpleBindings params = new SimpleBindings();
if(scopeName == null){
scopeNamequery = "from PolicyEditorScopes";
params.put("scopeName", scopeName + "%");
}
PolicyController controller = getPolicyControllerInstance();
- List<Object> scopesList = null;
+ List<Object> scopesList;
if(PolicyController.isjUnit()){
scopesList = controller.getDataByQuery(scopeNamequery, null);
}else{
SimpleBindings params = new SimpleBindings();
params.put("scopeName", scopeName + "%");
- List<Object> activePolicies = null;
- List<Object> scopesList = null;
+ List<Object> activePolicies;
+ List<Object> scopesList;
if(PolicyController.isjUnit()){
activePolicies = controller.getDataByQuery(query, null);
scopesList = controller.getDataByQuery(scopeNamequery, null);
}
}
}
- String scopeNameCheck = null;
+ String scopeNameCheck;
for (Object list : activePolicies) {
PolicyVersion policy = (PolicyVersion) list;
String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator));
private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
try {
- PolicyEntity entity = null;
+ PolicyEntity entity;
PolicyController controller = getPolicyControllerInstance();
String policyVersionName = newPath.replace(".xml", "");
private JSONObject cloneRecord(String newpolicyName, String oldScope, String removeoldPolicyExtension, String newScope, String removenewPolicyExtension, PolicyEntity entity, String userId) throws ServletException{
FileWriter fw = null;
- String queryEntityName = null;
+ String queryEntityName;
PolicyController controller = getPolicyControllerInstance();
PolicyEntity cloneEntity = new PolicyEntity();
cloneEntity.setPolicyName(newpolicyName);
path = path.substring(path.indexOf('/')+1);
String policyNamewithExtension = path.replace("/", File.separator);
String policyVersionName = policyNamewithExtension.replace(".xml", "");
- String query = "";
+ String query;
SimpleBindings policyParams = new SimpleBindings();
if(path.endsWith(".xml")){
policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf('.'));
SimpleBindings peParams = new SimpleBindings();
peParams.put("split_1", split[1]);
peParams.put("split_0", split[0]);
- List<Object> queryData = null;
+ List<Object> queryData;
if(PolicyController.isjUnit()){
queryData = controller.getDataByQuery(query, null);
}else{
}
}
if(sendFlag){
- AnnotationConfigApplicationContext ctx = null;
- try {
+ try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
to = list.getLoginIds()+"@"+PolicyController.getSmtpEmailExtension();
to = to.trim();
- ctx = new AnnotationConfigApplicationContext();
ctx.register(PolicyNotificationMail.class);
ctx.refresh();
JavaMailSenderImpl mailSender = ctx.getBean(JavaMailSenderImpl.class);
mailMsg.setSubject(subject);
mailMsg.setText(message);
mailSender.send(mimeMessage);
- if(mode.equalsIgnoreCase("Rename") || mode.contains("Delete") || mode.contains("Move")){
+ if("Rename".equalsIgnoreCase(mode) || mode.contains("Delete") || mode.contains("Move")){
policyNotificationDao.delete(watch);
}
} catch (Exception e) {
policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Exception Occured in Policy Notification" +e);
- }finally{
- if(ctx != null){
- ctx.close();
- }
}
}
}
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
-import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Path;
}
private static String processPolicy() {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace("ENTER");
-
- FileInputStream pIS = null;
- try {
- pIS = new FileInputStream(policyFile);
+ }
+ try (FileInputStream pIS = new FileInputStream(policyFile)){
Object policy = XACMLPolicyScanner.readPolicy(pIS);
if (policy == null)
throw new IllegalArgumentException("Policy File " + policyFile.getName() +
": " + e.getMessage();
LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + msg, e);
throw new IllegalArgumentException(msg);
- } finally {
- if (pIS != null) {
- try {
- pIS.close();
- } catch (IOException e) {
- LOGGER.warn(e.getMessage(), e);
- }
- }
}
}
CreateBRMSParamController.commonClassDao = commonClassDao;
}
- public CreateBRMSParamController(){}
+ public CreateBRMSParamController(){
+ // Empty constructor
+ }
protected PolicyRestAdapter policyAdapter = null;
private HashMap<String, String> dynamicLayoutMap;
String[] components = params.toString().split(":");
String caption = "";
for (int i = 0; i < components.length; i++) {
- String type = "";
+ String type;
if (i == 0) {
caption = components[i];
}
String[] components = params.toString().split("\\);");
if(components!= null && components.length > 0){
for (int i = 0; i < components.length; i++) {
- String value = null;
+ String value;
components[i] = components[i]+")";
String caption = components[i].substring(0,
components[i].indexOf('('));
policyData.setEditPolicy(true);
}
- String body = "";
+ String body;
body = "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " +
brmsTemplateVlaue + policyData.getRuleName() + "%$> \n */ \n";
AttributeDesignatorType designator = match.getAttributeDesignator();
String attributeId = designator.getAttributeId();
- if (attributeId.equals("RiskType")){
+ if ("RiskType".equals(attributeId)){
policyAdapter.setRiskType(value);
}
- if (attributeId.equals("RiskLevel")){
+ if ("RiskLevel".equals(attributeId)){
policyAdapter.setRiskLevel(value);
}
- if (attributeId.equals("guard")){
+ if ("guard".equals(attributeId)){
policyAdapter.setGuard(value);
}
- if (attributeId.equals("TTLDate") && !value.contains("NA")){
+ if ("TTLDate".equals(attributeId) && !value.contains("NA")){
PolicyController controller = new PolicyController();
String newDate = controller.convertDate(value);
policyAdapter.setTtlDate(newDate);
CreateClosedLoopFaultController.commonclassdao = commonclassdao;
}
- public CreateClosedLoopFaultController(){}
+ public CreateClosedLoopFaultController(){
+ // Empty constructor
+ }
public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root){
try{
TrapDatas trapDatas = (TrapDatas) object;
ArrayList<Object> attributeList = new ArrayList<>();
// Read the Trap
- if(!trap.equals("nill")){
+ if(! "nill".equals(trap)){
try{
if(trap.startsWith("Trap")){
- if(trap.equals("Trap1")){
+ if("Trap1".equals(trap)){
attributeList = trapDatas.getTrap1();
- }else if(trap.equals("Trap2")){
+ }else if("Trap2".equals(trap)){
attributeList = trapDatas.getTrap2();
- }else if(trap.equals("Trap3")){
+ }else if("Trap3".equals(trap)){
attributeList = trapDatas.getTrap3();
- }else if(trap.equals("Trap4")){
+ }else if("Trap4".equals(trap)){
attributeList = trapDatas.getTrap4();
- }else if(trap.equals("Trap5")){
+ }else if("Trap5".equals(trap)){
attributeList = trapDatas.getTrap5();
- }else if(trap.equals("Trap6")){
+ }else if("Trap6".equals(trap)){
attributeList = trapDatas.getTrap6();
}
}else{
if(trap.startsWith("Fault")){
- if(trap.equals("Fault1")){
+ if("Fault1".equals(trap)){
attributeList = trapDatas.getTrap1();
- }else if(trap.equals("Fault2")){
+ }else if("Fault2".equals(trap)){
attributeList = trapDatas.getTrap2();
- }else if(trap.equals("Fault3")){
+ }else if("Fault3".equals(trap)){
attributeList = trapDatas.getTrap3();
- }else if(trap.equals("Fault4")){
+ }else if("Fault4".equals(trap)){
attributeList = trapDatas.getTrap4();
- }else if(trap.equals("Fault5")){
+ }else if("Fault5".equals(trap)){
attributeList = trapDatas.getTrap5();
- }else if(trap.equals("Fault6")){
+ }else if("Fault6".equals(trap)){
attributeList = trapDatas.getTrap6();
}
}
String attributeId = designator.getAttributeId();
// First match in the target is OnapName, so set that value.
- if (attributeId.equals("ONAPName")) {
+ if ("ONAPName".equals(attributeId)) {
policyAdapter.setOnapName(value);
OnapName onapName = new OnapName();
onapName.setOnapName(value);
policyAdapter.setOnapNameField(onapName);
}
- if (attributeId.equals("RiskType")){
+ if ("RiskType".equals(attributeId)){
policyAdapter.setRiskType(value);
}
- if (attributeId.equals("RiskLevel")){
+ if ("RiskLevel".equals(attributeId)){
policyAdapter.setRiskLevel(value);
}
- if (attributeId.equals("guard")){
+ if ("guard".equals(attributeId)){
policyAdapter.setGuard(value);
}
- if (attributeId.equals("TTLDate") && !value.contains("NA")){
+ if ("TTLDate".equals(attributeId) && !value.contains("NA")){
PolicyController controller = new PolicyController();
String newDate = controller.convertDate(value);
policyAdapter.setTtlDate(newDate);
ObjectMapper mapper = new ObjectMapper();
try {
ClosedLoopFaultBody closedLoopBody = mapper.readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopFaultBody.class);
- if(closedLoopBody.getClosedLoopPolicyStatus().equalsIgnoreCase("ACTIVE")){
+ if("ACTIVE".equalsIgnoreCase(closedLoopBody.getClosedLoopPolicyStatus())){
closedLoopBody.setClosedLoopPolicyStatus("Active");
}else{
closedLoopBody.setClosedLoopPolicyStatus("InActive");
CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
}
- public CreateDcaeMicroServiceController(){}
+ public CreateDcaeMicroServiceController(){
+ // Empty Constructor
+ }
protected PolicyRestAdapter policyAdapter = null;
private int priorityCount;
Iterator<String> itr=keys.iterator();
while(itr.hasNext()){
String key= itr.next();
- if((!("type").equals(key) ||("required").equals(key)))
+ if(!("type").equals(key) ||("required").equals(key))
{
String value= keyValues.get(key);
//The "." in the value determines if its a string or a user defined type.
}
- if(keyValues.get("type").equalsIgnoreCase(LIST)){
- if(constraints == null || constraints.isEmpty()){
+ if(keyValues.get("type").equalsIgnoreCase(LIST) &&
+ (constraints == null || constraints.isEmpty()) ) {
referenceStringBuilder.append(keySetString+"=MANY-true"+",");
- }
}
}else{
//User defined Datatype.
JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
ObjectNode node = nodeFactory.objectNode();
String prevKey = null;
- String presKey = null;
+ String presKey;
for(String key: element.keySet()){
if(key.contains(".")){
presKey = key.substring(0,key.indexOf('.'));
List<Object> list = new ArrayList<>();
PrintWriter out = response.getWriter();
String responseString = mapper.writeValueAsString(returnModel);
- JSONObject j = null;
+ JSONObject j;
if("".equals(allManyTrueKeys)){
j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + "}");
}else{
for (Entry<String, String> keySet : attributeMap.entrySet()){
array = new JSONArray();
String value = keySet.getValue();
- if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
+ if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])){
array.put(value);
object.put(keySet.getKey().trim(), array);
}else {
array = new JSONArray();
String value = keySet.getValue().split(":")[0];
if (gsonObject.containsKey(value)){
- if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
+ if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])){
array.put(recursiveReference(value, gsonObject, enumAttribute));
object.put(keySet.getKey().trim(), array);
}else {
object.put(keySet.getKey().trim(), recursiveReference(value, gsonObject, enumAttribute));
}
}else {
- if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
+ if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])){
array.put(value.trim());
object.put(keySet.getKey().trim(), array);
}else {
String[] splitValue = m.getValue().split(":");
array = new JSONArray();
if (subAttributeMap.containsKey(splitValue[0])){
- if (m.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
+ if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])){
array.put(recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
object.put(m.getKey().trim(), array);
}else {
object.put(m.getKey().trim(), recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
}
} else{
- if (m.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
+ if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])){
array.put(splitValue[0].trim());
object.put(m.getKey().trim(), array);
}else {
if(referAttributes != null){
String[] referAarray = referAttributes.split(",");
- String []element= null;
+ String []element;
for(int i=0; i<referAarray.length; i++){
element = referAarray[i].split("=");
if(element.length > 1 && element[1].contains("MANY-true")){
AttributeDesignatorType designator = match.getAttributeDesignator();
String attributeId = designator.getAttributeId();
// First match in the target is OnapName, so set that value.
- if (attributeId.equals("ONAPName")) {
+ if ("ONAPName".equals(attributeId)) {
policyAdapter.setOnapName(value);
}
- if (attributeId.equals("ConfigName")){
+ if ("ConfigName".equals(attributeId)){
policyAdapter.setConfigName(value);
}
- if (attributeId.equals("uuid")){
+ if ("uuid".equals(attributeId)){
policyAdapter.setUuid(value);
}
- if (attributeId.equals("location")){
+ if ("location".equals(attributeId)){
policyAdapter.setLocation(value);
}
- if (attributeId.equals("RiskType")){
+ if ("RiskType".equals(attributeId)){
policyAdapter.setRiskType(value);
}
- if (attributeId.equals("RiskLevel")){
+ if ("RiskLevel".equals(attributeId)){
policyAdapter.setRiskLevel(value);
}
- if (attributeId.equals("guard")){
+ if ("guard".equals(attributeId)){
policyAdapter.setGuard(value);
}
- if (attributeId.equals("TTLDate") && !value.contains("NA")){
+ if ("TTLDate".equals(attributeId) && !value.contains("NA")){
PolicyController controller = new PolicyController();
String newDate = controller.convertDate(value);
policyAdapter.setTtlDate(newDate);
//Convert the map values and set into JSON body
public Map<String, String> convertMap(Map<String, String> attributesMap, Map<String, String> attributesRefMap) {
Map<String, String> attribute = new HashMap<>();
- StringBuilder temp = null;
+ StringBuilder temp;
String key;
String value;
for (Entry<String, String> entry : attributesMap.entrySet()) {
File file = new File(this.newFile);
fileList.add(file);
}
- String modelType= "";
+ String modelType;
if(! yml){
modelType="xmi";
//Process Main Model file first
int BUFFER = 2048;
File file = new File(zipFile);
- ZipFile zip = null;
- try {
- zip = new ZipFile(file);
+ try (ZipFile zip = new ZipFile(file)) {
String newPath = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
this.directory = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
checkZipDirectory(this.directory);
if (!entry.isDirectory()){
BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
int currentByte;
- byte data[] = new byte[BUFFER];
- FileOutputStream fos = new FileOutputStream(destFile);
- BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
- while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
- dest.write(data, 0, currentByte);
+ byte[] data = new byte[BUFFER];
+ try (FileOutputStream fos = new FileOutputStream(destFile);
+ BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) {
+ while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
+ dest.write(data, 0, currentByte);
+ }
+ dest.flush();
+ } catch (IOException e) {
+ LOGGER.error("Failed to write zip contents to {}" + destFile + e);
+ //
+ // PLD should I throw e?
+ //
+ throw e;
}
- dest.flush();
- dest.close();
- is.close();
}
if (currentEntry.endsWith(".zip")){
}
} catch (IOException e) {
LOGGER.error("Failed to unzip model file " + zipFile, e);
- }finally{
- try {
- if(zip != null)
- zip.close();
- } catch (IOException e) {
- LOGGER.error("Exception Occured While closing zipfile " + e);
- }
}
}
public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData){
- String jsonBody="";
+ String jsonBody;
termCollectorList = new ArrayList <>();
tagCollectorList = new ArrayList <>();
if(! policyData.getAttributes().isEmpty()){
}
}
jsonBody = constructJson(policyData);
- if (jsonBody != null && !jsonBody.equalsIgnoreCase("")) {
+ if (jsonBody != null && ! "".equalsIgnoreCase(jsonBody)) {
policyData.setJsonBody(jsonBody);
} else {
policyData.setJsonBody("{}");
}
private List<String> mapping(String expandableList) {
- String value = null;
- String desc = null;
+ String value;
+ String desc;
List <String> valueDesc= new ArrayList<>();
List<Object> prefixListData = commonClassDao.getData(PrefixList.class);
for (int i = 0; i< prefixListData.size(); i++) {
TermCollector tc1=null;
try {
//Json conversion.
- String data=null;
+ String data;
SecurityZone jpaSecurityZone;
data = entity.getConfigurationData().getConfigBody();
tc1 = mapper.readValue(data, TermCollector.class);
policyLogger.error("Exception Caused while Retriving the JSON body data" +e);
}
- Map<String, String> termTagMap=null;
+ Map<String, String> termTagMap;
if(tc1 != null){
for(int i=0;i<tc1.getFirewallRuleList().size();i++){
termTagMap = new HashMap <>();
if (("guard").equals(attributeId)){
policyAdapter.setGuard(value);
}
- if (attributeId.equals("TTLDate") && !value.contains("NA")){
+ if ("TTLDate".equals(attributeId) && !value.contains("NA")){
PolicyController controller = new PolicyController();
String newDate = controller.convertDate(value);
policyAdapter.setTtlDate(newDate);
}
}
TermList jpaTermList;
- String ruleSrcList=null;
- String ruleDestList=null;
- String ruleSrcPort=null;
- String ruleDestPort=null;
- String ruleAction=null;
- List <String> valueDesc= new ArrayList<>();
+ String ruleSrcList;
+ String ruleDestList;
+ String ruleSrcPort;
+ String ruleDestPort;
+ String ruleAction;
+ List <String> valueDesc;
StringBuffer displayString = new StringBuffer();
for (String id : termCollectorList) {
List<Object> tmList = commonClassDao.getDataById(TermList.class, "termName", id);
displayString.append("\n");
}
ruleDestList= jpaTermList.getDestIPList();
- if ( ruleDestList!= null && (!ruleDestList.isEmpty())&& !ruleDestList.equals("null")){
+ if ( ruleDestList!= null && (!ruleDestList.isEmpty())&& ! "null".equals(ruleDestList)){
displayString.append("Destination IP List: " + jpaTermList.getDestIPList());
displayString.append(" ; \t\n");
for(String destList:ruleDestList.split(",")){
}
ruleSrcPort=jpaTermList.getSrcPortList();
- if ( ruleSrcPort!= null && (!ruleSrcPort.isEmpty())&& !ruleSrcPort.equals("null")) {
+ if ( ruleSrcPort!= null && (!ruleSrcPort.isEmpty())&& !"null".equals(ruleSrcPort)) {
displayString.append("\n"+"Source Port List:"
+ ruleSrcPort);
displayString.append(" ; \t\n");
}
ruleDestPort= jpaTermList.getDestPortList();
- if (ruleDestPort != null && (!ruleDestPort.isEmpty())&& !ruleDestPort.equals("null")) {
+ if (ruleDestPort != null && (!ruleDestPort.isEmpty())&& !"null".equals(ruleDestPort)) {
displayString.append("\n"+"Destination Port List:"
+ ruleDestPort);
displayString.append(" ; \t\n");
}
//ExpandableServicesList
if((srcPort_map!=null) && (destPort_map!=null)){
- String servicesCollateString = (srcPort_map.get(tl) + "," + destPort_map.get(tl));
+ String servicesCollateString = srcPort_map.get(tl) + "," + destPort_map.get(tl);
expandableServicesList.add(servicesCollateString);
}else if (srcPort_map!=null){
expandableServicesList.add(srcPort_map.get(tl));
//ExpandablePrefixIPList
if ((srcIP_map!=null) && (destIP_map!=null))
{
- String collateString = (srcIP_map.get(tl) + "," + destIP_map
- .get(tl));
+ String collateString = srcIP_map.get(tl) + "," + destIP_map
+ .get(tl);
expandablePrefixIPList.add(collateString);
}
else if(srcIP_map!=null){
Set<AddressGroupJson> addrGroupArray= new HashSet<>();
Set<AddressMembers> addrArray= new HashSet<> ();
- ServiceGroupJson targetSg= null;
- AddressGroupJson addressSg=null;
- ServiceListJson targetAny= null;
- ServiceListJson targetAnyTcp=null;
- ServiceListJson targetAnyUdp=null;
+ ServiceGroupJson targetSg;
+ AddressGroupJson addressSg;
+ ServiceListJson targetAny;
+ ServiceListJson targetAnyTcp;
+ ServiceListJson targetAnyUdp;
for(String serviceList:expandableServicesList){
for(String t: serviceList.split(",")){
- if((!t.startsWith(GROUP))){
+ if(!t.startsWith(GROUP)){
if(!t.equals(ANY)){
ServiceList sl;
targetSl= new ServiceListJson();
Set<PrefixIPList> prefixIPList = new HashSet<>();
for(String prefixList:expandablePrefixIPList){
for(String prefixIP: prefixList.split(",")){
- if((!prefixIP.startsWith(GROUP))){
+ if(!prefixIP.startsWith(GROUP)){
if(!prefixIP.equals(ANY)){
List<AddressMembers> addMembersList= new ArrayList<>();
List<String> valueDesc;
AttributeDesignatorType designator = match.getAttributeDesignator();
String attributeId = designator.getAttributeId();
// First match in the target is OnapName, so set that value.
- if (attributeId.equals("ONAPName")) {
+ if ("ONAPName".equals(attributeId)) {
policyAdapter.setOnapName(value);
}
- if (attributeId.equals("RiskType")){
+ if ("RiskType".equals(attributeId)){
policyAdapter.setRiskType(value);
}
- if (attributeId.equals("RiskLevel")){
+ if ("RiskLevel".equals(attributeId)){
policyAdapter.setRiskLevel(value);
}
- if (attributeId.equals("guard")){
+ if ("guard".equals(attributeId)){
policyAdapter.setGuard(value);
}
- if (attributeId.equals("TTLDate") && !value.contains("NA")){
+ if ("TTLDate".equals(attributeId) && !value.contains("NA")){
PolicyController controller = new PolicyController();
String newDate = controller.convertDate(value);
policyAdapter.setTtlDate(newDate);
}
- if (attributeId.equals("ConfigName")){
+ if ("ConfigName".equals(attributeId)){
policyAdapter.setConfigName(value);
}
// After Onap and Config it is optional to have attributes, so
policyLogger.debug("Create an RMI connector client and connect it to the JMX connector server");
HashMap map = null;
- JMXConnector jmxConnection;
- try {
- jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map);
+ try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map)){
jmxConnection.connect();
Object o = jmxConnection.getMBeanServerConnection().getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), jmxAttribute);
- jmxConnection.close();
policyLogger.debug("pdpEvaluationNA value retreived: " + o);
return (long) o;
} catch (MalformedURLException e) {
*/
private void addPolicyToTable() {
policyActivityData = new ArrayList<>();
- String policyID = null;
- int policyFireCount = 0;
+ String policyID;
+ int policyFireCount;
Map<String, String> policyMap = new HashMap<>();
- Object policyList = null;
+ Object policyList;
//get list of policy
for (PDPGroup group : this.pdpConatiner.getGroups()){
for (String policyKeyValue : splitPolicy){
policyID = urnPolicyID(policyKeyValue);
policyFireCount = countPolicyID(policyKeyValue);
- if (policyID != null ){
- if (policyMap.containsKey(policyID)){
- JSONObject object = new JSONObject();
- object.put("policyId", policyMap.get(policyID));
- object.put("fireCount", policyFireCount);
- object.put("system", pdp.getId());
- policyActivityData.add(object);
- }
+ if (policyID != null && policyMap.containsKey(policyID)){
+ JSONObject object = new JSONObject();
+ object.put("policyId", policyMap.get(policyID));
+ object.put("fireCount", policyFireCount);
+ object.put("system", pdp.getId());
+ policyActivityData.add(object);
}
}
}else {
private Object getPolicy(String host, int port, String jmxAttribute){
policyLogger.debug("Create an RMI connector client and connect it to the JMX connector server for Policy: " + host);
HashMap map = null;
- JMXConnector jmxConnection;
- try {
- jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map);
+ try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map)) {
jmxConnection.connect();
Object o = jmxConnection.getMBeanServerConnection().getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), "policyMap");
- jmxConnection.close();
policyLogger.debug("policyMap value retreived: " + o);
return o;
} catch (MalformedURLException e) {
AttributeDesignatorType designator = match.getAttributeDesignator();
String attributeId = designator.getAttributeId();
// First match in the target is OnapName, so set that value.
- if (attributeId.equals("ONAPName")) {
+ if ("ONAPName".equals(attributeId)) {
policyAdapter.setOnapName(value);
}
// Component attributes are saved under Target here we are fetching them back.
if(!attributeList.isEmpty()) {
for(int i=0; i<attributeList.size() ; i++){
Map<String, String> map = (Map<String,String>)attributeList.get(i);
- if(map.get("key").equals("WorkStep")){
+ if("WorkStep".equals(map.get("key"))){
rainydayParams.setWorkstep(map.get("value"));
rainy=true;
- }else if(map.get("key").equals("BB_ID")){
+ }else if("BB_ID".equals(map.get("key"))){
rainydayParams.setBbid(map.get("value"));
rainy=true;
- }else if(map.get("key").equals("ServiceType")){
+ }else if("ServiceType".equals(map.get("key"))){
rainydayParams.setServiceType(map.get("value"));
rainy=true;
- }else if(map.get("key").equals("VNFType")){
+ }else if("VNFType".equals(map.get("key"))){
rainydayParams.setVnfType(map.get("value"));
rainy=true;
}
// get the condition data under the rule for rule Algorithms.
if(((RuleType) object).getEffect().equals(EffectType.DENY)) {
if(((RuleType) object).getAdviceExpressions()!=null){
- if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().equalsIgnoreCase("AAF")){
+ if("AAF".equalsIgnoreCase(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId())){
policyAdapter.setRuleProvider("AAF");
break;
- }else if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().equalsIgnoreCase("GUARD_YAML")){
+ }else if("GUARD_YAML".equalsIgnoreCase(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId())){
policyAdapter.setRuleProvider("GUARD_YAML");
- }else if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().equalsIgnoreCase("GUARD_BL_YAML")){
+ }else if("GUARD_BL_YAML".equalsIgnoreCase(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId())){
policyAdapter.setRuleProvider("GUARD_BL_YAML");
}
}else{
ApplyType decisionApply = (ApplyType) condition.getExpression().getValue();
decisionApply = (ApplyType) decisionApply.getExpression().get(0).getValue();
ruleAlgoirthmTracker = new LinkedList<>();
- if(policyAdapter.getRuleProvider()!=null && (policyAdapter.getRuleProvider().equals("GUARD_YAML")||(policyAdapter.getRuleProvider().equals("GUARD_BL_YAML")))){
+ if(policyAdapter.getRuleProvider()!=null && ("GUARD_YAML".equals(policyAdapter.getRuleProvider())||(policyAdapter.getRuleProvider().equals("GUARD_BL_YAML")))){
YAMLParams yamlParams = new YAMLParams();
for(int i=0; i<attributeList.size() ; i++){
Map<String, String> map = (Map<String,String>)attributeList.get(i);
yamlParams.setClname(map.get("value"));
}
}
- ApplyType apply = ((ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(0).getValue());
+ ApplyType apply = (ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(0).getValue();
yamlParams.setGuardActiveStart(((AttributeValueType)apply.getExpression().get(1).getValue()).getContent().get(0).toString());
yamlParams.setGuardActiveEnd(((AttributeValueType)apply.getExpression().get(2).getValue()).getContent().get(0).toString());
- if(policyAdapter.getRuleProvider().equals("GUARD_BL_YAML")){
+ if("GUARD_BL_YAML".equals(policyAdapter.getRuleProvider())){
apply = (ApplyType)((ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(1).getValue()).getExpression().get(2).getValue();
Iterator<JAXBElement<?>> attributes = apply.getExpression().iterator();
List<String> blackList = new ArrayList<>();
prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply);
policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList);
}
- } else if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals("Rainy_Day")&& ((RuleType) object).getEffect().equals(EffectType.PERMIT)) {
+ } else if(policyAdapter.getRuleProvider()!=null && "Rainy_Day".equals(policyAdapter.getRuleProvider())&& ((RuleType) object).getEffect().equals(EffectType.PERMIT)) {
TargetType ruleTarget = ((RuleType) object).getTarget();
AdviceExpressionsType adviceExpression = ((RuleType) object).getAdviceExpressions();
}
}
// Populate the key and value fields
- if (((jaxbDecisionTypes.get(0).getValue()) instanceof AttributeValueType)) {
+ if ((jaxbDecisionTypes.get(0).getValue() instanceof AttributeValueType)) {
ApplyType innerDecisionApply = (ApplyType) jaxbDecisionTypes.get(1).getValue();
List<JAXBElement<?>> jaxbInnerDecisionTypes = innerDecisionApply.getExpression();
if (jaxbInnerDecisionTypes.get(0).getValue() instanceof AttributeDesignatorType) {
try {
PolicyController controller = getPolicyControllerInstance();
Set<PDPPolicy> filteredPolicies = new HashSet<>();
- Set<String> scopes = null;
- List<String> roles = null;
+ Set<String> scopes;
+ List<String> roles;
String userId = isJunit() ? "Test" : UserUtils.getUserSession(request).getOrgUserId();
List<Object> userRoles = controller.getRoles(userId);
roles = new ArrayList<>();
this.groups.addAll(this.getGroupsData());
}
}else{
- if(!userRoles.isEmpty()){
- if(!scopes.isEmpty()){
- this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
- List<OnapPDPGroup> tempGroups = new ArrayList<>();
- if(!groups.isEmpty()){
- Iterator<OnapPDPGroup> pdpGroup = groups.iterator();
- while(pdpGroup.hasNext()){
- OnapPDPGroup group = pdpGroup.next();
- Set<PDPPolicy> policies = group.getPolicies();
- for(PDPPolicy policy : policies){
- for(String scope : scopes){
- scope = scope.replace(File.separator, ".");
- String policyName = policy.getId();
- if(policyName.contains(".Config_")){
- policyName = policyName.substring(0, policyName.lastIndexOf(".Config_"));
- }else if(policyName.contains(".Action_")){
- policyName = policyName.substring(0, policyName.lastIndexOf(".Action_"));
- }else if(policyName.contains(".Decision_")){
- policyName = policyName.substring(0, policyName.lastIndexOf(".Decision_"));
- }
- if(policyName.startsWith(scope)){
- filteredPolicies.add(policy);
- }
+ if(!userRoles.isEmpty() && !scopes.isEmpty()){
+ this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
+ List<OnapPDPGroup> tempGroups = new ArrayList<>();
+ if(!groups.isEmpty()){
+ Iterator<OnapPDPGroup> pdpGroup = groups.iterator();
+ while(pdpGroup.hasNext()){
+ OnapPDPGroup group = pdpGroup.next();
+ Set<PDPPolicy> policies = group.getPolicies();
+ for(PDPPolicy policy : policies){
+ for(String scope : scopes){
+ scope = scope.replace(File.separator, ".");
+ String policyName = policy.getId();
+ if(policyName.contains(".Config_")){
+ policyName = policyName.substring(0, policyName.lastIndexOf(".Config_"));
+ }else if(policyName.contains(".Action_")){
+ policyName = policyName.substring(0, policyName.lastIndexOf(".Action_"));
+ }else if(policyName.contains(".Decision_")){
+ policyName = policyName.substring(0, policyName.lastIndexOf(".Decision_"));
+ }
+ if(policyName.startsWith(scope)){
+ filteredPolicies.add(policy);
}
}
- pdpGroup.remove();
- StdPDPGroup newGroup = (StdPDPGroup) group;
- newGroup.setPolicies(filteredPolicies);
- tempGroups.add(newGroup);
- }
- groups.clear();
- groups = tempGroups;
- }
+ }
+ pdpGroup.remove();
+ StdPDPGroup newGroup = (StdPDPGroup) group;
+ newGroup.setPolicies(filteredPolicies);
+ tempGroups.add(newGroup);
+ }
+ groups.clear();
+ groups = tempGroups;
}
}
}
policyLogger.info("*****************************************************************************************************************************");
StdPDPGroup pdpGroupData = mapper.readValue(root.get("pdpGroupData").toString(), StdPDPGroup.class);
- if(pdpGroupData.getName().equals("Default")) {
+ if("Default".equals(pdpGroupData.getName())) {
throw new UnsupportedOperationException("You can't remove the Default Group.");
}else{
this.container.removeGroup(pdpGroupData, null);
}
public PolicyController() {
+ // Empty constructor
}
@PostConstruct
PolicyExportAndImportController.commonClassDao = commonClassDao;
}
- public PolicyExportAndImportController(){}
+ public PolicyExportAndImportController(){
+ // Empty constructor
+ }
@RequestMapping(value={"/policy_download/exportPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
public void exportPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{
try{
- String file = null;
+ String file;
selectedPolicy = new ArrayList<>();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
boolean configExists = false;
boolean actionExists = false;
String configName = null;
- String scope = null;
- boolean finalColumn = false;
+ String scope;
+ boolean finalColumn;
PolicyController controller = policyController != null ? getPolicyController() : new PolicyController();
String userId = UserUtils.getUserSession(request).getOrgUserId();
UserInfo userInfo = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", userId);
Iterator<Cell> cellIterator = currentRow.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
- if (getCellHeaderName(cell).equalsIgnoreCase("policyName")) {
+ if ("policyName".equalsIgnoreCase(getCellHeaderName(cell))) {
policyEntity.setPolicyName(cell.getStringCellValue());
}
- if (getCellHeaderName(cell).equalsIgnoreCase("scope")) {
+ if ("scope".equalsIgnoreCase(getCellHeaderName(cell))) {
policyEntity.setScope(cell.getStringCellValue());
}
- if (getCellHeaderName(cell).equalsIgnoreCase("policyData")) {
+ if ("policyData".equalsIgnoreCase(getCellHeaderName(cell))) {
policyEntity.setPolicyData(cell.getStringCellValue());
}
- if (getCellHeaderName(cell).equalsIgnoreCase("description")) {
+ if ("description".equalsIgnoreCase(getCellHeaderName(cell))) {
policyEntity.setDescription(cell.getStringCellValue());
}
- if (getCellHeaderName(cell).equalsIgnoreCase("configurationbody")) {
+ if ("configurationbody".equalsIgnoreCase(getCellHeaderName(cell))) {
if(policyEntity.getPolicyName().contains("Config_")){
configExists = true;
configurationDataEntity.setConfigBody(cell.getStringCellValue());
actionBodyEntity.setActionBody(cell.getStringCellValue());
}
}
- if (getCellHeaderName(cell).equalsIgnoreCase("configurationName")) {
+ if ("configurationName".equalsIgnoreCase(getCellHeaderName(cell))) {
finalColumn = true;
configName = cell.getStringCellValue();
if(policyEntity.getPolicyName().contains("Config_")){
}
if (roles.contains(ADMIN) || roles.contains(EDITOR)) {
if(scopes.isEmpty()){
- //return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
+ logger.error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
}else{
//1. if Role contains admin, then check if parent scope has role admin, if not don't create a scope and add to list.
if(roles.contains(ADMIN)){
}
public boolean isSupported(Object itemId) {
- return (itemId instanceof OnapPDPGroup);
+ return itemId instanceof OnapPDPGroup;
}
public synchronized void refreshGroups() {
if (this.policies.isEmpty()) {
return false;
}
- return (itemId.equals(this.policies.get(0)));
+ return itemId.equals(this.policies.get(0));
}
@Override
if (this.policies.isEmpty()) {
return false;
}
- return (itemId.equals(this.policies.get(this.policies.size() - 1)));
+ return itemId.equals(this.policies.get(this.policies.size() - 1));
}
@Override
}
Base64.Encoder encoder = Base64.getEncoder();
String encoding = encoder.encodeToString((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID)+":"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)).getBytes(StandardCharsets.UTF_8));
- HttpURLConnection connection = null;
+ HttpURLConnection connection;
UUID requestID = UUID.randomUUID();
URL url;
try {
public static boolean notifyPapOfDelete(String policyToDelete){
Base64.Encoder encoder = Base64.getEncoder();
String encoding = encoder.encodeToString((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID)+":"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)).getBytes(StandardCharsets.UTF_8));
- HttpURLConnection connection = null;
+ HttpURLConnection connection;
UUID requestID = UUID.randomUUID();
String papUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
if(papUrl == null){
}
Base64.Encoder encoder = Base64.getEncoder();
String encoding = encoder.encodeToString((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID)+":"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)).getBytes(StandardCharsets.UTF_8));
- HttpURLConnection connection = null;
+ HttpURLConnection connection;
UUID requestID = UUID.randomUUID();
URL url;
try {