error after committing code in git (jsp+servlets) - java

I have a java web project (jsp + servlets) that the local code works the property registry, if I commit to git and then give a git pull or git clone the property registry stops working, but none appear error, it simply does not record the data and only returns to the success page, this problem only occurs when I try to commit this version.
I tried to create a new repository and upload it as a new project but the problem continues
this is the DAO class
public boolean cadastrar(Imovel imovel) throws SQLException {
Connection connection = ConnectionFactory.getConexao();
//Endereço
String INSERTIMOVEL = "INSERT INTO Imovel VALUES (DEFAULT,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
String INSERTENDERECO = "INSERT INTO Endereco VALUES (DEFAULT,?,?,?,?,?,?,?)";
smt = connection.prepareStatement(INSERTENDERECO, Statement.RETURN_GENERATED_KEYS);
smt.setString(1, imovel.getEndereco().getLogradouro());
smt.setString(2, imovel.getEndereco().getComplemento());
smt.setInt(3, imovel.getEndereco().getNumero());
smt.setString(4, imovel.getEndereco().getCidade());
smt.setString(5, imovel.getEndereco().getCep());
smt.setString(6, imovel.getEndereco().getBairro());
smt.setString(7, imovel.getEndereco().getEstado());
smt.execute();
rs = smt.getGeneratedKeys();
rs.next();
//imovel
smt = connection.prepareStatement(INSERTIMOVEL);
smt.setString(1, imovel.getTitulo());
smt.setString(2, imovel.getDescricao());
smt.setString(3, "Em Análise");
smt.setString(4, "Ativo");
smt.setDouble(5, imovel.getValor());
smt.setDouble(6, imovel.getArea_total());
smt.setDouble(7, imovel.getArea_edificada());
smt.setInt(8, imovel.getComodos());
smt.setInt(9, imovel.getVagas_garagem());
smt.setInt(10, imovel.getBanheiros());
smt.setTimestamp(11, timestamp);
smt.setString(12, imovel.getDiretorio_imagem());
smt.setString(13, imovel.getTipo_imovel());
smt.setInt(14, imovel.getUsuario().getId_usuario());
smt.setInt(15, rs.getInt(1));
boolean rowInserted = smt.executeUpdate() > 0;
rs.close();
smt.close();
connection.close();
return rowInserted;
}
and this is the controller (i use command and factory patterns)
#Override
public String executar(HttpServletRequest request, HttpServletResponse response) {
try {
HttpSession usuarioLogado = request.getSession();
Sessao sessao = (Sessao) usuarioLogado.getAttribute("usuarioLogado");
Part filePart = request.getPart("uploadFile"); //
String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); //
InputStream fileContent = filePart.getInputStream();
imovel.setDiretorio_imagem(sessao.getId_usuario() + File.separator + fileName);
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = fileContent.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
byte[] bytes = os.toByteArray();
// cria o diretorio de upload
// esse caminho e relativo ao diretorio da aplicacao
ServletContext context = request.getServletContext();
String uploadPath = context.getRealPath("/") + "Resources\\upload" + File.separator + sessao.getId_usuario();
// caso o diretorio nao exista o bloco abaixo cria o mesmo
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
//converte o array de bytes em file e grava no diretorio
File f = new File(uploadPath + File.separator + fileName);
try (FileOutputStream fos = new FileOutputStream(f)) {
fos.write(bytes);
}
//Imovel Requests
String titulo = request.getParameter("titulo");
String descricao = request.getParameter("descricao");
int comodos = Integer.parseInt(request.getParameter("comodos"));
int banheiro = Integer.parseInt(request.getParameter("banheiro"));
int garagem = Integer.parseInt(request.getParameter("garagem"));
Double valor = Double.parseDouble(request.getParameter("valorimovel"));
Double areatotal = Double.parseDouble(request.getParameter("areatotal"));
Double areaedificada = Double.parseDouble(request.getParameter("areaedificada"));
String tpimovel = request.getParameter("tpimovel");
imovel.setTitulo(titulo);
imovel.setDescricao(descricao);
imovel.setComodos(comodos);
imovel.setBanheiros(banheiro);
imovel.setVagas_garagem(garagem);
imovel.setValor(valor);
imovel.setArea_total(areatotal);
imovel.setArea_edificada(areaedificada);
imovel.setTipo_imovel(tpimovel);
imovel.getUsuario().setId_usuario(sessao.getId_usuario());
//Endereço Requests
String logradouro = request.getParameter("logradouro");
int numero = Integer.parseInt(request.getParameter("numero"));
String complemento = request.getParameter("complemento");
String cidade = request.getParameter("cidade");
String estado = request.getParameter("estado");
String cep = request.getParameter("cep");
String bairro = request.getParameter("bairro");
//Endereço Set's
imovel.getEndereco().setLogradouro(logradouro);
imovel.getEndereco().setNumero(numero);
imovel.getEndereco().setComplemento(complemento);
imovel.getEndereco().setCidade(cidade);
imovel.getEndereco().setEstado(estado);
imovel.getEndereco().setCep(cep);
imovel.getEndereco().setBairro(bairro);
ImovelDAO dao = new ImovelDAO();
if (dao.cadastrar(imovel)) {
request.setAttribute("msg", "Seu imóvel foi cadastrado e passará por uma análise, fique de olho no seu email!");
return "index.jsp";
} else {
request.setAttribute("msgerro", "Ocorreu um erro ao tentar cadastrar o imóvel, tente novamente");
return "index.jsp";
}
} catch (SQLException | NumberFormatException | IOException | ServletException | MessagingException ex) {
request.setAttribute("msgerro", ex.getMessage());
return "index.jsp";
}
}

This line smt = connection.prepareStatement(INSERTIMOVEL); closes the previous statement and ResultSet. Get the value before that line.
int val = rs.getInt(1);
smt = connection.prepareStatement(INSERTIMOVEL);
// ...
smt.setInt(15, val);
If that is not the issue, please edit your question to include any exceptions or a diff with the last working version.

Related

How to create an FMD from a query in SQL using u.are.u SDK

I am working on a Digital Persona 5300 fingerprint reader, and I have an SQL database with fingerprints captured in varbinary format, I want to know if there is a way to obtain the fingerprint and generate an FMD to compare a fingerprint captured in the reader with the database to know who it belongs to.
Here is a part of my code that i have tried but cant get it to work
try{
Engine engine = UareUGlobal.GetEngine();
Fmd fmd = engine.CreateFmd(evt.capture_result.image, Fmd.Format.ANSI_378_2004);
m_fmds[0] = fmd; //Save the fingerprint capture
}
catch(UareUException e){ MessageBox.DpError("Engine.CreateFmd()", e); }
if(null != m_fmds[0] ){
//perform comparison
try{
Connection connection;
connection = con.conectar();
//Get all fingerprints
PreparedStatement identificarStmt = null;
try {
identificarStmt = connection.prepareStatement("SELECT no_empleado,id_relojChecador FROM relojChecador_empleado");
ResultSet rs = null;
rs = identificarStmt.executeQuery();
//Find the fingerprint
while(rs.next())
{
//Lee la plantilla de la base de datos
byte templateBuffer[] = rs.getBytes("id_relojChecador");
String nombre=rs.getString("no_empleado");
Fmd fmd = engine.CreateFmd(templateBuffer, templateBuffer.length, WIDTH, WIDTH, WIDTH, WIDTH, Fmd.Format.DP_REG_FEATURES);
int falsematch_rate = engine.Compare(m_fmds[0], 0, m_fmds[1], 0);
int target_falsematch_rate = Engine.PROBABILITY_ONE / 100000; //target rate is 0.00001
if(falsematch_rate < target_falsematch_rate){
m_text.append("Fingerprints matched.\n");
String str = String.format("dissimilarity score: 0x%x.\n", falsematch_rate);
m_text.append(str);
str = String.format("false match rate: %e.\n\n\n", (double)(falsematch_rate / Engine.PROBABILITY_ONE));
m_text.append(str);
}
else{
m_text.append("Fingerprints did not match.\n\n\n");
}
}
catch(UareUException e){ MessageBox.DpError("Engine.CreateFmd()", e); }
} } catch (SQLException ex) {
Logger.getLogger(Verification.class.getName()).log(Level.SEVERE, null, ex);
}
//discard FMDs
m_fmds[0] = null;
m_fmds[1] = null;
}

Read file.xml in FTP

I have a problem reading an .xml file in an FTP, and the following message appears: "ftp:\cifpag\FilesNotes\Maxdata_Venda_209016.XML (The syntax of the file name, directory name, or volume label is incorrect) ", in the code this commenting on the tests that already were done and what happens in each step, it follows the code below:
public class ImportXmlFromFTP {
private static Connection conexao;
private String endereco_ftp;
private String usuario;
private String senha;
private String caminho_ftp;
private String caminho_local;
private String valor;
public ImportXmlFromFTP(){
}
public void inicia() throws SocketException, IOException, SQLException {
//DADOS CONEXAO
this.conexao = ConexaoBancoDeDados.getConexao();
String sql = "SELECT daea_endereco_ftp, daea_usuario, daea_senha, daea_caminho_ftp, daea_caminho_local FROM sistema.dados_envio_arquivos";
PreparedStatement stmtSelect = this.conexao.prepareStatement(sql);
ResultSet rs = stmtSelect.executeQuery();
List<DadosEnviaArquivos> listaCliente = new ArrayList<DadosEnviaArquivos>();
while(rs.next()){
DadosEnviaArquivos dados = new DadosEnviaArquivos();
endereco_ftp = rs.getString("daea_endereco_ftp");
usuario = rs.getString("daea_usuario");
senha = rs.getString("daea_senha");
caminho_ftp = rs.getString("daea_caminho_ftp");
caminho_local = rs.getString("daea_caminho_local");
}
//CONEXAO COM FTP
FTPClient ftp = new FTPClient();
ftp.connect(endereco_ftp);
ftp.login( usuario, senha );
ftp.changeWorkingDirectory (caminho_ftp);
//PASTA COM OS ARQUIVOS
int m = 0;
String nomeArquivo = "";
File caminhoParaFTP = new File(caminho_local + "/");
File arquivos[] = caminhoParaFTP.listFiles();
while (m != arquivos.length){
nomeArquivo = arquivos[m].getName();
FileInputStream arqEnviar = new FileInputStream(caminhoParaFTP + "/" + nomeArquivo);
//IMPORTA PARA O FTP
if (ftp.storeFile (nomeArquivo, arqEnviar)) {
System.out.println("Arquivo armazenado com sucesso!");
arqEnviar.close();
//APAGA ARQUIVO DA PASTA LOCAL
File file = new File(caminhoParaFTP+"/"+nomeArquivo);
file.delete();
m++;
}else{
System.out.println ("Erro ao armazenar o arquivo.");
}
}
ftp.disconnect();
//LER ARQUIVO DO FTP E IMPORTAR PARA O SISTEMA
//PEGAR PASTA FTP
classe_FTP ClienteFTP = new classe_FTP();
ClienteFTP.Conectar(endereco_ftp, usuario, senha, 21);
String caminho = caminho_ftp;
ArrayList<String> nomes=new ArrayList<String>();
FTPFile[] arquivosFTP = ClienteFTP.Dir(caminho);
if (arquivosFTP != null) {
int length = arquivosFTP.length;
for (int g = 0; g < length; ++g) {
FTPFile p = arquivosFTP[g];
if (p.isFile()) {
String arquivoNominal = p.getName();
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
try {
//BEGIN TESTES
FileInputStream stream = new FileInputStream("ftp:\\\\cifensa.com.br\\ArquivosNotas\\" + arquivoNominal);
//InputStream is = new FileInputStream("ftp:\\\\" +"\\\\cifensa.com.br//ArquivosNotas//" + arquivoNominal);
//InputStream stream = ftp.retrieveFileStream(p.getName());
//System.out.println("Caminho: "+stream.toString());
//END TO TESTE
Document doc = builder.parse(stream);
NodeList listaDeVenda = doc.getElementsByTagName("venda");
int tamanhoDaLista = listaDeVenda.getLength();
NodeList listaDeProdutos = doc.getElementsByTagName("item");
int tamanhoDaListaDeProdutos = listaDeProdutos.getLength();
for(int k = 0; k < tamanhoDaListaDeProdutos; k++){
Pedido pedido = new Pedido();
String slq = "INSERT INTO sistema.pedido(pedi_produto, pedi_quantidade, pedi_preco_unidade_produto, pedi_cliente, pedi_numero_documento, pedi_data_documento, pedi_cliente_cpf, " +
"pedi_numero_documento_fiscal, pedi_unidade, pedi_total_desconto_produto, pedi_valor_desconto_produto, pedi_porcetagem_desconto_produto, " +
"pedi_empresa, pedi_vendedor, pedi_operacao ) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement stmt = conexao.prepareStatement(slq);
Node noDeProdutos = listaDeProdutos.item(k);
if(noDeProdutos.getNodeType() == Node.ELEMENT_NODE){
Element elementoProduto = (Element) noDeProdutos;
NodeList listaNosFilhosProdutos = elementoProduto.getChildNodes();
int tamandoListaNosFilhosProdutos = listaNosFilhosProdutos.getLength();
for(int l = 0; l < tamandoListaNosFilhosProdutos; l++){
Node nosFilhoProdutos = listaNosFilhosProdutos.item(l);
if(nosFilhoProdutos.getNodeType() == Node.ELEMENT_NODE){
Element elementoNoProduto = (Element) nosFilhoProdutos;
switch(elementoNoProduto.getTagName()){
case "VDIPRONOME":
stmt.setString(1, elementoNoProduto.getTextContent());
break;
case "VDIQTDE":
stmt.setDouble(2, Double.parseDouble(elementoNoProduto.getTextContent()));
break;
case "VDIVALOR":
stmt.setDouble(3, Double.parseDouble(elementoNoProduto.getTextContent()));
break;
}
}
}
}
for(int i = 0; i < tamanhoDaLista; i++ ){
Node noDeVenda = listaDeVenda.item(i);
if(noDeVenda.getNodeType() == Node.ELEMENT_NODE){
Element elementoVenda = (Element) noDeVenda;
NodeList listaNosFilhosVenda = elementoVenda.getChildNodes();
int tamanhoListaNosFilhosVenda = listaNosFilhosVenda.getLength();
for(int j = 0; j < tamanhoListaNosFilhosVenda; j++){
Node noFilhosVenda = listaNosFilhosVenda.item(j);
if(noFilhosVenda.getNodeType() == Node.ELEMENT_NODE){
Element elementoNoVenda = (Element) noFilhosVenda;
switch(elementoNoVenda.getTagName()){
case "VEDCLINOME":
stmt.setString(4, elementoNoVenda.getTextContent());
break;
case "VEDID":
stmt.setInt(5, Integer.parseInt(elementoNoVenda.getTextContent()));
break;
case "VEDABERTURA":
try{
String dataSemFormatacao = elementoNoVenda.getTextContent();
Timestamp ts = Timestamp.valueOf(dataSemFormatacao);
stmt.setTimestamp(6, ts);
} catch (Exception e) {
e.printStackTrace();
}
break;
case "CLICPFCGC":
stmt.setString(7, elementoNoVenda.getTextContent());
break;
}
}
}
}
stmt.setInt(8, 123);
stmt.setString(9, "UN");
stmt.setDouble(10, 23.4);
stmt.setDouble(11, 14.3);
stmt.setDouble(12, 14.5);
stmt.setInt(13, 1);
stmt.setInt(14, 1);
stmt.setInt(15, 1);
stmt.execute();
stmt.close();
System.out.println("Importado com sucesso!");
}//FIM DO FOR DE DADOS USUARIO
}//FIM DO FOR DE PRODUTOS
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
}
}
}
}
public static String getFileExtensionName(File f) {
if (f.getName().indexOf(".") == -1) {
return "";
} else {
return f.getName().substring(f.getName().length() - 3, f.getName().length());
}
}
public void para(){
}
}
You can read this example. https://www.codejava.net/java-se/networking/ftp/java-ftp-file-download-tutorial-and-example
Step 1: Download file to local store.
Step 2: Read file XML.
Good luck,
I was able to execute the code by transforming the XML file into a string and then returning to be an xml, I hope it helps but someone.
public class MyFTPClass {
private static FTPFile[] obterArquivosDiretorio(FTPClient ftp, String dirPath) throws IOException {
String cwd = ftp.printWorkingDirectory();
ftp.changeWorkingDirectory(dirPath);
FTPFile[] files = ftp.listFiles();
ftp.changeWorkingDirectory(cwd);
return files;
}
public static void main(String args[]) throws SAXException, ParserConfigurationException {
// Create an instance of FTPClient
FTPClient ftp = new FTPClient();
try {
// Establish a connection with the FTP URL
ftp.connect("caminho_ftp");
// Enter user details : user name and password
boolean isSuccess = ftp.login("usuario", "senha");
if (isSuccess) {
// Fetch the list of names of the files. In case of no files an
// empty array is returned
String path = "ArquivosNotas";
FTPFile[] listedDirectories = obterArquivosDiretorio(ftp, path);
int countXml = 1;
// Iterate on the returned list to obtain name of each file
for (FTPFile file : listedDirectories) {
if (file.getName().toLowerCase().contains("xml")) {
System.out.println();
System.out.println("Lendo " + countXml + " xml");
System.out.println();
InputStream stream = ftp.retrieveFileStream("ArquivosNotas/" + file.getName());
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
// xml vai virar uma string para depois fazer o parse para o document
StringBuilder sb = new StringBuilder();
String inline = "";
while ((inline = reader.readLine()) != null) {
sb.append(inline);
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
// convert string do xml para xml em document
Document doc = (Document) builder.parse(new ByteArrayInputStream(sb.toString().getBytes()));
NodeList listaDeVenda = doc.getElementsByTagName("venda");
int tamanhoDaLista = listaDeVenda.getLength();
NodeList listaDeProdutos = doc.getElementsByTagName("item");
int tamanhoDaListaDeProdutos = listaDeProdutos.getLength();
System.out.println();
System.out.println("Qtde itens xml " + tamanhoDaListaDeProdutos);
System.out.println("Finalizado " + countXml + " xml");
System.out.println();
countXml++;
stream.close();
reader.close();
ftp.completePendingCommand();
}
}
}
ftp.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ftp.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Can't delete a pdf file created using itext pdf library

I am using the IText pdf library (itextpdf.com/) to create pdf files for my project written in java.
The problem is: I create 2 pdfs at the result of my method and i want to delete the first, but seems like my first pdf file cannot be deleted for some reason. I have tried using File.delete(), putting File.delete() inside a "finally{}" block... nothing seems to work.
I am sure that i close my FileOutsputStream and do document.close() too! What can i do to remove this file?
public boolean gerarPDFDeStringVariosArquivosSemNumeroDePaginasComId(LinkedList < String > textosLidos, LinkedList < String > nomesDosArquivosLidos, File arquivoPdfOutput) {
try {
nomesDosArquivosLidosESeusIds = new HashMap < String, String > ();
FileOutputStream fos = new FileOutputStream(arquivoPdfOutput);
Document document = new Document();
PdfWriter.getInstance(document, fos);
document.open();
addMetaData(document);
addTitlePage(document);
for (int i = 0; i < textosLidos.size(); i++) {
String umTextoLido = textosLidos.get(i);
String umNomeArquivoLido = nomesDosArquivosLidos.get(i);
String idUmNomeArquivoLido = "#%&#" + "id_" + i + "#%&#";
this.nomesDosArquivosLidosESeusIds.put(umNomeArquivoLido, idUmNomeArquivoLido);
String umNomeArquivoLidoEIdDele = idUmNomeArquivoLido + " \n" + umNomeArquivoLido; //o id servirah para sabermos quantas paginas o arquivo possui no pdf
String textoLido2 = umTextoLido.replaceAll("\\t", " ");
addContent(document, textoLido2, umNomeArquivoLidoEIdDele);
}
document.close();
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean gerarPDFDeStringVariosArquivosComNumeroDePaginas(LinkedList < String > textosLidos, LinkedList < String > nomesDosArquivosLidos, File arquivoPdfOutput, File arquivoPdfOutputComNumeroDePaginas) {
/*primeiro vou executar gerarPDFDeStringVariosArquivosSemNumeroDePaginas para gerar um pdf com os
* ids de cada arquivo, seus textos, mas sem o numero de paginas e vou alterar a variavel local this.nomesDosArquivosLidosESeusIds
*/
boolean conseguiGerarPrimeiroPdf = gerarPDFDeStringVariosArquivosSemNumeroDePaginasComId(textosLidos, nomesDosArquivosLidos, arquivoPdfOutput);
if (conseguiGerarPrimeiroPdf == true) {
//agora vou pegar quantas paginas os arquivos tem
VerificaNumeroDePaginasDeCadaArquivoNoPdfGerado verificaNumeroDePaginas = new VerificaNumeroDePaginasDeCadaArquivoNoPdfGerado();
HashMap < String, Integer > arquivosEQuantasPaginasElesTem = verificaNumeroDePaginas.pegarNumeroDePaginasNoPdfDeCadaArquivo(this.nomesDosArquivosLidosESeusIds, nomesDosArquivosLidos, Main.FILE);
//agora comeco a criar o segundo pdf que terah o numero de paginas de cada arquivo
try {
FileOutputStream fos = new FileOutputStream(arquivoPdfOutputComNumeroDePaginas);
Document document = new Document();
PdfWriter.getInstance(document, fos);
document.open();
addMetaData(document);
addTitlePage(document);
for (int i = 0; i < textosLidos.size(); i++) {
String umTextoLido = textosLidos.get(i);
String umNomeArquivoLido = nomesDosArquivosLidos.get(i);
int quantasPaginasTemOArquivoLido = arquivosEQuantasPaginasElesTem.get(umNomeArquivoLido);
String umNomeArquivoLidoEPaginas;
if (quantasPaginasTemOArquivoLido > 1) {
umNomeArquivoLidoEPaginas = umNomeArquivoLido + " (" + quantasPaginasTemOArquivoLido + " páginas)";
} else {
umNomeArquivoLidoEPaginas = umNomeArquivoLido + " (" + quantasPaginasTemOArquivoLido + " página)";
}
String textoLido2 = umTextoLido.replaceAll("\\t", " ");
addContent(document, textoLido2, umNomeArquivoLidoEPaginas);
}
document.close();
fos.close();
arquivoPdfOutput.delete();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} else {
return false;
}
}
I do this to test:
File arquivoPdfGerar = new File(Main.FILE);
File arquivopdfGerarComNumeroDePaginas = new File(Main.FILE2);
/*PrintStream ps = new PrintStream(fileOutputStream);
System.setOut(ps);*/
LinkedList < String > nomesArquivosLidos = new LinkedList < String > ();
LinkedList < String > textosArquivosLidos = new LinkedList < String > ();
String url = "C:/Users/fábioandrews/Documents/git/PdfGeneratorForSoftwareRegistration/PdfGeneratorForSoftwareRegistration/src/br/ufrn/pairg/pdfgenerator/FirstPDF.java";
String nomeProjeto = "PdfGeneratorForSoftwareRegistration";
String arquivoLido = LeitorArquivoTexto.lerArquivoQualquerDeTexto(url);
String nomeArquivoLido = LeitorArquivoTexto.pegarNomeArquivo(url, nomeProjeto);
nomesArquivosLidos.add(nomeArquivoLido);
textosArquivosLidos.add(arquivoLido);
url = "C:/Users/fábioandrews/Documents/git/PdfGeneratorForSoftwareRegistration/PdfGeneratorForSoftwareRegistration/src/br/ufrn/pairg/pdfgenerator/Main.java";
nomeProjeto = "PdfGeneratorForSoftwareRegistration";
arquivoLido = LeitorArquivoTexto.lerArquivoQualquerDeTexto(url);
nomeArquivoLido = LeitorArquivoTexto.pegarNomeArquivo(url, nomeProjeto);
nomesArquivosLidos.add(nomeArquivoLido);
textosArquivosLidos.add(arquivoLido);
GeraPDFDeStringVariosArquivos geradorPdf = new GeraPDFDeStringVariosArquivos();
geradorPdf.gerarPDFDeStringVariosArquivosComNumeroDePaginas(textosArquivosLidos, nomesArquivosLidos, arquivoPdfGerar, arquivopdfGerarComNumeroDePaginas);
What about the following line ?
PdfWriter.getInstance(document, fos);
IMHO, this method/line
looks useless in you code as I don't find any reference to the object (PdfWriter) returned by it.
if this line can be removed, just do it ;-)
if not, you have to
hold PdfWriter object returned.
and close it (in a finally block as it should be done for the FileOutputStream and `Document' instances too).
Note: this remarks are done according to the itext version 5.5.6 I am using.
If you still have issues, you may plug this little tool (created by the autor of Jenkins). He saved me on an ooooold program.
Thanks for all your answers. The solution was right where Bruno Lowagie said: When i was reading the pdf files to count how many pages where there, i was not closing the pdfreader and therefore the file was still in use.
Thank you all for the answers ^^

java return data to java client

i have java client send to server (jetty-xmlrpc) query and receive data from server inside hashmap. sometime data is more big(e.g. 3645888 rows), when this data send to java client i have error ( java heap space ). how can i send data by 2 times for example ? or give me way to fix it
this is server function to get data and send it to client
public HashMap getFlickValues(String query,String query2){
System.out.println("Query is : "+query);
System.out.println("Query2 is: "+query2);
Connection c = null;
Connection c2 = null;
Statement st = null;
Statement st2 = null;
HashMap<String, Object[]> result = new HashMap<String, Object[]>();
ArrayList<Double> vaArrL = new ArrayList<Double>();
ArrayList<Double> vbArrL = new ArrayList<Double>();
ArrayList<Double> vcArrL = new ArrayList<Double>();
try {
Class.forName("org.postgresql.Driver");
String conString = "jdbc:postgresql://" + host + ":" + port + "/" + DBName +
"?user=" + user + "&pass=" + pass;
String conString1 = "jdbc:postgresql://" + host + ":" + port2 + "/" + DBName2 +
"?user=" + user + "&pass=" + pass;
//String conString1 = "jdbc:postgresql://127.0.0.1:5431/merkezdbram " +
// "?user=" + user + "&pass=" + pass;
/*c = DriverManager.getConnection(conString);
st = c.createStatement();
ResultSet rs = st.executeQuery(query);
while (rs.next()){
vaArrL.add(rs.getDouble("va"));
vbArrL.add(rs.getDouble("vb"));
vcArrL.add(rs.getDouble("vc"));
}*/
c = DriverManager.getConnection(conString);
//c.setAutoCommit(false);
c2 = DriverManager.getConnection(conString1);
//c2.setAutoCommit(false);
st = c.createStatement();
//st.setFetchSize(1000);
st2 = c2.createStatement();
//st2.setFetchSize(1000);
List<ResultSet> resultSets = new ArrayList<>();
resultSets.add(st.executeQuery(query));
resultSets.add(st2.executeQuery(query2));
ResultSets rs = new ResultSets(resultSets);
int count = 0;
int ResultSetSize = rs.getFetchSize();
System.out.println("ResultSetSize is "+ResultSetSize);
while (rs.next()){
//count++;
//if ( count == 2200000) { break;}
vaArrL.add(rs.getDoubleVa("va"));
vbArrL.add(rs.getDoubleVb("vb"));
vcArrL.add(rs.getDoubleVc("vc"));
}
int sz = vaArrL.size();
result.put("va", vaArrL.toArray(new Object[sz]));
result.put("vb", vbArrL.toArray(new Object[sz]));
result.put("vc", vcArrL.toArray(new Object[sz]));
//rs.close();
st.close();
c.close();
} catch ( Exception e ) {
System.out.println(e);
e.printStackTrace();
}
System.out.println("Flicker vaArrL.size = "+vaArrL.size());
return result;
}
and ResultSets class is :
class ResultSets {
private java.util.List<java.sql.ResultSet> resultSets;
private java.sql.ResultSet current;
public ResultSets(java.util.List<java.sql.ResultSet> resultSets) {
this.resultSets = new java.util.ArrayList<>(resultSets);
current = resultSets.remove(0);
}
public boolean next() throws SQLException {
if (current.next()) {
return true;
}else if (!resultSets.isEmpty()) {
current = resultSets.remove(0);
return next();
}
return false;
}
public Double getDoubleVa(String va) throws SQLException{
return current.getDouble("va");
}
public Double getDoubleVb(String vb) throws SQLException{
return current.getDouble("vb");
}
public Double getDoubleVc(String vc) throws SQLException{
return current.getDouble("vc");
}
}
i want way to return data to client without (java heap space) ?
i make -Xmx1024m for VM argument , but same problrm
i want solution in my code
thanks

Getting a NULL pointer exception on a input stream

Not quite sure why but I am getting a null pointer exception when declaring what input stream is and what it should take in (converting string in an input stream), the get.bytes (converting from string to input reader) I read up online and implemented
public void processTables()throws SQLException
{
dmd = con.getMetaData();
ResultSet schema= dmd.getSchemas();
ResultSet result = dmd.getTables(null,null,"%",null);
while(result.next()) {
String tablename = result.getString(3);
ResultSet column = dmd.getColumns(null,null,tablename,null);
ResultSetMetaData rmd = result.getMetaData();
int count = rmd.getColumnCount();
while(column.next()) {
for(int i=1; i<=count; i++) {
String col=column.getString(i);
System.out.println("Column: " + col);
String question = null;
InputStream col2 = new ByteArrayInputStream(col.getBytes());
BufferedReader brin;
brin = new BufferedReader(new InputStreamReader(col2));
try {
question = brin.readLine();
FileWriter output = new FileWriter("Columns.txt");
BufferedWriter out = new BufferedWriter(output);
out.write(question);
out.close();
} catch (IOException io) {
System.out.println("hello");
}
}
ResultSet fk = dmd.getImportedKeys(con.getCatalog(),null,tablename);
while (fk.next()) {
String fkTableName = fk.getString("FKTABLE_NAME");
String fkColName = fk.getString("FKCOLUMN_NAME");
String pkTableName = fk.getString("PKTABLE_NAME");
String pkColName = fk.getString("PKCOLUMN_NAME");
System.out.println("Name of Table: " + tablename);
System.out.println("Foreign Key: [" + fkTableName + "." + fkColName + "] REFERENCES [" + pkTableName + "." + pkColName +"]\n");
}
}
}
JAVA STACK TRACE down below
C:\Users\harma_000\Documents\Computer Science Year 2\SCC201\SCC201 13-14 CW Stud
ent Pack>java -classpath .;sqlite-jdbc4-3.8.2-SNAPSHOT.jar RefInteg
Db.constructor [lsh]
Db.Open : leaving
Column: null
Exception in thread "main" java.lang.NullPointerException
at Db.processTables(Db.java:42)
at RefInteg.checkDatabase(RefInteg.java:14)
at RefInteg.go(RefInteg.java:20)
at RefInteg.main(RefInteg.java:28)
C:\Users\harma_000\Documents\Computer Science Year 2\SCC201\SCC201 13-14 CW Stud
ent Pack>pause
Press any key to continue . . .
System.out.println("Column: " + col);
String question = null;
InputStream col2 = new ByteArrayInputStream(col.getBytes());
col is null, which is why col.getBytes() throws the NullPointerException
Btw. is is also indicated by your output Column: null

Categories

Resources