Skip to content

Commit

Permalink
Fixed more issues reported by SonarCloud [#354]
Browse files Browse the repository at this point in the history
 * Changed ComicFileUtils to a component.
  • Loading branch information
mcpierce committed May 9, 2021
1 parent ff217ba commit 9276e79
Show file tree
Hide file tree
Showing 20 changed files with 77 additions and 70 deletions.
Expand Up @@ -62,8 +62,9 @@ public abstract class AbstractArchiveAdaptor<I> implements ArchiveAdaptor, Initi
@Autowired protected FileTypeIdentifier fileTypeIdentifier;
@Autowired protected ComicInfoEntryAdaptor comicInfoEntryAdaptor;
@Autowired protected ComicFileHandler comicFileHandler;
protected List<EntryLoaderForType> loaders = new ArrayList<>();
@Autowired private ComicFileUtils comicFileUtils;

protected List<EntryLoaderForType> loaders = new ArrayList<>();
protected Map<String, EntryLoader> entryLoaders = new HashMap<>();
private Set<String> imageTypes = new HashSet<>();
private String defaultExtension;
Expand Down Expand Up @@ -260,7 +261,7 @@ public Comic saveComic(Comic source, boolean renamePages)
this.saveComicInternal(source, tempFilename, renamePages);

String filename =
ComicFileUtils.findAvailableFilename(
this.comicFileUtils.findAvailableFilename(
FilenameUtils.removeExtension(source.getFilename()), 0, this.defaultExtension);
var file1 = new File(tempFilename);
var file2 = new File(filename);
Expand Down
Expand Up @@ -145,7 +145,7 @@ public void loadComic(Comic comic, boolean ignoreComicInfoXml) throws ComicFileH
}

log.debug("Loading comic: " + comic.getFilename());
ArchiveAdaptor archiveAdaptor = this.getArchiveAdaptorFor(comic.getFilename());
var archiveAdaptor = this.getArchiveAdaptorFor(comic.getFilename());

try {
archiveAdaptor.loadComic(comic);
Expand Down Expand Up @@ -176,11 +176,11 @@ public void loadComicArchiveType(final Comic comic) throws ComicFileHandlerExcep

if (archiveMimeSubtype == null) throw new ComicFileHandlerException("Unknown comic type");

ArchiveType archiveType = this.archiveTypes.get(archiveMimeSubtype);
var archiveType = this.archiveTypes.get(archiveMimeSubtype);
log.debug("Archive type: {}", archiveType);
comic.setArchiveType(archiveType);

ArchiveAdaptor archiveAdaptor = this.archiveAdaptors.get(archiveMimeSubtype);
var archiveAdaptor = this.archiveAdaptors.get(archiveMimeSubtype);

if (archiveAdaptor == null)
throw new ComicFileHandlerException(
Expand Down
Expand Up @@ -58,7 +58,7 @@ public void loadContent(
final BufferedImage bimage = ImageIO.read(new ByteArrayInputStream(content));
final int width = bimage.getWidth();
final int height = bimage.getHeight();
Page page = new Page();
var page = new Page();
page.setFilename(filename);
page.setPageType(this.pageTypeRepository.getDefaultPageType());
page.setHash(hash);
Expand Down
Expand Up @@ -21,32 +21,48 @@
import java.io.File;
import java.text.MessageFormat;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

/**
* <code>ComicFileUtils</code> provides a set of utility methods related to comic files and
* filenames.
*
* @author Darryl L. Pierce
*/
@Component
@Log4j2
public class ComicFileUtils {
public static String findAvailableFilename(
String filename, int attempt, String defaultExtension) {
String candidate = filename;
/**
* Looks for the next available filename for a comic file.
*
* @param filename the root filename
* @param attempt the current attempt
* @param defaultExtension the extension for the file
* @return the filename to use
*/
public String findAvailableFilename(
final String filename, final int attempt, final String defaultExtension) {
String candidate = null;

if (attempt > 0) {
candidate = MessageFormat.format("{0}-{1}.{2}", filename, attempt, defaultExtension);
} else {
candidate = MessageFormat.format("{0}.{1}", filename, defaultExtension);
}

File file = new File(candidate);
var file = new File(candidate);
return (!file.exists())
? candidate
: findAvailableFilename(filename, ++attempt, defaultExtension);
: findAvailableFilename(filename, attempt + 1, defaultExtension);
}

public static boolean isComicFile(File file) {
/**
* Checks if the file is a comic file based on extension.
*
* @param file the file
* @return true if it's comic file
*/
public boolean isComicFile(File file) {
String name = file.getName().toUpperCase();
boolean result = (name.endsWith("CBZ") || name.endsWith("CBR") || name.endsWith("CB7"));
return result;
Expand Down
Expand Up @@ -22,7 +22,7 @@
@Log4j2
public class Utils {
public String createHash(byte[] bytes) {
StringBuilder result = new StringBuilder(convertToHexString(DigestUtils.md5Digest(bytes)));
var result = new StringBuilder(convertToHexString(DigestUtils.md5Digest(bytes)));
while (result.length() < 32) result = result.insert(0, "0");
return result.toString();
}
Expand Down
Expand Up @@ -68,7 +68,6 @@ public void testLoadJPGImage() throws IOException {

assertEquals(1, comic.getPageCount());
assertNotNull(comic.getPage(0));
// assertEquals(content, comic.getPage(0).getContent());
assertSame(pageType, comic.getPage(0).getPageType());
}

Expand All @@ -84,7 +83,6 @@ public void testLoadWebPImage() throws IOException {

assertEquals(1, comic.getPageCount());
assertNotNull(comic.getPage(0));
// assertEquals(content, comic.getPage(0).getContent());
assertSame(pageType, comic.getPage(0).getPageType());
}
}
Expand Up @@ -33,7 +33,7 @@ public class ComiXedApp implements CommandLineRunner {
public static final String FULL_NAME_AND_VERSION = FULL_NAME + " " + VERSION;

public static void main(String[] args) {
SpringApplication app = new SpringApplication(ComiXedApp.class);
var app = new SpringApplication(ComiXedApp.class);
app.run(args);
}

Expand Down
Expand Up @@ -76,7 +76,7 @@ public void afterPropertiesSet() throws Exception {
public void loadPlugins() throws PluginException {
log.debug("Clearing plugin list");
this.plugins.clear();
File pluginDirectory = new File(this.pluginLocation);
var pluginDirectory = new File(this.pluginLocation);
if (!pluginDirectory.exists()) {
log.debug("Plugin directory does not exist: {}", pluginDirectory.getAbsolutePath());
return;
Expand All @@ -87,7 +87,7 @@ public void loadPlugins() throws PluginException {
Collection<File> pluginFiles =
FileUtils.listFiles(pluginDirectory, new String[] {"cxp"}, false);
log.debug("Found {} file{} to process", pluginFiles.size(), pluginFiles.size() == 1 ? "" : "s");
int processed = 0;
var processed = 0;
for (File pluginFile : pluginFiles) {
try (InputStream input = new BufferedInputStream(new FileInputStream(pluginFile))) {
String fileType = this.fileTypeIdentifier.subtypeFor(input);
Expand Down Expand Up @@ -115,14 +115,14 @@ private void loadPluginDetails(File pluginFile) throws PluginException {
Map<String, byte[]> pluginEntries = new HashMap<>();

log.debug("opening archive");
try (ZipFile zipfile = new ZipFile(pluginFile); ) {
try (var zipfile = new ZipFile(pluginFile); ) {
log.debug("retrieving the list of archive entries");
Enumeration<ZipArchiveEntry> zipfileEntries = zipfile.getEntries();
while (zipfileEntries.hasMoreElements()) {
ZipArchiveEntry zipfileEntry = zipfileEntries.nextElement();
String filename = zipfileEntry.getName();
long filesize = zipfileEntry.getSize();
byte[] content = new byte[(int) filesize];
var content = new byte[(int) filesize];
log.debug("Loading plugin file: {} ({} bytes)", filename, filesize);
IOUtils.readFully(zipfile.getInputStream(zipfileEntry), content);
pluginEntries.put(filename, content);
Expand All @@ -132,7 +132,7 @@ private void loadPluginDetails(File pluginFile) throws PluginException {
}

log.debug("storing plugin details");
Plugin plugin = this.pluginObjectFactory.getObject();
var plugin = this.pluginObjectFactory.getObject();
plugin.setEntries(pluginEntries);
if (this.plugins.containsKey(plugin.getName()))
throw new PluginException("plugin already exists with name: " + plugin.getName());
Expand Down
Expand Up @@ -59,7 +59,7 @@ public List<PluginInterpreterEntry> getRuntime() {
public void afterPropertiesSet() throws Exception {
this.interpreters.clear();
log.debug("Loading plugin languages");
for (int index = 0; index < this.runtimes.size(); index++) {
for (var index = 0; index < this.runtimes.size(); index++) {
PluginInterpreterEntry entry = this.runtimes.get(index);

if (entry.isValid()) {
Expand Down
Expand Up @@ -59,14 +59,14 @@ public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
Throwable error = null;
Object response = null;

final Date started = new Date();
final var started = new Date();
try {
response = joinPoint.proceed();
} catch (Throwable throwable) {
error = throwable;
}
final Date ended = new Date();
final WebAuditLogEntry entry = new WebAuditLogEntry();
final var ended = new Date();
final var entry = new WebAuditLogEntry();
HttpServletRequest request =
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();

Expand All @@ -90,8 +90,8 @@ public Object around(ProceedingJoinPoint joinPoint) throws Throwable {

if (error != null) {
log.debug("Storing method exception stacktrace");
final StringWriter stringWriter = new StringWriter();
final PrintWriter printWriter = new PrintWriter(stringWriter);
final var stringWriter = new StringWriter();
final var printWriter = new PrintWriter(stringWriter);
error.printStackTrace(printWriter);
entry.setException(stringWriter.toString());
entry.setSuccessful(false);
Expand Down
Expand Up @@ -41,7 +41,7 @@ public void doFilter(
ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest currentRequest = (HttpServletRequest) servletRequest;
ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(currentRequest);
var wrappedRequest = new ContentCachingRequestWrapper(currentRequest);

chain.doFilter(wrappedRequest, servletResponse);
}
Expand Down
Expand Up @@ -31,7 +31,6 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
Expand Down Expand Up @@ -71,7 +70,7 @@ protected void doFilterInternal(
} else if (StringUtils.startsWith(header, BASIC_PREFIX)) {
String base64Credentials = header.substring(BASIC_PREFIX.length()).trim();
byte[] credDecoded = Base64.getDecoder().decode(base64Credentials);
String credentials = new String(credDecoded, StandardCharsets.UTF_8);
var credentials = new String(credDecoded, StandardCharsets.UTF_8);

String[] userDetails = credentials.split(":", 2);
if (!userDetails[0].equals(USER_PREFIX)) {
Expand All @@ -84,11 +83,11 @@ protected void doFilterInternal(
if (!StringUtils.isEmpty(username)
&& (SecurityContextHolder.getContext().getAuthentication() == null)) {

UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
var userDetails = this.userDetailsService.loadUserByUsername(username);

if (userDetails.getPassword().equals(password)
|| this.jwtTokenUtil.validateToken(authToken, userDetails)) {
UsernamePasswordAuthenticationToken authentication =
var authentication =
new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
Expand Down
Expand Up @@ -51,7 +51,7 @@ public class ComiXedAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String email = authentication.getName();
String password = authentication.getCredentials().toString();
var password = authentication.getCredentials().toString();

log.debug("Attempting to authenticate: email={}", email);

Expand Down
Expand Up @@ -56,8 +56,8 @@ public UserDetails loadUserByUsername(String email) throws UsernameNotFoundExcep
UserBuilder result = User.withUsername(email);

result.password(user.getPasswordHash());
String[] roles = new String[user.getRoles().size()];
for (int index = 0; index < user.getRoles().size(); index++) {
var roles = new String[user.getRoles().size()];
for (var index = 0; index < user.getRoles().size(); index++) {
roles[index] = user.getRoles().get(index).getName();
}
result.roles(roles);
Expand Down
Expand Up @@ -58,7 +58,7 @@ public Date getExpirationDateFromToken(String token) {
}

public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
final Claims claims = getAllClaimsFromToken(token);
final var claims = getAllClaimsFromToken(token);
return claimsResolver.apply(claims);
}

Expand All @@ -67,7 +67,7 @@ private Claims getAllClaimsFromToken(String token) {
}

private Boolean isTokenExpired(String token) {
final Date expiration = getExpirationDateFromToken(token);
final var expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
}

Expand All @@ -77,7 +77,7 @@ public String generateToken(ComiXedUser user) {

String doGenerateToken(String email) {

Claims claims = Jwts.claims().setSubject(email);
var claims = Jwts.claims().setSubject(email);
List<GrantedAuthority> authorities = new ArrayList<>();
try {
ComiXedUser user = this.userService.findByEmail(email);
Expand Down
Expand Up @@ -19,23 +19,19 @@
package org.comixedproject.controller.file;

import com.fasterxml.jackson.annotation.JsonView;
import java.io.File;
import java.io.IOException;
import java.util.List;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.IOUtils;
import org.comixedproject.adaptors.archive.ArchiveAdaptorException;
import org.comixedproject.auditlog.AuditableEndpoint;
import org.comixedproject.handlers.ComicFileHandlerException;
import org.comixedproject.model.file.ComicFile;
import org.comixedproject.model.net.GetAllComicsUnderRequest;
import org.comixedproject.model.net.ImportComicFilesRequest;
import org.comixedproject.model.net.comicfiles.LoadComicFilesResponse;
import org.comixedproject.service.comic.ComicService;
import org.comixedproject.service.file.FileService;
import org.comixedproject.task.QueueComicsTask;
import org.comixedproject.task.runner.TaskManager;
import org.comixedproject.utils.ComicFileUtils;
import org.comixedproject.views.View;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
Expand All @@ -53,7 +49,6 @@
@RequestMapping("/api/files")
@Log4j2
public class FileController {
@Autowired private ComicService comicService;
@Autowired private FileService fileService;
@Autowired private TaskManager taskManager;
@Autowired private ObjectFactory<QueueComicsTask> queueComicsWorkerTaskObjectFactory;
Expand Down Expand Up @@ -88,22 +83,6 @@ public LoadComicFilesResponse loadComicFiles(
return new LoadComicFilesResponse(this.fileService.getAllComicsUnder(directory, maximum));
}

private void getAllFilesUnder(File root, List<ComicFile> result) throws IOException {
for (File file : root.listFiles()) {
if (file.isDirectory()) {
log.debug("Searching directory: " + file.getAbsolutePath());
this.getAllFilesUnder(file, result);
} else {

if (ComicFileUtils.isComicFile(file)
&& (this.comicService.findByFilename(file.getCanonicalPath()) == null)) {
log.debug("Adding file: " + file.getCanonicalPath());
result.add(new ComicFile(file.getCanonicalPath(), file.length()));
}
}
}
}

/**
* Returns the content for the first image in the specified file.
*
Expand Down
Expand Up @@ -53,7 +53,6 @@ public class FileControllerTest {
private static final byte[] IMAGE_CONTENT = new byte[65535];
private static final String TEST_DIRECTORY = "src/test";
private static final List<String> TEST_FILENAMES = new ArrayList<>();
private static final int TEST_IMPORT_STATUS = 129;
private static final Integer TEST_LIMIT = RANDOM.nextInt();
private static final Integer TEST_NO_LIMIT = -1;
private static final boolean TEST_DELETE_BLOCKED_PAGES = RANDOM.nextBoolean();
Expand All @@ -73,6 +72,19 @@ public class FileControllerTest {
@Mock private QueueComicsTask queueComicsWorkerTask;
@Mock private TaskManager taskManager;

@Test
public void testGetImportFileCoverServiceThrowsException()
throws ArchiveAdaptorException, ComicFileHandlerException {
Mockito.when(fileService.getImportFileCover(Mockito.anyString()))
.thenThrow(ComicFileHandlerException.class);

final byte[] result = controller.getImportFileCover(COMIC_ARCHIVE);

assertNotNull(result);

Mockito.verify(fileService, Mockito.times(1)).getImportFileCover(COMIC_ARCHIVE);
}

@Test
public void testGetImportFileCover() throws ArchiveAdaptorException, ComicFileHandlerException {
Mockito.when(fileService.getImportFileCover(Mockito.anyString())).thenReturn(IMAGE_CONTENT);
Expand Down

0 comments on commit 9276e79

Please sign in to comment.