Skip to content
Snippets Groups Projects
Commit d493cd17 authored by Mirco Nasuti's avatar Mirco Nasuti
Browse files

Merge branch 'sonar_suggestions' into 'stable'

Sonar suggestions

Many changes following the code quality recommendations from Sonar.

See merge request !8
parents d0a420d2 5b264a65
No related branches found
No related tags found
No related merge requests found
Showing
with 128 additions and 156 deletions
......@@ -3,21 +3,6 @@
* Based on gregturn code at : 'https://github.com/spring-guides/tut-spring-boot-oauth2'.
*/
/*
* Copyright 2012-2015 the original author or authors.
*
* 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.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hbp.mip;
import com.fasterxml.jackson.core.JsonProcessingException;
......@@ -93,7 +78,7 @@ import java.security.Principal;
@Api(value = "/", description = "MIP API")
public class MIPApplication extends WebSecurityConfigurerAdapter {
private Logger logger = Logger.getLogger(this.getClass());
private static final Logger LOGGER = Logger.getLogger(MIPApplication.class);
@Autowired
OAuth2ClientContext oauth2ClientContext;
......@@ -184,9 +169,9 @@ public class MIPApplication extends WebSecurityConfigurerAdapter {
cookie.setPath("/");
response.addCookie(cookie);
} catch (JsonProcessingException e) {
logger.trace(e);
LOGGER.trace(e);
} catch (UnsupportedEncodingException e) {
logger.trace(e);
LOGGER.trace(e);
}
return principal;
}
......@@ -277,8 +262,7 @@ public class MIPApplication extends WebSecurityConfigurerAdapter {
}
private CsrfTokenRepository csrfTokenRepository() {
HttpSessionCsrfTokenRepository repository = httpSessionCsrfTokenRepository;
return repository;
return httpSessionCsrfTokenRepository;
}
}
......
......@@ -33,7 +33,7 @@ import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
@Api(value = "/apps", description = "the apps API")
public class AppsApi {
private Logger logger = Logger.getLogger(this.getClass());
private static final Logger LOGGER = Logger.getLogger(AppsApi.class);
@Autowired
MIPApplication mipApplication;
......@@ -109,7 +109,7 @@ public class AppsApi {
}
catch (ConstraintViolationException cve)
{
logger.trace(cve);
LOGGER.trace(cve);
if(session.getTransaction() != null)
{
session.getTransaction().rollback();
......@@ -118,7 +118,7 @@ public class AppsApi {
}
catch (NonUniqueObjectException nuoe)
{
logger.trace(nuoe);
LOGGER.trace(nuoe);
if(session.getTransaction() != null)
{
session.getTransaction().rollback();
......
......@@ -32,7 +32,7 @@ import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
@Api(value = "/articles", description = "the articles API")
public class ArticlesApi {
private Logger logger = Logger.getLogger(this.getClass());
private static final Logger LOGGER = Logger.getLogger(ArticlesApi.class);
@Autowired
MIPApplication mipApplication;
......@@ -60,11 +60,6 @@ public class ArticlesApi {
else
{
queryString += " AND (status='published' or u.username= :username)";
if(team != null && team)
{
// TODO: decide if this is needed
//queryString += " AND u.team= :team";
}
}
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
......@@ -102,7 +97,7 @@ public class ArticlesApi {
User user = mipApplication.getUser();
article.setCreatedAt(new Date());
if (article.getStatus().equals("published")) {
if ("published".equals(article.getStatus())) {
article.setPublishedAt(new Date());
}
article.setCreatedBy(user);
......@@ -131,13 +126,7 @@ public class ArticlesApi {
}
} while(count > 0);
Slugify slg = null;
try {
slg = new Slugify();
} catch (IOException e) {
logger.trace(e);
}
String slug = slg != null ? slg.slugify(article.getTitle()) : "";
String slug = new Slugify().slugify(article.getTitle());
i = 0;
do {
......@@ -159,8 +148,9 @@ public class ArticlesApi {
session.save(article);
session.getTransaction().commit();
} catch (Exception e)
{
} catch (IOException e) {
LOGGER.trace(e);
} catch (Exception e) {
if(session.getTransaction() != null)
{
session.getTransaction().rollback();
......@@ -194,7 +184,7 @@ public class ArticlesApi {
session.getTransaction().commit();
if (!article.getStatus().equals("published") && !article.getCreatedBy().getUsername().equals(user.getUsername()))
if (!"published".equals(article.getStatus()) && !article.getCreatedBy().getUsername().equals(user.getUsername()))
{
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
......
......@@ -35,7 +35,7 @@ import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-01-07T07:38:20.227Z")
public class ExperimentApi {
private Logger logger = Logger.getLogger(this.getClass());
private static final Logger LOGGER = Logger.getLogger(ExperimentApi.class);
private static final String EXAREME_ALGO_JSON_FILE="data/exareme_algorithms.json";
......@@ -62,48 +62,25 @@ public class ExperimentApi {
// this runs in the background. For future optimization: use a thread pool
new Thread() {
@Override
public void run() {
try {
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
String query = experiment.computeQuery();
System.out.println("Running experiment: " + query);
// create query
try {
con.setRequestMethod("POST");
} catch (ProtocolException pe) { logger.trace(pe); } // ignore; won't happen
con.addRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Content-Length", Integer.toString(query.length()));
con.setFollowRedirects(true);
con.setReadTimeout(3600000); // 1 hour: 60*60*1000 ms
// write body of query
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.write(query.getBytes("UTF8"));
wr.flush();
wr.close();
// get response
InputStream stream = con.getResponseCode() < 400 ? con.getInputStream() : con.getErrorStream();
BufferedReader in = new BufferedReader(new InputStreamReader(stream));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine + '\n');
}
in.close();
HttpURLConnection con = createConnection(obj, query);
writeQueryBody(con, query);
String response = readResponse(con);
// write to experiment
experiment.setResult(response.toString().replace("\0", ""));
experiment.setResult(response.replace("\0", ""));
experiment.setHasError(con.getResponseCode() >= 400);
experiment.setHasServerError(con.getResponseCode() >= 500);
} catch (ProtocolException pe) {
LOGGER.trace(pe);
} catch (IOException ioe) {
// write error to
logger.trace(ioe);
logger.warn("Experiment failed to run properly !");
LOGGER.trace(ioe);
LOGGER.warn("Experiment failed to run properly !");
experiment.setHasError(true);
experiment.setHasServerError(true);
experiment.setResult(ioe.getMessage());
......@@ -126,6 +103,36 @@ public class ExperimentApi {
}.start();
}
private static String readResponse(HttpURLConnection con) throws IOException {
InputStream stream = con.getResponseCode() < 400 ? con.getInputStream() : con.getErrorStream();
BufferedReader in = new BufferedReader(new InputStreamReader(stream));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine + '\n');
}
in.close();
return response.toString();
}
private static void writeQueryBody(HttpURLConnection con, String query) throws IOException {
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.write(query.getBytes("UTF8"));
wr.flush();
wr.close();
}
private static HttpURLConnection createConnection(URL url, String query) throws IOException {
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.addRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Content-Length", Integer.toString(query.length()));
con.setInstanceFollowRedirects(true);
con.setReadTimeout(3600000); // 1 hour: 60*60*1000 ms
con.setDoOutput(true);
return con;
}
@ApiOperation(value = "Send a request to the workflow to run an experiment", response = Experiment.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Success") })
@RequestMapping(method = RequestMethod.POST)
......@@ -158,8 +165,8 @@ public class ExperimentApi {
{
transaction.rollback();
}
logger.trace(e);
logger.warn("Cannot create experiment to run ! This is probably caused by a bad request !");
LOGGER.trace(e);
LOGGER.warn("Cannot create experiment to run ! This is probably caused by a bad request !");
// 400 here probably
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
......@@ -173,7 +180,7 @@ public class ExperimentApi {
{
sendPost(experiment);
}
} catch (MalformedURLException mue) { logger.trace(mue.getMessage()); } // ignore
} catch (MalformedURLException mue) { LOGGER.trace(mue.getMessage()); } // ignore
return new ResponseEntity<>(gson.toJson(experiment), HttpStatus.OK);
}
......@@ -183,7 +190,7 @@ public class ExperimentApi {
Model model = experiment.getModel();
String algoCode = "WP_LINEAR_REGRESSION";
LinkedList<ExaremeQueryElement> queryElements = new LinkedList<>();
List<ExaremeQueryElement> queryElements = new LinkedList<>();
for (Variable var : model.getQuery().getVariables())
{
ExaremeQueryElement el = new ExaremeQueryElement();
......@@ -224,6 +231,7 @@ public class ExperimentApi {
String jsonQuery = new Gson().toJson(queryElements);
new Thread() {
@Override
public void run() {
try {
String url = miningExaremeQueryUrl + "/" + algoCode;
......@@ -239,8 +247,8 @@ public class ExperimentApi {
experiment.setResult("Unsupported variables !");
}
} catch (Exception e) {
logger.trace(e);
logger.warn("Failed to run Exareme algorithm !");
LOGGER.trace(e);
LOGGER.warn("Failed to run Exareme algorithm !");
experiment.setHasError(true);
experiment.setHasServerError(true);
experiment.setResult(e.getMessage());
......@@ -267,7 +275,7 @@ public class ExperimentApi {
new JsonParser().parse(test);
} catch (JsonParseException jpe)
{
logger.trace(jpe); // This is the normal behavior when the input string is not JSON-ified
LOGGER.trace(jpe); // This is the normal behavior when the input string is not JSON-ified
return false;
}
return true;
......@@ -276,7 +284,7 @@ public class ExperimentApi {
private boolean isExaremeAlgo(Experiment experiment) {
JsonArray algorithms = new JsonParser().parse(experiment.getAlgorithms()).getAsJsonArray();
String algoCode = algorithms.get(0).getAsJsonObject().get("code").getAsString();
return algoCode.equals("glm_exareme");
return "glm_exareme".equals(algoCode);
}
@ApiOperation(value = "get an experiment", response = Experiment.class)
......@@ -289,8 +297,8 @@ public class ExperimentApi {
try {
experimentUuid = UUID.fromString(uuid);
} catch (IllegalArgumentException iae) {
logger.trace(iae);
logger.warn("An invalid Experiment UUID was received !");
LOGGER.trace(iae);
LOGGER.warn("An invalid Experiment UUID was received !");
return ResponseEntity.badRequest().body("Invalid Experiment UUID");
}
......@@ -329,8 +337,8 @@ public class ExperimentApi {
try {
experimentUuid = UUID.fromString(uuid);
} catch (IllegalArgumentException iae) {
logger.trace(iae);
logger.warn("An invalid Experiment UUID was received !");
LOGGER.trace(iae);
LOGGER.warn("An invalid Experiment UUID was received !");
return ResponseEntity.badRequest().body("Invalid Experiment UUID");
}
......@@ -370,8 +378,8 @@ public class ExperimentApi {
try {
experimentUuid = UUID.fromString(uuid);
} catch (IllegalArgumentException iae) {
logger.trace(iae);
logger.warn("An invalid Experiment UUID was received !");
LOGGER.trace(iae);
LOGGER.warn("An invalid Experiment UUID was received !");
return ResponseEntity.badRequest().body("Invalid Experiment UUID");
}
......@@ -436,7 +444,7 @@ public class ExperimentApi {
baseQuery += mine ? "e.createdBy = :user" : "(e.createdBy = :user OR e.shared is true)";
if (modelSlug == null || modelSlug.equals("")) {
if (modelSlug == null || "".equals(modelSlug)) {
hibernateQuery = session.createQuery(baseQuery);
} else {
hibernateQuery = session.createQuery(baseQuery + " AND e.model.slug = :slug");
......@@ -489,7 +497,7 @@ public class ExperimentApi {
@ApiParam(value = "maxResultCount", required = false) @RequestParam("maxResultCount") int maxResultCount
) {
if (maxResultCount <= 0 && (modelSlug == null || modelSlug.equals(""))) {
if (maxResultCount <= 0 && (modelSlug == null || "".equals(modelSlug))) {
return new ResponseEntity<>("You must provide at least a slug or a limit of result", HttpStatus.BAD_REQUEST);
}
......@@ -499,7 +507,7 @@ public class ExperimentApi {
@ApiOperation(value = "List available methods and validations", response = String.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Success") })
@RequestMapping(path = "/methods", method = RequestMethod.GET)
public ResponseEntity<String> listAvailableMethodsAndValidations() throws Exception {
public ResponseEntity<String> listAvailableMethodsAndValidations() throws IOException {
StringBuilder response = new StringBuilder();
......
......@@ -29,7 +29,7 @@ import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-01-07T07:38:20.227Z")
public class ModelsApi {
private Logger logger = Logger.getLogger(this.getClass());
private static final Logger LOGGER = Logger.getLogger(ModelsApi.class);
@Autowired
MIPApplication mipApplication;
......@@ -60,11 +60,6 @@ public class ModelsApi {
else
{
queryString += " AND (m.valid=true or u.username= :username)";
if(team != null && team)
{
// TODO: decide if this is needed
//queryString += " AND u.team= :team";
}
}
queryString += " ORDER BY m.createdAt DESC";
......@@ -95,7 +90,7 @@ public class ModelsApi {
}
for(Model model:models){
String ds_code = model.getDataset().getCode();
String dsCode = model.getDataset().getCode();
session = HibernateUtil.getSessionFactory().getCurrentSession();
Dataset dataset = null;
......@@ -103,7 +98,7 @@ public class ModelsApi {
session.beginTransaction();
dataset = (Dataset) session
.createQuery("from Dataset where code= :code")
.setString("code", ds_code)
.setString("code", dsCode)
.uniqueResult();
session.getTransaction().commit();
} catch (Exception e)
......@@ -163,14 +158,7 @@ public class ModelsApi {
}
} while(count > 0);
Slugify slg = null;
String slug = "";
try {
slg = new Slugify();
slug = slg.slugify(model.getTitle());
} catch (IOException e) {
logger.trace(e);
}
String slug = new Slugify().slugify(model.getTitle());
i = 0;
do {
......@@ -196,6 +184,8 @@ public class ModelsApi {
session.save(model);
session.getTransaction().commit();
} catch (IOException e) {
LOGGER.trace(e);
} catch (Exception e)
{
if(session.getTransaction() != null)
......@@ -219,7 +209,6 @@ public class ModelsApi {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Model model = null;
Query query;
try {
session.beginTransaction();
......@@ -387,41 +376,7 @@ public class ModelsApi {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@ApiOperation(value = "Copy a model", response = Model.class)
@ApiResponses(value = { @ApiResponse(code = 201, message = "Model copied"), @ApiResponse(code = 404, message = "Not found") })
@RequestMapping(value = "/{slug}/copies", method = RequestMethod.POST)
public ResponseEntity<Model> copyAModel(
@ApiParam(value = "slug", required = true) @PathVariable("slug") String slug,
@RequestBody @ApiParam(value = "Model to update", required = true) Model model
) {
User user = mipApplication.getUser();
String originalSlug = model.getSlug();
String copySlug;
do {
copySlug = originalSlug+" copy_"+randomStr(20);
} while (getAModel(copySlug) == null);
model.setSlug(copySlug);
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
try{
session.beginTransaction();
session.save(model);
session.getTransaction().commit();
} catch (Exception e)
{
if(session.getTransaction() != null)
{
session.getTransaction().rollback();
throw e;
}
}
return new ResponseEntity<>(HttpStatus.CREATED).ok(model);
}
private String randomStr(int length) {
private static String randomStr(int length) {
char[] chars = "abcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
StringBuilder sb = new StringBuilder();
Random random = new Random();
......
......@@ -44,6 +44,9 @@ public class App {
public App() {
/*
* Empty constructor is needed by Hibernate
*/
}
......
......@@ -55,6 +55,9 @@ public class Article {
public Article() {
/*
* Empty constructor is needed by Hibernate
*/
}
......
......@@ -41,6 +41,9 @@ public class Config {
public Config() {
/*
* Empty constructor is needed by Hibernate
*/
}
......
......@@ -39,6 +39,9 @@ public class Dataset {
public Dataset() {
/*
* Empty constructor is needed by Hibernate
*/
}
......
......@@ -78,6 +78,9 @@ public class Experiment {
private boolean resultsViewed = false;
public Experiment() {
/*
* Empty constructor is needed by Hibernate
*/
}
public String computeQuery() {
......
......@@ -34,6 +34,9 @@ public class Filter {
public Filter() {
/*
* Empty constructor is needed by Hibernate
*/
}
......
......@@ -17,6 +17,9 @@ public class GeneralStats {
public GeneralStats() {
/*
* Empty constructor is needed by Hibernate
*/
}
......
......@@ -32,6 +32,9 @@ public class Group {
public Group() {
/*
* Empty constructor is needed by Hibernate
*/
}
......@@ -70,15 +73,4 @@ public class Group {
this.groups = groups;
}
public Group clone()
{
Group g = new Group();
g.setCode(this.getCode());
g.setLabel(this.getLabel());
g.setParent(this.getParent());
g.setGroups(this.getGroups());
return g;
}
}
......@@ -59,6 +59,9 @@ public class Model {
public Model() {
/*
* Empty constructor is needed by Hibernate
*/
}
......
......@@ -52,6 +52,9 @@ public class Query {
public Query() {
/*
* Empty constructor is needed by Hibernate
*/
}
......
......@@ -22,6 +22,9 @@ public class Tag {
public Tag() {
/*
* Empty constructor is needed by Hibernate
*/
}
......
......@@ -88,6 +88,9 @@ public class User {
public User() {
/*
* Empty constructor is needed by Hibernate
*/
}
......@@ -133,7 +136,7 @@ public class User {
p = Pattern.compile("title=([\\w ]+)");
m = p.matcher(userInfo);
if (m.find()) {
if (m.group(1).equals("Mr")) {
if ("Mr".equals(m.group(1))) {
this.gender = "Male";
} else {
this.gender = "Female";
......
......@@ -59,6 +59,9 @@ public class Variable {
public Variable() {
/*
* Empty constructor is needed by Hibernate
*/
}
......
......@@ -33,6 +33,9 @@ public class Vote {
public Vote() {
/*
* Empty constructor is needed by Hibernate
*/
}
......
......@@ -18,7 +18,11 @@ public class CORSFilter implements Filter {
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void init(FilterConfig filterConfig) {
/* Nothing to do */
}
public void destroy() {}
public void destroy() {
/* Nothing to do */
}
}
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment