/**
* MailArchiver is an application that provides services for storing and managing e-mail messages through a Web Services SOAP interface.
* Copyright (C) 2012 Marcio Andre Scholl Levien and Fernando Alberto Reuter Wendt and Jose Ronaldo Nogueira Fonseca Junior
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see .
*/
/******************************************************************************\
*
* This product was developed by
*
* SERVIÇO FEDERAL DE PROCESSAMENTO DE DADOS (SERPRO),
*
* a government company established under Brazilian law (5.615/70),
* at Department of Development of Porto Alegre.
*
\******************************************************************************/
package serpro.mailarchiver.util;
import com.ctc.wstx.stax.WstxOutputFactory;
import com.google.common.io.Files;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.StringTokenizer;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import org.codehaus.staxmate.SMOutputFactory;
import org.codehaus.staxmate.out.SMOutputDocument;
import org.codehaus.staxmate.out.SMOutputElement;
import serpro.mailarchiver.service.web.ServiceFault;
public class GearsUtil {
private static final String USER_LOG_FILENAME = "user_log_" +
new SimpleDateFormat("dd.MM.yy.HH.mm.ss").
format(new Date()) + ".log";
private static final String USER_LOG_FILEPATH = System.getProperty("user.home");
private static final Logger log = Logger.getLocalLogger();
// apenas concatena o nome do arquivo ao path independentemente de Os
public static String loadFilePaths(String pathGears, String fileName) {
final String fullPath = pathGears + File.separatorChar + fileName;
if(fullPath!=null){
File file = new File(fullPath);
if(file.exists() && !file.isDirectory()){
return fullPath;
}
} return null;
}
public static String loadParentFilePath(String fileName) {
File file = new File(fileName);
if(file.exists()){
if (file.isDirectory()) {
File[] lista = file.listFiles();
for (int i = 0; i < lista.length; i++) {
if(lista[i].getName().equalsIgnoreCase(fileName)){
return lista[i].getPath();
}else{
String result = loadFilePaths(lista[i].getPath(), fileName);
if (result != null){
return result;
}
}
}
}
}return null;
}
// extair as url da tabela entries refernte ao fonte da mensagem
public static String unserializeUrlEntries(String serializedMailString){
// System.out.println("GearsUtil.unserializeUrlEntries sendo executado... ");
log.debug("GearsUtil.unserializeUrlEntries sendo executado... ");
final String key = "url_export_file";
String result = null;
int index = serializedMailString.indexOf(key);
if(index!=-1){
StringTokenizer token = new StringTokenizer(serializedMailString.substring(index), ":", false);
while(token.hasMoreElements()){
String next = token.nextElement().toString();
if(next.contains(key)){
int numberChars = Integer.parseInt(token.nextElement().toString());
// para escapar as aspas duplas finais
numberChars++;
//começa no indice 1 para escapar as aspas duplas iniciais
result = token.nextElement().toString().substring(1, numberChars);
// System.out.println("url_export_file estraída..: " + result);
log.debug("url_export_file estraída..: " + result);
}
}
}
// System.out.println("GearsUtil.unserializeUrlEntries sendo finalizado... ");
log.debug("GearsUtil.unserializeUrlEntries sendo finalizado... ");
return result;
}
private static final String[] flagKeys = new String[]{"Importance", "Recent", "Unseen", "Answered", "Draft", "Deleted", "Flagged", "Forwarded" };
private static Set getUnserializeHeaderParameters(String serializedHeaderString, String unseen){
// System.out.println("GearsUtil.unserializeHeaderParameters sendo executado... ");
log.debug("GearsUtil.unserializeHeaderParameters sendo executado... ");
Set flags = new HashSet();
for(String key : flagKeys){
int index = serializedHeaderString.indexOf(key);
if(index!=-1){
StringTokenizer token = new StringTokenizer(serializedHeaderString.substring(index), ":", false);
while(token.hasMoreElements()){
String next = token.nextElement().toString();
String valueType = next.substring(next.length()-1);
if(next.contains(key)){
if(valueType.equalsIgnoreCase("s")){//flag do tipo String
// outros tipos de flags serão desconsiderados
int numberChars = Integer.parseInt(token.nextElement().toString());
// para escapar as aspas duplas finais
numberChars++;
String value = null;
try{
value = token.nextElement().toString().substring(1, numberChars);
}catch(StringIndexOutOfBoundsException ex){
log.error("Falha na extração de tags da mensagem de header..: " + serializedHeaderString, ex);
// return null;
}
if(value != null){
if(key.equalsIgnoreCase("unseen") && ((value.equalsIgnoreCase(" ") || value.equalsIgnoreCase("n")) && unseen.equals("0"))){
flags.add("seen");
} else if(key.equalsIgnoreCase("recent") && value.equalsIgnoreCase("n")){
flags.add("unseen");
} else if(key.equalsIgnoreCase("flagged") && value.equalsIgnoreCase("f")){
flags.add("flagged");
} else if(key.equalsIgnoreCase("importance") && value.equalsIgnoreCase("high")){
flags.add("importance_high");
} else if(key.equalsIgnoreCase("draft") && value.equalsIgnoreCase("x")){
flags.add("draft");
if(flags.contains("answered")){
flags.add("forwarded");
}
} else if(key.equalsIgnoreCase("answered") && value.equalsIgnoreCase("a")){
flags.add("answered");
if(flags.contains("draft")){
flags.add("forwarded");
}
} else if(key.equalsIgnoreCase("forwarded") && (value.equalsIgnoreCase("f")
|| flags.contains("answered") || flags.contains("draft"))){
flags.add("forwarded");
}
}
}break;
}
}
}
}
// System.out.println("GearsUtil.unserializeHeaderParameters sendo finalizado... ");
log.debug("GearsUtil.unserializeHeaderParameters sendo finalizado... ");
return flags;
}
public static String writeQueryConfigHeaders(String messageId, String serializedHeaderString, String unseen) throws ServiceFault{
// System.out.println("GearsUtil.writeQueryConfigHeaders sendo executado... ");
log.debug("GearsUtil.writeQueryConfigHeaders sendo executado... ");
String xml = null;
Set headerElements = getUnserializeHeaderParameters(serializedHeaderString, unseen);
if(headerElements != null && headerElements.size()>0){
XMLOutputFactory xmloutf = new WstxOutputFactory();
SMOutputFactory smoutf = new SMOutputFactory(xmloutf);
StringWriter strWriter = new StringWriter();
try {
SMOutputDocument document = smoutf.createOutputDocument(strWriter);
SMOutputElement tagElement = document.addElement("tag");
SMOutputElement messageElement = tagElement.addElement("message");
messageElement.addAttribute("id", messageId);
Iterator flags = headerElements.iterator();
while(flags.hasNext()){
SMOutputElement value = messageElement.addElement("add");
value.addAttribute("value", flags.next().toString());
}
document.closeRoot();
} catch (XMLStreamException ex) {
log.error("Falha na extração dos flags da mensagem lida da column mail.header - MessageId.: " + messageId + ex);
return null;
}
xml = strWriter.toString();
}
// System.out.println("GearsUtil.writeQueryConfigHeaders sendo finalizado... ");
log.debug("GearsUtil.writeQueryConfigHeaders sendo finalizado... ");
return xml;
}
// extair o fonte da mensagem via stream de leitura
// os dados lidos do arquivo serão empacotados em uma String
public static String getMessageRFC822(String messagePath){
// System.out.println("GearsUtil.getMessageRFC822 sendo executado... ");
log.debug("GearsUtil.getMessageRFC822 sendo executado... ");
String result = null;
try {
// System.out.println("Path da mensagem no filesystem..: " + messagePath);
log.debug("Path da mensagem no filesystem..: " + messagePath);
if(new File(messagePath).exists()){
// result = Files.toString(new File(messagePath), Charsets.Windows_1252);
result = Files.toString(new File(messagePath), Charsets.UTF_8);
}
}
catch (IOException ioex) {
log.error(ioex);
}
finally{
// System.out.println("GearsUtil.getMessageRFC822 sendo finalizado... ");
log.debug("GearsUtil.getMessageRFC822 sendo finalizado... ");
return result;
}
}
// inserir informações de mensagens não arquivadas em arquivo de log
public static void writeInUserLogFile(String messageError, Integer messageFails){
try {
String pathFile = USER_LOG_FILEPATH + File.separatorChar + USER_LOG_FILENAME;
FileWriter writer = null;
if(!new File(pathFile).exists()){
writer = new FileWriter(pathFile, true);
writer.write("Listagem de mensagens não arquivadas no MailArchiver");
}
if(writer==null){
writer = new FileWriter(pathFile, true);
}
writer.write("\n" + messageFails + " - " + messageError);
writer.close();
} catch (IOException ex) {
log.error(ex);
}
}
}