package org.oransc.ric.portal.dashboard;
-import java.io.IOException;
import java.lang.invoke.MethodHandles;
import org.slf4j.Logger;
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
- public static void main(String[] args) throws IOException {
- SpringApplication.run(DashboardApplication.class, args);
+ public static void main(String[] args) {
+ SpringApplication.run(DashboardApplication.class);
// Ensure this appears on the console by using level WARN
logger.warn("main: version '{}' successful start",
getImplementationVersion(MethodHandles.lookup().lookupClass()));
*/
package org.oransc.ric.portal.dashboard;
-import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.type.TypeReference;
-import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
+import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
* Provides simple user-management services.
*
* This first implementation serializes user details to a file.
- *
- * TODO: migrate to a database.
*/
public class DashboardUserManager {
logger.debug("ctor: removing file {}", userFile.getAbsolutePath());
File f = new File(DashboardUserManager.USER_FILE_PATH);
if (f.exists())
- f.delete();
+ Files.delete(f.toPath());
users.clear();
}
}
return null;
}
- private void saveUsers() throws JsonGenerationException, JsonMappingException, IOException {
+ private void saveUsers() throws IOException {
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(userFile, users);
}
* Allow at most one thread to create a user at one time.
*/
public synchronized void createUser(EcompUser user) throws PortalAPIException {
- logger.debug("createUser: loginId is " + user.getLoginId());
+ if (logger.isDebugEnabled()) {
+ logger.debug("createUser: loginId is {}", user.getLoginId());
+ }
if (users.contains(user))
throw new PortalAPIException("User exists: " + user.getLoginId());
users.add(user);
* last-edit-wins of course.
*/
public synchronized void updateUser(String loginId, EcompUser user) throws PortalAPIException {
- logger.debug("editUser: loginId is " + loginId);
+ logger.debug("editUser: loginId is {}", loginId);
int index = users.indexOf(user);
if (index < 0)
throw new PortalAPIException("User does not exist: " + user.getLoginId());
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.oransc.ric.portal.dashboard.config;
-import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringContextCache implements ApplicationContextAware {
- private static ApplicationContext applicationContext = null;
+ private ApplicationContext applicationContext = null;
@Override
- public void setApplicationContext(final ApplicationContext appContext) throws BeansException {
+ public void setApplicationContext(final ApplicationContext appContext) {
applicationContext = appContext;
}
- public static ApplicationContext getApplicationContext() {
+ public ApplicationContext getApplicationContext() {
return applicationContext;
}
* Resource paths that do not require authentication, especially including
* Swagger-generated documentation.
*/
- public static final String[] OPEN_PATHS = { //
+ @SuppressWarnings("squid:S1075")
+ protected static final String[] OPEN_PATHS = { //
"/v2/api-docs", //
"/swagger-resources/**", //
"/swagger-ui.html", //
}
@Bean
- public PortalAuthManager portalAuthManagerBean()
- throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException,
- IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
+ public PortalAuthManager portalAuthManagerBean() throws ClassNotFoundException, InstantiationException,
+ IllegalAccessException, InvocationTargetException, NoSuchMethodException {
return new PortalAuthManager(appName, userName, password, decryptor, userCookie);
}
* bypass this filter, which seems to me means the filter participates
* correctly.
*/
- public PortalAuthenticationFilter portalAuthenticationFilterBean()
- throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException,
- IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
- PortalAuthenticationFilter portalAuthenticationFilter =
- new PortalAuthenticationFilter(portalapiSecurity, portalAuthManagerBean(), this.userManager);
- return portalAuthenticationFilter;
+ public PortalAuthenticationFilter portalAuthenticationFilterBean() throws ClassNotFoundException,
+ InstantiationException, IllegalAccessException, IOException, InvocationTargetException, NoSuchMethodException {
+ return new PortalAuthenticationFilter(portalapiSecurity, portalAuthManagerBean(), this.userManager);
}
}
* On error
*/
@RequestMapping(
- method = {RequestMethod.OPTIONS, RequestMethod.GET}, //
- path = {"/policy", "/user"})
+ method = {RequestMethod.GET}, //
+ path = {"/policy"})
public void forwardAngularRoutes(HttpServletRequest request, HttpServletResponse response) throws IOException {
URL url = new URL(request.getScheme(), request.getServerName(), request.getServerPort(), "/index.html");
if (logger.isDebugEnabled())
*/
@ApiOperation(value = "Gets the policy types from Near Realtime-RIC")
@GetMapping(POLICY_TYPES_METHOD)
- @Secured({ DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD })
+ @Secured({DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD})
public ResponseEntity<String> getAllPolicyTypes(HttpServletResponse response) {
logger.debug("getAllPolicyTypes");
return this.policyAgentApi.getAllPolicyTypes();
@ApiOperation(value = "Returns the policy instances for the given policy type.")
@GetMapping(POLICY_TYPES_METHOD + "/{" + POLICY_TYPE_ID_NAME + "}/" + POLICIES_NAME)
- @Secured({ DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD })
+ @Secured({DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD})
public ResponseEntity<String> getPolicyInstances(@PathVariable(POLICY_TYPE_ID_NAME) String policyTypeIdString) {
logger.debug("getPolicyInstances {}", policyTypeIdString);
return this.policyAgentApi.getPolicyInstancesForType(policyTypeIdString);
@ApiOperation(value = "Returns a policy instance of a type")
@GetMapping(POLICY_TYPES_METHOD + "/{" + POLICY_TYPE_ID_NAME + "}/" + POLICIES_NAME + "/{" + POLICY_INSTANCE_ID_NAME
- + "}")
- @Secured({ DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD })
+ + "}")
+ @Secured({DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD})
public ResponseEntity<Object> getPolicyInstance(@PathVariable(POLICY_TYPE_ID_NAME) String policyTypeIdString,
- @PathVariable(POLICY_INSTANCE_ID_NAME) String policyInstanceId) {
+ @PathVariable(POLICY_INSTANCE_ID_NAME) String policyInstanceId) {
logger.debug("getPolicyInstance {}:{}", policyTypeIdString, policyInstanceId);
return this.policyAgentApi.getPolicyInstance(policyInstanceId);
}
@ApiOperation(value = "Creates the policy instances for the given policy type.")
@PutMapping(POLICY_TYPES_METHOD + "/{" + POLICY_TYPE_ID_NAME + "}/" + POLICIES_NAME + "/{" + POLICY_INSTANCE_ID_NAME
- + "}")
- @Secured({ DashboardConstants.ROLE_ADMIN })
+ + "}")
+ @Secured({DashboardConstants.ROLE_ADMIN})
public ResponseEntity<String> putPolicyInstance(@PathVariable(POLICY_TYPE_ID_NAME) String policyTypeIdString,
- @RequestParam(name = "ric", required = true) String ric,
- @PathVariable(POLICY_INSTANCE_ID_NAME) String policyInstanceId, @RequestBody String instance) {
- logger.debug("putPolicyInstance typeId: {}, instanceId: {}, instance: {}", policyTypeIdString, policyInstanceId,
- instance);
+ @RequestParam(name = "ric", required = true) String ric,
+ @PathVariable(POLICY_INSTANCE_ID_NAME) String policyInstanceId, @RequestBody String instance) {
+ logger.debug("putPolicyInstance ric: {}, typeId: {}, instanceId: {}, instance: {}", ric, policyTypeIdString,
+ policyInstanceId, instance);
return this.policyAgentApi.putPolicy(policyTypeIdString, policyInstanceId, instance, ric);
}
@ApiOperation(value = "Deletes the policy instances for the given policy type.")
@DeleteMapping(POLICY_TYPES_METHOD + "/{" + POLICY_TYPE_ID_NAME + "}/" + POLICIES_NAME + "/{"
- + POLICY_INSTANCE_ID_NAME + "}")
- @Secured({ DashboardConstants.ROLE_ADMIN })
+ + POLICY_INSTANCE_ID_NAME + "}")
+ @Secured({DashboardConstants.ROLE_ADMIN})
public ResponseEntity<String> deletePolicyInstance(@PathVariable(POLICY_TYPE_ID_NAME) String policyTypeIdString,
- @PathVariable(POLICY_INSTANCE_ID_NAME) String policyInstanceId) {
+ @PathVariable(POLICY_INSTANCE_ID_NAME) String policyInstanceId) {
logger.debug("deletePolicyInstance typeId: {}, instanceId: {}", policyTypeIdString, policyInstanceId);
return this.policyAgentApi.deletePolicy(policyInstanceId);
}
@ApiOperation(value = "Returns the rics supporting the given policy type.")
@GetMapping("/rics")
- @Secured({ DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD })
+ @Secured({DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD})
public ResponseEntity<String> getRicsSupportingType(
- @RequestParam(name = "policyType", required = true) String supportingPolicyType) {
+ @RequestParam(name = "policyType", required = true) String supportingPolicyType) {
logger.debug("getRicsSupportingType {}", supportingPolicyType);
return this.policyAgentApi.getRicsSupportingType(supportingPolicyType);
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+ @SuppressWarnings("squid:S1075")
public static final String ERROR_PATH = "/error";
private final ErrorAttributes errorAttributes;
if (t != null)
logger.warn("handleError", t);
Map<String, Object> attributes = errorAttributes.getErrorAttributes(servletWebRequest, true);
- attributes.forEach((attribute, value) -> {
- logger.warn("handleError: {} -> {}", attribute, value);
- });
+ attributes.forEach((attribute, value) -> logger.warn("handleError: {} -> {}", attribute, value));
// Return the name of the page INCLUDING suffix, which I guess is a "view" name.
// Just "error" is not enough, but don't seem to need a ModelAndView object.
return "error.html";
public class EcompUserDetails implements UserDetails {
private static final long serialVersionUID = 1L;
- private final EcompUser ecompUser;
+ private transient final EcompUser ecompUser;
// This is the default Spring role-name prefix.
private static final String ROLEP = "ROLE_";
public ResponseEntity<Object> getPolicyInstance(String id);
public ResponseEntity<String> putPolicy(String policyTypeIdString, String policyInstanceId, Object json,
- String ric);
+ String ric);
public ResponseEntity<String> deletePolicy(String policyInstanceId);
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Type;
+import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
-import java.util.Vector;
import org.immutables.gson.Gson;
import org.immutables.value.Value;
RestTemplate restTemplate = new RestTemplate();
private static com.google.gson.Gson gson = new GsonBuilder() //
- .serializeNulls() //
- .create(); //
+ .serializeNulls() //
+ .create(); //
private final String urlPrefix;
@Autowired
public PolicyAgentApiImpl(
- @org.springframework.beans.factory.annotation.Value("${policycontroller.url.prefix}") final String urlPrefix) {
+ @org.springframework.beans.factory.annotation.Value("${policycontroller.url.prefix}") final String urlPrefix) {
logger.debug("ctor prefix '{}'", urlPrefix);
this.urlPrefix = urlPrefix;
}
}
try {
- Type listType = new TypeToken<List<ImmutablePolicyInfo>>() {
- }.getType();
+ Type listType = new TypeToken<List<ImmutablePolicyInfo>>() {}.getType();
List<PolicyInfo> rspParsed = gson.fromJson(rsp.getBody(), listType);
PolicyInstances result = new PolicyInstances();
for (PolicyInfo p : rspParsed) {
@Override
public ResponseEntity<String> putPolicy(String policyTypeIdString, String policyInstanceId, Object json,
- String ric) {
+ String ric) {
String url = baseUrl() + "/policy?type={type}&instance={instance}&ric={ric}&service={service}";
Map<String, ?> uriVariables = Map.of( //
- "type", policyTypeIdString, //
- "instance", policyInstanceId, //
- "ric", ric, //
- "service", "dashboard");
+ "type", policyTypeIdString, //
+ "instance", policyInstanceId, //
+ "ric", ric, //
+ "service", "dashboard");
try {
this.restTemplate.put(url, createJsonHttpEntity(json), uriVariables);
String rsp = this.restTemplate.getForObject(url, String.class, uriVariables);
try {
- Type listType = new TypeToken<List<ImmutableRicInfo>>() {
- }.getType();
+ Type listType = new TypeToken<List<ImmutableRicInfo>>() {}.getType();
List<RicInfo> rspParsed = gson.fromJson(rsp, listType);
- Collection<String> result = new Vector<>(rspParsed.size());
+ Collection<String> result = new ArrayList<>(rspParsed.size());
for (RicInfo ric : rspParsed) {
result.add(ric.ricName());
}
private HttpEntity<Object> createJsonHttpEntity(Object content) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
- return new HttpEntity<Object>(content, headers);
+ return new HttpEntity<>(content, headers);
}
}
private final String userIdCookieName;
public PortalAuthManager(final String appName, final String username, final String password,
- final String decryptorClassName, final String userCookie)
- throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException,
- InvocationTargetException, NoSuchMethodException, SecurityException {
+ final String decryptorClassName, final String userCookie) throws ClassNotFoundException, InstantiationException,
+ IllegalAccessException, InvocationTargetException, NoSuchMethodException {
credentialsMap = new HashMap<>();
credentialsMap.put(IPortalRestCentralService.CREDENTIALS_APP, appName);
credentialsMap.put(IPortalRestCentralService.CREDENTIALS_USER, username);
* created and EPService cookie is set.
* </UL>
*
- * TODO: What about sessions? Will this be stateless?
+ * Open question: What about sessions? Will this be stateless?
*
* This filter uses no annotations to avoid Spring's automatic registration,
* which add this filter in the chain in the wrong order.
private final DashboardUserManager userManager;
public PortalAuthenticationFilter(boolean portalSecurity, PortalAuthManager authManager,
- DashboardUserManager userManager) {
+ DashboardUserManager userManager) throws IOException {
this.enforcePortalSecurity = portalSecurity;
this.authManager = authManager;
this.userManager = userManager;
if (in == null) {
String msg = "Failed to find property file on classpath: " + pf;
logger.error(msg);
- throw new RuntimeException(msg);
+ throw new IOException(msg);
} else {
try {
in.close();
String redirectUrl = portalBaseUrl + "?" + PortalAuthenticationFilter.REDIRECT_URL_KEY + "=" + encodedAppUrl;
String aHref = "<a href=\"" + redirectUrl + "\">";
// If only Java had "here" documents.
- String body = String.join(//
+ return String.join(//
System.getProperty("line.separator"), //
"<html>", //
"<head>", //
"</p>", //
"</body>", //
"</html>");
- return body;
}
/**
import org.oransc.ric.portal.dashboard.config.SpringContextCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
/**
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+ @Autowired
+ private SpringContextCache springContextCache;
private final PortalAuthManager authManager;
private final DashboardUserManager userManager;
public PortalRestCentralServiceImpl() throws IOException, PortalAPIException {
- final ApplicationContext context = SpringContextCache.getApplicationContext();
+ final ApplicationContext context = springContextCache.getApplicationContext();
authManager = context.getBean(PortalAuthManager.class);
userManager = context.getBean(DashboardUserManager.class);
}
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
public class PortalSdkDecryptorAes implements IPortalSdkDecryptor {
- @SuppressWarnings("deprecation")
+ @Override
+ @SuppressWarnings("squid:CallToDeprecatedMethod")
public String decrypt(String cipherText) throws CipherUtilException {
return CipherUtil.decrypt(cipherText);
}
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
private static final HostnameVerifier jvmHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
- private static final HostnameVerifier trivialHostnameVerifier = new HostnameVerifier() {
- @Override
- public boolean verify(String hostname, SSLSession sslSession) {
- return true;
- }
- };
+ private static final HostnameVerifier trivialHostnameVerifier = (hostname, sslSession) -> true;
private static final TrustManager[] UNQUESTIONING_TRUST_MANAGER = new TrustManager[] {new X509TrustManager() {
+ @SuppressWarnings("squid:S1168") // Must return null to get wanted behaviour.
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
+ // Do nothing.
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
+ // Do nothing.
}
}};
*/
package org.oransc.ric.portal.dashboard;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
import java.lang.invoke.MethodHandles;
import org.junit.jupiter.api.Test;
* Keeps the test server alive forever. Use a guard so this test is never run by
* Jenkins.
*/
+ @SuppressWarnings("squid:S2699") // To avoid warning about missing assertion.
@EnabledIfSystemProperty(named = "org.oransc.ric.portal.dashboard", matches = "mock")
@Test
public void keepServerAlive() {
} catch (Exception ex) {
logger.warn(ex.toString());
}
- assertEquals(1, 2);
}
}
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private static com.google.gson.Gson gson = new GsonBuilder() //
- .serializeNulls() //
- .create(); //
+ .serializeNulls() //
+ .create(); //
@Bean
public PolicyAgentApi policyAgentApi() {
@Override
public ResponseEntity<String> putPolicy(String policyTypeIdString, String policyInstanceId, Object json,
- String ric) {
+ String ric) {
database.putInstance(policyTypeIdString, policyInstanceId, json, ric);
return new ResponseEntity<>("Policy was put successfully", HttpStatus.OK);
}
private String getStringFromFile(String path) {
try {
- InputStream inputStream = MethodHandles.lookup().lookupClass().getClassLoader()
- .getResourceAsStream(path);
+ InputStream inputStream =
+ MethodHandles.lookup().lookupClass().getClassLoader().getResourceAsStream(path);
return new BufferedReader(new InputStreamReader(inputStream)).lines().collect(Collectors.joining("\n"));
} catch (Exception e) {
logger.error("Cannot read file :" + path, e);
void putInstance(String typeId, String instanceId, Object instanceData, String ric) {
PolicyInfo i = ImmutablePolicyInfo.builder().json(instanceData).lastModified(getTimeStampUTC())
- .id(instanceId).ric(ric).service("service").type(typeId).build();
+ .id(instanceId).ric(ric).service("service").type(typeId).build();
instances.put(instanceId, i);
}
<mat-nav-list [ngClass]="{'dark': darkMode}">
<a mat-list-item routerLink="/" (click)="onSidenavClose()">
<mat-icon>home</mat-icon> <span class="nav-caption">Home</span>
- </a>
- <a mat-list-item routerLink="/control" (click)="onSidenavClose()">
- <mat-icon>settings</mat-icon><span class="nav-caption">Control</span>
- </a>
+ </a>
<a mat-list-item routerLink="/policy" (click)="onSidenavClose()">
<mat-icon>assignment</mat-icon> <span class="nav-caption">Policy</span>
- </a>
+ </a>
</mat-nav-list>