Skip to content

Commit bfa670a

Browse files
committed
Fixed code smells
1 parent 07cef63 commit bfa670a

File tree

26 files changed

+558
-158
lines changed

26 files changed

+558
-158
lines changed

logicaldoc-core/src/main/java/com/logicaldoc/core/automation/Automation.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -302,7 +302,7 @@ private void forbidRuntimeUsage(String expression) throws ForbiddenCodeException
302302
} else {
303303
Pattern runtimePattern = Pattern.compile("\\.\\s*(getRuntime|runtime)", Pattern.DOTALL);
304304
Matcher m = runtimePattern.matcher(expression);
305-
while (m.find()) {
305+
if (m.find()) {
306306
String snippet = expression.substring(Math.max(0, m.start() - 50),
307307
Math.min(expression.length() - 1, m.end() + 50));
308308
log.error("Detected possible suspicious access to java.lang.Runtime: {}", snippet);

logicaldoc-core/src/main/java/com/logicaldoc/core/communication/EMailSender.java

Lines changed: 48 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -333,29 +333,47 @@ public void send(EMail email) throws MessagingException {
333333
/*
334334
* If we have to images, the parts must be 'related' otherwise 'mixed'
335335
*/
336-
Multipart mpMessage = new MimeMultipart(email.getImages().isEmpty() ? "mixed" : "related");
336+
Multipart multipartMessage = new MimeMultipart(email.getImages().isEmpty() ? "mixed" : "related");
337337

338338
if (StringUtils.isNotEmpty(email.getMessageText())) {
339339
MimeBodyPart body = buildBodyPart(email);
340-
mpMessage.addBodyPart(body);
340+
multipartMessage.addBodyPart(body);
341341
}
342342

343-
int i = 1;
344-
for (String image : email.getImages()) {
345-
MimeBodyPart imageBodyPart = new MimeBodyPart();
343+
includeImages(email, multipartMessage);
346344

347-
try {
348-
DataSource ds = new URLDataSource(UrlUtil.toURL(image));
349-
imageBodyPart.setDataHandler(new DataHandler(ds));
350-
} catch (MalformedURLException | URISyntaxException e) {
345+
includeAttachments(email, multipartMessage);
346+
347+
message.setContent(multipartMessage);
348+
349+
MailDateFormat formatter = new MailDateFormat();
350+
formatter.setTimeZone(TimeZone.getTimeZone("GMT")); // always use UTC
351+
// for outgoing mail
352+
Date now = new Date();
353+
message.setHeader("Date", formatter.format(now));
354+
355+
if (!Context.get().getProperties().getBoolean("smtp.nosend", false)) {
356+
try (Transport transport = buildTransport(session);) {
357+
transport.sendMessage(message, message.getAllRecipients());
358+
} catch (IOException e) {
351359
throw new MessagingException(e.getMessage(), e);
352360
}
353361

354-
imageBodyPart.setHeader("Content-ID", "<image_" + (i++) + ">");
355-
imageBodyPart.setDisposition("inline");
356-
mpMessage.addBodyPart(imageBodyPart);
362+
log.info("Sent email with subject '{}' to recipients {}", email.getSubject(),
363+
email.getAllRecipientsEmails());
364+
} else {
365+
log.info("Email with subject '{}' not sent because of the config parameter smtp.nosend",
366+
email.getSubject());
357367
}
358368

369+
/*
370+
* If the case, we save the email as document in LogicalDOC's repository
371+
*/
372+
email.setSentDate(now);
373+
historycizeOutgoingEmail(email, message, from);
374+
}
375+
376+
private void includeAttachments(EMail email, Multipart multipartMessage) throws MessagingException {
359377
for (Integer partId : email.getAttachments().keySet()) {
360378
EMailAttachment att = email.getAttachment(partId);
361379
String mime = detectMimeType(att);
@@ -370,48 +388,40 @@ public void send(EMail email) throws MessagingException {
370388
throw new MessagingException(e.getMessage(), e);
371389
}
372390

373-
if (StringUtils.isNotEmpty(att.getDisposition()))
374-
if ("remove".equals(att.getDisposition()))
391+
if (StringUtils.isNotEmpty(att.getDisposition())) {
392+
if ("remove".equals(att.getDisposition())) {
375393
part.removeHeader("Content-Disposition");
376-
else
394+
} else {
377395
part.setDisposition(att.getDisposition());
396+
}
397+
}
378398

379399
if (StringUtils.isNotEmpty(att.getContentType()))
380400
part.setHeader("Content-Type", att.getContentType());
381401

382402
if (StringUtils.isNotEmpty(att.getContentEncoding()))
383403
part.setHeader("Content-Transfer-Encoding", att.getContentEncoding());
384404

385-
mpMessage.addBodyPart(part);
405+
multipartMessage.addBodyPart(part);
386406
}
407+
}
387408

388-
message.setContent(mpMessage);
389-
390-
MailDateFormat formatter = new MailDateFormat();
391-
formatter.setTimeZone(TimeZone.getTimeZone("GMT")); // always use UTC
392-
// for outgoing mail
393-
Date now = new Date();
394-
message.setHeader("Date", formatter.format(now));
409+
private void includeImages(EMail email, Multipart multipartMessage) throws MessagingException {
410+
int i = 1;
411+
for (String image : email.getImages()) {
412+
MimeBodyPart imageBodyPart = new MimeBodyPart();
395413

396-
if (!Context.get().getProperties().getBoolean("smtp.nosend", false)) {
397-
try (Transport transport = buildTransport(session);) {
398-
transport.sendMessage(message, message.getAllRecipients());
399-
} catch (IOException e) {
414+
try {
415+
DataSource ds = new URLDataSource(UrlUtil.toURL(image));
416+
imageBodyPart.setDataHandler(new DataHandler(ds));
417+
} catch (MalformedURLException | URISyntaxException e) {
400418
throw new MessagingException(e.getMessage(), e);
401419
}
402420

403-
log.info("Sent email with subject '{}' to recipients {}", email.getSubject(),
404-
email.getAllRecipientsEmails());
405-
} else {
406-
log.info("Email with subject '{}' not sent because of the config parameter smtp.nosend",
407-
email.getSubject());
421+
imageBodyPart.setHeader("Content-ID", "<image_" + (i++) + ">");
422+
imageBodyPart.setDisposition("inline");
423+
multipartMessage.addBodyPart(imageBodyPart);
408424
}
409-
410-
/*
411-
* If the case, we save the email as document in LogicalDOC's repository
412-
*/
413-
email.setSentDate(now);
414-
historycizeOutgoingEmail(email, message, from);
415425
}
416426

417427
protected InternetAddress prepareFrom(EMail email) throws AddressException {

logicaldoc-core/src/main/java/com/logicaldoc/core/parser/AbiWordParser.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ public String getContent() {
5050
String tmp = content.toString();
5151
if (tmp != null && tmp.length() > 0) {
5252
// Clean all the unwanted characters
53-
tmp = tmp.replaceAll("[<>\"“�`]", "");
53+
tmp = tmp.replaceAll("[<>\"]", "");
5454
}
5555
return tmp;
5656
}

logicaldoc-core/src/main/java/com/logicaldoc/core/searchengine/saved/HibernateSearchDAO.java

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,20 +19,22 @@
1919
*/
2020
public class HibernateSearchDAO extends HibernatePersistentObjectDAO<SavedSearch> implements SearchDAO {
2121

22+
private static final String USERID = "userId";
23+
2224
private HibernateSearchDAO() {
2325
super(SavedSearch.class);
2426
super.log = LoggerFactory.getLogger(HibernateSearchDAO.class);
2527
}
2628

2729
@Override
2830
public List<SavedSearch> findByUserId(long userId) throws PersistenceException {
29-
return findByWhere(ENTITY + ".userId = :userId", Map.of("userId", userId), ENTITY + ".name asc", null);
31+
return findByWhere(ENTITY + ".userId = :userId", Map.of(USERID, userId), ENTITY + ".name asc", null);
3032
}
3133

3234
@Override
3335
public SavedSearch findByUserIdAndName(long userId, String name) throws PersistenceException {
3436
List<SavedSearch> searches = findByWhere(ENTITY + ".userId = :userId and " + ENTITY + ".name = :name",
35-
Map.of("userId", userId, "name", name), null, null);
37+
Map.of(USERID, userId, "name", name), null, null);
3638
if (searches.isEmpty())
3739
return null;
3840
else
@@ -74,7 +76,7 @@ private void setUniqueName(SavedSearch search) {
7476

7577
// Execute the query to populate the sets
7678
try {
77-
SqlRowSet rs = queryForRowSet(query.toString(), Map.of("userId", search.getUserId(), "baseName",
79+
SqlRowSet rs = queryForRowSet(query.toString(), Map.of(USERID, search.getUserId(), "baseName",
7880
baseName.toLowerCase() + "%", "id", search.getId()), null);
7981
if (rs != null)
8082
while (rs.next()) {

logicaldoc-core/src/main/java/com/logicaldoc/core/security/Device.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,9 +80,9 @@ public Device() {
8080
* @param request the current request
8181
*/
8282
public Device(HttpServletRequest request) {
83-
UserAgent agent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
84-
8583
setDeviceId(getDeviceId(request));
84+
85+
UserAgent agent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
8686
setBrowser(agent.getBrowser().getName());
8787

8888
if (agent.getBrowserVersion() != null)

logicaldoc-core/src/main/java/com/logicaldoc/core/security/HibernateDeviceDAO.java

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -123,11 +123,7 @@ public boolean isTrustedDevice(String username, HttpServletRequest request) thro
123123
return false;
124124

125125
List<Device> trustedDevices = findTrustedDevices(user.getId());
126-
for (Device device : trustedDevices)
127-
if (device.equals(requestDevice))
128-
return true;
129-
130-
return false;
126+
return trustedDevices.stream().anyMatch(d -> d.getDeviceId().equals(requestDevice.getDeviceId()));
131127
}
132128

133129
@Override

logicaldoc-core/src/main/java/com/logicaldoc/core/security/SessionManager.java

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.logicaldoc.core.security;
22

33
import java.nio.charset.StandardCharsets;
4+
import java.security.NoSuchAlgorithmException;
45
import java.text.DateFormat;
56
import java.text.SimpleDateFormat;
67
import java.util.ArrayList;
@@ -33,6 +34,7 @@
3334
import com.logicaldoc.core.security.user.User;
3435
import com.logicaldoc.core.security.user.UserDAO;
3536
import com.logicaldoc.util.Context;
37+
import com.logicaldoc.util.crypt.CryptUtil;
3638
import com.logicaldoc.util.sql.SqlUtil;
3739

3840
/**
@@ -466,11 +468,36 @@ public String getSessionId(HttpServletRequest request) {
466468
if (auth instanceof LDAuthenticationToken ldAuthenticationToken)
467469
return ldAuthenticationToken.getSid();
468470

469-
if (request != null && Context.get().getProperties().getBoolean("security.useclientid", true)) {
470-
Client client = buildClient(request);
471-
Session session = getByClientId(client.getId());
472-
if (session != null && isOpen(session.getSid()))
473-
return session.getSid();
471+
return getSessionIdFromClient(request);
472+
}
473+
474+
private String getSessionIdFromClient(HttpServletRequest request) {
475+
if (request == null || !Context.get().getProperties().getBoolean("security.useclientid", false))
476+
return null;
477+
478+
Client client = buildClient(request);
479+
Session session = getByClientId(client.getId());
480+
481+
/*
482+
* In case of ClienID match, we must check the session provides Basic
483+
* Authentication and refers to the same username
484+
*/
485+
if (session != null && isOpen(session.getSid()) && session.getUsername().equals(client.getUsername())) {
486+
String[] credentials = getBasicCredentials(request);
487+
if (credentials.length == 2) {
488+
try {
489+
/*
490+
* In case the current user has defined a password, also
491+
* check it matches with the basic authentication
492+
*/
493+
final String sessionUserPassword = session.getUser().getPassword();
494+
if (StringUtils.isEmpty(sessionUserPassword)
495+
|| CryptUtil.encryptSHA256(credentials[1]).equals(sessionUserPassword))
496+
return session.getSid();
497+
} catch (NoSuchAlgorithmException e) {
498+
log.error("Unable to check credentials", e);
499+
}
500+
}
474501
}
475502

476503
return null;
@@ -488,13 +515,13 @@ else if (StringUtils.isNotEmpty(request.getHeader(PARAM_SID)))
488515
sid = request.getHeader(PARAM_SID);
489516
else if (request.getAttribute(PARAM_SID) != null
490517
&& StringUtils.isNotEmpty((String) request.getAttribute(PARAM_SID)))
491-
sid = (String) request.getAttribute(PARAM_SID);
518+
sid = (String) request.getAttribute(PARAM_SID);
492519
else if (request.getSession(true).getAttribute(PARAM_SID) != null
493520
&& StringUtils.isNotEmpty((String) request.getSession(true).getAttribute(PARAM_SID)))
494521
sid = (String) request.getSession(true).getAttribute(PARAM_SID);
495-
else
522+
else
496523
sid = getSessionIdFromCookie(request);
497-
524+
498525
return sid;
499526
}
500527

logicaldoc-core/src/main/java/com/logicaldoc/core/sequence/HibernateSequenceDAO.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
*/
2121
public class HibernateSequenceDAO extends HibernatePersistentObjectDAO<Sequence> implements SequenceDAO {
2222

23+
private static final String TENANTID = "tenantId";
2324
private static final String AND = " and ";
2425

2526
private HibernateSequenceDAO() {
@@ -88,7 +89,7 @@ public List<Sequence> findByName(String name, long tenantId) {
8889
String query = " " + ENTITY + ".tenantId = :tenantId " + AND + ENTITY + ".name like :name ";
8990

9091
try {
91-
return findByWhere(query, Map.of("tenantId", tenantId, "name", name + "%"), null, null);
92+
return findByWhere(query, Map.of(TENANTID, tenantId, "name", name + "%"), null, null);
9293
} catch (PersistenceException e) {
9394
log.error(e.getMessage(), e);
9495
return new ArrayList<>();
@@ -126,7 +127,7 @@ private Sequence findSequence(String sequenceName, long objectId, long tenantId,
126127
String query = "select ld_id from ld_sequence where ld_name = :name and ld_objectid = :objectId and ld_tenantid = :tenantId";
127128
try {
128129
long sequenceId = queryForLong(query,
129-
Map.of("tenantId", tenantId, "objectId", objectId, "name", sequenceName));
130+
Map.of(TENANTID, tenantId, "objectId", objectId, "name", sequenceName));
130131
if (sequenceId != 0L)
131132
sequence = findById(sequenceId);
132133
} catch (Exception t) {
@@ -142,7 +143,7 @@ private List<Sequence> findSequences(String sequenceName, long objectId, long te
142143
query += AND + ENTITY + ".objectId = :objectId ";
143144
query += AND + ENTITY + ".name = :name ";
144145

145-
sequences = findByWhere(query, Map.of("tenantId", tenantId, "objectId", objectId, "name", sequenceName),
146+
sequences = findByWhere(query, Map.of(TENANTID, tenantId, "objectId", objectId, "name", sequenceName),
146147
null, null);
147148
} catch (Exception t) {
148149
// Nothing to do

logicaldoc-core/src/main/java/com/logicaldoc/core/task/DefaultSchedulerFactory.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ public Scheduler getObject() {
4545
return super.getObject();
4646
else {
4747
log.debug(ASPECT_DISABLED);
48-
return null;
48+
return new DummyScheduler();
4949
}
5050
}
5151

0 commit comments

Comments
 (0)