/*
Copyright 2006 - 2011 Under Dusken
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 no.dusken.aranea.admin.control.issue;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
import no.dusken.aranea.model.Issue;
import no.dusken.aranea.model.IssuePage;
import no.dusken.aranea.service.IssueService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.inject.Inject;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
/**
* @author Marvin B. Lillehaug <lillehau@underdusken.no>
*/
@Component
public class IssueIndexer {
private Logger logger = LoggerFactory.getLogger(IssueIndexer.class);
@Inject
private File pdfDirectory;
@Inject
private IssueService issueService;
public void tryToIndexIssue(Issue issue) {
try {
indexIssue(issue);
} catch (Exception exception) {
logger.error("Unable to index issue " + issue, exception);
}
}
private void indexIssue(Issue issue) throws IOException {
if (pagesNotPreviouslyStored(issue)) {
File pdfFile = getPdfFile(issue);
if (pdfFile.exists()) {
PdfReader pdfReader = new PdfReader(new FileInputStream(pdfFile));
addPagesToIssue(pdfReader, issue);
}
}
}
private void addPagesToIssue(PdfReader pdfReader, Issue issue) throws IOException {
for (int pageNumber = 1; pageNumber <= pdfReader.getNumberOfPages(); pageNumber++) {
addPageToIssue(pageNumber, pdfReader, issue);
}
}
private void addPageToIssue(int pageNumber, PdfReader pdfReader, Issue issue) throws IOException {
IssuePage issuePage = getIssuePage(pageNumber, pdfReader, issue);
issue.addIssuePage(issuePage);
}
private IssuePage getIssuePage(int pageNumber, PdfReader pdfReader, Issue issue) throws IOException {
String textInPage = PdfTextExtractor.getTextFromPage(pdfReader, pageNumber);
return new IssuePage(pageNumber, textInPage, issue);
}
private boolean pagesNotPreviouslyStored(Issue issue) {
return !issue.hasPdfPages();
}
private File getPdfFile(Issue issue) {
return new File(pdfDirectory, issue.getRelativePdfFilePath());
}
}