code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
package br.ufrgs.engsoft.ejb;
import java.util.HashMap;
import javax.ejb.Singleton;
import br.ufrgs.engsoft.ejb.local.DatabaseEJBLocal;
import br.ufrgs.engsoft.entity.Autor;
import br.ufrgs.engsoft.entity.Referencia;
/**
* Implementacao do bean de sessao Singleton.
* Usado para simular um banco de dados.
*/
@Singleton
public class DatabaseEJB implements DatabaseEJBLocal {
// Usado para simular um campo auto-incremento do banco de dados
private Integer referenciaId;
private Integer autorId;
// Usados para simular tabelas no banco de dados
private HashMap<Integer, Autor> autores = null;
private HashMap<Integer, Referencia> referencias = null;
/**
* Construtor padrao.
*/
public DatabaseEJB() {
// inicializacao
autores = this.inicializarAutores();
referenciaId = autores.size()+1;
referencias = this.inicializarReferencias();
referenciaId = referencias.size()+1;
}
public Integer getNewAutorId() {
return autorId++;
}
public Integer getNewReferenciaId() {
return referenciaId++;
}
public HashMap<Integer, Autor> getAutores() {
return autores;
}
public HashMap<Integer, Referencia> getReferencias() {
return referencias;
}
/**
* Inicializa a tabela de autores.
* @return autores
*/
private HashMap<Integer, Autor> inicializarAutores() {
HashMap<Integer, Autor> tabela = new HashMap<Integer, Autor>();
Autor autor = new Autor();
autor.setId(1);
autor.setNome("Luis Fernando");
autor.setSobrenome("Verissimo");
tabela.put(autor.getId(), autor);
autor = new Autor();
autor.setId(2);
autor.setNome("Jorge");
autor.setSobrenome("Amado");
tabela.put(autor.getId(), autor);
autor = new Autor();
autor.setId(3);
autor.setNome("Machado de");
autor.setSobrenome("Assis");
tabela.put(autor.getId(), autor);
autor = new Autor();
autor.setId(4);
autor.setNome("Chico");
autor.setSobrenome("Buarque");
tabela.put(autor.getId(), autor);
return tabela;
}
/**
* Inicializa a tabela de autores.
* @return autores
*/
private HashMap<Integer, Referencia> inicializarReferencias() {
Autor autor = new Autor();
autor.setId(1);
autor.setNome("Luis Fernando");
autor.setSobrenome("Verissimo");
HashMap<Integer, Referencia> tabela = new HashMap<Integer, Referencia>();
Referencia referencia = new Referencia();
referencia.setId(1);
referencia.setAutor(autor);
referencia.setTitulo("A grande mulher nua");
referencia.setAnoPublicacao(1975);
referencia.setEditora("Jose Olympio");
tabela.put(referencia.getId(), referencia);
referencia = new Referencia();
referencia.setId(2);
referencia.setAutor(autor);
referencia.setTitulo("O popular");
referencia.setAnoPublicacao(1973);
referencia.setEditora("Jose Olympio");
tabela.put(referencia.getId(), referencia);
referencia = new Referencia();
referencia.setId(3);
referencia.setAutor(autor);
referencia.setTitulo("A mesa voadora");
referencia.setAnoPublicacao(1982);
referencia.setEditora("Globo");
tabela.put(referencia.getId(), referencia);
autor = new Autor();
autor.setId(2);
autor.setNome("Jorge");
autor.setSobrenome("Amado");
referencia = new Referencia();
referencia.setId(4);
referencia.setAutor(autor);
referencia.setTitulo("O pais do carnaval");
referencia.setAnoPublicacao(1930);
tabela.put(referencia.getId(), referencia);
referencia = new Referencia();
referencia.setId(5);
referencia.setAutor(autor);
referencia.setTitulo("Gabriela cravo e canela");
referencia.setAnoPublicacao(1958);
tabela.put(referencia.getId(), referencia);
return tabela;
}
} | Java |
package br.ufrgs.engsoft.ejb;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.ejb.Stateless;
import br.ufrgs.engsoft.ejb.local.DatabaseEJBLocal;
import br.ufrgs.engsoft.ejb.remote.AutorEJBRemote;
import br.ufrgs.engsoft.ejb.remote.ReferenciaEJBRemote;
import br.ufrgs.engsoft.entity.Autor;
import br.ufrgs.engsoft.entity.Referencia;
/**
* Implementacao do bean de sessao Stateless.
* Usado para obter informacoes sobre referencias.
*/
@Stateless
public class ReferenciaEJB implements ReferenciaEJBRemote {
@EJB // A injecao ocorre no deploy da aplicacao
private DatabaseEJBLocal database;
@EJB // A injecao ocorre no deploy da aplicacao
private AutorEJBRemote autorEJB;
/*
* (non-Javadoc)
* @see br.ufrgs.engsoft.ejb.impl.ReferenciaEJB#incluirReferencia(br.ufrgs.engsoft.entity.Referencia)
*/
public Referencia incluirReferencia(Referencia referencia) {
//
if (referencia==null) throw new EJBException("Referencia nao pode ser nula!");
// Caso nao informado usar auto-incremento
if (referencia.getId()==null || referencia.getId()==0) referencia.setId(database.getNewReferenciaId());
// Caso tenha referencia com mesmo Id retornar falso
if (database.getReferencias().containsKey(referencia.getId())) throw new EJBException("Identificador da Referencia ja cadastrado!");
// Validacao do preenchimento do campo titulo
if (referencia.getTitulo()==null || referencia.getTitulo().isEmpty()) throw new EJBException("Titulo deve ser informado!");
// Validacao do preenchimento do campo titulo
if (referencia.getAutor()==null || referencia.getAutor().getId()==null || referencia.getAutor().getId()==0) throw new EJBException("Autor deve ser informado!");
// Atribui o autor correspondente ao id
Autor autor = autorEJB.getAutorById(referencia.getAutor().getId());
if (autor==null) throw new EJBException("Autor nao encontrado!");
referencia.setAutor(autor);
// Adicionando nova referencia a tabela
database.getReferencias().put(referencia.getId(), referencia);
return referencia;
}
/*
* (non-Javadoc)
* @see br.ufrgs.engsoft.ejb.impl.ReferenciaEJB#listarReferencia()
*/
public Collection<Referencia> listarReferencia() {
return database.getReferencias().values();
}
/*
* (non-Javadoc)
* @see br.ufrgs.engsoft.ejb.impl.ReferenciaEJB#listarReferencia()
*/
public Collection<Referencia> listarReferenciaPorAutor(Integer idAutor) {
Collection<Referencia> retorno = new ArrayList<Referencia>();
Collection<Referencia> referencias = database.getReferencias().values();
for (Referencia ref : referencias) {
if (idAutor.equals(ref.getAutor().getId())) retorno.add(ref);
}
return retorno;
}
}
| Java |
package br.ufrgs.engsoft.servlet;
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import br.ufrgs.engsoft.ui.Controller;
import br.ufrgs.engsoft.util.AcaoEnum;
import br.ufrgs.engsoft.util.HtmlParameterEnum;
import br.ufrgs.engsoft.util.HtmlUtil;
/**
* Servlet principal da aplicacao.
*/
@WebServlet("/paginas/*")
public class PublicacaoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Encaminha tratamento para o metodo doPost()
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String codigoHtml = null;
try { // Definicao de variaveis
AcaoEnum acaoUsuario = null;
HashMap<HtmlParameterEnum, Object> parametrosHtml = null;
// Obtem o parametro de Request "acao"
String parametroRequest = request.getParameter("acao");
// Obtendo o Enum correspondente a acao
acaoUsuario = AcaoEnum.valueOfByAcao(parametroRequest);
// Obtem o controlador referente a acao solicitada pelo usuario
Controller controlador = acaoUsuario.getControllerFactory();
// Tratamento da requisicao HTTP pelo controlador
// (retorna valores a serem substituidos por parametros no HTML)
parametrosHtml = controlador.processaAcao(request);
// Obtem o codigo HTML referente a acao solicitada pelo usuario
codigoHtml = HtmlUtil.getCodigoHtmlDaAcao(acaoUsuario);
// Substituindo parametros do HTML pelos valores gerados pelo controlador
codigoHtml = HtmlUtil.replaceParameters(codigoHtml, parametrosHtml);
} catch (Exception e) {
e.printStackTrace();
// Caso algum excecao seja lancada apresentar tela de erro padrao
codigoHtml = HtmlUtil.getCodigoHtmlDaAcao(AcaoEnum.ERROR);
codigoHtml = HtmlUtil.replaceParameter(codigoHtml, HtmlParameterEnum.MENSAGEM_ERRO, e);
} finally {
// Imprime no objeto de resposta HTTP o codigo HTML gerado pela aplicacao
response.getOutputStream().print(codigoHtml);
}
}
} | Java |
package br.ufrgs.engsoft.ui;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import br.ufrgs.engsoft.util.HtmlParameterEnum;
/**
* Controlador de erro.
*/
public class DefaultController implements Controller {
/*
* (non-Javadoc)
* @see br.ufrgs.engsoft.ui.Controller#processaAcao(javax.servlet.http.HttpServletRequest)
*/
public HashMap<HtmlParameterEnum, Object> processaAcao(HttpServletRequest request) {
return null;
}
}
| Java |
package br.ufrgs.engsoft.ui;
import java.util.Collection;
import java.util.HashMap;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import br.ufrgs.engsoft.ejb.remote.AutorEJBRemote;
import br.ufrgs.engsoft.ejb.remote.ReferenciaEJBRemote;
import br.ufrgs.engsoft.entity.Autor;
import br.ufrgs.engsoft.entity.Referencia;
import br.ufrgs.engsoft.util.EntityUtil;
import br.ufrgs.engsoft.util.HtmlParameterEnum;
/**
* Controlador da acao Nova Referencia.
*/
public class IncluirReferenciaController implements Controller {
/*
* (non-Javadoc)
* @see br.ufrgs.engsoft.ui.Controller#processaAcao()
*/
public HashMap<HtmlParameterEnum, Object> processaAcao(HttpServletRequest request) throws NamingException {
String idAutor = request.getParameter(HtmlParameterEnum.AUTOR_ID.name());
if (idAutor==null) {
// Caso nao exista o parametro idAutor entao o usuario esta solicitando
// a inclusao de um novo regitro.
return inicializaFormularioInclusao();
} else {
// Caso exista o parametro ele esta processando a inclusao do registro.
// Constroi o objeto a partir do request
idAutor = request.getParameter(HtmlParameterEnum.AUTOR_ID.name());
Referencia referencia = EntityUtil.getReferenciaFromRequest(request);
// Obtem o ReferenciaEJB
ReferenciaEJBRemote referenciaEJB = (ReferenciaEJBRemote) new InitialContext().lookup("java:global/PublicacaoWEB/ReferenciaEJB");
// Executa a chamada ao metodo do EJB que fara a inclusao no banco de dados
referenciaEJB.incluirReferencia(referencia);
// Executa o return se nenhuma exception for lancada
return null;
}
}
private HashMap<HtmlParameterEnum, Object> inicializaFormularioInclusao() throws NamingException {
// Obtem o AutorEJB
AutorEJBRemote autorEJB = (AutorEJBRemote) new InitialContext().lookup("java:global/PublicacaoWEB/AutorEJB");
// Carrega os autores do banco de dados.
Collection<Autor> listaAutores = autorEJB.listarAutores();
// Adiciona a lista como HtmlParameterEnum
HashMap<HtmlParameterEnum, Object> parametros = new HashMap<HtmlParameterEnum, Object>();
parametros.put(HtmlParameterEnum.AUTOR_LISTA, listaAutores);
return parametros;
}
}
| Java |
package br.ufrgs.engsoft.ui;
import java.util.HashMap;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import br.ufrgs.engsoft.util.HtmlParameterEnum;
/**
* Interface que padroniza os controladores da aplicacao.
*/
public interface Controller {
/**
* Retorna os parametros que serao substituidos no HTML.
* @param request
* @throws NamingException
*/
public HashMap<HtmlParameterEnum, Object> processaAcao(HttpServletRequest request) throws NamingException;
}
| Java |
package br.ufrgs.engsoft.ui;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import br.ufrgs.engsoft.ejb.remote.ReferenciaEJBRemote;
import br.ufrgs.engsoft.entity.Referencia;
import br.ufrgs.engsoft.util.HtmlParameterEnum;
/**
* Controlador da acao Listar Referencia.
*/
public class ListarReferenciaController implements Controller {
/*
* (non-Javadoc)
* @see br.ufrgs.engsoft.ui.Controller#processaAcao(javax.servlet.http.HttpServletRequest)
*/
public HashMap<HtmlParameterEnum, Object> processaAcao(HttpServletRequest request) throws NamingException {
// Obtem o ReferenciaEJB
ReferenciaEJBRemote referenciaEJB = (ReferenciaEJBRemote) new InitialContext().lookup("java:global/PublicacaoWEB/ReferenciaEJB");
// Obtem a lista de referencias
List<Referencia> referencias = new ArrayList<Referencia>(referenciaEJB.listarReferencia());
Collections.sort(referencias);
// Adiciona aos parametros HTML
HashMap<HtmlParameterEnum, Object> param = new HashMap<HtmlParameterEnum, Object>();
param.put(HtmlParameterEnum.REFERENCIA_LISTA, referencias);
return param;
}
}
| Java |
package br.ufrgs.engsoft.rest;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;
import br.ufrgs.engsoft.ejb.remote.ReferenciaEJBRemote;
import br.ufrgs.engsoft.entity.Referencia;
@Path("/Referencia") // Define o caminho de publicacao
@Consumes({"application/xml", "application/json"}) // Define o padrao da entrada
@Produces({"application/xml", "application/json"}) // Define o padrao de retorno
public class ReferenciaResource {
@Context
private UriInfo uriInfo; // Informacoes sobre o contexto da aplicacao
@GET // Responde requisicoes do tipo HTTP-GET sem parametro
public List<Referencia> getAllReferencias() throws NamingException {
ReferenciaEJBRemote referenciaEJB = (ReferenciaEJBRemote) new InitialContext()
.lookup("java:global/PublicacaoWEB/ReferenciaEJB");
return new ArrayList<Referencia>(referenciaEJB.listarReferencia());
}
@GET // Responde requisicoes do tipo HTTP-GET
@Path("{id}/") // Define um parametro ao url (polimorfismo atraves de parametro)
public List<Referencia> getReferenciasByAutor(@PathParam("id") Integer idAutor ) throws NamingException {
// Obtendo o ReferenciaEJB
ReferenciaEJBRemote referenciaEJB = (ReferenciaEJBRemote) new InitialContext()
.lookup("java:global/PublicacaoWEB/ReferenciaEJB");
// Executando a consulta de referencias por autor
Collection<Referencia> referencias = referenciaEJB.listarReferenciaPorAutor(idAutor);
return new ArrayList<Referencia>(referencias); // Retornando os resultados
}
@POST
public Response createNewReferencia(JAXBElement<Referencia> referenciaJaxb) throws NamingException {
// Obtendo a entidade a partir de um JAXBElement (unbind)
Referencia referencia = referenciaJaxb.getValue();
// Obtendo o ReferenciaEJB
ReferenciaEJBRemote referenciaEJB = (ReferenciaEJBRemote) new InitialContext()
.lookup("java:global/PublicacaoWEB/ReferenciaEJB");
// Executando a inclusao de referencia
referenciaEJB.incluirReferencia(referencia);
// Gerando a URI de resposta
URI referenciaUri = uriInfo.getAbsolutePathBuilder().path(referencia.getId().toString()).build();
return Response.created(referenciaUri).build(); // Retornando a URI de resposta
}
}
| Java |
package br.ufrgs.engsoft.rest;
import java.util.ArrayList;
import java.util.List;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import br.ufrgs.engsoft.ejb.remote.AutorEJBRemote;
import br.ufrgs.engsoft.entity.Autor;
@Path("/autor") // Define o caminho de publicacao
@Consumes({"application/xml", "application/json"}) // Define formatacao da entrada
@Produces({"application/xml", "application/json"}) // Define formatacao do retorno
public class AutorResource {
@GET // Metodo que responde requisicoes HTTP-GET
public List<Autor> getAllAutors() throws NamingException {
AutorEJBRemote autorEJB = (AutorEJBRemote) new InitialContext().lookup("java:global/PublicacaoWEB/AutorEJB");
return new ArrayList<Autor>(autorEJB.listarAutores());
}
}
| Java |
package br.ufrgs.engsoft.util;
import javax.servlet.http.HttpServletRequest;
import br.ufrgs.engsoft.entity.Autor;
import br.ufrgs.engsoft.entity.Referencia;
public class EntityUtil {
private EntityUtil() {}
public static Referencia getReferenciaFromRequest(HttpServletRequest request) {
Referencia referencia = new Referencia();
referencia.setId(integerConverter(request.getParameter(HtmlParameterEnum.REFERENCIA_ID.name())));
referencia.setAutor(new Autor(integerConverter(request.getParameter(HtmlParameterEnum.AUTOR_ID.name()))));
referencia.setTitulo(request.getParameter(HtmlParameterEnum.REFERENCIA_TITULO.name()));
referencia.setAnoPublicacao(integerConverter(request.getParameter(HtmlParameterEnum.REFERENCIA_ANO_PUBLICACAO.name())));
referencia.setSubtitulo(request.getParameter(HtmlParameterEnum.REFERENCIA_SUBTITULO.name()));
referencia.setEdicao(request.getParameter(HtmlParameterEnum.REFERENCIA_EDICAO.name()));
referencia.setLocalPublicacao(request.getParameter(HtmlParameterEnum.REFERENCIA_LOCAL_PUBLICACAO.name()));
referencia.setEditora(request.getParameter(HtmlParameterEnum.REFERENCIA_EDITORA.name()));
referencia.setNumeroPaginas(integerConverter(request.getParameter(HtmlParameterEnum.REFERENCIA_NUMERO_PAGINAS.name())));
referencia.setNumeroVolumes(integerConverter(request.getParameter(HtmlParameterEnum.REFERENCIA_NUMERO_VOLUMES.name())));
referencia.setSerie(integerConverter(request.getParameter(HtmlParameterEnum.REFERENCIA_SERIE.name())));
return referencia;
}
private static Integer integerConverter(String param) {
try {
if (param==null || "".equals(param.trim())) return 0;
return Integer.parseInt(param);
} catch (NumberFormatException e) {
throw new RuntimeException("Campos (num)ericos nao podem receber caracteres!");
}
}
}
| Java |
package br.ufrgs.engsoft.util;
/**
* Classe Enumerator usada para padronizar os parametros do HTML.
*/
public enum HtmlParameterEnum {
// Entidade Autor
AUTOR_ID,
AUTOR_NOME,
AUTOR_SOBRENOME,
AUTOR_NOME_E_SOBRENOME,
AUTOR_LISTA,
// Entidade Referencia
REFERENCIA_ID,
REFERENCIA_TITULO,
REFERENCIA_ANO_PUBLICACAO,
REFERENCIA_SUBTITULO,
REFERENCIA_EDICAO,
REFERENCIA_LOCAL_PUBLICACAO,
REFERENCIA_EDITORA,
REFERENCIA_NUMERO_PAGINAS,
REFERENCIA_NUMERO_VOLUMES,
REFERENCIA_SERIE,
REFERENCIA_LISTA,
// Pagina de erro
MENSAGEM_ERRO;
}
| Java |
package br.ufrgs.engsoft.util;
import br.ufrgs.engsoft.ui.Controller;
import br.ufrgs.engsoft.ui.DefaultController;
import br.ufrgs.engsoft.ui.IncluirReferenciaController;
import br.ufrgs.engsoft.ui.ListarReferenciaController;
/**
* Classe Enumerator usada para padronizar a identificacao das paginas HTML.
*/
public enum AcaoEnum {
INDEX("Pagina Inicial", DefaultController.class, "index.html"), // Pagina inicial
ERROR("erro", DefaultController.class, "error.html"), // Pagina padrao de erro
INCLUIR_REFERENCIA("Incluir Referencia", IncluirReferenciaController.class, "incluir_referencia.html"), // Pagina nova referencia
INCLUIR("Incluir", IncluirReferenciaController.class, "confirmacao.html"), // Inclusao de referencia
CANCELAR("Cancelar", DefaultController.class, "index.html"), // Cancelar inclusao de referencia
LISTAR_REFERENCIA("Listar Referencia", ListarReferenciaController.class, "listar_referencia.html") // Lista de referencias
;
private String acaoHtml;
private Class<? extends Controller> controlador;
private String fileName;
private AcaoEnum(String acao, Class<? extends Controller> controlador, String fileName) {
this.acaoHtml = acao;
this.controlador = controlador;
this.fileName = fileName;
}
private String getAcaoHtml() {
return acaoHtml;
}
public Controller getControllerFactory() throws InstantiationException, IllegalAccessException {
return controlador.newInstance();
}
public static AcaoEnum valueOfByAcao(String acao) {
if (acao == null || acao.isEmpty())
return INDEX;
AcaoEnum[] valores = AcaoEnum.values();
for (AcaoEnum valor : valores)
if (valor.getAcaoHtml().equals(acao))
return valor;
throw new RuntimeException("Acao " + acao
+ " nao registrada no sistema.");
}
public String getFileName() {
return fileName;
}
}
| Java |
package br.ufrgs.engsoft.util;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import br.ufrgs.engsoft.entity.Autor;
import br.ufrgs.engsoft.entity.Referencia;
/**
* Classe utilitaria para manipulacao do codigo HTML.
*/
public class HtmlUtil {
/**
* Retorna o codigo HTML de um arquivo de interface com o usuario.
* @param fileName
* @return String
* @throws IOException
*/
public static String getCodigoHtmlDaAcao(AcaoEnum page) throws IOException {
String fileName = "/br/ufrgs/engsoft/ui/html/" + page.getFileName();
StringBuffer retorno = new StringBuffer();
URL resource = HtmlUtil.class.getResource(fileName);
if (resource==null) throw new IOException("Arquivo "+fileName+" nao encontrado!");
BufferedReader in = new BufferedReader(new FileReader(resource.getFile()));
String str;
while((str = in.readLine()) != null) {
retorno.append(str);
}
in.close();
return retorno.toString();
}
/**
* Substitui um conjunto de parametros em um codigo HTML.
* @param htmlCode
* @param parameters
* @return htmlCode
*/
public static String replaceParameters(String htmlCode, HashMap<HtmlParameterEnum, Object> parameters) {
// Nao ha parametros a serem alterados
if (parameters==null || parameters.size()==0) return htmlCode;
Iterator<HtmlParameterEnum> keys = parameters.keySet().iterator();
HtmlParameterEnum key = null;
while (keys.hasNext()) {
key = keys.next();
htmlCode = replaceParameter(htmlCode, key, parameters.get(key));
}
return htmlCode;
}
/**
* Substitui um parametro em um codigo HTML.
* @param htmlCode
* @param parametro
* @param value
* @return htmlCode
*/
public static String replaceParameter(String htmlCode, HtmlParameterEnum parametro, Object value) {
if (value instanceof Collection)
return htmlCode.replace("["+parametro.name()+"]", getOptionsHtmlCode((Collection) value));
else if (value instanceof Throwable)
return htmlCode.replace("["+parametro.name()+"]", getHtmlCode((Throwable) value));
else
return htmlCode.replace("["+parametro.name()+"]", (String)value);
}
/**
* Varre uma excecao em busca da mensagem de erro.
* @param e
* @return String
*/
private static String getHtmlCode(Throwable e) {
if (e.getMessage()==null && e.getCause()==null) return e.toString();
if (e.getMessage()==null) return getHtmlCode(e.getCause());
return e.getMessage();
}
/**
* Para gerar codigo HTML em campo do tipo select.
*/
private static String getOptionsHtmlCode(Collection options) {
StringBuffer sb = new StringBuffer();
for (Object option : options)
if (option instanceof Autor)
sb.append(getOption((Autor) option));
else if(option instanceof Referencia)
sb.append(getOption((Referencia) option));
return sb.toString();
}
/**
* Para gerar codigo HTML a partir da entidade Autor.
* @param autor
* @return htmlCode
*/
private static String getOption(Autor autor) {
return "<option value=\""+((Autor) autor).getId()+"\">"+((Autor) autor).getNomeSobrenome()+"</option>";
}
/**
* Para gerar codigo HTML a partir da entidade Autor.
* @param ref
* @return htmlCode
*/
private static String getOption(Referencia ref) {
return "<tr>" + "<td class=\"linha\">"+((Referencia) ref).getAnoPublicacao()+"</td>"+
"<td class=\"linha\">"+((Referencia) ref).getTitulo()+"</td>"+
"<td class=\"linha\">"+((Referencia) ref).getAutor().getNomeSobrenome()+"</td>"+
"<td class=\"linha\">"+((Referencia) ref).getId()+"</td>"+"</tr>";
}
}
| Java |
package data;
public class Data implements IData {
private int[] operatorID;
private String[] operatorPassword;
public Data() {
// Testdata
operatorID = new int[]{11,12,13,14,15};
operatorPassword = new String[]{"opr11", "opr12", "opr13", "opr14", "opr15"};
}
/* (non-Javadoc)
* @see src.IData#getOprID()
*/
@Override
public int[] getOprID(){
return operatorID;
}
/* (non-Javadoc)
* @see src.IData#getOprPassword()
*/
@Override
public String[] getOprPassword(){
return operatorPassword;
}
}
| Java |
package data;
public interface IData {
public abstract int[] getOprID();
public abstract String[] getOprPassword();
} | Java |
package functionality;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.locks.Lock;
public interface ITransmitter {
public abstract boolean rm20(PrintWriter out, BufferedReader in, String n,
String prompt1, String prompt2, String prompt3) throws IOException;
public abstract String secondAnswer(PrintWriter out, BufferedReader in)
throws IOException;
public abstract String dispWghtScl(PrintWriter out, BufferedReader in)
throws IOException;
public abstract String dispTxtScl(PrintWriter out, BufferedReader in, String text)
throws IOException;
public abstract String zeroScale(PrintWriter out, BufferedReader in)
throws IOException;
public abstract String tareScale(PrintWriter out, BufferedReader in)
throws IOException;
public abstract String readScale(PrintWriter out, BufferedReader in)
throws IOException;
public abstract Lock getLock();
int getInputUserId(PrintWriter out, BufferedReader in);
String getInputPassword(PrintWriter out, BufferedReader in);
String getOprPassword(int id);
} | Java |
package functionality;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import data.Data;
import data.IData;
public class Transmitter implements ITransmitter {
private volatile Lock lock;
private IData data;
public Transmitter(IData data){
lock = new ReentrantLock();
this.data = data;
}
/* (non-Javadoc)
* @see src.ITransmitter#getUserInputs(java.io.PrintWriter, java.io.BufferedReader)
*/
@Override
public int getInputUserId(PrintWriter out, BufferedReader in){
int userID = 0;
try {
if (rm20(out, in, "4 ", "\"Indtast \"", "\"dit \"", "\"brugerID\"")){
userID = Integer.parseInt(secondAnswer(out, in));
}
} catch (IOException e) {
System.out.println("Operatør-login tråd fejlet");
} catch (NumberFormatException e) {
System.out.println("Bruger har indtastet ugyldigt bruger ID");
}
return userID;
}
@Override
public String getInputPassword(PrintWriter out, BufferedReader in){
String password = "";
try {
if (rm20(out, in, "4 ", "\"Indtast \"", "\"dit \"", "\"password\"")){
password = secondAnswer(out, in);
}
} catch (IOException e) {
System.out.println("Operatør-login tråd fejlet");
} catch (NumberFormatException e) {
System.out.println("Bruger har indtastet ugyldigt bruger ID");
}
return password;
}
/* (non-Javadoc)
* @see src.ITransmitter#rm20(java.io.PrintWriter, java.io.BufferedReader, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public boolean rm20(PrintWriter out, BufferedReader in, String n, String prompt1, String prompt2, String prompt3) throws IOException {
String reply = "";
out.println("RM20 " + n + prompt1 + prompt2 + prompt3);
reply = in.readLine();
if (reply.equalsIgnoreCase("RM20 B")){
return true;
} else {
return false;
}
}
/* (non-Javadoc)
* @see src.ITransmitter#weightAnswer(java.io.PrintWriter, java.io.BufferedReader)
*/
@Override
public String secondAnswer(PrintWriter out, BufferedReader in) throws IOException{
String output = "";
String reply = in.readLine();
String r1 = reply.substring(0, 6);
if (r1.equalsIgnoreCase("RM20 A")){
output = reply.substring(7).trim();
} else {
output = "Bruger afbrudt.";
}
return output;
}
/* (non-Javadoc)
* @see src.ITransmitter#dispWghtScl(java.io.PrintWriter, java.io.BufferedReader)
*/
@Override
public String dispWghtScl(PrintWriter out, BufferedReader in) throws IOException {
String reply = "";
if (lock.tryLock()){
try {
String dispWghtScl = "DW";
out.println(dispWghtScl);
reply = in.readLine();
if (!reply.substring(0, 2).equalsIgnoreCase("ES")){
reply = "Vægt opdateret.";
} else {
reply = "Kommando fejlet.";
}
} finally {
lock.unlock();
}
}else {
reply = "Vægt optaget.";
}
return reply;
}
/* (non-Javadoc)
* @see src.ITransmitter#dispTxtScl(java.io.PrintWriter, java.io.BufferedReader)
*/
@Override
public String dispTxtScl(PrintWriter out, BufferedReader in, String text) throws IOException {
String reply = "";
String dispTxtScl = "D ";
out.println(dispTxtScl + text);
reply = in.readLine();
if (!reply.substring(0, 2).equalsIgnoreCase("ES")){
reply = "Displaytekst ændret.";
} else {
reply = "Kommando fejlet.";
}
return reply;
}
/* (non-Javadoc)
* @see src.ITransmitter#zeroScale(java.io.PrintWriter, java.io.BufferedReader)
*/
@Override
public String zeroScale(PrintWriter out, BufferedReader in) throws IOException{
String zeroScale = "Z";
String reply = "";
out.println(zeroScale);
reply = in.readLine();
if (!reply.substring(0, 2).equalsIgnoreCase("ES")){
reply = "Vægt nulstillet.";
} else {
reply = "Kommando fejlet.";
}
return reply;
}
/* (non-Javadoc)
* @see src.ITransmitter#tareScale(java.io.PrintWriter, java.io.BufferedReader)
*/
@Override
public String tareScale(PrintWriter out, BufferedReader in) throws IOException{
String tareScale = "T";
String reply = "";
out.println(tareScale);
reply = in.readLine();
if (!reply.substring(0, 2).equalsIgnoreCase("ES")){
reply = "Tara Vægt: " + reply.substring(4);
} else {
reply = "Kommando fejlet.";
}
return reply;
}
/* (non-Javadoc)
* @see src.ITransmitter#readScale(java.io.PrintWriter, java.io.BufferedReader)
*/
@Override
public String readScale(PrintWriter out, BufferedReader in) throws IOException{
String readScale = "S";
String reply = "";
out.println(readScale);
reply = in.readLine();
if (!reply.substring(0, 2).equalsIgnoreCase("ES")){
reply = "Vægt: " + reply.substring(4);
} else {
reply = "Kommando fejlet.";
}
return reply;
}
@Override
public Lock getLock(){
return this.lock;
}
@Override
public String getOprPassword(int id){
int p = -1;
int[] oprID = data.getOprID();
for (int i=0; i<oprID.length; i++){
if (oprID[i] == id){
i = p;
}
}
String[] oprPass = data.getOprPassword();
return oprPass[p];
}
}
| Java |
package src;
import java.util.Scanner;
import boundary.IMenu;
import boundary.Menu;
import controller.IMenuController;
import controller.MenuController;
import controller.OperatorLoginController;
import data.Data;
import data.IData;
import functionality.ITransmitter;
import functionality.Transmitter;
public class Main {
public static void main(String[] args) {
if (args.length == 0){ // Hvis ingen host og port er valgt forudsættes det at Scale.exe kører på localHost port 4567
args = new String[2];
args[0] = "localHost";
args[1] = "4567";
}
Scanner scanner = new Scanner(System.in);
IData data = new Data();
ITransmitter transmit = new Transmitter(data);
OperatorLoginController oprLogin = new OperatorLoginController(args, transmit);
IMenu menu = new Menu(scanner);
IMenuController control = new MenuController(menu, oprLogin, transmit, args);
control.run();
}
} | Java |
package boundary;
import java.util.Scanner;
public class Menu implements IMenu {
private Scanner scanner;
public Menu(Scanner scanner){
this.scanner = scanner;
}
/* (non-Javadoc)
* @see src.IMenu#showMenu()
*/
@Override
public int showMenu(){
int choice;
System.out.println("Følgende muligheder er til rådighed: "
+ "\rTast 1 for Read Scale."
+ "\rTast 2 for Tare Scale."
+ "\rTast 3 for Zero Scale (nulstille)."
+ "\rTast 4 for Display Text on Scale."
+ "\rTast 5 for Display Weight on Scale."
+ "\rTast 6 for RM20 kommando."
+ "\rTast 7 for at afslutte.");
String input = scanner.nextLine();
switch (input) {
case "1":
choice = 1;
break;
case "2":
choice = 2;
break;
case "3":
choice = 3;
break;
case "4":
choice = 4;
break;
case "5":
choice = 5;
break;
case "6":
choice = 6;
break;
case "7":
choice = 7;
break;
default:
choice = 0;
break;
}
return choice;
}
@Override
public void showMsg(String msg){
System.out.println(msg);
}
@Override
public String getText() {
System.out.println("Indtast tekst: ");
String text = scanner.nextLine();
return text;
}
}
| Java |
package boundary;
public interface IMenu {
public abstract int showMenu();
public abstract void showMsg(String string);
public abstract String getText();
} | Java |
package controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.locks.Lock;
import boundary.IMenu;
import data.IData;
import functionality.ITransmitter;
public class MenuController implements IMenuController {
private IMenu menu;
private OperatorLoginController oprLogin;
private ITransmitter transmit;
private PrintWriter out;
private BufferedReader in;
private String host;
private int port;
private String[] args;
public MenuController (IMenu menu, OperatorLoginController oprLogin, ITransmitter transmit, String[] args) {
this.menu = menu;
this.oprLogin = oprLogin;
this.transmit = transmit;
this.args = args;
this.host = args[0];
this.port = Integer.parseInt(args[1]);
}
public void run(){
Thread loginThread = new Thread(oprLogin, "RM20 Tråd");
loginThread.start();
// Vi sikrer at operatør-login tråden starter først og låser de synchronized metoder i Transmitter
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startMenu(); // Resten af programmet startes
// Vi sikrer at den oprindelige login-tråd er afsluttet før programmet afsluttes
try {
loginThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void startMenu(){
try (Socket socket = new Socket(host, port);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));){
this.out = out;
this.in = in;
program();
} catch (UnknownHostException e) {
System.out.println("Ukendt host: " + host);
System.exit(1);
} catch (IOException e) {
System.out.println("Ingen forbindelse... Genstart program.");
System.exit(1);
}
}
@Override
public void program() throws IOException{
int choice;
String reply = "";
do {
choice = menu.showMenu();
switch (choice){
case 1:
reply = transmit.readScale(out, in);
break;
case 2:
reply = transmit.tareScale(out, in);
break;
case 3:
reply = transmit.zeroScale(out, in);
break;
case 4: {
Lock lock = transmit.getLock();
if (lock.tryLock()){
try{
String text = menu.getText();
reply = transmit.dispTxtScl(out, in, text);
} finally {
lock.unlock();
}
} else {
reply = "Vægt optaget.";
}
}
break;
case 5:
reply = transmit.dispWghtScl(out, in);
break;
case 6:
{
startOprLogin();
reply = "Operatør-login forsøgt startet.";
}
break;
case 7:
reply = "Menuen afsluttes.";
break;
default:
reply = "Input ikke godkendt.";
}
menu.showMsg(reply);
}
while (choice != 7);
}
@Override
public void startOprLogin(){
Thread loginThread = new Thread(new OperatorLoginController(args, transmit));
loginThread.start();
}
}
| Java |
package controller;
public interface IOperatorLoginController {
public abstract void run();
} | Java |
package controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.locks.Lock;
import data.IData;
import functionality.ITransmitter;
public class OperatorLoginController implements Runnable, IOperatorLoginController {
private String host;
private int port;
private ITransmitter transmit;
public OperatorLoginController(String[] args, ITransmitter transmit){
this.host = args[0];
this.port = Integer.parseInt(args[1]);
this.transmit = transmit;
}
@Override
public void run() {
try (Socket socket2 = new Socket(host, port);
PrintWriter out = new PrintWriter(socket2.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket2.getInputStream()));){
Lock lock = transmit.getLock();
if (lock.tryLock()){
System.out.println("Operatør-login startet!");
try {
int userID = transmit.getInputUserId(out, in);
System.out.println("Indtastet userID: " + userID);
String password = transmit.getInputPassword(out, in);
System.out.println("Indtastet password: " + password);
if (transmit.getOprPassword(userID).equals(password)){
transmit.dispTxtScl(out, in, "Operatoer godkendt");
System.out.println("Operatør " + userID + " er logget ind.");
} else {
transmit.dispTxtScl(out, in, "Forkert login");
System.out.println("Operatør " + userID + " har indtastet forkert password.");
}
System.out.println("Operatør-login tråd termineret (Operatør har indtastet UserID + Password, eller afbrudt loginsekvens).");
} finally {
lock.unlock();
}
}
else {
System.out.println("Operatør-login kunne ikke startes. Forsøg igen senere.");
}
}catch (UnknownHostException e) {
System.out.println("Ukendt host: " + host);
System.exit(1);
} catch (IOException e) {
System.out.println("Ingen forbindelse... Genstart program.");
System.exit(1);
}
}
}
| Java |
package controller;
import java.io.IOException;
public interface IMenuController {
public abstract void run();
/**
* Connecter til Scale.exe og starter menuen (program())
* Kan modtage kommandoer fra konsol og sende disse til WeightConsole. Modtager svar og viser dette.
* @param args args[0] = host, args[1] = port
*/
public abstract void startMenu();
public abstract void program() throws IOException;
public abstract void startOprLogin();
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.url;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* See http://en.wikipedia.org/wiki/URL_normalization for a reference Note: some
* parts of the code are adapted from: http://stackoverflow.com/a/4057470/405418
*
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public class URLCanonicalizer {
public static String getCanonicalURL(String url) {
return getCanonicalURL(url, null);
}
public static String getCanonicalURL(String href, String context) {
try {
URL canonicalURL = new URL(UrlResolver.resolveUrl(context == null ? "" : context, href));
String host = canonicalURL.getHost().toLowerCase();
if (host == "") {
// This is an invalid Url.
return null;
}
String path = canonicalURL.getPath();
/*
* Normalize: no empty segments (i.e., "//"), no segments equal to
* ".", and no segments equal to ".." that are preceded by a segment
* not equal to "..".
*/
path = new URI(path.replace("\\", "/")).normalize().toString();
/*
* Convert '//' -> '/'
*/
int idx = path.indexOf("//");
while (idx >= 0) {
path = path.replace("//", "/");
idx = path.indexOf("//");
}
/*
* Drop starting '/../'
*/
while (path.startsWith("/../")) {
path = path.substring(3);
}
/*
* Trim
*/
path = path.trim();
final SortedMap<String, String> params = createParameterMap(canonicalURL.getQuery());
final String queryString;
if (params != null && params.size() > 0) {
String canonicalParams = canonicalize(params);
queryString = (canonicalParams.isEmpty() ? "" : "?" + canonicalParams);
} else {
queryString = "";
}
/*
* Add starting slash if needed
*/
if (path.length() == 0) {
path = "/" + path;
}
/*
* Drop default port: example.com:80 -> example.com
*/
int port = canonicalURL.getPort();
if (port == canonicalURL.getDefaultPort()) {
port = -1;
}
String protocol = canonicalURL.getProtocol().toLowerCase();
String pathAndQueryString = normalizePath(path) + queryString;
URL result = new URL(protocol, host, port, pathAndQueryString);
return result.toExternalForm();
} catch (MalformedURLException ex) {
return null;
} catch (URISyntaxException ex) {
return null;
}
}
/**
* Takes a query string, separates the constituent name-value pairs, and
* stores them in a SortedMap ordered by lexicographical order.
*
* @return Null if there is no query string.
*/
private static SortedMap<String, String> createParameterMap(final String queryString) {
if (queryString == null || queryString.isEmpty()) {
return null;
}
final String[] pairs = queryString.split("&");
final Map<String, String> params = new HashMap<>(pairs.length);
for (final String pair : pairs) {
if (pair.length() == 0) {
continue;
}
String[] tokens = pair.split("=", 2);
switch (tokens.length) {
case 1:
if (pair.charAt(0) == '=') {
params.put("", tokens[0]);
} else {
params.put(tokens[0], "");
}
break;
case 2:
params.put(tokens[0], tokens[1]);
break;
}
}
return new TreeMap<>(params);
}
/**
* Canonicalize the query string.
*
* @param sortedParamMap
* Parameter name-value pairs in lexicographical order.
* @return Canonical form of query string.
*/
private static String canonicalize(final SortedMap<String, String> sortedParamMap) {
if (sortedParamMap == null || sortedParamMap.isEmpty()) {
return "";
}
final StringBuffer sb = new StringBuffer(100);
for (Map.Entry<String, String> pair : sortedParamMap.entrySet()) {
final String key = pair.getKey().toLowerCase();
if (key.equals("jsessionid") || key.equals("phpsessid") || key.equals("aspsessionid")) {
continue;
}
if (sb.length() > 0) {
sb.append('&');
}
sb.append(percentEncodeRfc3986(pair.getKey()));
if (!pair.getValue().isEmpty()) {
sb.append('=');
sb.append(percentEncodeRfc3986(pair.getValue()));
}
}
return sb.toString();
}
/**
* Percent-encode values according the RFC 3986. The built-in Java
* URLEncoder does not encode according to the RFC, so we make the extra
* replacements.
*
* @param string
* Decoded string.
* @return Encoded string per RFC 3986.
*/
private static String percentEncodeRfc3986(String string) {
try {
string = string.replace("+", "%2B");
string = URLDecoder.decode(string, "UTF-8");
string = URLEncoder.encode(string, "UTF-8");
return string.replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
} catch (Exception e) {
return string;
}
}
private static String normalizePath(final String path) {
return path.replace("%7E", "~").replace(" ", "%20");
}
} | Java |
package edu.uci.ics.crawler4j.url;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;
/**
* This class is a singleton which obtains a list of TLDs (from online or a zip file) in order to compare against those TLDs
* */
public class TLDList {
private final static String TLD_NAMES_ONLINE_URL = "https://publicsuffix.org/list/effective_tld_names.dat";
private final static String TLD_NAMES_ZIP_FILENAME = "tld-names.zip";
private final static String TLD_NAMES_TXT_FILENAME = "tld-names.txt";
private final static Logger logger = LoggerFactory.getLogger(TLDList.class);
private Set<String> tldSet = new HashSet<>(10000);
private static TLDList instance = new TLDList(); // Singleton
private TLDList() {
try {
InputStream stream = null;
try {
logger.debug("Fetching the most updated TLD list online");
URL url = new URL(TLD_NAMES_ONLINE_URL);
stream = url.openStream();
} catch (Exception ex) {
logger.warn("Couldn't fetch the online list of TLDs from: {}", TLD_NAMES_ONLINE_URL);
logger.info("Fetching the list from a local file {}", TLD_NAMES_ZIP_FILENAME);
ZipFile zipFile = new ZipFile(this.getClass().getClassLoader().getResource(TLD_NAMES_ZIP_FILENAME).getFile());
ZipArchiveEntry entry = zipFile.getEntry(TLD_NAMES_TXT_FILENAME);
stream = zipFile.getInputStream(entry);
}
if (stream == null) {
throw new Exception("Couldn't fetch the TLD list online or from a local file");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.isEmpty() || line.startsWith("//")) {
continue;
}
tldSet.add(line);
}
reader.close();
stream.close();
} catch (Exception e) {
logger.error("Couldn't find " + TLD_NAMES_TXT_FILENAME, e);
System.exit(-1);
}
}
public static TLDList getInstance() {
return instance;
}
public boolean contains(String str) {
return tldSet.contains(str);
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.url;
import java.io.Serializable;
import com.sleepycat.persist.model.Entity;
import com.sleepycat.persist.model.PrimaryKey;
/**
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
@Entity
public class WebURL implements Serializable {
private static final long serialVersionUID = 1L;
@PrimaryKey
private String url;
private int docid;
private int parentDocid;
private String parentUrl;
private short depth;
private String domain;
private String subDomain;
private String path;
private String anchor;
private byte priority;
private String tag;
/**
* @return unique document id assigned to this Url.
*/
public int getDocid() {
return docid;
}
public void setDocid(int docid) {
this.docid = docid;
}
@Override
public int hashCode() {
return url.hashCode();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
WebURL otherUrl = (WebURL) o;
return url != null && url.equals(otherUrl.getURL());
}
@Override
public String toString() {
return url;
}
/**
* @return Url string
*/
public String getURL() {
return url;
}
public void setURL(String url) {
this.url = url;
int domainStartIdx = url.indexOf("//") + 2;
int domainEndIdx = url.indexOf('/', domainStartIdx);
domainEndIdx = domainEndIdx > domainStartIdx ? domainEndIdx : url.length();
domain = url.substring(domainStartIdx, domainEndIdx);
subDomain = "";
String[] parts = domain.split("\\.");
if (parts.length > 2) {
domain = parts[parts.length - 2] + "." + parts[parts.length - 1];
int limit = 2;
if (TLDList.getInstance().contains(domain)) {
domain = parts[parts.length - 3] + "." + domain;
limit = 3;
}
for (int i = 0; i < parts.length - limit; i++) {
if (subDomain.length() > 0) {
subDomain += ".";
}
subDomain += parts[i];
}
}
path = url.substring(domainEndIdx);
int pathEndIdx = path.indexOf('?');
if (pathEndIdx >= 0) {
path = path.substring(0, pathEndIdx);
}
}
/**
* @return
* unique document id of the parent page. The parent page is the
* page in which the Url of this page is first observed.
*/
public int getParentDocid() {
return parentDocid;
}
public void setParentDocid(int parentDocid) {
this.parentDocid = parentDocid;
}
/**
* @return
* url of the parent page. The parent page is the page in which
* the Url of this page is first observed.
*/
public String getParentUrl() {
return parentUrl;
}
public void setParentUrl(String parentUrl) {
this.parentUrl = parentUrl;
}
/**
* @return
* crawl depth at which this Url is first observed. Seed Urls
* are at depth 0. Urls that are extracted from seed Urls are at depth 1, etc.
*/
public short getDepth() {
return depth;
}
public void setDepth(short depth) {
this.depth = depth;
}
/**
* @return
* domain of this Url. For 'http://www.example.com/sample.htm', domain will be 'example.com'
*/
public String getDomain() {
return domain;
}
public String getSubDomain() {
return subDomain;
}
/**
* @return
* path of this Url. For 'http://www.example.com/sample.htm', domain will be 'sample.htm'
*/
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
/**
* @return
* anchor string. For example, in <a href="example.com">A sample anchor</a>
* the anchor string is 'A sample anchor'
*/
public String getAnchor() {
return anchor;
}
public void setAnchor(String anchor) {
this.anchor = anchor;
}
/**
* @return priority for crawling this URL. A lower number results in higher priority.
*/
public byte getPriority() {
return priority;
}
public void setPriority(byte priority) {
this.priority = priority;
}
/**
* @return tag in which this URL is found
* */
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
} | Java |
/**
* This class is adopted from Htmlunit with the following copyright:
*
* Copyright (c) 2002-2012 Gargoyle Software Inc.
*
* 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 edu.uci.ics.crawler4j.url;
public final class UrlResolver {
/**
* Resolves a given relative URL against a base URL. See
* <a href="http://www.faqs.org/rfcs/rfc1808.html">RFC1808</a>
* Section 4 for more details.
*
* @param baseUrl The base URL in which to resolve the specification.
* @param relativeUrl The relative URL to resolve against the base URL.
* @return the resolved specification.
*/
public static String resolveUrl(final String baseUrl, final String relativeUrl) {
if (baseUrl == null) {
throw new IllegalArgumentException("Base URL must not be null");
}
if (relativeUrl == null) {
throw new IllegalArgumentException("Relative URL must not be null");
}
final Url url = resolveUrl(parseUrl(baseUrl.trim()), relativeUrl.trim());
return url.toString();
}
/**
* Returns the index within the specified string of the first occurrence of
* the specified search character.
*
* @param s the string to search
* @param searchChar the character to search for
* @param beginIndex the index at which to start the search
* @param endIndex the index at which to stop the search
* @return the index of the first occurrence of the character in the string or <tt>-1</tt>
*/
private static int indexOf(final String s, final char searchChar, final int beginIndex, final int endIndex) {
for (int i = beginIndex; i < endIndex; i++) {
if (s.charAt(i) == searchChar) {
return i;
}
}
return -1;
}
/**
* Parses a given specification using the algorithm depicted in
* <a href="http://www.faqs.org/rfcs/rfc1808.html">RFC1808</a>:
*
* Section 2.4: Parsing a URL
*
* An accepted method for parsing URLs is useful to clarify the
* generic-RL syntax of Section 2.2 and to describe the algorithm for
* resolving relative URLs presented in Section 4. This section
* describes the parsing rules for breaking down a URL (relative or
* absolute) into the component parts described in Section 2.1. The
* rules assume that the URL has already been separated from any
* surrounding text and copied to a "parse string". The rules are
* listed in the order in which they would be applied by the parser.
*
* @param spec The specification to parse.
* @return the parsed specification.
*/
private static Url parseUrl(final String spec) {
final Url url = new Url();
int startIndex = 0;
int endIndex = spec.length();
// Section 2.4.1: Parsing the Fragment Identifier
//
// If the parse string contains a crosshatch "#" character, then the
// substring after the first (left-most) crosshatch "#" and up to the
// end of the parse string is the <fragment> identifier. If the
// crosshatch is the last character, or no crosshatch is present, then
// the fragment identifier is empty. The matched substring, including
// the crosshatch character, is removed from the parse string before
// continuing.
//
// Note that the fragment identifier is not considered part of the URL.
// However, since it is often attached to the URL, parsers must be able
// to recognize and set aside fragment identifiers as part of the
// process.
final int crosshatchIndex = indexOf(spec, '#', startIndex, endIndex);
if (crosshatchIndex >= 0) {
url.fragment_ = spec.substring(crosshatchIndex + 1, endIndex);
endIndex = crosshatchIndex;
}
// Section 2.4.2: Parsing the Scheme
//
// If the parse string contains a colon ":" after the first character
// and before any characters not allowed as part of a scheme name (i.e.,
// any not an alphanumeric, plus "+", period ".", or hyphen "-"), the
// <scheme> of the URL is the substring of characters up to but not
// including the first colon. These characters and the colon are then
// removed from the parse string before continuing.
final int colonIndex = indexOf(spec, ':', startIndex, endIndex);
if (colonIndex > 0) {
final String scheme = spec.substring(startIndex, colonIndex);
if (isValidScheme(scheme)) {
url.scheme_ = scheme;
startIndex = colonIndex + 1;
}
}
// Section 2.4.3: Parsing the Network Location/Login
//
// If the parse string begins with a double-slash "//", then the
// substring of characters after the double-slash and up to, but not
// including, the next slash "/" character is the network location/login
// (<net_loc>) of the URL. If no trailing slash "/" is present, the
// entire remaining parse string is assigned to <net_loc>. The double-
// slash and <net_loc> are removed from the parse string before
// continuing.
//
// Note: We also accept a question mark "?" or a semicolon ";" character as
// delimiters for the network location/login (<net_loc>) of the URL.
final int locationStartIndex;
int locationEndIndex;
if (spec.startsWith("//", startIndex)) {
locationStartIndex = startIndex + 2;
locationEndIndex = indexOf(spec, '/', locationStartIndex, endIndex);
if (locationEndIndex >= 0) {
startIndex = locationEndIndex;
}
}
else {
locationStartIndex = -1;
locationEndIndex = -1;
}
// Section 2.4.4: Parsing the Query Information
//
// If the parse string contains a question mark "?" character, then the
// substring after the first (left-most) question mark "?" and up to the
// end of the parse string is the <query> information. If the question
// mark is the last character, or no question mark is present, then the
// query information is empty. The matched substring, including the
// question mark character, is removed from the parse string before
// continuing.
final int questionMarkIndex = indexOf(spec, '?', startIndex, endIndex);
if (questionMarkIndex >= 0) {
if ((locationStartIndex >= 0) && (locationEndIndex < 0)) {
// The substring of characters after the double-slash and up to, but not
// including, the question mark "?" character is the network location/login
// (<net_loc>) of the URL.
locationEndIndex = questionMarkIndex;
startIndex = questionMarkIndex;
}
url.query_ = spec.substring(questionMarkIndex + 1, endIndex);
endIndex = questionMarkIndex;
}
// Section 2.4.5: Parsing the Parameters
//
// If the parse string contains a semicolon ";" character, then the
// substring after the first (left-most) semicolon ";" and up to the end
// of the parse string is the parameters (<params>). If the semicolon
// is the last character, or no semicolon is present, then <params> is
// empty. The matched substring, including the semicolon character, is
// removed from the parse string before continuing.
final int semicolonIndex = indexOf(spec, ';', startIndex, endIndex);
if (semicolonIndex >= 0) {
if ((locationStartIndex >= 0) && (locationEndIndex < 0)) {
// The substring of characters after the double-slash and up to, but not
// including, the semicolon ";" character is the network location/login
// (<net_loc>) of the URL.
locationEndIndex = semicolonIndex;
startIndex = semicolonIndex;
}
url.parameters_ = spec.substring(semicolonIndex + 1, endIndex);
endIndex = semicolonIndex;
}
// Section 2.4.6: Parsing the Path
//
// After the above steps, all that is left of the parse string is the
// URL <path> and the slash "/" that may precede it. Even though the
// initial slash is not part of the URL path, the parser must remember
// whether or not it was present so that later processes can
// differentiate between relative and absolute paths. Often this is
// done by simply storing the preceding slash along with the path.
if ((locationStartIndex >= 0) && (locationEndIndex < 0)) {
// The entire remaining parse string is assigned to the network
// location/login (<net_loc>) of the URL.
locationEndIndex = endIndex;
}
else if (startIndex < endIndex) {
url.path_ = spec.substring(startIndex, endIndex);
}
// Set the network location/login (<net_loc>) of the URL.
if ((locationStartIndex >= 0) && (locationEndIndex >= 0)) {
url.location_ = spec.substring(locationStartIndex, locationEndIndex);
}
return url;
}
/*
* Returns true if specified string is a valid scheme name.
*/
private static boolean isValidScheme(final String scheme) {
final int length = scheme.length();
if (length < 1) {
return false;
}
char c = scheme.charAt(0);
if (!Character.isLetter(c)) {
return false;
}
for (int i = 1; i < length; i++) {
c = scheme.charAt(i);
if (!Character.isLetterOrDigit(c) && c != '.' && c != '+' && c != '-') {
return false;
}
}
return true;
}
/**
* Resolves a given relative URL against a base URL using the algorithm
* depicted in <a href="http://www.faqs.org/rfcs/rfc1808.html">RFC1808</a>:
*
* Section 4: Resolving Relative URLs
*
* This section describes an example algorithm for resolving URLs within
* a context in which the URLs may be relative, such that the result is
* always a URL in absolute form. Although this algorithm cannot
* guarantee that the resulting URL will equal that intended by the
* original author, it does guarantee that any valid URL (relative or
* absolute) can be consistently transformed to an absolute form given a
* valid base URL.
*
* @param baseUrl The base URL in which to resolve the specification.
* @param relativeUrl The relative URL to resolve against the base URL.
* @return the resolved specification.
*/
private static Url resolveUrl(final Url baseUrl, final String relativeUrl) {
final Url url = parseUrl(relativeUrl);
// Step 1: The base URL is established according to the rules of
// Section 3. If the base URL is the empty string (unknown),
// the embedded URL is interpreted as an absolute URL and
// we are done.
if (baseUrl == null) {
return url;
}
// Step 2: Both the base and embedded URLs are parsed into their
// component parts as described in Section 2.4.
// a) If the embedded URL is entirely empty, it inherits the
// entire base URL (i.e., is set equal to the base URL)
// and we are done.
if (relativeUrl.length() == 0) {
return new Url(baseUrl);
}
// b) If the embedded URL starts with a scheme name, it is
// interpreted as an absolute URL and we are done.
if (url.scheme_ != null) {
return url;
}
// c) Otherwise, the embedded URL inherits the scheme of
// the base URL.
url.scheme_ = baseUrl.scheme_;
// Step 3: If the embedded URL's <net_loc> is non-empty, we skip to
// Step 7. Otherwise, the embedded URL inherits the <net_loc>
// (if any) of the base URL.
if (url.location_ != null) {
return url;
}
url.location_ = baseUrl.location_;
// Step 4: If the embedded URL path is preceded by a slash "/", the
// path is not relative and we skip to Step 7.
if ((url.path_ != null) && ((url.path_.length() > 0) && ('/' == url.path_.charAt(0)))) {
url.path_ = removeLeadingSlashPoints(url.path_);
return url;
}
// Step 5: If the embedded URL path is empty (and not preceded by a
// slash), then the embedded URL inherits the base URL path,
// and
if (url.path_ == null) {
url.path_ = baseUrl.path_;
// a) if the embedded URL's <params> is non-empty, we skip to
// step 7; otherwise, it inherits the <params> of the base
// URL (if any) and
if (url.parameters_ != null) {
return url;
}
url.parameters_ = baseUrl.parameters_;
// b) if the embedded URL's <query> is non-empty, we skip to
// step 7; otherwise, it inherits the <query> of the base
// URL (if any) and we skip to step 7.
if (url.query_ != null) {
return url;
}
url.query_ = baseUrl.query_;
return url;
}
// Step 6: The last segment of the base URL's path (anything
// following the rightmost slash "/", or the entire path if no
// slash is present) is removed and the embedded URL's path is
// appended in its place. The following operations are
// then applied, in order, to the new path:
final String basePath = baseUrl.path_;
String path = "";
if (basePath != null) {
final int lastSlashIndex = basePath.lastIndexOf('/');
if (lastSlashIndex >= 0) {
path = basePath.substring(0, lastSlashIndex + 1);
}
}
else {
path = "/";
}
path = path.concat(url.path_);
// a) All occurrences of "./", where "." is a complete path
// segment, are removed.
int pathSegmentIndex;
while ((pathSegmentIndex = path.indexOf("/./")) >= 0) {
path = path.substring(0, pathSegmentIndex + 1).concat(path.substring(pathSegmentIndex + 3));
}
// b) If the path ends with "." as a complete path segment,
// that "." is removed.
if (path.endsWith("/.")) {
path = path.substring(0, path.length() - 1);
}
// c) All occurrences of "<segment>/../", where <segment> is a
// complete path segment not equal to "..", are removed.
// Removal of these path segments is performed iteratively,
// removing the leftmost matching pattern on each iteration,
// until no matching pattern remains.
while ((pathSegmentIndex = path.indexOf("/../")) > 0) {
final String pathSegment = path.substring(0, pathSegmentIndex);
final int slashIndex = pathSegment.lastIndexOf('/');
if (slashIndex < 0) {
continue;
}
if (!"..".equals(pathSegment.substring(slashIndex))) {
path = path.substring(0, slashIndex + 1).concat(path.substring(pathSegmentIndex + 4));
}
}
// d) If the path ends with "<segment>/..", where <segment> is a
// complete path segment not equal to "..", that
// "<segment>/.." is removed.
if (path.endsWith("/..")) {
final String pathSegment = path.substring(0, path.length() - 3);
final int slashIndex = pathSegment.lastIndexOf('/');
if (slashIndex >= 0) {
path = path.substring(0, slashIndex + 1);
}
}
path = removeLeadingSlashPoints(path);
url.path_ = path;
// Step 7: The resulting URL components, including any inherited from
// the base URL, are recombined to give the absolute form of
// the embedded URL.
return url;
}
/**
* "/.." at the beginning should be removed as browsers do (not in RFC)
*/
private static String removeLeadingSlashPoints(String path) {
while (path.startsWith("/..")) {
path = path.substring(3);
}
return path;
}
/**
* Class <tt>Url</tt> represents a Uniform Resource Locator.
*
* @author Martin Tamme
*/
private static class Url {
String scheme_;
String location_;
String path_;
String parameters_;
String query_;
String fragment_;
/**
* Creates a <tt>Url</tt> object.
*/
public Url() {
}
/**
* Creates a <tt>Url</tt> object from the specified
* <tt>Url</tt> object.
*
* @param url a <tt>Url</tt> object.
*/
public Url(final Url url) {
scheme_ = url.scheme_;
location_ = url.location_;
path_ = url.path_;
parameters_ = url.parameters_;
query_ = url.query_;
fragment_ = url.fragment_;
}
/**
* Returns a string representation of the <tt>Url</tt> object.
*
* @return a string representation of the <tt>Url</tt> object.
*/
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
if (scheme_ != null) {
sb.append(scheme_);
sb.append(':');
}
if (location_ != null) {
sb.append("//");
sb.append(location_);
}
if (path_ != null) {
sb.append(path_);
}
if (parameters_ != null) {
sb.append(';');
sb.append(parameters_);
}
if (query_ != null) {
sb.append('?');
sb.append(query_);
}
if (fragment_ != null) {
sb.append('#');
sb.append(fragment_);
}
return sb.toString();
}
}
}
| Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.fetcher;
import java.util.concurrent.TimeUnit;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
public class IdleConnectionMonitorThread extends Thread {
private final PoolingHttpClientConnectionManager connMgr;
private volatile boolean shutdown;
public IdleConnectionMonitorThread(PoolingHttpClientConnectionManager connMgr) {
super("Connection Manager");
this.connMgr = connMgr;
}
@Override
public void run() {
try {
while (!shutdown) {
synchronized (this) {
wait(5000);
// Close expired connections
connMgr.closeExpiredConnections();
// Optionally, close connections
// that have been idle longer than 30 sec
connMgr.closeIdleConnections(30, TimeUnit.SECONDS);
}
}
} catch (InterruptedException ex) {
// terminate
}
}
public void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.fetcher;
import java.io.EOFException;
import java.io.IOException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.util.EntityUtils;
import edu.uci.ics.crawler4j.crawler.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public class PageFetchResult {
protected static final Logger logger = LoggerFactory.getLogger(PageFetchResult.class);
protected int statusCode;
protected HttpEntity entity = null;
protected Header[] responseHeaders = null;
protected String fetchedUrl = null;
protected String movedToUrl = null;
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public HttpEntity getEntity() {
return entity;
}
public void setEntity(HttpEntity entity) {
this.entity = entity;
}
public Header[] getResponseHeaders() {
return responseHeaders;
}
public void setResponseHeaders(Header[] responseHeaders) {
this.responseHeaders = responseHeaders;
}
public String getFetchedUrl() {
return fetchedUrl;
}
public void setFetchedUrl(String fetchedUrl) {
this.fetchedUrl = fetchedUrl;
}
public boolean fetchContent(Page page) {
try {
page.load(entity);
page.setFetchResponseHeaders(responseHeaders);
return true;
} catch (Exception e) {
logger.info("Exception while fetching content for: {} [{}]",page.getWebURL().getURL(), e.getMessage());
}
return false;
}
public void discardContentIfNotConsumed() {
try {
if (entity != null) {
EntityUtils.consume(entity);
}
} catch (EOFException e) {
// We can ignore this exception. It can happen on compressed streams
// which are not repeatable
} catch (IOException e) {
// We can ignore this exception. It can happen if the stream is
// closed.
} catch (Exception e) {
e.printStackTrace();
}
}
public String getMovedToUrl() {
return movedToUrl;
}
public void setMovedToUrl(String movedToUrl) {
this.movedToUrl = movedToUrl;
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.fetcher;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.net.ssl.SSLContext;
import edu.uci.ics.crawler4j.crawler.*;
import edu.uci.ics.crawler4j.crawler.authentication.AuthInfo;
import edu.uci.ics.crawler4j.crawler.authentication.BasicAuthInfo;
import edu.uci.ics.crawler4j.crawler.authentication.FormAuthInfo;
import edu.uci.ics.crawler4j.crawler.exceptions.PageBiggerThanMaxSizeException;
import org.apache.http.*;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.*;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.uci.ics.crawler4j.url.URLCanonicalizer;
import edu.uci.ics.crawler4j.url.WebURL;
/**
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public class PageFetcher extends Configurable {
protected static final Logger logger = LoggerFactory.getLogger(PageFetcher.class);
protected PoolingHttpClientConnectionManager connectionManager;
protected CloseableHttpClient httpClient;
protected final Object mutex = new Object();
protected long lastFetchTime = 0;
protected IdleConnectionMonitorThread connectionMonitorThread = null;
public PageFetcher(CrawlConfig config) {
super(config);
RequestConfig requestConfig = RequestConfig.custom()
.setExpectContinueEnabled(false)
.setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
.setRedirectsEnabled(false)
.setSocketTimeout(config.getSocketTimeout())
.setConnectTimeout(config.getConnectionTimeout())
.build();
RegistryBuilder<ConnectionSocketFactory> connRegistryBuilder = RegistryBuilder.create();
connRegistryBuilder.register("http", PlainConnectionSocketFactory.INSTANCE);
if (config.isIncludeHttpsPages()) {
try { // Fixing: https://code.google.com/p/crawler4j/issues/detail?id=174
// By always trusting the ssl certificate
SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(final X509Certificate[] chain, String authType) {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
connRegistryBuilder.register("https", sslsf);
} catch (Exception e) {
logger.warn("Exception thrown while trying to register https");
logger.debug("Stacktrace", e);
}
}
Registry<ConnectionSocketFactory> connRegistry = connRegistryBuilder.build();
connectionManager = new PoolingHttpClientConnectionManager(connRegistry);
connectionManager.setMaxTotal(config.getMaxTotalConnections());
connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());
HttpClientBuilder clientBuilder = HttpClientBuilder.create();
clientBuilder.setDefaultRequestConfig(requestConfig);
clientBuilder.setConnectionManager(connectionManager);
clientBuilder.setUserAgent(config.getUserAgentString());
if (config.getProxyHost() != null) {
if (config.getProxyUsername() != null) {
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
new AuthScope(config.getProxyHost(), config.getProxyPort()),
new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort());
clientBuilder.setProxy(proxy);
logger.debug("Working through Proxy: {}", proxy.getHostName());
}
httpClient = clientBuilder.build();
if (config.getAuthInfos() != null && !config.getAuthInfos().isEmpty()) {
doAuthetication(config.getAuthInfos());
}
if (connectionMonitorThread == null) {
connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager);
}
connectionMonitorThread.start();
}
private void doAuthetication(List<AuthInfo> authInfos) {
for (AuthInfo authInfo : authInfos) {
if (authInfo.getAuthenticationType().equals(AuthInfo.AuthenticationType.BASIC_AUTHENTICATION)) {
doBasicLogin((BasicAuthInfo) authInfo);
} else {
doFormLogin((FormAuthInfo) authInfo);
}
}
}
/**
* BASIC authentication<br/>
* Official Example: https://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientAuthentication.java
* */
private void doBasicLogin(BasicAuthInfo authInfo) {
logger.info("BASIC authentication for: " + authInfo.getLoginTarget());
HttpHost targetHost = new HttpHost(authInfo.getHost(), authInfo.getPort(), authInfo.getProtocol());
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials(authInfo.getUsername(), authInfo.getPassword()));
httpClient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider)
.build();
}
/**
* FORM authentication<br/>
* Official Example: https://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientFormLogin.java
* */
private void doFormLogin(FormAuthInfo authInfo) {
logger.info("FORM authentication for: " + authInfo.getLoginTarget());
String fullUri = authInfo.getProtocol() + "://" + authInfo.getHost() + ":" + authInfo.getPort() + authInfo.getLoginTarget();
HttpPost httpPost = new HttpPost(fullUri);
List<NameValuePair> formParams = new ArrayList<>();
formParams.add(new BasicNameValuePair(authInfo.getUsernameFormStr(), authInfo.getUsername()));
formParams.add(new BasicNameValuePair(authInfo.getPasswordFormStr(), authInfo.getPassword()));
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");
httpPost.setEntity(entity);
httpClient.execute(httpPost);
logger.debug("Successfully Logged in with user: " + authInfo.getUsername() + " to: " + authInfo.getHost());
} catch (UnsupportedEncodingException e) {
logger.error("Encountered a non supported encoding while trying to login to: " + authInfo.getHost(), e);
} catch (ClientProtocolException e) {
logger.error("While trying to login to: " + authInfo.getHost() + " - Client protocol not supported", e);
} catch (IOException e) {
logger.error("While trying to login to: " + authInfo.getHost() + " - Error making request", e);
}
}
public PageFetchResult fetchPage(WebURL webUrl) throws InterruptedException, IOException, PageBiggerThanMaxSizeException {
// Getting URL, setting headers & content
PageFetchResult fetchResult = new PageFetchResult();
String toFetchURL = webUrl.getURL();
HttpGet get = null;
try {
get = new HttpGet(toFetchURL);
// Applying Politeness delay
synchronized (mutex) {
long now = (new Date()).getTime();
if (now - lastFetchTime < config.getPolitenessDelay()) {
Thread.sleep(config.getPolitenessDelay() - (now - lastFetchTime));
}
lastFetchTime = (new Date()).getTime();
}
HttpResponse response = httpClient.execute(get);
fetchResult.setEntity(response.getEntity());
fetchResult.setResponseHeaders(response.getAllHeaders());
// Setting HttpStatus
int statusCode = response.getStatusLine().getStatusCode();
// If Redirect ( 3xx )
if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY
|| statusCode == HttpStatus.SC_MULTIPLE_CHOICES || statusCode == HttpStatus.SC_SEE_OTHER
|| statusCode == HttpStatus.SC_TEMPORARY_REDIRECT || statusCode == 308) { // todo follow https://issues.apache.org/jira/browse/HTTPCORE-389
Header header = response.getFirstHeader("Location");
if (header != null) {
String movedToUrl = URLCanonicalizer.getCanonicalURL(header.getValue(), toFetchURL);
fetchResult.setMovedToUrl(movedToUrl);
}
} else if (statusCode == HttpStatus.SC_OK) { // is 200, everything looks ok
fetchResult.setFetchedUrl(toFetchURL);
String uri = get.getURI().toString();
if (!uri.equals(toFetchURL)) {
if (!URLCanonicalizer.getCanonicalURL(uri).equals(toFetchURL)) {
fetchResult.setFetchedUrl(uri);
}
}
// Checking maximum size
if (fetchResult.getEntity() != null) {
long size = fetchResult.getEntity().getContentLength();
if (size > config.getMaxDownloadSize()) {
throw new PageBiggerThanMaxSizeException(size);
}
}
}
fetchResult.setStatusCode(statusCode);
return fetchResult;
} finally { // occurs also with thrown exceptions
if (fetchResult.getEntity() == null && get != null) {
get.abort();
}
}
}
public synchronized void shutDown() {
if (connectionMonitorThread != null) {
connectionManager.shutdown();
connectionMonitorThread.shutdown();
}
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.parser;
import edu.uci.ics.crawler4j.url.WebURL;
import java.util.Map;
import java.util.Set;
public class HtmlParseData implements ParseData {
private String html;
private String text;
private String title;
private Map<String, String> metaTags;
private Set<WebURL> outgoingUrls;
public String getHtml() {
return html;
}
public void setHtml(String html) {
this.html = html;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Map<String, String> getMetaTags() {
return metaTags;
}
public void setMetaTags(Map<String, String> metaTags) {
this.metaTags = metaTags;
}
@Override
public Set<WebURL> getOutgoingUrls() {
return outgoingUrls;
}
@Override
public void setOutgoingUrls(Set<WebURL> outgoingUrls) {
this.outgoingUrls = outgoingUrls;
}
@Override
public String toString() {
return text;
}
} | Java |
package edu.uci.ics.crawler4j.parser;
public class ExtractedUrlAnchorPair {
private String href;
private String anchor;
private String tag;
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
public String getAnchor() {
return anchor;
}
public void setAnchor(String anchor) {
this.anchor = anchor;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.parser;
import edu.uci.ics.crawler4j.url.WebURL;
import java.util.Set;
public interface ParseData {
Set<WebURL> getOutgoingUrls();
void setOutgoingUrls(Set<WebURL> outgoingUrls);
@Override
String toString();
} | Java |
package edu.uci.ics.crawler4j.parser;
/**
* Created by Avi on 8/19/2014.
*
* This Exception will be thrown whenever the parser tries to parse not allowed content<br>
* For example when the parser tries to parse binary content although the user configured it not to do it
*/
public class NotAllowedContentException extends Exception {
public NotAllowedContentException() {
super("Not allowed to parse this type of content");
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.parser;
import edu.uci.ics.crawler4j.url.WebURL;
import java.util.HashSet;
import java.util.Set;
public class TextParseData implements ParseData {
private String textContent;
private Set<WebURL> outgoingUrls = new HashSet<>();
public String getTextContent() {
return textContent;
}
public void setTextContent(String textContent) {
this.textContent = textContent;
}
@Override
public Set<WebURL> getOutgoingUrls() {
return outgoingUrls;
}
@Override
public void setOutgoingUrls(Set<WebURL> outgoingUrls) {
this.outgoingUrls = outgoingUrls;
}
@Override
public String toString() {
return textContent;
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.parser;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.HashSet;
import java.util.Set;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import edu.uci.ics.crawler4j.url.WebURL;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BinaryParseData implements ParseData {
private static final Logger logger = LoggerFactory.getLogger(BinaryParseData.class);
private static final String DEFAULT_ENCODING = "UTF-8";
private static final String DEFAULT_OUTPUT_FORMAT = "html";
private static final Parser AUTO_DETECT_PARSER = new AutoDetectParser();
private static final SAXTransformerFactory SAX_TRANSFORMER_FACTORY = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
private final ParseContext context = new ParseContext();
private Set<WebURL> outgoingUrls = new HashSet<>();
private String html = null;
public BinaryParseData() {
context.set(Parser.class, AUTO_DETECT_PARSER);
}
public void setBinaryContent(byte[] data) {
InputStream inputStream = new ByteArrayInputStream(data);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
TransformerHandler handler = getTransformerHandler(outputStream, DEFAULT_OUTPUT_FORMAT, DEFAULT_ENCODING);
AUTO_DETECT_PARSER.parse(inputStream, handler, new Metadata(), context);
// Hacking the following line to remove Tika's inserted DocType
String htmlContent = new String(outputStream.toByteArray(), DEFAULT_ENCODING).replace("http://www.w3.org/1999/xhtml", "");
setHtml(htmlContent);
} catch (TransformerConfigurationException e) {
logger.error("Error configuring handler", e);
} catch (UnsupportedEncodingException e) {
logger.error("Encoding for content not supported", e);
} catch (Exception e) {
logger.error("Error parsing file", e);
}
}
/**
* Returns a transformer handler that serializes incoming SAX events to
* XHTML or HTML (depending the given method) using the given output encoding.
*
* @param encoding output encoding, or <code>null</code> for the platform default
*/
private static TransformerHandler getTransformerHandler(OutputStream out, String method, String encoding)
throws TransformerConfigurationException {
TransformerHandler transformerHandler = SAX_TRANSFORMER_FACTORY.newTransformerHandler();
Transformer transformer = transformerHandler.getTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, method);
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
if (encoding != null) {
transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
}
transformerHandler.setResult(new StreamResult(new PrintStream(out)));
return transformerHandler;
}
/** @return Parsed binary content or null */
public String getHtml() {
return html;
}
public void setHtml(String html) {
this.html = html;
}
@Override
public Set<WebURL> getOutgoingUrls() {
return outgoingUrls;
}
@Override
public void setOutgoingUrls(Set<WebURL> outgoingUrls) {
this.outgoingUrls = outgoingUrls;
}
@Override
public String toString() {
if (html == null || html.isEmpty()) {
return "No data parsed yet";
} else {
return getHtml();
}
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.parser;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashSet;
import java.util.Set;
import edu.uci.ics.crawler4j.util.Net;
import org.apache.tika.language.LanguageIdentifier;
import org.apache.tika.metadata.DublinCore;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.html.HtmlParser;
import edu.uci.ics.crawler4j.crawler.Configurable;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.url.URLCanonicalizer;
import edu.uci.ics.crawler4j.url.WebURL;
import edu.uci.ics.crawler4j.util.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public class Parser extends Configurable {
protected static final Logger logger = LoggerFactory.getLogger(Parser.class);
private HtmlParser htmlParser;
private ParseContext parseContext;
public Parser(CrawlConfig config) {
super(config);
htmlParser = new HtmlParser();
parseContext = new ParseContext();
}
public boolean parse(Page page, String contextURL) throws NotAllowedContentException {
if (Util.hasBinaryContent(page.getContentType())) {
BinaryParseData parseData = new BinaryParseData();
if (config.isIncludeBinaryContentInCrawling()) {
parseData.setBinaryContent(page.getContentData());
page.setParseData(parseData);
} else {
throw new NotAllowedContentException();
}
parseData.setOutgoingUrls(Net.extractUrls(parseData.getHtml()));
return parseData.getHtml() != null;
} else if (Util.hasPlainTextContent(page.getContentType())) {
try {
TextParseData parseData = new TextParseData();
if (page.getContentCharset() == null) {
parseData.setTextContent(new String(page.getContentData()));
} else {
parseData.setTextContent(new String(page.getContentData(), page.getContentCharset()));
}
parseData.setOutgoingUrls(Net.extractUrls(parseData.getTextContent()));
page.setParseData(parseData);
return true;
} catch (Exception e) {
logger.error("{}, while parsing: {}", e.getMessage(), page.getWebURL().getURL());
return false;
}
}
Metadata metadata = new Metadata();
HtmlContentHandler contentHandler = new HtmlContentHandler();
InputStream inputStream = null;
try {
inputStream = new ByteArrayInputStream(page.getContentData());
htmlParser.parse(inputStream, contentHandler, metadata, parseContext);
} catch (Exception e) {
logger.error("{}, while parsing: {}", e.getMessage(), page.getWebURL().getURL());
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
logger.error("{}, while parsing: {}", e.getMessage(), page.getWebURL().getURL());
}
}
if (page.getContentCharset() == null) {
page.setContentCharset(metadata.get("Content-Encoding"));
}
HtmlParseData parseData = new HtmlParseData();
parseData.setText(contentHandler.getBodyText().trim());
parseData.setTitle(metadata.get(DublinCore.TITLE));
parseData.setMetaTags(contentHandler.getMetaTags());
// Please note that identifying language takes less than 10 milliseconds
LanguageIdentifier languageIdentifier = new LanguageIdentifier(parseData.getText());
page.setLanguage(languageIdentifier.getLanguage());
Set<WebURL> outgoingUrls = new HashSet<>();
String baseURL = contentHandler.getBaseUrl();
if (baseURL != null) {
contextURL = baseURL;
}
int urlCount = 0;
for (ExtractedUrlAnchorPair urlAnchorPair : contentHandler.getOutgoingUrls()) {
String href = urlAnchorPair.getHref();
if (href == null || href.trim().length() == 0) {
continue;
}
String hrefLoweredCase = href.trim().toLowerCase();
if (!hrefLoweredCase.contains("javascript:") && !hrefLoweredCase.contains("mailto:") && !hrefLoweredCase.contains("@")) {
String url = URLCanonicalizer.getCanonicalURL(href, contextURL);
if (url != null) {
WebURL webURL = new WebURL();
webURL.setURL(url);
webURL.setTag(urlAnchorPair.getTag());
webURL.setAnchor(urlAnchorPair.getAnchor());
outgoingUrls.add(webURL);
urlCount++;
if (urlCount > config.getMaxOutgoingLinksToFollow()) {
break;
}
}
}
}
parseData.setOutgoingUrls(outgoingUrls);
try {
if (page.getContentCharset() == null) {
parseData.setHtml(new String(page.getContentData()));
} else {
parseData.setHtml(new String(page.getContentData(), page.getContentCharset()));
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return false;
}
page.setParseData(parseData);
return true;
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.parser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class HtmlContentHandler extends DefaultHandler {
private final int MAX_ANCHOR_LENGTH = 100;
private enum Element {
A, AREA, LINK, IFRAME, FRAME, EMBED, IMG, BASE, META, BODY
}
private static class HtmlFactory {
private static Map<String, Element> name2Element;
static {
name2Element = new HashMap<>();
for (Element element : Element.values()) {
name2Element.put(element.toString().toLowerCase(), element);
}
}
public static Element getElement(String name) {
return name2Element.get(name);
}
}
private String base;
private String metaRefresh;
private String metaLocation;
private Map<String, String> metaTags = new HashMap<>();
private boolean isWithinBodyElement;
private StringBuilder bodyText;
private List<ExtractedUrlAnchorPair> outgoingUrls;
private ExtractedUrlAnchorPair curUrl = null;
private boolean anchorFlag = false;
private StringBuilder anchorText = new StringBuilder();
public HtmlContentHandler() {
isWithinBodyElement = false;
bodyText = new StringBuilder();
outgoingUrls = new ArrayList<>();
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
Element element = HtmlFactory.getElement(localName);
if (element == Element.A || element == Element.AREA || element == Element.LINK) {
String href = attributes.getValue("href");
if (href != null) {
anchorFlag = true;
curUrl = new ExtractedUrlAnchorPair();
curUrl.setHref(href);
curUrl.setTag(localName);
outgoingUrls.add(curUrl);
}
return;
}
if (element == Element.IMG) {
String imgSrc = attributes.getValue("src");
if (imgSrc != null) {
curUrl = new ExtractedUrlAnchorPair();
curUrl.setHref(imgSrc);
curUrl.setTag(localName);
outgoingUrls.add(curUrl);
}
return;
}
if (element == Element.IFRAME || element == Element.FRAME || element == Element.EMBED) {
String src = attributes.getValue("src");
if (src != null) {
curUrl = new ExtractedUrlAnchorPair();
curUrl.setHref(src);
curUrl.setTag(localName);
outgoingUrls.add(curUrl);
}
return;
}
if (element == Element.BASE) {
if (base != null) { // We only consider the first occurrence of the Base element.
String href = attributes.getValue("href");
if (href != null) {
base = href;
}
}
return;
}
if (element == Element.META) {
String equiv = attributes.getValue("http-equiv");
if (equiv == null) { // This condition covers several cases of XHTML meta
equiv = attributes.getValue("name");
}
String content = attributes.getValue("content");
if (equiv != null && content != null) {
equiv = equiv.toLowerCase();
metaTags.put(equiv, content);
// http-equiv="refresh" content="0;URL=http://foo.bar/..."
if (equiv.equals("refresh") && (metaRefresh == null)) {
int pos = content.toLowerCase().indexOf("url=");
if (pos != -1) {
metaRefresh = content.substring(pos + 4);
}
curUrl = new ExtractedUrlAnchorPair();
curUrl.setHref(metaRefresh);
curUrl.setTag(localName);
outgoingUrls.add(curUrl);
}
// http-equiv="location" content="http://foo.bar/..."
if (equiv.equals("location") && (metaLocation == null)) {
metaLocation = content;
curUrl = new ExtractedUrlAnchorPair();
curUrl.setHref(metaRefresh);
curUrl.setTag(localName);
outgoingUrls.add(curUrl);
}
}
return;
}
if (element == Element.BODY) {
isWithinBodyElement = true;
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
Element element = HtmlFactory.getElement(localName);
if (element == Element.A || element == Element.AREA || element == Element.LINK) {
anchorFlag = false;
if (curUrl != null) {
String anchor = anchorText.toString().replaceAll("\n", " ").replaceAll("\t", " ").trim();
if (!anchor.isEmpty()) {
if (anchor.length() > MAX_ANCHOR_LENGTH) {
anchor = anchor.substring(0, MAX_ANCHOR_LENGTH) + "...";
}
curUrl.setTag(localName);
curUrl.setAnchor(anchor);
}
anchorText.delete(0, anchorText.length());
}
curUrl = null;
}
if (element == Element.BODY) {
isWithinBodyElement = false;
}
}
@Override
public void characters(char ch[], int start, int length) throws SAXException {
if (isWithinBodyElement) {
bodyText.append(ch, start, length);
if (anchorFlag) {
anchorText.append(new String(ch, start, length));
}
}
}
public String getBodyText() {
return bodyText.toString();
}
public List<ExtractedUrlAnchorPair> getOutgoingUrls() {
return outgoingUrls;
}
public String getBaseUrl() {
return base;
}
public Map<String, String> getMetaTags() {
return metaTags;
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.frontier;
import com.sleepycat.je.*;
import edu.uci.ics.crawler4j.crawler.Configurable;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.util.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public class DocIDServer extends Configurable {
protected static final Logger logger = LoggerFactory.getLogger(DocIDServer.class);
protected Database docIDsDB = null;
protected final Object mutex = new Object();
protected int lastDocID;
public DocIDServer(Environment env, CrawlConfig config) throws DatabaseException {
super(config);
DatabaseConfig dbConfig = new DatabaseConfig();
dbConfig.setAllowCreate(true);
dbConfig.setTransactional(config.isResumableCrawling());
dbConfig.setDeferredWrite(!config.isResumableCrawling());
docIDsDB = env.openDatabase(null, "DocIDs", dbConfig);
if (config.isResumableCrawling()) {
int docCount = getDocCount();
if (docCount > 0) {
logger.info("Loaded {} URLs that had been detected in previous crawl.", docCount);
lastDocID = docCount;
}
} else {
lastDocID = 0;
}
}
/**
* Returns the docid of an already seen url.
*
* @param url the URL for which the docid is returned.
* @return the docid of the url if it is seen before. Otherwise -1 is returned.
*/
public int getDocId(String url) {
synchronized (mutex) {
if (docIDsDB == null) {
return -1;
}
OperationStatus result;
DatabaseEntry value = new DatabaseEntry();
try {
DatabaseEntry key = new DatabaseEntry(url.getBytes());
result = docIDsDB.get(null, key, value, null);
if (result == OperationStatus.SUCCESS && value.getData().length > 0) {
return Util.byteArray2Int(value.getData());
}
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
}
public int getNewDocID(String url) {
synchronized (mutex) {
try {
// Make sure that we have not already assigned a docid for this URL
int docid = getDocId(url);
if (docid > 0) {
return docid;
}
lastDocID++;
docIDsDB.put(null, new DatabaseEntry(url.getBytes()), new DatabaseEntry(Util.int2ByteArray(lastDocID)));
return lastDocID;
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
}
public void addUrlAndDocId(String url, int docId) throws Exception {
synchronized (mutex) {
if (docId <= lastDocID) {
throw new Exception("Requested doc id: " + docId + " is not larger than: " + lastDocID);
}
// Make sure that we have not already assigned a docid for this URL
int prevDocid = getDocId(url);
if (prevDocid > 0) {
if (prevDocid == docId) {
return;
}
throw new Exception("Doc id: " + prevDocid + " is already assigned to URL: " + url);
}
docIDsDB.put(null, new DatabaseEntry(url.getBytes()), new DatabaseEntry(Util.int2ByteArray(docId)));
lastDocID = docId;
}
}
public boolean isSeenBefore(String url) {
return getDocId(url) != -1;
}
public int getDocCount() {
try {
return (int) docIDsDB.count();
} catch (DatabaseException e) {
e.printStackTrace();
}
return -1;
}
public void close() {
try {
docIDsDB.close();
} catch (DatabaseException e) {
e.printStackTrace();
}
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.frontier;
import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;
import edu.uci.ics.crawler4j.url.WebURL;
/**
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public class WebURLTupleBinding extends TupleBinding<WebURL> {
@Override
public WebURL entryToObject(TupleInput input) {
WebURL webURL = new WebURL();
webURL.setURL(input.readString());
webURL.setDocid(input.readInt());
webURL.setParentDocid(input.readInt());
webURL.setParentUrl(input.readString());
webURL.setDepth(input.readShort());
webURL.setPriority(input.readByte());
webURL.setAnchor(input.readString());
return webURL;
}
@Override
public void objectToEntry(WebURL url, TupleOutput output) {
output.writeString(url.getURL());
output.writeInt(url.getDocid());
output.writeInt(url.getParentDocid());
output.writeString(url.getParentUrl());
output.writeShort(url.getDepth());
output.writeByte(url.getPriority());
output.writeString(url.getAnchor());
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.frontier;
import com.sleepycat.je.*;
import edu.uci.ics.crawler4j.url.WebURL;
import edu.uci.ics.crawler4j.util.Util;
import java.util.ArrayList;
import java.util.List;
/**
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public class WorkQueues {
protected Database urlsDB = null;
protected Environment env;
protected boolean resumable;
protected WebURLTupleBinding webURLBinding;
protected final Object mutex = new Object();
public WorkQueues(Environment env, String dbName, boolean resumable) throws DatabaseException {
this.env = env;
this.resumable = resumable;
DatabaseConfig dbConfig = new DatabaseConfig();
dbConfig.setAllowCreate(true);
dbConfig.setTransactional(resumable);
dbConfig.setDeferredWrite(!resumable);
urlsDB = env.openDatabase(null, dbName, dbConfig);
webURLBinding = new WebURLTupleBinding();
}
public List<WebURL> get(int max) throws DatabaseException {
synchronized (mutex) {
int matches = 0;
List<WebURL> results = new ArrayList<>(max);
Cursor cursor = null;
OperationStatus result;
DatabaseEntry key = new DatabaseEntry();
DatabaseEntry value = new DatabaseEntry();
Transaction txn;
if (resumable) {
txn = env.beginTransaction(null, null);
} else {
txn = null;
}
try {
cursor = urlsDB.openCursor(txn, null);
result = cursor.getFirst(key, value, null);
while (matches < max && result == OperationStatus.SUCCESS) {
if (value.getData().length > 0) {
results.add(webURLBinding.entryToObject(value));
matches++;
}
result = cursor.getNext(key, value, null);
}
} catch (DatabaseException e) {
if (txn != null) {
txn.abort();
txn = null;
}
throw e;
} finally {
if (cursor != null) {
cursor.close();
}
if (txn != null) {
txn.commit();
}
}
return results;
}
}
public void delete(int count) throws DatabaseException {
synchronized (mutex) {
int matches = 0;
Cursor cursor = null;
OperationStatus result;
DatabaseEntry key = new DatabaseEntry();
DatabaseEntry value = new DatabaseEntry();
Transaction txn;
if (resumable) {
txn = env.beginTransaction(null, null);
} else {
txn = null;
}
try {
cursor = urlsDB.openCursor(txn, null);
result = cursor.getFirst(key, value, null);
while (matches < count && result == OperationStatus.SUCCESS) {
cursor.delete();
matches++;
result = cursor.getNext(key, value, null);
}
} catch (DatabaseException e) {
if (txn != null) {
txn.abort();
txn = null;
}
throw e;
} finally {
if (cursor != null) {
cursor.close();
}
if (txn != null) {
txn.commit();
}
}
}
}
/*
* The key that is used for storing URLs determines the order
* they are crawled. Lower key values results in earlier crawling.
* Here our keys are 6 bytes. The first byte comes from the URL priority.
* The second byte comes from depth of crawl at which this URL is first found.
* The rest of the 4 bytes come from the docid of the URL. As a result,
* URLs with lower priority numbers will be crawled earlier. If priority
* numbers are the same, those found at lower depths will be crawled earlier.
* If depth is also equal, those found earlier (therefore, smaller docid) will
* be crawled earlier.
*/
protected DatabaseEntry getDatabaseEntryKey(WebURL url) {
byte[] keyData = new byte[6];
keyData[0] = url.getPriority();
keyData[1] = (url.getDepth() > Byte.MAX_VALUE ? Byte.MAX_VALUE : (byte) url.getDepth());
Util.putIntInByteArray(url.getDocid(), keyData, 2);
return new DatabaseEntry(keyData);
}
public void put(WebURL url) throws DatabaseException {
DatabaseEntry value = new DatabaseEntry();
webURLBinding.objectToEntry(url, value);
Transaction txn;
if (resumable) {
txn = env.beginTransaction(null, null);
} else {
txn = null;
}
urlsDB.put(txn, getDatabaseEntryKey(url), value);
if (resumable) {
if (txn != null) {
txn.commit();
}
}
}
public long getLength() {
try {
return urlsDB.count();
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
public void close() {
try {
urlsDB.close();
} catch (DatabaseException e) {
e.printStackTrace();
}
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.frontier;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import edu.uci.ics.crawler4j.crawler.Configurable;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.frontier.Counters.ReservedCounterNames;
import edu.uci.ics.crawler4j.url.WebURL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public class Frontier extends Configurable {
protected static final Logger logger = LoggerFactory.getLogger(Frontier.class);
protected WorkQueues workQueues;
protected InProcessPagesDB inProcessPages;
protected final Object mutex = new Object();
protected final Object waitingList = new Object();
protected boolean isFinished = false;
protected long scheduledPages;
protected Counters counters;
public Frontier(Environment env, CrawlConfig config) {
super(config);
this.counters = new Counters(env, config);
try {
workQueues = new WorkQueues(env, "PendingURLsDB", config.isResumableCrawling());
if (config.isResumableCrawling()) {
scheduledPages = counters.getValue(ReservedCounterNames.SCHEDULED_PAGES);
inProcessPages = new InProcessPagesDB(env);
long numPreviouslyInProcessPages = inProcessPages.getLength();
if (numPreviouslyInProcessPages > 0) {
logger.info("Rescheduling {} URLs from previous crawl.", numPreviouslyInProcessPages);
scheduledPages -= numPreviouslyInProcessPages;
while (true) {
List<WebURL> urls = inProcessPages.get(100);
if (urls.size() == 0) {
break;
}
scheduleAll(urls);
inProcessPages.delete(urls.size());
}
}
} else {
inProcessPages = null;
scheduledPages = 0;
}
} catch (DatabaseException e) {
logger.error("Error while initializing the Frontier: {}", e.getMessage());
workQueues = null;
}
}
public void scheduleAll(List<WebURL> urls) {
int maxPagesToFetch = config.getMaxPagesToFetch();
synchronized (mutex) {
int newScheduledPage = 0;
for (WebURL url : urls) {
if (maxPagesToFetch > 0 && (scheduledPages + newScheduledPage) >= maxPagesToFetch) {
break;
}
try {
workQueues.put(url);
newScheduledPage++;
} catch (DatabaseException e) {
logger.error("Error while putting the url in the work queue.");
}
}
if (newScheduledPage > 0) {
scheduledPages += newScheduledPage;
counters.increment(Counters.ReservedCounterNames.SCHEDULED_PAGES, newScheduledPage);
}
synchronized (waitingList) {
waitingList.notifyAll();
}
}
}
public void schedule(WebURL url) {
int maxPagesToFetch = config.getMaxPagesToFetch();
synchronized (mutex) {
try {
if (maxPagesToFetch < 0 || scheduledPages < maxPagesToFetch) {
workQueues.put(url);
scheduledPages++;
counters.increment(Counters.ReservedCounterNames.SCHEDULED_PAGES);
}
} catch (DatabaseException e) {
logger.error("Error while putting the url in the work queue.");
}
}
}
public void getNextURLs(int max, List<WebURL> result) {
while (true) {
synchronized (mutex) {
if (isFinished) {
return;
}
try {
List<WebURL> curResults = workQueues.get(max);
workQueues.delete(curResults.size());
if (inProcessPages != null) {
for (WebURL curPage : curResults) {
inProcessPages.put(curPage);
}
}
result.addAll(curResults);
} catch (DatabaseException e) {
logger.error("Error while getting next urls: {}", e.getMessage());
e.printStackTrace();
}
if (result.size() > 0) {
return;
}
}
try {
synchronized (waitingList) {
waitingList.wait();
}
} catch (InterruptedException ignored) {
// Do nothing
}
if (isFinished) {
return;
}
}
}
public void setProcessed(WebURL webURL) {
counters.increment(ReservedCounterNames.PROCESSED_PAGES);
if (inProcessPages != null) {
if (!inProcessPages.removeURL(webURL)) {
logger.warn("Could not remove: {} from list of processed pages.", webURL.getURL());
}
}
}
public long getQueueLength() {
return workQueues.getLength();
}
public long getNumberOfAssignedPages() {
return inProcessPages.getLength();
}
public long getNumberOfProcessedPages() {
return counters.getValue(ReservedCounterNames.PROCESSED_PAGES);
}
public boolean isFinished() {
return isFinished;
}
public void close() {
workQueues.close();
counters.close();
if (inProcessPages != null) {
inProcessPages.close();
}
}
public void finish() {
isFinished = true;
synchronized (waitingList) {
waitingList.notifyAll();
}
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.frontier;
import com.sleepycat.je.*;
import edu.uci.ics.crawler4j.crawler.Configurable;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.util.Util;
import java.util.HashMap;
import java.util.Map;
/**
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public class Counters extends Configurable {
public class ReservedCounterNames {
public final static String SCHEDULED_PAGES = "Scheduled-Pages";
public final static String PROCESSED_PAGES = "Processed-Pages";
}
protected Database statisticsDB = null;
protected Environment env;
protected final Object mutex = new Object();
protected Map<String, Long> counterValues;
public Counters(Environment env, CrawlConfig config) throws DatabaseException {
super(config);
this.env = env;
this.counterValues = new HashMap<>();
/*
* When crawling is set to be resumable, we have to keep the statistics
* in a transactional database to make sure they are not lost if crawler
* is crashed or terminated unexpectedly.
*/
if (config.isResumableCrawling()) {
DatabaseConfig dbConfig = new DatabaseConfig();
dbConfig.setAllowCreate(true);
dbConfig.setTransactional(true);
dbConfig.setDeferredWrite(false);
statisticsDB = env.openDatabase(null, "Statistics", dbConfig);
OperationStatus result;
DatabaseEntry key = new DatabaseEntry();
DatabaseEntry value = new DatabaseEntry();
Transaction tnx = env.beginTransaction(null, null);
Cursor cursor = statisticsDB.openCursor(tnx, null);
result = cursor.getFirst(key, value, null);
while (result == OperationStatus.SUCCESS) {
if (value.getData().length > 0) {
String name = new String(key.getData());
long counterValue = Util.byteArray2Long(value.getData());
counterValues.put(name, new Long(counterValue));
}
result = cursor.getNext(key, value, null);
}
cursor.close();
tnx.commit();
}
}
public long getValue(String name) {
synchronized (mutex) {
Long value = counterValues.get(name);
if (value == null) {
return 0;
}
return value.longValue();
}
}
public void setValue(String name, long value) {
synchronized (mutex) {
try {
counterValues.put(name, new Long(value));
if (statisticsDB != null) {
Transaction txn = env.beginTransaction(null, null);
statisticsDB.put(txn, new DatabaseEntry(name.getBytes()),
new DatabaseEntry(Util.long2ByteArray(value)));
txn.commit();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void increment(String name) {
increment(name, 1);
}
public void increment(String name, long addition) {
synchronized (mutex) {
long prevValue = getValue(name);
setValue(name, prevValue + addition);
}
}
public void close() {
try {
if (statisticsDB != null) {
statisticsDB.close();
}
} catch (DatabaseException e) {
e.printStackTrace();
}
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.frontier;
import com.sleepycat.je.Cursor;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.Transaction;
import edu.uci.ics.crawler4j.url.WebURL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class maintains the list of pages which are
* assigned to crawlers but are not yet processed.
* It is used for resuming a previous crawl.
*
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public class InProcessPagesDB extends WorkQueues {
private static final Logger logger = LoggerFactory.getLogger(InProcessPagesDB.class);
public InProcessPagesDB(Environment env) throws DatabaseException {
super(env, "InProcessPagesDB", true);
long docCount = getLength();
if (docCount > 0) {
logger.info("Loaded {} URLs that have been in process in the previous crawl.", docCount);
}
}
public boolean removeURL(WebURL webUrl) {
synchronized (mutex) {
try {
DatabaseEntry key = getDatabaseEntryKey(webUrl);
Cursor cursor = null;
OperationStatus result;
DatabaseEntry value = new DatabaseEntry();
Transaction txn = env.beginTransaction(null, null);
try {
cursor = urlsDB.openCursor(txn, null);
result = cursor.getSearchKey(key, value, null);
if (result == OperationStatus.SUCCESS) {
result = cursor.delete();
if (result == OperationStatus.SUCCESS) {
return true;
}
}
} catch (DatabaseException e) {
if (txn != null) {
txn.abort();
txn = null;
}
throw e;
} finally {
if (cursor != null) {
cursor.close();
}
if (txn != null) {
txn.commit();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
} | Java |
package edu.uci.ics.crawler4j.crawler.exceptions;
import uk.org.lidalia.slf4jext.Level;
/**
* Created by Avi Hayun on 12/8/2014.
*
* Occurs when the crawler encounters a Redirect problem, like redirecting to a visited-already page, or redirecting to nothing
*/
public class RedirectException extends Exception {
public Level level;
public RedirectException(Level level, String msg) {
super(msg);
this.level = level;
}
} | Java |
package edu.uci.ics.crawler4j.crawler.exceptions;
/**
* Created by Avi Hayun on 12/8/2014.
* Thrown when trying to fetch a page which is bigger than allowed size
*/
public class PageBiggerThanMaxSizeException extends Exception {
long pageSize;
public PageBiggerThanMaxSizeException(long pageSize) {
super("Aborted fetching of this URL as it's size ( " + pageSize + " ) exceeds the maximum size");
this.pageSize = pageSize;
}
public long getPageSize() {
return pageSize;
}
} | Java |
package edu.uci.ics.crawler4j.crawler.exceptions;
/**
* Created by Avi Hayun on 12/8/2014.
*
* Thrown when there is a problem with the parsing of the content - this is a tagging exception
*/
public class ParseException extends Exception {
} | Java |
package edu.uci.ics.crawler4j.crawler.exceptions;
/**
* Created by Avi Hayun on 12/8/2014.
*
* Thrown when there is a problem with the content fetching - this is a tagging exception
*/
public class ContentFetchException extends Exception {
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.crawler;
/**
* Several core components of crawler4j extend this class
* to make them configurable.
*
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public abstract class Configurable {
protected CrawlConfig config;
protected Configurable(CrawlConfig config) {
this.config = config;
}
public CrawlConfig getConfig() {
return config;
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.crawler;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.frontier.DocIDServer;
import edu.uci.ics.crawler4j.frontier.Frontier;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
import edu.uci.ics.crawler4j.url.URLCanonicalizer;
import edu.uci.ics.crawler4j.url.WebURL;
import edu.uci.ics.crawler4j.util.IO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* The controller that manages a crawling session. This class creates the
* crawler threads and monitors their progress.
*
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public class CrawlController extends Configurable {
static final Logger logger = LoggerFactory.getLogger(CrawlController.class);
/**
* The 'customData' object can be used for passing custom crawl-related
* configurations to different components of the crawler.
*/
protected Object customData;
/**
* Once the crawling session finishes the controller collects the local data
* of the crawler threads and stores them in this List.
*/
protected List<Object> crawlersLocalData = new ArrayList<>();
/**
* Is the crawling of this session finished?
*/
protected boolean finished;
/**
* Is the crawling session set to 'shutdown'. Crawler threads monitor this
* flag and when it is set they will no longer process new pages.
*/
protected boolean shuttingDown;
protected PageFetcher pageFetcher;
protected RobotstxtServer robotstxtServer;
protected Frontier frontier;
protected DocIDServer docIdServer;
protected final Object waitingLock = new Object();
protected final Environment env;
public CrawlController(CrawlConfig config, PageFetcher pageFetcher, RobotstxtServer robotstxtServer)
throws Exception {
super(config);
config.validate();
File folder = new File(config.getCrawlStorageFolder());
if (!folder.exists()) {
if (!folder.mkdirs()) {
throw new Exception("Couldn't create this folder: " + folder.getAbsolutePath());
}
}
boolean resumable = config.isResumableCrawling();
EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setAllowCreate(true);
envConfig.setTransactional(resumable);
envConfig.setLocking(resumable);
File envHome = new File(config.getCrawlStorageFolder() + "/frontier");
if (!envHome.exists()) {
if (!envHome.mkdir()) {
throw new Exception("Couldn't create this folder: " + envHome.getAbsolutePath());
}
}
if (!resumable) {
IO.deleteFolderContents(envHome);
}
env = new Environment(envHome, envConfig);
docIdServer = new DocIDServer(env, config);
frontier = new Frontier(env, config);
this.pageFetcher = pageFetcher;
this.robotstxtServer = robotstxtServer;
finished = false;
shuttingDown = false;
}
/**
* Start the crawling session and wait for it to finish.
*
* @param _c
* the class that implements the logic for crawler threads
* @param numberOfCrawlers
* the number of concurrent threads that will be contributing in
* this crawling session.
* @param <T> Your class extending WebCrawler
*/
public <T extends WebCrawler> void start(final Class<T> _c, final int numberOfCrawlers) {
this.start(_c, numberOfCrawlers, true);
}
/**
* Start the crawling session and return immediately.
*
* @param _c
* the class that implements the logic for crawler threads
* @param numberOfCrawlers
* the number of concurrent threads that will be contributing in
* this crawling session.
* @param <T> Your class extending WebCrawler
*/
public <T extends WebCrawler> void startNonBlocking(final Class<T> _c, final int numberOfCrawlers) {
this.start(_c, numberOfCrawlers, false);
}
protected <T extends WebCrawler> void start(final Class<T> _c, final int numberOfCrawlers, boolean isBlocking) {
try {
finished = false;
crawlersLocalData.clear();
final List<Thread> threads = new ArrayList<>();
final List<T> crawlers = new ArrayList<>();
for (int i = 1; i <= numberOfCrawlers; i++) {
T crawler = _c.newInstance();
Thread thread = new Thread(crawler, "Crawler " + i);
crawler.setThread(thread);
crawler.init(i, this);
thread.start();
crawlers.add(crawler);
threads.add(thread);
logger.info("Crawler {} started", i);
}
final CrawlController controller = this;
Thread monitorThread = new Thread(new Runnable() {
@Override
public void run() {
try {
synchronized (waitingLock) {
while (true) {
sleep(10);
boolean someoneIsWorking = false;
for (int i = 0; i < threads.size(); i++) {
Thread thread = threads.get(i);
if (!thread.isAlive()) {
if (!shuttingDown) {
logger.info("Thread {} was dead, I'll recreate it", i);
T crawler = _c.newInstance();
thread = new Thread(crawler, "Crawler " + (i + 1));
threads.remove(i);
threads.add(i, thread);
crawler.setThread(thread);
crawler.init(i + 1, controller);
thread.start();
crawlers.remove(i);
crawlers.add(i, crawler);
}
} else if (crawlers.get(i).isNotWaitingForNewURLs()) {
someoneIsWorking = true;
}
}
if (!someoneIsWorking) {
// Make sure again that none of the threads
// are
// alive.
logger.info("It looks like no thread is working, waiting for 10 seconds to make sure...");
sleep(10);
someoneIsWorking = false;
for (int i = 0; i < threads.size(); i++) {
Thread thread = threads.get(i);
if (thread.isAlive() && crawlers.get(i).isNotWaitingForNewURLs()) {
someoneIsWorking = true;
}
}
if (!someoneIsWorking) {
if (!shuttingDown) {
long queueLength = frontier.getQueueLength();
if (queueLength > 0) {
continue;
}
logger.info("No thread is working and no more URLs are in queue waiting for another 10 seconds to make sure...");
sleep(10);
queueLength = frontier.getQueueLength();
if (queueLength > 0) {
continue;
}
}
logger.info("All of the crawlers are stopped. Finishing the process...");
// At this step, frontier notifies the
// threads that were
// waiting for new URLs and they should
// stop
frontier.finish();
for (T crawler : crawlers) {
crawler.onBeforeExit();
crawlersLocalData.add(crawler.getMyLocalData());
}
logger.info("Waiting for 10 seconds before final clean up...");
sleep(10);
frontier.close();
docIdServer.close();
pageFetcher.shutDown();
finished = true;
waitingLock.notifyAll();
env.close();
return;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
monitorThread.start();
if (isBlocking) {
waitUntilFinish();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Wait until this crawling session finishes.
*/
public void waitUntilFinish() {
while (!finished) {
synchronized (waitingLock) {
if (finished) {
return;
}
try {
waitingLock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* Once the crawling session finishes the controller collects the local data
* of the crawler threads and stores them in a List. This function returns
* the reference to this list.
*
* @return List of Objects which are your local data
*/
public List<Object> getCrawlersLocalData() {
return crawlersLocalData;
}
protected static void sleep(int seconds) {
try {
Thread.sleep(seconds * 1000);
} catch (Exception ignored) {
// Do nothing
}
}
/**
* Adds a new seed URL. A seed URL is a URL that is fetched by the crawler
* to extract new URLs in it and follow them for crawling.
*
* @param pageUrl
* the URL of the seed
*/
public void addSeed(String pageUrl) {
addSeed(pageUrl, -1);
}
/**
* Adds a new seed URL. A seed URL is a URL that is fetched by the crawler
* to extract new URLs in it and follow them for crawling. You can also
* specify a specific document id to be assigned to this seed URL. This
* document id needs to be unique. Also, note that if you add three seeds
* with document ids 1,2, and 7. Then the next URL that is found during the
* crawl will get a doc id of 8. Also you need to ensure to add seeds in
* increasing order of document ids.
*
* Specifying doc ids is mainly useful when you have had a previous crawl
* and have stored the results and want to start a new crawl with seeds
* which get the same document ids as the previous crawl.
*
* @param pageUrl
* the URL of the seed
* @param docId
* the document id that you want to be assigned to this seed URL.
*
*/
public void addSeed(String pageUrl, int docId) {
String canonicalUrl = URLCanonicalizer.getCanonicalURL(pageUrl);
if (canonicalUrl == null) {
logger.error("Invalid seed URL: {}", pageUrl);
return;
}
if (docId < 0) {
docId = docIdServer.getDocId(canonicalUrl);
if (docId > 0) {
// This URL is already seen.
return;
}
docId = docIdServer.getNewDocID(canonicalUrl);
} else {
try {
docIdServer.addUrlAndDocId(canonicalUrl, docId);
} catch (Exception e) {
logger.error("Could not add seed: {}", e.getMessage());
}
}
WebURL webUrl = new WebURL();
webUrl.setURL(canonicalUrl);
webUrl.setDocid(docId);
webUrl.setDepth((short) 0);
if (!robotstxtServer.allows(webUrl)) {
logger.info("Robots.txt does not allow this seed: {}", pageUrl);
} else {
frontier.schedule(webUrl);
}
}
/**
* This function can called to assign a specific document id to a url. This
* feature is useful when you have had a previous crawl and have stored the
* Urls and their associated document ids and want to have a new crawl which
* is aware of the previously seen Urls and won't re-crawl them.
*
* Note that if you add three seen Urls with document ids 1,2, and 7. Then
* the next URL that is found during the crawl will get a doc id of 8. Also
* you need to ensure to add seen Urls in increasing order of document ids.
*
* @param url
* the URL of the page
* @param docId
* the document id that you want to be assigned to this URL.
*
*/
public void addSeenUrl(String url, int docId) {
String canonicalUrl = URLCanonicalizer.getCanonicalURL(url);
if (canonicalUrl == null) {
logger.error("Invalid Url: {}", url);
return;
}
try {
docIdServer.addUrlAndDocId(canonicalUrl, docId);
} catch (Exception e) {
logger.error("Could not add seen url: {}", e.getMessage());
}
}
public PageFetcher getPageFetcher() {
return pageFetcher;
}
public void setPageFetcher(PageFetcher pageFetcher) {
this.pageFetcher = pageFetcher;
}
public RobotstxtServer getRobotstxtServer() {
return robotstxtServer;
}
public void setRobotstxtServer(RobotstxtServer robotstxtServer) {
this.robotstxtServer = robotstxtServer;
}
public Frontier getFrontier() {
return frontier;
}
public void setFrontier(Frontier frontier) {
this.frontier = frontier;
}
public DocIDServer getDocIdServer() {
return docIdServer;
}
public void setDocIdServer(DocIDServer docIdServer) {
this.docIdServer = docIdServer;
}
public Object getCustomData() {
return customData;
}
public void setCustomData(Object customData) {
this.customData = customData;
}
public boolean isFinished() {
return this.finished;
}
public boolean isShuttingDown() {
return shuttingDown;
}
/**
* Set the current crawling session set to 'shutdown'. Crawler threads
* monitor the shutdown flag and when it is set to true, they will no longer
* process new pages.
*/
public void shutdown() {
logger.info("Shutting down...");
this.shuttingDown = true;
getPageFetcher().shutDown();
frontier.finish();
}
}
| Java |
package edu.uci.ics.crawler4j.crawler.authentication;
import javax.swing.text.html.FormSubmitEvent.MethodType;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by Avi Hayun on 11/23/2014.
*
* Abstract class containing authentication information needed to login into a user/password protected site<br>
* This class should be extended by specific authentication types like form authentication and basic authentication etc<br>
* <br>
* This class contains all of the mutual authentication data for all authentication types
*/
public abstract class AuthInfo {
public enum AuthenticationType {
BASIC_AUTHENTICATION, FORM_AUTHENTICATION
}
protected AuthenticationType authenticationType;
protected MethodType httpMethod;
protected String protocol;
protected String host;
protected String loginTarget;
protected int port;
protected String username;
protected String password;
/** Constructs a new AuthInfo. */
public AuthInfo() {
}
/**
* This constructor should only be used by extending classes
*
* @param authenticationType Pick the one which matches your authentication
* @param httpMethod Choose POST / GET
* @param loginUrl Full URL of the login page
* @param username Username for Authentication
* @param password Password for Authentication
*
* @throws MalformedURLException Make sure your URL is valid
*/
protected AuthInfo(AuthenticationType authenticationType, MethodType httpMethod, String loginUrl, String username, String password) throws MalformedURLException {
this.authenticationType = authenticationType;
this.httpMethod = httpMethod;
URL url = new URL(loginUrl);
this.protocol = url.getProtocol();
this.host = url.getHost();
this.port = url.getDefaultPort();
this.loginTarget = url.getFile();
this.username = username;
this.password = password;
}
/**
* @return Authentication type (BASIC, FORM)
*/
public AuthenticationType getAuthenticationType() {
return authenticationType;
}
/**
*
* @param authenticationType Should be set only by extending classes (BASICAuthInfo, FORMAuthInfo)
*/
public void setAuthenticationType(AuthenticationType authenticationType) {
this.authenticationType = authenticationType;
}
/**
*
* @return httpMethod (POST, GET)
*/
public MethodType getHttpMethod() {
return httpMethod;
}
/**
* @param httpMethod Should be set by extending classes (POST, GET)
*/
public void setHttpMethod(MethodType httpMethod) {
this.httpMethod = httpMethod;
}
/**
* @return protocol type (http, https)
*/
public String getProtocol() {
return protocol;
}
/**
* @param protocol Don't set this one unless you know what you are doing (protocol: http, https)
*/
public void setProtocol(String protocol) {
this.protocol = protocol;
}
/**
* @return host (www.sitename.com)
*/
public String getHost() {
return host;
}
/**
* @param host Don't set this one unless you know what you are doing (sets the domain name)
*/
public void setHost(String host) {
this.host = host;
}
/**
* @return file/path which is the rest of the url after the domain name (eg: /login.php)
*/
public String getLoginTarget() {
return loginTarget;
}
/**
* @param loginTarget Don't set this one unless you know what you are doing (eg: /login.php)
*/
public void setLoginTarget(String loginTarget) {
this.loginTarget = loginTarget;
}
/**
* @return port number (eg: 80, 443)
*/
public int getPort() {
return port;
}
/**
* @param port Don't set this one unless you know what you are doing (eg: 80, 443)
*/
public void setPort(int port) {
this.port = port;
}
/**
* @return username used for Authentication
*/
public String getUsername() {
return username;
}
/**
* @param username username used for Authentication
*/
public void setUsername(String username) {
this.username = username;
}
/**
* @return password used for Authentication
*/
public String getPassword() {
return password;
}
/**
* @param password password used for Authentication
*/
public void setPassword(String password) {
this.password = password;
}
} | Java |
package edu.uci.ics.crawler4j.crawler.authentication;
import javax.swing.text.html.FormSubmitEvent.MethodType;
import java.net.MalformedURLException;
/**
* Created by Avi Hayun on 11/25/2014.
*
* BasicAuthInfo contains the authentication information needed for BASIC authentication (extending AuthInfo which has all common auth info in it)
*
* BASIC authentication in PHP:
* <ul>
* <li>http://php.net/manual/en/features.http-auth.php</li>
* <li>http://stackoverflow.com/questions/4150507/how-can-i-use-basic-http-authentication-in-php</li>
* </ul>
*/
public class BasicAuthInfo extends AuthInfo {
/**
* Constructor
*
* @param username Username used for Authentication
* @param password Password used for Authentication
* @param loginUrl Full Login URL beginning with "http..." till the end of the url
*
* @throws MalformedURLException Make sure your URL is valid
*/
public BasicAuthInfo(String username, String password, String loginUrl) throws MalformedURLException {
super(AuthenticationType.BASIC_AUTHENTICATION, MethodType.GET, loginUrl, username, password);
}
} | Java |
package edu.uci.ics.crawler4j.crawler.authentication;
import javax.swing.text.html.FormSubmitEvent.MethodType;
import java.net.MalformedURLException;
/**
* Created by Avi Hayun on 11/25/2014.
*
* FormAuthInfo contains the authentication information needed for FORM authentication (extending AuthInfo which has all common auth info in it)
* Basically, this is the most common authentication, where you will get to a site and you will need to enter a username and password into an HTML form
*/
public class FormAuthInfo extends AuthInfo {
private String usernameFormStr;
private String passwordFormStr;
/**
* Constructor
*
* @param username Username to login with
* @param password Password to login with
* @param loginUrl Full login URL, starting with "http"... ending with the full URL
* @param usernameFormStr "Name" attribute of the username form field
* @param passwordFormStr "Name" attribute of the password form field
*
* @throws MalformedURLException Make sure your URL is valid
*/
public FormAuthInfo(String username, String password, String loginUrl, String usernameFormStr, String passwordFormStr) throws MalformedURLException {
super(AuthenticationType.FORM_AUTHENTICATION, MethodType.POST, loginUrl, username, password);
this.usernameFormStr = usernameFormStr;
this.passwordFormStr = passwordFormStr;
}
/**
* @return username html "name" form attribute
*/
public String getUsernameFormStr() {
return usernameFormStr;
}
/**
* @param usernameFormStr username html "name" form attribute
*/
public void setUsernameFormStr(String usernameFormStr) {
this.usernameFormStr = usernameFormStr;
}
/**
* @return password html "name" form attribute
*/
public String getPasswordFormStr() {
return passwordFormStr;
}
/**
* @param passwordFormStr password html "name" form attribute
*/
public void setPasswordFormStr(String passwordFormStr) {
this.passwordFormStr = passwordFormStr;
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.crawler;
import edu.uci.ics.crawler4j.crawler.authentication.AuthInfo;
import java.util.ArrayList;
import java.util.List;
public class CrawlConfig {
/**
* The folder which will be used by crawler for storing the intermediate
* crawl data. The content of this folder should not be modified manually.
*/
private String crawlStorageFolder;
/**
* If this feature is enabled, you would be able to resume a previously
* stopped/crashed crawl. However, it makes crawling slightly slower
*/
private boolean resumableCrawling = false;
/**
* Maximum depth of crawling For unlimited depth this parameter should be
* set to -1
*/
private int maxDepthOfCrawling = -1;
/**
* Maximum number of pages to fetch For unlimited number of pages, this
* parameter should be set to -1
*/
private int maxPagesToFetch = -1;
/**
* user-agent string that is used for representing your crawler to web
* servers. See http://en.wikipedia.org/wiki/User_agent for more details
*/
private String userAgentString = "crawler4j (http://code.google.com/p/crawler4j/)";
/**
* Politeness delay in milliseconds (delay between sending two requests to
* the same host).
*/
private int politenessDelay = 200;
/**
* Should we also crawl https pages?
*/
private boolean includeHttpsPages = true;
/**
* Should we fetch binary content such as images, audio, ...?
*/
private boolean includeBinaryContentInCrawling = false;
/**
* Maximum Connections per host
*/
private int maxConnectionsPerHost = 100;
/**
* Maximum total connections
*/
private int maxTotalConnections = 100;
/**
* Socket timeout in milliseconds
*/
private int socketTimeout = 20000;
/**
* Connection timeout in milliseconds
*/
private int connectionTimeout = 30000;
/**
* Max number of outgoing links which are processed from a page
*/
private int maxOutgoingLinksToFollow = 5000;
/**
* Max allowed size of a page. Pages larger than this size will not be
* fetched.
*/
private int maxDownloadSize = 1048576;
/**
* Should we follow redirects?
*/
private boolean followRedirects = true;
/**
* If crawler should run behind a proxy, this parameter can be used for
* specifying the proxy host.
*/
private String proxyHost = null;
/**
* If crawler should run behind a proxy, this parameter can be used for
* specifying the proxy port.
*/
private int proxyPort = 80;
/**
* If crawler should run behind a proxy and user/pass is needed for
* authentication in proxy, this parameter can be used for specifying the
* username.
*/
private String proxyUsername = null;
/**
* If crawler should run behind a proxy and user/pass is needed for
* authentication in proxy, this parameter can be used for specifying the
* password.
*/
private String proxyPassword = null;
/**
* List of possible authentications needed by crawler
*/
private List<AuthInfo> authInfos;
public CrawlConfig() {
}
/**
* Validates the configs specified by this instance.
*
* @throws Exception on Validation fail
*/
public void validate() throws Exception {
if (crawlStorageFolder == null) {
throw new Exception("Crawl storage folder is not set in the CrawlConfig.");
}
if (politenessDelay < 0) {
throw new Exception("Invalid value for politeness delay: " + politenessDelay);
}
if (maxDepthOfCrawling < -1) {
throw new Exception("Maximum crawl depth should be either a positive number or -1 for unlimited depth.");
}
if (maxDepthOfCrawling > Short.MAX_VALUE) {
throw new Exception("Maximum value for crawl depth is " + Short.MAX_VALUE);
}
}
public String getCrawlStorageFolder() {
return crawlStorageFolder;
}
/**
* The folder which will be used by crawler for storing the intermediate
* crawl data. The content of this folder should not be modified manually.
*
* @param crawlStorageFolder The folder for the crawler's storage
*/
public void setCrawlStorageFolder(String crawlStorageFolder) {
this.crawlStorageFolder = crawlStorageFolder;
}
public boolean isResumableCrawling() {
return resumableCrawling;
}
/**
* If this feature is enabled, you would be able to resume a previously
* stopped/crashed crawl. However, it makes crawling slightly slower
*
* @param resumableCrawling Should crawling be resumable between runs ?
*/
public void setResumableCrawling(boolean resumableCrawling) {
this.resumableCrawling = resumableCrawling;
}
public int getMaxDepthOfCrawling() {
return maxDepthOfCrawling;
}
/**
* Maximum depth of crawling For unlimited depth this parameter should be set to -1
*
* @param maxDepthOfCrawling Depth of crawling (all links on current page = depth of 1)
*/
public void setMaxDepthOfCrawling(int maxDepthOfCrawling) {
this.maxDepthOfCrawling = maxDepthOfCrawling;
}
public int getMaxPagesToFetch() {
return maxPagesToFetch;
}
/**
* Maximum number of pages to fetch For unlimited number of pages, this parameter should be set to -1
*
* @param maxPagesToFetch How many pages to fetch from all threads together ?
*/
public void setMaxPagesToFetch(int maxPagesToFetch) {
this.maxPagesToFetch = maxPagesToFetch;
}
/**
*
* @return userAgentString
*/
public String getUserAgentString() {
return userAgentString;
}
/**
* user-agent string that is used for representing your crawler to web
* servers. See http://en.wikipedia.org/wiki/User_agent for more details
*
* @param userAgentString Custom userAgent string to use as your crawler's identifier
*/
public void setUserAgentString(String userAgentString) {
this.userAgentString = userAgentString;
}
public int getPolitenessDelay() {
return politenessDelay;
}
/**
* Politeness delay in milliseconds (delay between sending two requests to
* the same host).
*
* @param politenessDelay
* the delay in milliseconds.
*/
public void setPolitenessDelay(int politenessDelay) {
this.politenessDelay = politenessDelay;
}
public boolean isIncludeHttpsPages() {
return includeHttpsPages;
}
/**
* @param includeHttpsPages Should we crawl https pages?
*/
public void setIncludeHttpsPages(boolean includeHttpsPages) {
this.includeHttpsPages = includeHttpsPages;
}
public boolean isIncludeBinaryContentInCrawling() {
return includeBinaryContentInCrawling;
}
/**
*
* @param includeBinaryContentInCrawling Should we fetch binary content such as images, audio, ...?
*/
public void setIncludeBinaryContentInCrawling(boolean includeBinaryContentInCrawling) {
this.includeBinaryContentInCrawling = includeBinaryContentInCrawling;
}
public int getMaxConnectionsPerHost() {
return maxConnectionsPerHost;
}
/**
* @param maxConnectionsPerHost Maximum Connections per host
*/
public void setMaxConnectionsPerHost(int maxConnectionsPerHost) {
this.maxConnectionsPerHost = maxConnectionsPerHost;
}
public int getMaxTotalConnections() {
return maxTotalConnections;
}
/**
* @param maxTotalConnections Maximum total connections
*/
public void setMaxTotalConnections(int maxTotalConnections) {
this.maxTotalConnections = maxTotalConnections;
}
public int getSocketTimeout() {
return socketTimeout;
}
/**
* @param socketTimeout Socket timeout in milliseconds
*/
public void setSocketTimeout(int socketTimeout) {
this.socketTimeout = socketTimeout;
}
public int getConnectionTimeout() {
return connectionTimeout;
}
/**
* @param connectionTimeout Connection timeout in milliseconds
*/
public void setConnectionTimeout(int connectionTimeout) {
this.connectionTimeout = connectionTimeout;
}
public int getMaxOutgoingLinksToFollow() {
return maxOutgoingLinksToFollow;
}
/**
* @param maxOutgoingLinksToFollow Max number of outgoing links which are processed from a page
*/
public void setMaxOutgoingLinksToFollow(int maxOutgoingLinksToFollow) {
this.maxOutgoingLinksToFollow = maxOutgoingLinksToFollow;
}
public int getMaxDownloadSize() {
return maxDownloadSize;
}
/**
* @param maxDownloadSize Max allowed size of a page. Pages larger than this size will not be fetched.
*/
public void setMaxDownloadSize(int maxDownloadSize) {
this.maxDownloadSize = maxDownloadSize;
}
public boolean isFollowRedirects() {
return followRedirects;
}
/**
* @param followRedirects Should we follow redirects?
*/
public void setFollowRedirects(boolean followRedirects) {
this.followRedirects = followRedirects;
}
public String getProxyHost() {
return proxyHost;
}
/**
* @param proxyHost If crawler should run behind a proxy, this parameter can be used for specifying the proxy host.
*/
public void setProxyHost(String proxyHost) {
this.proxyHost = proxyHost;
}
public int getProxyPort() {
return proxyPort;
}
/**
* @param proxyPort If crawler should run behind a proxy, this parameter can be used for specifying the proxy port.
*/
public void setProxyPort(int proxyPort) {
this.proxyPort = proxyPort;
}
public String getProxyUsername() {
return proxyUsername;
}
/**
* @param proxyUsername
* If crawler should run behind a proxy and user/pass is needed for
* authentication in proxy, this parameter can be used for specifying the username.
*/
public void setProxyUsername(String proxyUsername) {
this.proxyUsername = proxyUsername;
}
public String getProxyPassword() {
return proxyPassword;
}
/**
* If crawler should run behind a proxy and user/pass is needed for
* authentication in proxy, this parameter can be used for specifying the password.
*
* @param proxyPassword String Password
*/
public void setProxyPassword(String proxyPassword) {
this.proxyPassword = proxyPassword;
}
/**
* @return the authentications Information
*/
public List<AuthInfo> getAuthInfos() {
return authInfos;
}
public void addAuthInfo(AuthInfo authInfo) {
if (this.authInfos == null) {
this.authInfos = new ArrayList<AuthInfo>();
}
this.authInfos.add(authInfo);
}
/**
* @param authInfos authenticationInformations to set
*/
public void setAuthInfos(List<AuthInfo> authInfos) {
this.authInfos = authInfos;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Crawl storage folder: " + getCrawlStorageFolder() + "\n");
sb.append("Resumable crawling: " + isResumableCrawling() + "\n");
sb.append("Max depth of crawl: " + getMaxDepthOfCrawling() + "\n");
sb.append("Max pages to fetch: " + getMaxPagesToFetch() + "\n");
sb.append("User agent string: " + getUserAgentString() + "\n");
sb.append("Include https pages: " + isIncludeHttpsPages() + "\n");
sb.append("Include binary content: " + isIncludeBinaryContentInCrawling() + "\n");
sb.append("Max connections per host: " + getMaxConnectionsPerHost() + "\n");
sb.append("Max total connections: " + getMaxTotalConnections() + "\n");
sb.append("Socket timeout: " + getSocketTimeout() + "\n");
sb.append("Max total connections: " + getMaxTotalConnections() + "\n");
sb.append("Max outgoing links to follow: " + getMaxOutgoingLinksToFollow() + "\n");
sb.append("Max download size: " + getMaxDownloadSize() + "\n");
sb.append("Should follow redirects?: " + isFollowRedirects() + "\n");
sb.append("Proxy host: " + getProxyHost() + "\n");
sb.append("Proxy port: " + getProxyPort() + "\n");
sb.append("Proxy username: " + getProxyUsername() + "\n");
sb.append("Proxy password: " + getProxyPassword() + "\n");
return sb.toString();
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.crawler;
import edu.uci.ics.crawler4j.crawler.exceptions.ContentFetchException;
import edu.uci.ics.crawler4j.crawler.exceptions.PageBiggerThanMaxSizeException;
import edu.uci.ics.crawler4j.crawler.exceptions.ParseException;
import edu.uci.ics.crawler4j.crawler.exceptions.RedirectException;
import edu.uci.ics.crawler4j.fetcher.PageFetchResult;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.frontier.DocIDServer;
import edu.uci.ics.crawler4j.frontier.Frontier;
import edu.uci.ics.crawler4j.parser.NotAllowedContentException;
import edu.uci.ics.crawler4j.parser.ParseData;
import edu.uci.ics.crawler4j.parser.Parser;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
import edu.uci.ics.crawler4j.url.WebURL;
import org.apache.http.HttpStatus;
import org.apache.http.impl.EnglishReasonPhraseCatalog;
import uk.org.lidalia.slf4jext.Level;
import uk.org.lidalia.slf4jext.Logger;
import uk.org.lidalia.slf4jext.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* WebCrawler class in the Runnable class that is executed by each crawler thread.
*
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public class WebCrawler implements Runnable {
protected static final Logger logger = LoggerFactory.getLogger(WebCrawler.class);
/**
* The id associated to the crawler thread running this instance
*/
protected int myId;
/**
* The controller instance that has created this crawler thread. This
* reference to the controller can be used for getting configurations of the
* current crawl or adding new seeds during runtime.
*/
protected CrawlController myController;
/**
* The thread within which this crawler instance is running.
*/
private Thread myThread;
/**
* The parser that is used by this crawler instance to parse the content of the fetched pages.
*/
private Parser parser;
/**
* The fetcher that is used by this crawler instance to fetch the content of pages from the web.
*/
private PageFetcher pageFetcher;
/**
* The RobotstxtServer instance that is used by this crawler instance to
* determine whether the crawler is allowed to crawl the content of each page.
*/
private RobotstxtServer robotstxtServer;
/**
* The DocIDServer that is used by this crawler instance to map each URL to a unique docid.
*/
private DocIDServer docIdServer;
/**
* The Frontier object that manages the crawl queue.
*/
private Frontier frontier;
/**
* Is the current crawler instance waiting for new URLs? This field is
* mainly used by the controller to detect whether all of the crawler
* instances are waiting for new URLs and therefore there is no more work
* and crawling can be stopped.
*/
private boolean isWaitingForNewURLs;
/**
* Initializes the current instance of the crawler
*
* @param id
* the id of this crawler instance
* @param crawlController
* the controller that manages this crawling session
*/
public void init(int id, CrawlController crawlController) {
this.myId = id;
this.pageFetcher = crawlController.getPageFetcher();
this.robotstxtServer = crawlController.getRobotstxtServer();
this.docIdServer = crawlController.getDocIdServer();
this.frontier = crawlController.getFrontier();
this.parser = new Parser(crawlController.getConfig());
this.myController = crawlController;
this.isWaitingForNewURLs = false;
}
/**
* Get the id of the current crawler instance
*
* @return the id of the current crawler instance
*/
public int getMyId() {
return myId;
}
public CrawlController getMyController() {
return myController;
}
/**
* This function is called just before starting the crawl by this crawler
* instance. It can be used for setting up the data structures or
* initializations needed by this crawler instance.
*/
public void onStart() {
// Do nothing by default
// Sub-classed can override this to add their custom functionality
}
/**
* This function is called just before the termination of the current
* crawler instance. It can be used for persisting in-memory data or other
* finalization tasks.
*/
public void onBeforeExit() {
// Do nothing by default
// Sub-classed can override this to add their custom functionality
}
/**
* This function is called once the header of a page is fetched. It can be
* overridden by sub-classes to perform custom logic for different status
* codes. For example, 404 pages can be logged, etc.
*
* @param webUrl WebUrl containing the statusCode
* @param statusCode Html Status Code number
* @param statusDescription Html Status COde description
*/
protected void handlePageStatusCode(WebURL webUrl, int statusCode, String statusDescription) {
// Do nothing by default
// Sub-classed can override this to add their custom functionality
}
/**
* This function is called before processing of the page's URL
* It can be overridden by subclasses for tweaking of the url before processing it.
* For example, http://abc.com/def?a=123 - http://abc.com/def
*
* @param curURL current URL which can be tweaked before processing
* @return tweaked WebURL
*/
protected WebURL handleUrlBeforeProcess(WebURL curURL) {
return curURL;
}
/**
* This function is called if the content of a url is bigger than allowed size.
*
* @param urlStr - The URL which it's content is bigger than allowed size
*/
protected void onPageBiggerThanMaxSize(String urlStr, long pageSize) {
logger.warn("Skipping a URL: {} which was bigger ( {} ) than max allowed size", urlStr, pageSize);
}
/**
* This function is called if the crawler encountered an unexpected http status code ( a status code other than 3xx)
*
* @param urlStr URL in which an unexpected error was encountered while crawling
* @param statusCode Html StatusCode
* @param contentType Type of Content
* @param description Error Description
*/
protected void onUnexpectedStatusCode(String urlStr, int statusCode, String contentType, String description) {
logger.warn("Skipping URL: {}, StatusCode: {}, {}, {}", urlStr, statusCode, contentType, description);
// Do nothing by default (except basic logging)
// Sub-classed can override this to add their custom functionality
}
/**
* This function is called if the content of a url could not be fetched.
*
* @param webUrl URL which content failed to be fetched
*/
protected void onContentFetchError(WebURL webUrl) {
logger.warn("Can't fetch content of: {}", webUrl.getURL());
// Do nothing by default (except basic logging)
// Sub-classed can override this to add their custom functionality
}
/**
* This function is called if there has been an error in parsing the content.
*
* @param webUrl URL which failed on parsing
*/
protected void onParseError(WebURL webUrl) {
logger.warn("Parsing error of: {}", webUrl.getURL());
// Do nothing by default (Except logging)
// Sub-classed can override this to add their custom functionality
}
/**
* The CrawlController instance that has created this crawler instance will
* call this function just before terminating this crawler thread. Classes
* that extend WebCrawler can override this function to pass their local
* data to their controller. The controller then puts these local data in a
* List that can then be used for processing the local data of crawlers (if needed).
*
* @return currently NULL
*/
public Object getMyLocalData() {
return null;
}
public void run() {
onStart();
while (true) {
List<WebURL> assignedURLs = new ArrayList<>(50);
isWaitingForNewURLs = true;
frontier.getNextURLs(50, assignedURLs);
isWaitingForNewURLs = false;
if (assignedURLs.size() == 0) {
if (frontier.isFinished()) {
return;
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
logger.error("Error occurred", e);
}
} else {
for (WebURL curURL : assignedURLs) {
if (curURL != null) {
curURL = handleUrlBeforeProcess(curURL);
processPage(curURL);
frontier.setProcessed(curURL);
}
if (myController.isShuttingDown()) {
logger.info("Exiting because of controller shutdown.");
return;
}
}
}
}
}
/**
* Classes that extends WebCrawler should overwrite this function to tell the
* crawler whether the given url should be crawled or not. The following
* implementation indicates that all urls should be included in the crawl.
*
* @param url
* the url which we are interested to know whether it should be
* included in the crawl or not.
* @param page
* Page context from which this URL was scraped
* @return if the url should be included in the crawl it returns true,
* otherwise false is returned.
*/
public boolean shouldVisit(Page page, WebURL url) {
return true;
}
/**
* Classes that extends WebCrawler should overwrite this function to process
* the content of the fetched and parsed page.
*
* @param page
* the page object that is just fetched and parsed.
*/
public void visit(Page page) {
// Do nothing by default
// Sub-classed should override this to add their custom functionality
}
private void processPage(WebURL curURL) {
PageFetchResult fetchResult = null;
try {
if (curURL == null) {
throw new Exception("Failed processing a NULL url !?");
}
fetchResult = pageFetcher.fetchPage(curURL);
int statusCode = fetchResult.getStatusCode();
handlePageStatusCode(curURL, statusCode, EnglishReasonPhraseCatalog.INSTANCE.getReason(statusCode, Locale.ENGLISH)); // Finds the status reason for all known statuses
Page page = new Page(curURL);
page.setFetchResponseHeaders(fetchResult.getResponseHeaders());
page.setStatusCode(statusCode);
if (statusCode != HttpStatus.SC_OK) { // Not 200
if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY
|| statusCode == HttpStatus.SC_MULTIPLE_CHOICES || statusCode == HttpStatus.SC_SEE_OTHER
|| statusCode == HttpStatus.SC_TEMPORARY_REDIRECT || statusCode == 308) { // is 3xx todo follow https://issues.apache.org/jira/browse/HTTPCORE-389
page.setRedirect(true);
if (myController.getConfig().isFollowRedirects()) {
String movedToUrl = fetchResult.getMovedToUrl();
if (movedToUrl == null) {
throw new RedirectException(Level.WARN, "Unexpected error, URL: " + curURL + " is redirected to NOTHING");
}
page.setRedirectedToUrl(movedToUrl);
int newDocId = docIdServer.getDocId(movedToUrl);
if (newDocId > 0) {
throw new RedirectException(Level.DEBUG, "Redirect page: " + curURL + " is already seen");
}
WebURL webURL = new WebURL();
webURL.setURL(movedToUrl);
webURL.setParentDocid(curURL.getParentDocid());
webURL.setParentUrl(curURL.getParentUrl());
webURL.setDepth(curURL.getDepth());
webURL.setDocid(-1);
webURL.setAnchor(curURL.getAnchor());
if (shouldVisit(page, webURL)) {
if (robotstxtServer.allows(webURL)) {
webURL.setDocid(docIdServer.getNewDocID(movedToUrl));
frontier.schedule(webURL);
} else {
logger.debug("Not visiting: {} as per the server's \"robots.txt\" policy", webURL.getURL());
}
} else {
logger.debug("Not visiting: {} as per your \"shouldVisit\" policy", webURL.getURL());
}
}
} else { // All other http codes other than 3xx & 200
String description = EnglishReasonPhraseCatalog.INSTANCE.getReason(fetchResult.getStatusCode(), Locale.ENGLISH); // Finds the status reason for all known statuses
String contentType = fetchResult.getEntity() == null ? "" : fetchResult.getEntity().getContentType().getValue();
onUnexpectedStatusCode(curURL.getURL(), fetchResult.getStatusCode(), contentType, description);
}
} else { // if status code is 200
if (!curURL.getURL().equals(fetchResult.getFetchedUrl())) {
if (docIdServer.isSeenBefore(fetchResult.getFetchedUrl())) {
throw new RedirectException(Level.DEBUG, "Redirect page: " + curURL + " has already been seen");
}
curURL.setURL(fetchResult.getFetchedUrl());
curURL.setDocid(docIdServer.getNewDocID(fetchResult.getFetchedUrl()));
}
if (!fetchResult.fetchContent(page)) {
throw new ContentFetchException();
}
if (!parser.parse(page, curURL.getURL())) {
throw new ParseException();
}
ParseData parseData = page.getParseData();
List<WebURL> toSchedule = new ArrayList<>();
int maxCrawlDepth = myController.getConfig().getMaxDepthOfCrawling();
for (WebURL webURL : parseData.getOutgoingUrls()) {
webURL.setParentDocid(curURL.getDocid());
webURL.setParentUrl(curURL.getURL());
int newdocid = docIdServer.getDocId(webURL.getURL());
if (newdocid > 0) {
// This is not the first time that this Url is visited. So, we set the depth to a negative number.
webURL.setDepth((short) -1);
webURL.setDocid(newdocid);
} else {
webURL.setDocid(-1);
webURL.setDepth((short) (curURL.getDepth() + 1));
if (maxCrawlDepth == -1 || curURL.getDepth() < maxCrawlDepth) {
if (shouldVisit(page, webURL)) {
if (robotstxtServer.allows(webURL)) {
webURL.setDocid(docIdServer.getNewDocID(webURL.getURL()));
toSchedule.add(webURL);
} else {
logger.debug("Not visiting: {} as per the server's \"robots.txt\" policy", webURL.getURL());
}
} else {
logger.debug("Not visiting: {} as per your \"shouldVisit\" policy", webURL.getURL());
}
}
}
}
frontier.scheduleAll(toSchedule);
visit(page);
}
} catch (PageBiggerThanMaxSizeException e) {
onPageBiggerThanMaxSize(curURL.getURL(), e.getPageSize());
} catch (ParseException pe) {
onParseError(curURL);
} catch (ContentFetchException cfe) {
onContentFetchError(curURL);
} catch (RedirectException re) {
logger.log(re.level, re.getMessage());
} catch (NotAllowedContentException nace) {
logger.debug("Skipping: {} as it contains binary content which you configured not to crawl", curURL.getURL());
} catch (Exception e) {
String urlStr = (curURL == null ? "NULL" : curURL.getURL());
logger.error("{}, while processing: {}", e.getMessage(), urlStr);
logger.debug("Stacktrace", e);
} finally {
if (fetchResult != null) {
fetchResult.discardContentIfNotConsumed();
}
}
}
public Thread getThread() {
return myThread;
}
public void setThread(Thread myThread) {
this.myThread = myThread;
}
public boolean isNotWaitingForNewURLs() {
return !isWaitingForNewURLs;
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.crawler;
import java.nio.charset.Charset;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.util.EntityUtils;
import edu.uci.ics.crawler4j.parser.ParseData;
import edu.uci.ics.crawler4j.url.WebURL;
/**
* This class contains the data for a fetched and parsed page.
*
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public class Page {
/**
* The URL of this page.
*/
protected WebURL url;
/**
* Redirection flag
*/
protected boolean redirect;
/**
* The URL to which this page will be redirected to
*/
protected String redirectedToUrl;
/**
* Status of the page
*/
protected int statusCode;
/**
* The content of this page in binary format.
*/
protected byte[] contentData;
/**
* The ContentType of this page.
* For example: "text/html; charset=UTF-8"
*/
protected String contentType;
/**
* The encoding of the content.
* For example: "gzip"
*/
protected String contentEncoding;
/**
* The charset of the content.
* For example: "UTF-8"
*/
protected String contentCharset;
/**
* Language of the Content.
*/
private String language;
/**
* Headers which were present in the response of the
* fetch request
*/
protected Header[] fetchResponseHeaders;
/**
* The parsed data populated by parsers
*/
protected ParseData parseData;
public Page(WebURL url) {
this.url = url;
}
/**
* Loads the content of this page from a fetched HttpEntity.
*
* @param entity HttpEntity
* @throws Exception when load fails
*/
public void load(HttpEntity entity) throws Exception {
contentType = null;
Header type = entity.getContentType();
if (type != null) {
contentType = type.getValue();
}
contentEncoding = null;
Header encoding = entity.getContentEncoding();
if (encoding != null) {
contentEncoding = encoding.getValue();
}
Charset charset = ContentType.getOrDefault(entity).getCharset();
if (charset != null) {
contentCharset = charset.displayName();
}
contentData = EntityUtils.toByteArray(entity);
}
public WebURL getWebURL() {
return url;
}
public void setWebURL(WebURL url) {
this.url = url;
}
public boolean isRedirect() {
return redirect;
}
public void setRedirect(boolean redirect) {
this.redirect = redirect;
}
public String getRedirectedToUrl() {
return redirectedToUrl;
}
public void setRedirectedToUrl(String redirectedToUrl) {
this.redirectedToUrl = redirectedToUrl;
}
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
/**
* Returns headers which were present in the response of the fetch request
*
* @return Header Array, the response headers
*/
public Header[] getFetchResponseHeaders() {
return fetchResponseHeaders;
}
public void setFetchResponseHeaders(Header[] headers) {
fetchResponseHeaders = headers;
}
/**
* @return parsed data generated for this page by parsers
*/
public ParseData getParseData() {
return parseData;
}
public void setParseData(ParseData parseData) {
this.parseData = parseData;
}
/**
* @return content of this page in binary format.
*/
public byte[] getContentData() {
return contentData;
}
public void setContentData(byte[] contentData) {
this.contentData = contentData;
}
/**
* @return ContentType of this page.
* For example: "text/html; charset=UTF-8"
*/
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
/**
* @return encoding of the content.
* For example: "gzip"
*/
public String getContentEncoding() {
return contentEncoding;
}
public void setContentEncoding(String contentEncoding) {
this.contentEncoding = contentEncoding;
}
/**
* @return charset of the content.
* For example: "UTF-8"
*/
public String getContentCharset() {
return contentCharset;
}
public void setContentCharset(String contentCharset) {
this.contentCharset = contentCharset;
}
/**
* @return Language
*/
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.robotstxt;
/**
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public class HostDirectives {
// If we fetched the directives for this host more than
// 24 hours, we have to re-fetch it.
private static final long EXPIRATION_DELAY = 24 * 60 * 1000L;
private RuleSet disallows = new RuleSet();
private RuleSet allows = new RuleSet();
private long timeFetched;
private long timeLastAccessed;
public HostDirectives() {
timeFetched = System.currentTimeMillis();
}
public boolean needsRefetch() {
return (System.currentTimeMillis() - timeFetched > EXPIRATION_DELAY);
}
public boolean allows(String path) {
timeLastAccessed = System.currentTimeMillis();
return !disallows.containsPrefixOf(path) || allows.containsPrefixOf(path);
}
public void addDisallow(String path) {
disallows.add(path);
}
public void addAllow(String path) {
allows.add(path);
}
public long getLastAccessTime() {
return timeLastAccessed;
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.robotstxt;
public class RobotstxtConfig {
/**
* Should the crawler obey Robots.txt protocol? More info on Robots.txt is
* available at http://www.robotstxt.org/
*/
private boolean enabled = true;
/**
* user-agent name that will be used to determine whether some servers have
* specific rules for this agent name.
*/
private String userAgentName = "crawler4j";
/**
* The maximum number of hosts for which their robots.txt is cached.
*/
private int cacheSize = 500;
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getUserAgentName() {
return userAgentName;
}
public void setUserAgentName(String userAgentName) {
this.userAgentName = userAgentName;
}
public int getCacheSize() {
return cacheSize;
}
public void setCacheSize(int cacheSize) {
this.cacheSize = cacheSize;
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.robotstxt;
import java.util.SortedSet;
import java.util.TreeSet;
public class RuleSet extends TreeSet<String> {
private static final long serialVersionUID = 1L;
@Override
public boolean add(String str) {
SortedSet<String> sub = headSet(str);
if (!sub.isEmpty() && str.startsWith(sub.last())) {
// no need to add; prefix is already present
return false;
}
boolean retVal = super.add(str);
sub = tailSet(str + "\0");
while (!sub.isEmpty() && sub.first().startsWith(str)) {
// remove redundant entries
sub.remove(sub.first());
}
return retVal;
}
public boolean containsPrefixOf(String s) {
SortedSet<String> sub = headSet(s);
// because redundant prefixes have been eliminated,
// only a test against last item in headSet is necessary
if (!sub.isEmpty() && s.startsWith(sub.last())) {
return true; // prefix substring exists
}
// might still exist exactly (headSet does not contain boundary)
return contains(s);
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.robotstxt;
import java.util.StringTokenizer;
/**
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public class RobotstxtParser {
private static final String PATTERNS_USERAGENT = "(?i)^User-agent:.*";
private static final String PATTERNS_DISALLOW = "(?i)Disallow:.*";
private static final String PATTERNS_ALLOW = "(?i)Allow:.*";
private static final int PATTERNS_USERAGENT_LENGTH = 11;
private static final int PATTERNS_DISALLOW_LENGTH = 9;
private static final int PATTERNS_ALLOW_LENGTH = 6;
public static HostDirectives parse(String content, String myUserAgent) {
HostDirectives directives = null;
boolean inMatchingUserAgent = false;
StringTokenizer st = new StringTokenizer(content, "\n");
while (st.hasMoreTokens()) {
String line = st.nextToken();
int commentIndex = line.indexOf("#");
if (commentIndex > -1) {
line = line.substring(0, commentIndex);
}
// remove any html markup
line = line.replaceAll("<[^>]+>", "");
line = line.trim();
if (line.length() == 0) {
continue;
}
if (line.matches(PATTERNS_USERAGENT)) {
String ua = line.substring(PATTERNS_USERAGENT_LENGTH).trim().toLowerCase();
if (ua.equals("*") || ua.contains(myUserAgent)) {
inMatchingUserAgent = true;
} else {
inMatchingUserAgent = false;
}
} else if (line.matches(PATTERNS_DISALLOW)) {
if (!inMatchingUserAgent) {
continue;
}
String path = line.substring(PATTERNS_DISALLOW_LENGTH).trim();
if (path.endsWith("*")) {
path = path.substring(0, path.length() - 1);
}
path = path.trim();
if (path.length() > 0) {
if (directives == null) {
directives = new HostDirectives();
}
directives.addDisallow(path);
}
} else if (line.matches(PATTERNS_ALLOW)) {
if (!inMatchingUserAgent) {
continue;
}
String path = line.substring(PATTERNS_ALLOW_LENGTH).trim();
if (path.endsWith("*")) {
path = path.substring(0, path.length() - 1);
}
path = path.trim();
if (directives == null) {
directives = new HostDirectives();
}
directives.addAllow(path);
}
}
return directives;
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.robotstxt;
import java.net.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import edu.uci.ics.crawler4j.crawler.exceptions.PageBiggerThanMaxSizeException;
import org.apache.http.HttpStatus;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.fetcher.PageFetchResult;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.url.WebURL;
import edu.uci.ics.crawler4j.util.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public class RobotstxtServer {
private static final Logger logger = LoggerFactory.getLogger(RobotstxtServer.class);
protected RobotstxtConfig config;
protected final Map<String, HostDirectives> host2directivesCache = new HashMap<>();
protected PageFetcher pageFetcher;
public RobotstxtServer(RobotstxtConfig config, PageFetcher pageFetcher) {
this.config = config;
this.pageFetcher = pageFetcher;
}
private static String getHost(URL url) {
return url.getHost().toLowerCase();
}
public boolean allows(WebURL webURL) {
if (!config.isEnabled()) {
return true;
}
try {
URL url = new URL(webURL.getURL());
String host = getHost(url);
String path = url.getPath();
HostDirectives directives = host2directivesCache.get(host);
if (directives != null && directives.needsRefetch()) {
synchronized (host2directivesCache) {
host2directivesCache.remove(host);
directives = null;
}
}
if (directives == null) {
directives = fetchDirectives(url);
}
return directives.allows(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
return true;
}
private HostDirectives fetchDirectives(URL url) {
WebURL robotsTxtUrl = new WebURL();
String host = getHost(url);
String port = (url.getPort() == url.getDefaultPort() || url.getPort() == -1) ? "" : ":" + url.getPort();
robotsTxtUrl.setURL("http://" + host + port + "/robots.txt");
HostDirectives directives = null;
PageFetchResult fetchResult = null;
try {
fetchResult = pageFetcher.fetchPage(robotsTxtUrl);
if (fetchResult.getStatusCode() == HttpStatus.SC_OK) {
Page page = new Page(robotsTxtUrl);
fetchResult.fetchContent(page);
if (Util.hasPlainTextContent(page.getContentType())) {
String content;
if (page.getContentCharset() == null) {
content = new String(page.getContentData());
} else {
content = new String(page.getContentData(), page.getContentCharset());
}
directives = RobotstxtParser.parse(content, config.getUserAgentName());
}
}
} catch (SocketException | UnknownHostException | SocketTimeoutException se) {
// No logging here, as it just means that robots.txt doesn't exist on this server which is perfectly ok
} catch (PageBiggerThanMaxSizeException pbtms) {
logger.error("Error occurred while fetching (robots) url: {}, {}", robotsTxtUrl.getURL(), pbtms.getMessage());
} catch (Exception e) {
logger.error("Error occurred while fetching (robots) url: " + robotsTxtUrl.getURL(), e);
} finally {
if (fetchResult != null) {
fetchResult.discardContentIfNotConsumed();
}
}
if (directives == null) {
// We still need to have this object to keep track of the time we
// fetched it
directives = new HostDirectives();
}
synchronized (host2directivesCache) {
if (host2directivesCache.size() == config.getCacheSize()) {
String minHost = null;
long minAccessTime = Long.MAX_VALUE;
for (Entry<String, HostDirectives> entry : host2directivesCache.entrySet()) {
if (entry.getValue().getLastAccessTime() < minAccessTime) {
minAccessTime = entry.getValue().getLastAccessTime();
minHost = entry.getKey();
}
}
host2directivesCache.remove(minHost);
}
host2directivesCache.put(host, directives);
}
return directives;
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.util;
/**
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public class Util {
public static byte[] long2ByteArray(long l) {
byte[] array = new byte[8];
int i, shift;
for(i = 0, shift = 56; i < 8; i++, shift -= 8) {
array[i] = (byte)(0xFF & (l >> shift));
}
return array;
}
public static byte[] int2ByteArray(int value) {
byte[] b = new byte[4];
for (int i = 0; i < 4; i++) {
int offset = (3 - i) * 8;
b[i] = (byte) ((value >>> offset) & 0xFF);
}
return b;
}
public static void putIntInByteArray(int value, byte[] buf, int offset) {
for (int i = 0; i < 4; i++) {
int valueOffset = (3 - i) * 8;
buf[offset + i] = (byte) ((value >>> valueOffset) & 0xFF);
}
}
public static int byteArray2Int(byte[] b) {
int value = 0;
for (int i = 0; i < 4; i++) {
int shift = (4 - 1 - i) * 8;
value += (b[i] & 0x000000FF) << shift;
}
return value;
}
public static long byteArray2Long(byte[] b) {
int value = 0;
for (int i = 0; i < 8; i++) {
int shift = (8 - 1 - i) * 8;
value += (b[i] & 0x000000FF) << shift;
}
return value;
}
public static boolean hasBinaryContent(String contentType) {
String typeStr = contentType != null ? contentType.toLowerCase() : "";
return typeStr.contains("image") || typeStr.contains("audio") || typeStr.contains("video") || typeStr.contains("application");
}
public static boolean hasPlainTextContent(String contentType) {
String typeStr = contentType != null ? contentType.toLowerCase() : "";
return typeStr.contains("text") && !typeStr.contains("html");
}
} | Java |
package edu.uci.ics.crawler4j.util;
import edu.uci.ics.crawler4j.url.WebURL;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by Avi Hayun on 9/22/2014.
* Net related Utils
*/
public class Net {
private static Pattern pattern = initializePattern();
public static Set<WebURL> extractUrls(String input) {
Set<WebURL> extractedUrls = new HashSet<>();
if (input != null) {
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
WebURL webURL = new WebURL();
String urlStr = matcher.group();
if (!urlStr.startsWith("http"))
urlStr = "http://" + urlStr;
webURL.setURL(urlStr);
extractedUrls.add(webURL);
}
}
return extractedUrls;
}
/** Singleton like one time call to initialize the Pattern */
private static Pattern initializePattern() {
return Pattern.compile(
"\\b(((ht|f)tp(s?)\\:\\/\\/|~\\/|\\/)|www.)" +
"(\\w+:\\w+@)?(([-\\w]+\\.)+(com|org|net|gov" +
"|mil|biz|info|mobi|name|aero|jobs|museum" +
"|travel|[a-z]{2}))(:[\\d]{1,5})?" +
"(((\\/([-\\w~!$+|.,=]|%[a-f\\d]{2})+)+|\\/)+|\\?|#)?" +
"((\\?([-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?" +
"([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)" +
"(&(?:[-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?" +
"([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)*)*" +
"(#([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)?\\b");
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public class IO {
private static Logger logger = LoggerFactory.getLogger(IO.class);
public static boolean deleteFolder(File folder) {
return deleteFolderContents(folder) && folder.delete();
}
public static boolean deleteFolderContents(File folder) {
logger.info("Deleting content of: " + folder.getAbsolutePath());
File[] files = folder.listFiles();
for (File file : files) {
if (file.isFile()) {
if (!file.delete()) {
return false;
}
} else {
if (!deleteFolder(file)) {
return false;
}
}
}
return true;
}
public static void writeBytesToFile(byte[] bytes, String destination) {
try {
FileOutputStream fos = new FileOutputStream(destination);
FileChannel fc = fos.getChannel();
fc.write(ByteBuffer.wrap(bytes));
fc.close();
fos.close();
} catch (Exception e) {
logger.error("Failed to write file: " + destination, e);
}
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.basic;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.url.WebURL;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.http.Header;
/**
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public class BasicCrawler extends WebCrawler {
private final static Pattern BINARY_FILES_EXTENSIONS =
Pattern.compile(".*\\.(bmp|gif|jpe?g|png|tiff?|pdf|ico|xaml|pict|rif|pptx?|ps" +
"|mid|mp2|mp3|mp4|wav|wma|au|aiff|flac|ogg|3gp|aac|amr|au|vox" +
"|avi|mov|mpe?g|ra?m|m4v|smil|wm?v|swf|aaf|asf|flv|mkv" +
"|zip|rar|gz|7z|aac|ace|alz|apk|arc|arj|dmg|jar|lzip|lha)" +
"(\\?.*)?$"); // For url Query parts ( URL?q=... )
/**
* You should implement this function to specify whether the given url
* should be crawled or not (based on your crawling logic).
*/
@Override
public boolean shouldVisit(Page page, WebURL url) {
String href = url.getURL().toLowerCase();
return !BINARY_FILES_EXTENSIONS.matcher(href).matches() && href.startsWith("http://www.ics.uci.edu/");
}
/**
* This function is called when a page is fetched and ready to be processed
* by your program.
*/
@Override
public void visit(Page page) {
int docid = page.getWebURL().getDocid();
String url = page.getWebURL().getURL();
String domain = page.getWebURL().getDomain();
String path = page.getWebURL().getPath();
String subDomain = page.getWebURL().getSubDomain();
String parentUrl = page.getWebURL().getParentUrl();
String anchor = page.getWebURL().getAnchor();
logger.debug("Docid: {}", docid);
logger.info("URL: ", url);
logger.debug("Domain: '{}'", domain);
logger.debug("Sub-domain: '{}'", subDomain);
logger.debug("Path: '{}'", path);
logger.debug("Parent page: {}", parentUrl);
logger.debug("Anchor text: {}", anchor);
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
String text = htmlParseData.getText();
String html = htmlParseData.getHtml();
Set<WebURL> links = htmlParseData.getOutgoingUrls();
logger.debug("Text length: {}", text.length());
logger.debug("Html length: {}", html.length());
logger.debug("Number of outgoing links: {}", links.size());
}
Header[] responseHeaders = page.getFetchResponseHeaders();
if (responseHeaders != null) {
logger.debug("Response headers:");
for (Header header : responseHeaders) {
logger.debug("\t{}: {}", header.getName(), header.getValue());
}
}
logger.debug("=============");
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.basic;
import com.sleepycat.je.txn.LockerFactory;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public class BasicCrawlController {
private static Logger logger = LoggerFactory.getLogger(BasicCrawlController.class);
public static void main(String[] args) throws Exception {
if (args.length != 2) {
logger.info("Needed parameters: ");
logger.info("\t rootFolder (it will contain intermediate crawl data)");
logger.info("\t numberOfCralwers (number of concurrent threads)");
return;
}
/*
* crawlStorageFolder is a folder where intermediate crawl data is
* stored.
*/
String crawlStorageFolder = args[0];
/*
* numberOfCrawlers shows the number of concurrent threads that should
* be initiated for crawling.
*/
int numberOfCrawlers = Integer.parseInt(args[1]);
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorageFolder);
/*
* Be polite: Make sure that we don't send more than 1 request per
* second (1000 milliseconds between requests).
*/
config.setPolitenessDelay(1000);
/*
* You can set the maximum crawl depth here. The default value is -1 for
* unlimited depth
*/
config.setMaxDepthOfCrawling(2);
/*
* You can set the maximum number of pages to crawl. The default value
* is -1 for unlimited number of pages
*/
config.setMaxPagesToFetch(1000);
/**
* Do you want crawler4j to crawl also binary data ?
* example: the contents of pdf, or the metadata of images etc
*/
config.setIncludeBinaryContentInCrawling(false);
/*
* Do you need to set a proxy? If so, you can use:
* config.setProxyHost("proxyserver.example.com");
* config.setProxyPort(8080);
*
* If your proxy also needs authentication:
* config.setProxyUsername(username); config.getProxyPassword(password);
*/
/*
* This config parameter can be used to set your crawl to be resumable
* (meaning that you can resume the crawl from a previously
* interrupted/crashed crawl). Note: if you enable resuming feature and
* want to start a fresh crawl, you need to delete the contents of
* rootFolder manually.
*/
config.setResumableCrawling(false);
/*
* Instantiate the controller for this crawl.
*/
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
/*
* For each crawl, you need to add some seed urls. These are the first
* URLs that are fetched and then the crawler starts following links
* which are found in these pages
*/
controller.addSeed("http://www.ics.uci.edu/");
controller.addSeed("http://www.ics.uci.edu/~lopes/");
controller.addSeed("http://www.ics.uci.edu/~welling/");
/*
* Start the crawl. This is a blocking operation, meaning that your code
* will reach the line after this only when crawling is finished.
*/
controller.start(BasicCrawler.class, numberOfCrawlers);
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.multiple;
import java.util.Set;
import java.util.regex.Pattern;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.url.WebURL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public class BasicCrawler extends WebCrawler {
private Logger logger = LoggerFactory.getLogger(BasicCrawler.class);
private final static Pattern FILTERS = Pattern.compile(".*(\\.(css|js|bmp|gif|jpe?g" + "|png|tiff?|mid|mp2|mp3|mp4"
+ "|wav|avi|mov|mpeg|ram|m4v|pdf" + "|rm|smil|wmv|swf|wma|zip|rar|gz))$");
private String[] myCrawlDomains;
@Override
public void onStart() {
myCrawlDomains = (String[]) myController.getCustomData();
}
@Override
public boolean shouldVisit(Page page, WebURL url) {
String href = url.getURL().toLowerCase();
if (FILTERS.matcher(href).matches()) {
return false;
}
for (String crawlDomain : myCrawlDomains) {
if (href.startsWith(crawlDomain)) {
return true;
}
}
return false;
}
@Override
public void visit(Page page) {
int docid = page.getWebURL().getDocid();
String url = page.getWebURL().getURL();
int parentDocid = page.getWebURL().getParentDocid();
logger.debug("Docid: {}", docid);
logger.info("URL: {}", url);
logger.debug("Docid of parent page: {}", parentDocid);
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
String text = htmlParseData.getText();
String html = htmlParseData.getHtml();
Set<WebURL> links = htmlParseData.getOutgoingUrls();
logger.debug("Text length: {}", text.length());
logger.debug("Html length: {}", html.length());
logger.debug("Number of outgoing links: {}", links.size());
}
logger.debug("=============");
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.multiple;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public class MultipleCrawlerController {
private static Logger logger = LoggerFactory.getLogger(MultipleCrawlerController.class);
public static void main(String[] args) throws Exception {
if (args.length != 1) {
logger.info("Needed parameter: ");
logger.info("\t rootFolder (it will contain intermediate crawl data)");
return;
}
/*
* crawlStorageFolder is a folder where intermediate crawl data is
* stored.
*/
String crawlStorageFolder = args[0];
CrawlConfig config1 = new CrawlConfig();
CrawlConfig config2 = new CrawlConfig();
/*
* The two crawlers should have different storage folders for their
* intermediate data
*/
config1.setCrawlStorageFolder(crawlStorageFolder + "/crawler1");
config2.setCrawlStorageFolder(crawlStorageFolder + "/crawler2");
config1.setPolitenessDelay(1000);
config2.setPolitenessDelay(2000);
config1.setMaxPagesToFetch(50);
config2.setMaxPagesToFetch(100);
/*
* We will use different PageFetchers for the two crawlers.
*/
PageFetcher pageFetcher1 = new PageFetcher(config1);
PageFetcher pageFetcher2 = new PageFetcher(config2);
/*
* We will use the same RobotstxtServer for both of the crawlers.
*/
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher1);
CrawlController controller1 = new CrawlController(config1, pageFetcher1, robotstxtServer);
CrawlController controller2 = new CrawlController(config2, pageFetcher2, robotstxtServer);
String[] crawler1Domains = new String[] { "http://www.ics.uci.edu/", "http://www.cnn.com/" };
String[] crawler2Domains = new String[] { "http://en.wikipedia.org/" };
controller1.setCustomData(crawler1Domains);
controller2.setCustomData(crawler2Domains);
controller1.addSeed("http://www.ics.uci.edu/");
controller1.addSeed("http://www.cnn.com/");
controller1.addSeed("http://www.ics.uci.edu/~lopes/");
controller1.addSeed("http://www.cnn.com/POLITICS/");
controller2.addSeed("http://en.wikipedia.org/wiki/Main_Page");
controller2.addSeed("http://en.wikipedia.org/wiki/Obama");
controller2.addSeed("http://en.wikipedia.org/wiki/Bing");
/*
* The first crawler will have 5 concurrent threads and the second
* crawler will have 7 threads.
*/
controller1.startNonBlocking(BasicCrawler.class, 5);
controller2.startNonBlocking(BasicCrawler.class, 7);
controller1.waitUntilFinish();
logger.info("Crawler 1 is finished.");
controller2.waitUntilFinish();
logger.info("Crawler 2 is finished.");
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.shutdown;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.url.WebURL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
import java.util.regex.Pattern;
/**
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public class BasicCrawler extends WebCrawler {
private Logger logger = LoggerFactory.getLogger(BasicCrawler.class);
private final static Pattern FILTERS = Pattern.compile(".*(\\.(css|js|bmp|gif|jpe?g" + "|png|tiff?|mid|mp2|mp3|mp4"
+ "|wav|avi|mov|mpeg|ram|m4v|pdf" + "|rm|smil|wmv|swf|wma|zip|rar|gz))$");
private final static String DOMAIN = "http://www.ics.uci.edu/";
@Override
public boolean shouldVisit(Page page, WebURL url) {
String href = url.getURL().toLowerCase();
return !FILTERS.matcher(href).matches() && href.startsWith(DOMAIN);
}
@Override
public void visit(Page page) {
int docid = page.getWebURL().getDocid();
String url = page.getWebURL().getURL();
int parentDocid = page.getWebURL().getParentDocid();
logger.debug("Docid: {}", docid);
logger.info("URL: {}", url);
logger.debug("Docid of parent page: {}", parentDocid);
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
String text = htmlParseData.getText();
String html = htmlParseData.getHtml();
Set<WebURL> links = htmlParseData.getOutgoingUrls();
logger.debug("Text length: {}", text.length());
logger.debug("Html length: {}", html.length());
logger.debug("Number of outgoing links: {}", links.size());
}
logger.debug("=============");
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.shutdown;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public class ControllerWithShutdown {
private static Logger logger = LoggerFactory.getLogger(ControllerWithShutdown.class);
public static void main(String[] args) throws Exception {
if (args.length != 2) {
logger.info("Needed parameters: ");
logger.info("\t rootFolder (it will contain intermediate crawl data)");
logger.info("\t numberOfCralwers (number of concurrent threads)");
return;
}
/*
* crawlStorageFolder is a folder where intermediate crawl data is
* stored.
*/
String crawlStorageFolder = args[0];
/*
* numberOfCrawlers shows the number of concurrent threads that should
* be initiated for crawling.
*/
int numberOfCrawlers = Integer.parseInt(args[1]);
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorageFolder);
config.setPolitenessDelay(1000);
// Unlimited number of pages can be crawled.
config.setMaxPagesToFetch(-1);
/*
* Instantiate the controller for this crawl.
*/
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
/*
* For each crawl, you need to add some seed urls. These are the first
* URLs that are fetched and then the crawler starts following links
* which are found in these pages
*/
controller.addSeed("http://www.ics.uci.edu/~welling/");
controller.addSeed("http://www.ics.uci.edu/~lopes/");
controller.addSeed("http://www.ics.uci.edu/");
/*
* Start the crawl. This is a blocking operation, meaning that your code
* will reach the line after this only when crawling is finished.
*/
controller.startNonBlocking(BasicCrawler.class, numberOfCrawlers);
// Wait for 30 seconds
Thread.sleep(30 * 1000);
// Send the shutdown request and then wait for finishing
controller.shutdown();
controller.waitUntilFinish();
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.localdata;
import java.util.List;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LocalDataCollectorController {
private static Logger logger = LoggerFactory.getLogger(LocalDataCollectorController.class);
public static void main(String[] args) throws Exception {
if (args.length != 2) {
logger.info("Needed parameters: ");
logger.info("\t rootFolder (it will contain intermediate crawl data)");
logger.info("\t numberOfCralwers (number of concurrent threads)");
return;
}
String rootFolder = args[0];
int numberOfCrawlers = Integer.parseInt(args[1]);
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(rootFolder);
config.setMaxPagesToFetch(10);
config.setPolitenessDelay(1000);
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
controller.addSeed("http://www.ics.uci.edu/");
controller.start(LocalDataCollectorCrawler.class, numberOfCrawlers);
List<Object> crawlersLocalData = controller.getCrawlersLocalData();
long totalLinks = 0;
long totalTextSize = 0;
int totalProcessedPages = 0;
for (Object localData : crawlersLocalData) {
CrawlStat stat = (CrawlStat) localData;
totalLinks += stat.getTotalLinks();
totalTextSize += stat.getTotalTextSize();
totalProcessedPages += stat.getTotalProcessedPages();
}
logger.info("Aggregated Statistics:");
logger.info("\tProcessed Pages: {}", totalProcessedPages);
logger.info("\tTotal Links found: {}", totalLinks);
logger.info("\tTotal Text Size: {}", totalTextSize);
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.localdata;
import org.apache.http.HttpStatus;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.fetcher.PageFetchResult;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.parser.ParseData;
import edu.uci.ics.crawler4j.parser.Parser;
import edu.uci.ics.crawler4j.url.WebURL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
/**
* This class is a demonstration of how crawler4j can be used to download a
* single page and extract its title and text.
*/
public class Downloader {
private Parser parser;
private PageFetcher pageFetcher;
private Logger logger = LoggerFactory.getLogger(Downloader.class);
public Downloader() {
CrawlConfig config = new CrawlConfig();
parser = new Parser(config);
pageFetcher = new PageFetcher(config);
}
private Page download(String url) {
WebURL curURL = new WebURL();
curURL.setURL(url);
PageFetchResult fetchResult = null;
try {
fetchResult = pageFetcher.fetchPage(curURL);
if (fetchResult.getStatusCode() == HttpStatus.SC_OK) {
Page page = new Page(curURL);
fetchResult.fetchContent(page);
if (parser.parse(page, curURL.getURL())) {
return page;
}
}
} catch (Exception e) {
logger.error("Error occurred while fetching url: " + curURL.getURL(), e);
} finally {
if (fetchResult != null)
{
fetchResult.discardContentIfNotConsumed();
}
}
return null;
}
public void processUrl(String url) {
logger.debug("Processing: {}", url);
Page page = download(url);
if (page != null) {
ParseData parseData = page.getParseData();
if (parseData != null) {
if (parseData instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) parseData;
logger.debug("Title: {}", htmlParseData.getTitle());
logger.debug("Text length: {}", htmlParseData.getText().length());
logger.debug("Html length: {}", htmlParseData.getHtml().length());
}
} else {
logger.warn("Couldn't parse the content of the page.");
}
} else {
logger.warn("Couldn't fetch the content of the page.");
}
logger.debug("==============");
}
public static void main(String[] args) {
Downloader downloader = new Downloader();
downloader.processUrl("http://en.wikipedia.org/wiki/Main_Page/");
downloader.processUrl("http://www.yahoo.com/");
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.localdata;
public class CrawlStat {
private int totalProcessedPages;
private long totalLinks;
private long totalTextSize;
public int getTotalProcessedPages() {
return totalProcessedPages;
}
public void setTotalProcessedPages(int totalProcessedPages) {
this.totalProcessedPages = totalProcessedPages;
}
public void incProcessedPages() {
this.totalProcessedPages++;
}
public long getTotalLinks() {
return totalLinks;
}
public void setTotalLinks(long totalLinks) {
this.totalLinks = totalLinks;
}
public long getTotalTextSize() {
return totalTextSize;
}
public void setTotalTextSize(long totalTextSize) {
this.totalTextSize = totalTextSize;
}
public void incTotalLinks(int count) {
this.totalLinks += count;
}
public void incTotalTextSize(int count) {
this.totalTextSize += count;
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.localdata;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.url.WebURL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.util.Set;
import java.util.regex.Pattern;
public class LocalDataCollectorCrawler extends WebCrawler {
private Logger logger = LoggerFactory.getLogger(LocalDataCollectorCrawler.class);
Pattern filters = Pattern.compile(".*(\\.(css|js|bmp|gif|jpe?g" + "|png|tiff?|mid|mp2|mp3|mp4"
+ "|wav|avi|mov|mpeg|ram|m4v|pdf" + "|rm|smil|wmv|swf|wma|zip|rar|gz))$");
CrawlStat myCrawlStat;
public LocalDataCollectorCrawler() {
myCrawlStat = new CrawlStat();
}
@Override
public boolean shouldVisit(Page page, WebURL url) {
String href = url.getURL().toLowerCase();
return !filters.matcher(href).matches() && href.startsWith("http://www.ics.uci.edu/");
}
@Override
public void visit(Page page) {
logger.info("Visited: {}", page.getWebURL().getURL());
myCrawlStat.incProcessedPages();
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData parseData = (HtmlParseData) page.getParseData();
Set<WebURL> links = parseData.getOutgoingUrls();
myCrawlStat.incTotalLinks(links.size());
try {
myCrawlStat.incTotalTextSize(parseData.getText().getBytes("UTF-8").length);
} catch (UnsupportedEncodingException ignored) {
// Do nothing
}
}
// We dump this crawler statistics after processing every 50 pages
if (myCrawlStat.getTotalProcessedPages() % 50 == 0) {
dumpMyData();
}
}
/**
* This function is called by controller to get the local data of this crawler when job is finished
*/
@Override
public Object getMyLocalData() {
return myCrawlStat;
}
/**
* This function is called by controller before finishing the job.
* You can put whatever stuff you need here.
*/
@Override
public void onBeforeExit() {
dumpMyData();
}
public void dumpMyData() {
int id = getMyId();
// You can configure the log to output to file
logger.info("Crawler {} > Processed Pages: {}", id, myCrawlStat.getTotalProcessedPages());
logger.info("Crawler {} > Total Links Found: {}", id, myCrawlStat.getTotalLinks());
logger.info("Crawler {} > Total Text Size: {}", id, myCrawlStat.getTotalTextSize());
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.statushandler;
import java.util.regex.Pattern;
import org.apache.http.HttpStatus;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.url.WebURL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public class StatusHandlerCrawler extends WebCrawler {
private Logger logger = LoggerFactory.getLogger(StatusHandlerCrawler.class);
private final static Pattern FILTERS = Pattern.compile(".*(\\.(css|js|bmp|gif|jpe?g" + "|png|tiff?|mid|mp2|mp3|mp4"
+ "|wav|avi|mov|mpeg|ram|m4v|pdf" + "|rm|smil|wmv|swf|wma|zip|rar|gz))$");
/**
* You should implement this function to specify whether
* the given url should be crawled or not (based on your
* crawling logic).
*/
@Override
public boolean shouldVisit(Page page, WebURL url) {
String href = url.getURL().toLowerCase();
return !FILTERS.matcher(href).matches() && href.startsWith("http://www.ics.uci.edu/");
}
/**
* This function is called when a page is fetched and ready
* to be processed by your program.
*/
@Override
public void visit(Page page) {
// Do nothing
}
@Override
protected void handlePageStatusCode(WebURL webUrl, int statusCode, String statusDescription) {
if (statusCode != HttpStatus.SC_OK) {
if (statusCode == HttpStatus.SC_NOT_FOUND) {
logger.warn("Broken link: {}, this link was found in page: {}", webUrl.getURL(), webUrl.getParentUrl());
} else {
logger.warn("Non success status for link: {} status code: {}, description: ", webUrl.getURL(), statusCode, statusDescription);
}
}
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.statushandler;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public class StatusHandlerCrawlController {
private static Logger logger = LoggerFactory.getLogger(StatusHandlerCrawlController.class);
public static void main(String[] args) throws Exception {
if (args.length != 2) {
logger.info("Needed parameters: ");
logger.info("\t rootFolder (it will contain intermediate crawl data)");
logger.info("\t numberOfCralwers (number of concurrent threads)");
return;
}
/*
* crawlStorageFolder is a folder where intermediate crawl data is
* stored.
*/
String crawlStorageFolder = args[0];
/*
* numberOfCrawlers shows the number of concurrent threads that should
* be initiated for crawling.
*/
int numberOfCrawlers = Integer.parseInt(args[1]);
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorageFolder);
/*
* Be polite: Make sure that we don't send more than 1 request per
* second (1000 milliseconds between requests).
*/
config.setPolitenessDelay(1000);
/*
* You can set the maximum crawl depth here. The default value is -1 for
* unlimited depth
*/
config.setMaxDepthOfCrawling(2);
/*
* You can set the maximum number of pages to crawl. The default value
* is -1 for unlimited number of pages
*/
config.setMaxPagesToFetch(1000);
/*
* Do you need to set a proxy? If so, you can use:
* config.setProxyHost("proxyserver.example.com");
* config.setProxyPort(8080);
*
* If your proxy also needs authentication:
* config.setProxyUsername(username); config.getProxyPassword(password);
*/
/*
* This config parameter can be used to set your crawl to be resumable
* (meaning that you can resume the crawl from a previously
* interrupted/crashed crawl). Note: if you enable resuming feature and
* want to start a fresh crawl, you need to delete the contents of
* rootFolder manually.
*/
config.setResumableCrawling(false);
/*
* Instantiate the controller for this crawl.
*/
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
/*
* For each crawl, you need to add some seed urls. These are the first
* URLs that are fetched and then the crawler starts following links
* which are found in these pages
*/
controller.addSeed("http://www.ics.uci.edu/~welling/");
controller.addSeed("http://www.ics.uci.edu/~lopes/");
controller.addSeed("http://www.ics.uci.edu/");
/*
* Start the crawl. This is a blocking operation, meaning that your code
* will reach the line after this only when crawling is finished.
*/
controller.start(StatusHandlerCrawler.class, numberOfCrawlers);
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.imagecrawler;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public class ImageCrawlController {
private static Logger logger = LoggerFactory.getLogger(ImageCrawlController.class);
public static void main(String[] args) throws Exception {
if (args.length < 3) {
logger.info("Needed parameters: ");
logger.info("\t rootFolder (it will contain intermediate crawl data)");
logger.info("\t numberOfCralwers (number of concurrent threads)");
logger.info("\t storageFolder (a folder for storing downloaded images)");
return;
}
String rootFolder = args[0];
int numberOfCrawlers = Integer.parseInt(args[1]);
String storageFolder = args[2];
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(rootFolder);
/*
* Since images are binary content, we need to set this parameter to
* true to make sure they are included in the crawl.
*/
config.setIncludeBinaryContentInCrawling(true);
String[] crawlDomains = new String[] { "http://uci.edu/" };
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
for (String domain : crawlDomains) {
controller.addSeed(domain);
}
ImageCrawler.configure(crawlDomains, storageFolder);
controller.start(ImageCrawler.class, numberOfCrawlers);
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.imagecrawler;
import java.security.MessageDigest;
/**
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
public class Cryptography {
private static final char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
'f' };
public static String MD5(String str) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes());
return hexStringFromBytes(md.digest());
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
private static String hexStringFromBytes(byte[] b) {
String hex = "";
int msb;
int lsb;
int i;
// MSB maps to idx 0
for (i = 0; i < b.length; i++) {
msb = (b[i] & 0x000000FF) / 16;
lsb = (b[i] & 0x000000FF) % 16;
hex = hex + hexChars[msb] + hexChars[lsb];
}
return (hex);
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.imagecrawler;
import java.io.File;
import java.util.regex.Pattern;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.parser.BinaryParseData;
import edu.uci.ics.crawler4j.url.WebURL;
import edu.uci.ics.crawler4j.util.IO;
/**
* @author Yasser Ganjisaffar [lastname at gmail dot com]
*/
/*
* This class shows how you can crawl images on the web and store them in a
* folder. This is just for demonstration purposes and doesn't scale for large
* number of images. For crawling millions of images you would need to store
* downloaded images in a hierarchy of folders
*/
public class ImageCrawler extends WebCrawler {
private static final Pattern filters = Pattern.compile(".*(\\.(css|js|mid|mp2|mp3|mp4|wav|avi|mov|mpeg|ram|m4v|pdf"
+ "|rm|smil|wmv|swf|wma|zip|rar|gz))$");
private static final Pattern imgPatterns = Pattern.compile(".*(\\.(bmp|gif|jpe?g|png|tiff?))$");
private static File storageFolder;
private static String[] crawlDomains;
public static void configure(String[] domain, String storageFolderName) {
ImageCrawler.crawlDomains = domain;
storageFolder = new File(storageFolderName);
if (!storageFolder.exists()) {
storageFolder.mkdirs();
}
}
@Override
public boolean shouldVisit(Page page, WebURL url) {
String href = url.getURL().toLowerCase();
if (filters.matcher(href).matches()) {
return false;
}
if (imgPatterns.matcher(href).matches()) {
return true;
}
for (String domain : crawlDomains) {
if (href.startsWith(domain)) {
return true;
}
}
return false;
}
@Override
public void visit(Page page) {
String url = page.getWebURL().getURL();
// We are only interested in processing images
if (!(page.getParseData() instanceof BinaryParseData)) {
return;
}
if (!imgPatterns.matcher(url).matches()) {
return;
}
// Not interested in very small images
if (page.getContentData().length < 10 * 1024) {
return;
}
// get a unique name for storing this image
String extension = url.substring(url.lastIndexOf("."));
String hashedName = Cryptography.MD5(url) + extension;
// store image
IO.writeBytesToFile(page.getContentData(), storageFolder.getAbsolutePath() + "/" + hashedName);
logger.info("Stored: {}", url);
}
} | Java |
package controlador;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.table.AbstractTableModel;
import modelo.Datos;
import modelo.Ingrediente;
import modelo.Producto;
import vista.DlgListadoIngredientes;
import java.util.*;
public class ContListadoIngredientes {
private class Detalle {
public Detalle(Ingrediente ingr) {
ingrediente = ingr;
productos = "";
ArrayList<Producto> t = Datos.getInstancia().getProductos().productosPorIngrediente(ingr.getCodigo());
cantidad = t.size();
boolean b = true;
for (Producto pr : t) {
if (b) b = false; else this.productos += ", ";
this.productos += pr.getNombre();
}
}
Ingrediente ingrediente;
int cantidad;
String productos;
}
private DlgListadoIngredientes dlg = null;
private Detalle[] lista = null;
private AbstractTableModel tmodelo = null;
public ContListadoIngredientes() {
}
public void mostrar(JFrame frame) {
dlg = new DlgListadoIngredientes(frame, this);
dlg.setLocationRelativeTo(null);
dlg.setVisible(true);
ArrayList<Ingrediente> lst = Datos.getInstancia().getIngredientes().ingredientesGeneral();
lista = new Detalle[lst.size()];
for (int i = 0; i < lst.size(); ++i)
lista[i] = new Detalle(lst.get(i));
Arrays.sort(lista, new Comparator<Detalle>() {
@Override
public int compare(Detalle a, Detalle b) {
return b.cantidad - a.cantidad;
}
});
tmodelo = new AbstractTableModel() {
private static final long serialVersionUID = 1L;
@Override
public int getColumnCount() {
return 3;
}
@Override
public String getColumnName(int col) {
switch (col) {
case 0: return "Ingrediente";
case 1: return "Cantidad";
case 2: return "Producto";
}
return null;
}
@Override
public int getRowCount() {
return lista.length;
}
@Override
public Object getValueAt(int row, int col) {
Detalle obj = lista[row];
switch (col) {
case 0: return obj.ingrediente.getNombre();
case 1: return obj.cantidad;
case 2: return obj.productos;
}
return null;
}
};
dlg.getTblIngredientes().setModel(tmodelo);
dlg.getRbAscendente().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
Arrays.sort(lista, new Comparator<Detalle>() {
@Override
public int compare(Detalle a, Detalle b) {
return a.cantidad - b.cantidad;
}
});
tmodelo.fireTableDataChanged();
}
});
dlg.getRbDescendente().addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
Arrays.sort(lista, new Comparator<Detalle>() {
@Override
public int compare(Detalle a, Detalle b) {
return b.cantidad - a.cantidad;
}
});
tmodelo.fireTableDataChanged();
}
});
dlg.getBtSalir().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
dlg.dispose();
}
});
dlg.getRbDescendente().setSelected(true);
}
}
| Java |
package controlador;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.table.AbstractTableModel;
import modelo.Categoria;
import modelo.Datos;
import vista.DlgActualizarCategorias;
public class ContActualizarCategoria {
private DlgActualizarCategorias dlg = null;
private ArrayList<Categoria> lista = null;
private AbstractTableModel tmodelo = null;
private Categoria cat=null;
public ContActualizarCategoria() {
}
public void mostrar(JFrame frame) {
dlg = new DlgActualizarCategorias(frame, this);
dlg.setLocationRelativeTo(null);
dlg.setVisible(true);
lista = Datos.getInstancia().getCategorias().categoriasGeneral();
tmodelo = new AbstractTableModel() {
private static final long serialVersionUID = 1L;
@Override
public int getColumnCount() {
return 1;
}
@Override
public String getColumnName(int col) {
switch (col) {
case 0: return "Categoria";
}
return null;
}
@Override
public int getRowCount() {
return lista.size();
}
@Override
public Object getValueAt(int row, int col) {
Categoria obj = lista.get(row);
switch (col) {
case 0: return obj.getNombre();
}
return null;
}
};
dlg.getTblCategorias().setModel(tmodelo);
dlg.getBtAnadir().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
ContCategoria contcat = new ContCategoria();
contcat.mostrarAnadir(dlg);
lista = Datos.getInstancia().getCategorias().categoriasGeneral();
tmodelo.fireTableStructureChanged();
}
});
dlg.getBtModificar().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
ContCategoria contcat = new ContCategoria();
if (dlg.getTblCategorias().getSelectedRow()!=-1)
{
cat = lista.get(dlg.getTblCategorias().getSelectedRow());
contcat.mostrarModificar(dlg,cat);
tmodelo.fireTableStructureChanged();
}
else
dlg.mostrarMensaje("Seleccione una categoria");
}
});
dlg.getBtSalir().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
dlg.dispose();
}
});
}
} | Java |
package controlador;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFrame;
import javax.swing.table.AbstractTableModel;
import modelo.Categoria;
import modelo.Datos;
import modelo.DetalleProducto;
import modelo.Ingrediente;
import modelo.Producto;
import vista.DlgProducto;
public class ContProducto {
private class Detalle {
public Detalle(Ingrediente ingr, double cant) {
ingrediente = ingr;
cantidad = cant;
}
Ingrediente ingrediente;
double cantidad;
}
private DlgProducto dlg = null;
private ArrayList<Detalle> lista = new ArrayList<Detalle>();
private ArrayList<Categoria> categorias;
private AbstractTableModel tmodelo = null;
private ComboBoxModel cbl;
private JFrame frm;
public ContProducto() {
}
public void mostrarAnadir(JFrame frame) {
dlg = new DlgProducto(frame, this);
dlg.setLocationRelativeTo(null);
dlg.setTitle("Agregar producto");
frm = frame;
categorias = Datos.getInstancia().getCategorias().categoriasGeneral();
cbl = new DefaultComboBoxModel(categorias.toArray());
dlg.getCbCategoria().setModel(cbl);
tmodelo = new AbstractTableModel() {
private static final long serialVersionUID = 1L;
@Override
public int getColumnCount() {
return 2;
}
@Override
public String getColumnName(int col) {
switch (col) {
case 0: return "Ingrediente";
case 1: return "Cantidad";
}
return null;
}
@Override
public int getRowCount() {
return lista.size();
}
@Override
public Object getValueAt(int row, int col) {
Detalle obj = lista.get(row);
switch (col) {
case 0: return obj.ingrediente.getNombre();
case 1: return String.format("%.2f", obj.cantidad).replace(',', '.');
}
return null;
}
@Override
public void setValueAt(Object value, int row, int col) {
Detalle obj = lista.get(row);
try {
double n = Double.parseDouble(value.toString());
if (n > 0) {
obj.cantidad = n;
fireTableRowsUpdated(row, row);
} else
dlg.mostrarMensaje("Se requiere un número superior a 0.");
} catch (NumberFormatException ex) {
dlg.mostrarMensaje("Valor inválido.");
}
}
@Override
public boolean isCellEditable(int row, int col) {
return col == 1;
}
};
dlg.getTblIngredientes().setModel(tmodelo);
dlg.getBtAnadir().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
ContSelecIngre c = new ContSelecIngre();
Ingrediente ingr = c.mostrar(frm);
if (ingr != null) {
lista.add(new Detalle(ingr, 1));
int i = tmodelo.getRowCount();
tmodelo.fireTableRowsInserted(i, i);
}
}
});
dlg.getBtQuitar().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
int i = dlg.getTblIngredientes().getSelectedRow();
if (i >= 0) {
lista.remove(i);
tmodelo.fireTableRowsDeleted(i, i);
}
}
});
dlg.getBtAceptar().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
try {
String nombre = dlg.getTxtNombre().getText();
double precio = Double.parseDouble(dlg.getTxtPrecio().getText());
Categoria cat = (Categoria) cbl.getSelectedItem();
if (nombre.length() == 0) {
dlg.mostrarMensaje("Campo vacio para el nombre.");
} else {
Producto pr = Datos.getInstancia().getProductos().anadir(nombre, precio, cat);
for (Detalle det : lista)
Datos.getInstancia().getDetallesProducto().anadir(pr, det.ingrediente, det.cantidad);
if(dlg.getTblIngredientes().getRowCount()!=0)
{
dlg.mostrarMensaje("REGISTRADO");
dlg.dispose();
}
else
dlg.mostrarMensaje("Debe Agregar Ingredientes");
}
} catch (NumberFormatException ex) {
dlg.mostrarMensaje("Valor invalido para el campo de precio.");
}
}
});
dlg.getBtSalir().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
dlg.dispose();
}
});
dlg.setModalityType(ModalityType.APPLICATION_MODAL);
dlg.setVisible(true);
}
public void mostrarModificar(JFrame frame, final Producto pr) {
dlg = new DlgProducto(frame, this);
dlg.setLocationRelativeTo(null);
dlg.setTitle("Modificar producto");
categorias = Datos.getInstancia().getCategorias().categoriasGeneral();
cbl = new DefaultComboBoxModel(categorias.toArray());
dlg.getCbCategoria().setModel(cbl);
dlg.getTxtNombre().setText(pr.getNombre());
dlg.getTxtPrecio().setText(String.format("%.2f", pr.getPrecio()).replace(',', '.'));
cbl.setSelectedItem(pr.getCategoria());
for (DetalleProducto det : Datos.getInstancia().getDetallesProducto().detallesPorProducto(pr.getCodigo()))
lista.add(new Detalle(det.ingrediente, det.cantidad));
tmodelo = new AbstractTableModel() {
private static final long serialVersionUID = 1L;
@Override
public int getColumnCount() {
return 2;
}
@Override
public String getColumnName(int col) {
switch (col) {
case 0: return "Ingrediente";
case 1: return "Cantidad";
}
return null;
}
@Override
public int getRowCount() {
return lista.size();
}
@Override
public Object getValueAt(int row, int col) {
Detalle obj = lista.get(row);
switch (col) {
case 0: return obj.ingrediente.getNombre();
case 1: return String.format("%.2f", obj.cantidad).replace(',', '.');
}
return null;
}
@Override
public void setValueAt(Object value, int row, int col) {
Detalle obj = lista.get(row);
try {
double n = Double.parseDouble(value.toString());
if (n > 0) {
obj.cantidad = n;
fireTableRowsUpdated(row, row);
} else
dlg.mostrarMensaje("Se requiere un numero superior a 0.");
} catch (NumberFormatException ex) {
dlg.mostrarMensaje("Valor invalido.");
}
}
@Override
public boolean isCellEditable(int row, int col) {
return col == 1;
}
};
dlg.getTblIngredientes().setModel(tmodelo);
dlg.getBtAnadir().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
ContSelecIngre c = new ContSelecIngre();
Ingrediente ingr = c.mostrar(frm);
if (ingr != null) {
lista.add(new Detalle(ingr, 1));
int i = tmodelo.getRowCount();
tmodelo.fireTableRowsInserted(i, i);
}
}
});
dlg.getBtQuitar().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
int i = dlg.getTblIngredientes().getSelectedRow();
if (i >= 0) {
lista.remove(i);
tmodelo.fireTableRowsDeleted(i, i);
}
}
});
dlg.getBtAceptar().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
try {
String nombre = dlg.getTxtNombre().getText();
double precio = Double.parseDouble(dlg.getTxtPrecio().getText());
Categoria cat = (Categoria) cbl.getSelectedItem();
if (nombre.length() == 0) {
dlg.mostrarMensaje("Campo vacio para el nombre.");
} else {
pr.setNombre(nombre);
pr.setPrecio(precio);
pr.setCategoria(cat);
Datos.getInstancia().getDetallesProducto().eliminarPorProducto(pr.getCodigo());
for (Detalle det : lista)
Datos.getInstancia().getDetallesProducto().anadir(pr, det.ingrediente, det.cantidad);
if(dlg.getTblIngredientes().getRowCount()!=0)
{
dlg.mostrarMensaje("MODIFICADO");
dlg.dispose();
}
else
dlg.mostrarMensaje("Debe Agregar Ingredientes");
}
} catch (NumberFormatException ex) {
dlg.mostrarMensaje("Valor invalido para el campo de precio.");
}
}
});
dlg.getBtSalir().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
dlg.dispose();
}
});
dlg.setModalityType(ModalityType.APPLICATION_MODAL);
dlg.setVisible(true);
}
}
| Java |
package controlador;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import javax.swing.JFrame;
import javax.swing.table.AbstractTableModel;
import modelo.Datos;
import modelo.DetalleOrden;
import modelo.Producto;
import vista.DlgListadoVentas;
public class ContListadoVentas {
private class Detalle {
public Detalle(Producto pr) {
producto = pr;
cantidad = 0;
for (DetalleOrden det : Datos.getInstancia().getDetallesOrden().detallesPorProducto(pr.getCodigo()))
cantidad += det.getCantidad();
monto = cantidad * pr.getPrecio();
}
Producto producto;
int cantidad;
double monto;
}
private DlgListadoVentas dlg = null;
private AbstractTableModel tmodelo = null;
private Detalle[] lista = null;
public ContListadoVentas() {
}
public void mostrar(JFrame frame) {
dlg = new DlgListadoVentas(frame, this);
dlg.setLocationRelativeTo(null);
dlg.setVisible(true);
ArrayList<Producto> lst = Datos.getInstancia().getProductos().productosGeneral();
lista = new Detalle[lst.size()];
for (int i = 0; i < lst.size(); ++i)
lista[i] = new Detalle(lst.get(i));
Arrays.sort(lista, new Comparator<Detalle>() {
@Override
public int compare(Detalle a, Detalle b) {
return -Double.compare(a.monto, b.monto);
}
});
tmodelo = new AbstractTableModel() {
private static final long serialVersionUID = 1L;
@Override
public int getColumnCount() {
return 3;
}
@Override
public String getColumnName(int col) {
switch (col) {
case 0: return "Producto";
case 1: return "Cantidad";
case 2: return "Monto";
}
return null;
}
@Override
public int getRowCount() {
return lista.length;
}
@Override
public Object getValueAt(int row, int col) {
Detalle obj = lista[row];
switch (col) {
case 0: return obj.producto.getNombre();
case 1: return obj.cantidad;
case 2: return String.format("%.2f", obj.monto);
}
return null;
}
};
dlg.getTblVentas().setModel(tmodelo);
dlg.getTblVentas().setSelectionMode(0);
dlg.getRbMontoAscendente().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
Arrays.sort(lista, new Comparator<Detalle>() {
@Override
public int compare(Detalle a, Detalle b) {
return Double.compare(a.monto, b.monto);
}
});
tmodelo.fireTableDataChanged();
}
});
dlg.getRbMontoDescendente().addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
Arrays.sort(lista, new Comparator<Detalle>() {
@Override
public int compare(Detalle a, Detalle b) {
return -Double.compare(a.monto, b.monto);
}
});
tmodelo.fireTableDataChanged();
}
});
dlg.getRbCantidadAscendente().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
Arrays.sort(lista, new Comparator<Detalle>() {
@Override
public int compare(Detalle a, Detalle b) {
return a.cantidad - b.cantidad;
}
});
tmodelo.fireTableDataChanged();
}
});
dlg.getRbCantidadDescendente().addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
Arrays.sort(lista, new Comparator<Detalle>() {
@Override
public int compare(Detalle a, Detalle b) {
return b.cantidad - a.cantidad;
}
});
tmodelo.fireTableDataChanged();
}
});
dlg.getBtSalir().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
dlg.dispose();
}
});
dlg.getRbMontoDescendente().setSelected(true);
}
}
| Java |
package controlador;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JDialog;
import modelo.Categoria;
import modelo.Datos;
import vista.DlgCategoria;
public class ContCategoria {
private DlgCategoria dlg = null;
private Categoria cat;
public ContCategoria() {
}
public void mostrarAnadir(JDialog dialog) {
dlg = new DlgCategoria(dialog, this);
dlg.setLocationRelativeTo(null);
dlg.setTitle("Agregar Categoria");
dlg.getBtAceptar().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if(!dlg.getTxtNombre().equalsIgnoreCase(""))
{
Datos.getInstancia().getCategorias().anadir(dlg.getTxtNombre());
dlg.mostrarMensaje("REGISTRADO");
dlg.dispose();
}
else
dlg.mostrarMensaje("Campo vacio");
}
});
dlg.getBtSalir().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
dlg.dispose();
}
});
dlg.setModalityType(ModalityType.APPLICATION_MODAL);
dlg.setVisible(true);
}
public void mostrarModificar(JDialog dialog, Categoria c) {
dlg = new DlgCategoria(dialog, this);
dlg.setLocationRelativeTo(null);
dlg.setTitle("Modificar Categoria");
cat=c;
dlg.setTxtNombre(cat.getNombre());
dlg.getBtAceptar().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if(!dlg.getTxtNombre().equalsIgnoreCase(""))
{
cat.setNombre(dlg.getTxtNombre());
Datos.getInstancia().getCategorias().actualizar(cat);
dlg.mostrarMensaje("MODIFICADO");
dlg.dispose();
}
else
dlg.mostrarMensaje("Campo vacio");
}
});
dlg.getBtSalir().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
dlg.dispose();
}
});
dlg.setModalityType(ModalityType.APPLICATION_MODAL);
dlg.setVisible(true);
}
} | Java |
package controlador;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.table.AbstractTableModel;
import modelo.CompraDAO;
import modelo.Datos;
import modelo.Ingrediente;
import modelo.IngredienteDAO;
import vista.DlgCompra;
public class ContCompra {
private class Detalle {
public Detalle(Ingrediente ing, double cant) {
ingrediente = ing;
cantidad = cant;
}
Ingrediente ingrediente;
double cantidad;
}
private DlgCompra dlg = null;
private ArrayList<Detalle> lista = new ArrayList<Detalle>();
private AbstractTableModel tmodelo = null;
private JFrame frm;
public ContCompra() {
}
public void mostrar(JFrame frame) {
dlg = new DlgCompra(frame, this);
dlg.setLocationRelativeTo(null);
dlg.getTblCompra().setSelectionMode(0);
dlg.getTblCompra().setAutoscrolls(true);
frm = frame;
tmodelo = new AbstractTableModel() {
private static final long serialVersionUID = 1L;
@Override
public int getColumnCount() {
return 2;
}
@Override
public String getColumnName(int col) {
switch (col) {
case 0: return "Ingrediente";
case 1: return "Cantidad";
}
return null;
}
@Override
public int getRowCount() {
return lista.size();
}
@Override
public Object getValueAt(int row, int col) {
Detalle obj = lista.get(row);
switch (col) {
case 0: return obj.ingrediente.getNombre();
case 1: return obj.cantidad;
}
return null;
}
@Override
public void setValueAt(Object value, int row, int col) {
Detalle obj = lista.get(row);
try {
double n = Double.parseDouble(value.toString());
if (n > 0) {
obj.cantidad = n;
fireTableRowsUpdated(row, row);
} else
dlg.mostrarMensaje("Se requiere un número superior a 0.");
} catch (NumberFormatException ex) {
dlg.mostrarMensaje("Valor inválido.");
}
}
@Override
public boolean isCellEditable(int row, int col) {
return col == 1;
}
};
dlg.getTblCompra().setModel(tmodelo);
dlg.getBtAnadir().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
ContSelecIngre contsing = new ContSelecIngre();
Ingrediente ing = contsing.mostrar(frm);
if (ing != null) {
lista.add(new Detalle(ing, 1));
int i = tmodelo.getRowCount();
tmodelo.fireTableRowsInserted(i - 1, i - 1);
}
}
});
dlg.getBtQuitar().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
int i = dlg.getTblCompra().getSelectedRow();
if (i >= 0) {
lista.remove(i);
tmodelo.fireTableRowsDeleted(i, i);
}
}
});
dlg.getBtAceptar().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
CompraDAO codao = Datos.getInstancia().getCompras();
IngredienteDAO indao=Datos.getInstancia().getIngredientes();
Ingrediente ing;
for (Detalle det : lista) {
ing=det.ingrediente;
codao.anadir(ing, det.cantidad);
ing.setCantidad(ing.getCantidad()+det.cantidad);
indao.actualizar(ing);
}
if(dlg.getTblCompra().getRowCount()!=0)
{
dlg.mostrarMensaje("Compra Efectuada");
dlg.dispose();
}
else
dlg.mostrarMensaje("Debe Agregar un Ingrediente");
}
});
dlg.getBtSalir().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
dlg.dispose();
}
});
dlg.setModalityType(ModalityType.APPLICATION_MODAL);
dlg.setVisible(true);
}
}
| Java |
package controlador;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.table.AbstractTableModel;
import modelo.Datos;
import modelo.Producto;
import vista.DlgActualizarProductos;
public class ContActualizarProductos {
private DlgActualizarProductos dlg = null;
private ArrayList<Producto> lista = null;
private AbstractTableModel tmodelo = null;
private JFrame frm;
public ContActualizarProductos() {
}
public void mostrar(JFrame frame) {
frm = frame;
dlg = new DlgActualizarProductos(frame, this);
dlg.setLocationRelativeTo(null);
dlg.setVisible(true);
lista = Datos.getInstancia().getProductos().productosGeneral();
tmodelo = new AbstractTableModel() {
private static final long serialVersionUID = 1L;
@Override
public int getColumnCount() {
return 3;
}
@Override
public String getColumnName(int col) {
switch (col) {
case 0: return "Producto";
case 1: return "Categoria";
case 2: return "Precio";
}
return null;
}
@Override
public int getRowCount() {
return lista.size();
}
@Override
public Object getValueAt(int row, int col) {
Producto obj = lista.get(row);
switch (col) {
case 0: return obj.getNombre();
case 1: return obj.getCategoria().getNombre();
case 2: return String.format("%.2f", obj.getPrecio());
}
return null;
}
};
dlg.getTblProductos().setModel(tmodelo);
dlg.getBtAnadir().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
ContProducto cont = new ContProducto();
cont.mostrarAnadir(frm);
lista = Datos.getInstancia().getProductos().productosGeneral();
tmodelo.fireTableStructureChanged();
}
});
dlg.getBtModificar().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
ContProducto cont = new ContProducto();
int i = dlg.getTblProductos().getSelectedRow();
if (i >= 0) {
cont.mostrarModificar(frm, lista.get(i));
tmodelo.fireTableDataChanged();
} else
dlg.mostrarMensaje("Seleccione un producto.");
}
});
dlg.getBtSalir().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
dlg.dispose();
}
});
}
}
| Java |
package controlador;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.table.AbstractTableModel;
import modelo.Datos;
import modelo.Ingrediente;
import vista.DlgActualizarIngredientes;
public class ContActualizarIngredientes {
private DlgActualizarIngredientes dlg = null;
private ArrayList<Ingrediente> lista = null;
private AbstractTableModel tmodelo = null;
private Ingrediente ing=null;
public ContActualizarIngredientes() {
}
public void mostrar(JFrame frame) {
dlg = new DlgActualizarIngredientes(frame, this);
dlg.setLocationRelativeTo(null);
dlg.setVisible(true);
lista = Datos.getInstancia().getIngredientes().ingredientesGeneral();
tmodelo = new AbstractTableModel() {
private static final long serialVersionUID = 1L;
@Override
public int getColumnCount() {
return 2;
}
@Override
public String getColumnName(int col) {
switch (col) {
case 0: return "Ingrediente";
case 1: return "Cantidad";
}
return null;
}
@Override
public int getRowCount() {
return lista.size();
}
@Override
public Object getValueAt(int row, int col) {
Ingrediente obj = lista.get(row);
switch (col) {
case 0: return obj.getNombre();
case 1: return obj.getCantidad();
}
return null;
}
};
dlg.getTblIngredientes().setModel(tmodelo);
dlg.getBtAnadir().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
ContIngrediente conting = new ContIngrediente();
conting.mostrarAnadir(dlg);
lista = Datos.getInstancia().getIngredientes().ingredientesGeneral();
tmodelo.fireTableStructureChanged();
}
});
dlg.getBtModificar().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
ContIngrediente conting = new ContIngrediente();
if (dlg.getTblIngredientes().getSelectedRow()!=-1)
{
ing = lista.get(dlg.getTblIngredientes().getSelectedRow());
conting.mostrarModificar(dlg,ing);
tmodelo.fireTableStructureChanged();
}
else
dlg.mostrarMensaje("Seleccione un Ingrediente");
}
});
dlg.getBtSalir().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
dlg.dispose();
}
});
}
}
| Java |
package controlador;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import vista.FrmPrincipal;
public class ContPrincipal {
private FrmPrincipal frm = null;
public ContPrincipal() {
}
public void mostrar(JFrame frame) {
frm = new FrmPrincipal(frame, this);
frm.setLocationRelativeTo(null);
frm.setVisible(true);
frm.getItmCategoria().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
ContActualizarCategoria contcats = new ContActualizarCategoria();
contcats.mostrar(frm);
}
});
frm.getItmIngrediente().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
ContActualizarIngredientes contings = new ContActualizarIngredientes();
contings.mostrar(frm);
}
});
frm.getItmProducto().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
ContActualizarProductos contprods = new ContActualizarProductos();
contprods.mostrar(frm);
}
});
frm.getItmVenta().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
ContOrden contord = new ContOrden();
contord.mostrar(frm);
}
});
frm.getItmCompra().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
ContCompra contcomp = new ContCompra();
contcomp.mostrar(frm);
}
});
frm.getItmProductos().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
ContListadoVentas contlvent = new ContListadoVentas();
contlvent.mostrar(frm);
}
});
frm.getItmIngredientes().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
ContListadoIngredientes contling = new ContListadoIngredientes();
contling.mostrar(frm);
}
});
}
}
| Java |
package controlador;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.table.AbstractTableModel;
import modelo.*;
import vista.DlgOrden;
public class ContOrden {
private class Detalle {
public Detalle(Producto pr, int cant) {
producto = pr;
cantidad = cant;
}
Producto producto;
int cantidad;
}
private DlgOrden dlg = null;
private ArrayList<Detalle> lista = new ArrayList<Detalle>();
private AbstractTableModel tmodelo = null;
private double total;
public ContOrden() {
}
public void mostrar(JFrame frame) {
dlg = new DlgOrden(frame, this);
dlg.setLocationRelativeTo(null);
dlg.getTblProductos().setSelectionMode(0);
tmodelo = new AbstractTableModel() {
private static final long serialVersionUID = 1L;
@Override
public int getColumnCount() {
return 4;
}
@Override
public String getColumnName(int col) {
switch (col) {
case 0: return "Producto";
case 1: return "Precio";
case 2: return "Cantidad";
case 3: return "Total";
}
return null;
}
@Override
public int getRowCount() {
return lista.size();
}
@Override
public Object getValueAt(int row, int col) {
Detalle obj = lista.get(row);
switch (col) {
case 0: return obj.producto.getNombre();
case 1: return String.format("%.2f", obj.producto.getPrecio());
case 2: return obj.cantidad;
case 3: return String.format("%.2f", obj.producto.getPrecio() * obj.cantidad);
}
return null;
}
@Override
public void setValueAt(Object value, int row, int col) {
Detalle obj = lista.get(row);
try {
int n = Integer.parseInt(value.toString());
if (n > 0) {
boolean b = true;
ArrayList<DetalleProducto> lst = Datos.getInstancia().getDetallesProducto().detallesPorProducto(obj.producto.getCodigo());
for (DetalleProducto det : lst)
if ((n - obj.cantidad) * det.getCantidad() > det.ingrediente.getCantidad())
b = false;
if (b) {
for (DetalleProducto det : lst) {
double t = (n - obj.cantidad) * det.getCantidad();
det.ingrediente.setApartado(det.ingrediente.getApartado() + t);
det.ingrediente.setCantidad(det.ingrediente.getCantidad() - t);
}
setTotal(total + (n - obj.cantidad) * obj.producto.getPrecio());
obj.cantidad = n;
fireTableRowsUpdated(row, row);
} else {
dlg.mostrarMensaje("No hay suficientes ingredientes.");
}
} else
dlg.mostrarMensaje("Se requiere un numero superior a 0.");
} catch (NumberFormatException ex) {
dlg.mostrarMensaje("Valor invalido.");
}
}
@Override
public boolean isCellEditable(int row, int col) {
return col == 2;
}
};
dlg.getTblProductos().setModel(tmodelo);
dlg.getBtAnadir().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
ContSelecProducto contspro = new ContSelecProducto();
Producto pr = contspro.mostrar(dlg);
IngredienteDAO indao=Datos.getInstancia().getIngredientes();
if (pr != null) {
boolean b = true;
ArrayList<DetalleProducto> lst = Datos.getInstancia().getDetallesProducto().detallesPorProducto(pr.getCodigo());
for (DetalleProducto det : lst)
if (det.getCantidad() > det.ingrediente.getCantidad())
b = false;
if (b) {
setTotal(total + pr.getPrecio());
lista.add(new Detalle(pr, 1));
for (DetalleProducto det : lst) {
double t = det.getCantidad();
det.ingrediente.setApartado(det.ingrediente.getApartado() + t);
det.ingrediente.setCantidad(det.ingrediente.getCantidad() - t);
indao.actualizar(det.ingrediente);
}
int i = tmodelo.getRowCount();
tmodelo.fireTableRowsInserted(i, i);
} else {
dlg.mostrarMensaje("No hay suficientes ingredientes.");
}
}
}
});
dlg.getBtQuitar().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
int i = dlg.getTblProductos().getSelectedRow();
IngredienteDAO indao=Datos.getInstancia().getIngredientes();
if (i >= 0) {
Detalle obj = lista.get(i);
ArrayList<DetalleProducto> lst = Datos.getInstancia().getDetallesProducto().detallesPorProducto(obj.producto.getCodigo());
for (DetalleProducto det : lst) {
double t = det.getCantidad();
det.ingrediente.setApartado(det.ingrediente.getApartado() - t);
det.ingrediente.setCantidad(det.ingrediente.getCantidad() + t);
}
setTotal(total - obj.producto.getPrecio() * obj.cantidad);
for (DetalleProducto det : lst) {
double t = det.getCantidad();
det.ingrediente.setApartado(det.ingrediente.getApartado() - t);
det.ingrediente.setCantidad(det.ingrediente.getCantidad() + t);
indao.actualizar(det.ingrediente);
}
lista.remove(i);
tmodelo.fireTableRowsDeleted(i, i);
}
}
});
dlg.getBtAceptar().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String cliente = dlg.getTxtCliente();
if (cliente.isEmpty())
dlg.mostrarMensaje("Ingrese el nombre del cliente.");
else if (dlg.getTblProductos().getRowCount() == 0)
dlg.mostrarMensaje("Debe Agregar Productos");
else {
DetalleOrdenDAO dodao = Datos.getInstancia().getDetallesOrden();
OrdenDAO odao = Datos.getInstancia().getOrdenes();
Orden or = odao.anadir(dlg.getTxtCliente(), total);
for (Detalle det : lista)
dodao.anadir(or, det.producto, det.cantidad);
IngredienteDAO idao = Datos.getInstancia().getIngredientes();
ArrayList<Ingrediente> ingredientes = idao.ingredientesGeneral();
for (Ingrediente i : ingredientes) {
i.setApartado(0);
idao.actualizar(i);
}
dlg.mostrarMensaje("Orden Registrada");
dlg.dispose();
}
}
});
dlg.getBtSalir().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
IngredienteDAO idao = Datos.getInstancia().getIngredientes();
ArrayList<Ingrediente> ingredientes = idao.ingredientesGeneral();
for (Ingrediente i : ingredientes) i.setApartado(0);
dlg.dispose();
}
});
dlg.setModalityType(ModalityType.APPLICATION_MODAL);
dlg.setVisible(true);
}
private void setTotal(double t) {
total = t;
dlg.getLblSubtotal().setText(String.format("Subtotal: %.2f", total));
}
}
| Java |
package controlador;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.table.AbstractTableModel;
import modelo.Datos;
import modelo.Ingrediente;
import vista.DlgSelecIngre;
public class ContSelecIngre {
private DlgSelecIngre dlg = null;
private ArrayList<Ingrediente> lista = null;
private AbstractTableModel tmodelo = null;
private Ingrediente ing = null;
public ContSelecIngre() {
}
public Ingrediente mostrar(JFrame frame) {
dlg = new DlgSelecIngre(frame, this);
dlg.setLocationRelativeTo(null);
lista = Datos.getInstancia().getIngredientes().ingredientesGeneral();
tmodelo = new AbstractTableModel() {
private static final long serialVersionUID = 1L;
@Override
public int getColumnCount() {
return 1;
}
@Override
public String getColumnName(int col) {
switch (col) {
case 0: return "Ingrediente";
}
return null;
}
@Override
public int getRowCount() {
return lista.size();
}
@Override
public Object getValueAt(int row, int col) {
Ingrediente obj = lista.get(row);
switch (col) {
case 0: return obj.getNombre();
}
return null;
}
};
dlg.getTblIngredientes().setModel(tmodelo);
dlg.getBtAceptar().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (dlg.getTblIngredientes().getSelectedRow()!=-1)
{
ing = lista.get(dlg.getTblIngredientes().getSelectedRow());
dlg.dispose();
}
else
dlg.mostrarMensaje("Seleccione un Ingrediente");
}
});
dlg.getBtSalir().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
dlg.dispose();
}
});
dlg.setModalityType(ModalityType.APPLICATION_MODAL);
dlg.setVisible(true);
return ing;
}
}
| Java |
package controlador;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JDialog;
import modelo.Datos;
import modelo.Ingrediente;
import vista.DlgIngrediente;
public class ContIngrediente {
private DlgIngrediente dlg = null;
private Ingrediente ing;
public ContIngrediente() {
}
public void mostrarAnadir(JDialog dialog) {
dlg = new DlgIngrediente(dialog, this);
dlg.setLocationRelativeTo(null);
dlg.setTitle("Agregar Ingrediente");
dlg.getBtAceptar().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if(!dlg.getTxtNombre().equalsIgnoreCase(""))
{
Datos.getInstancia().getIngredientes().anadir(dlg.getTxtNombre());
dlg.mostrarMensaje("REGISTRADO");
dlg.dispose();
}
else
dlg.mostrarMensaje("Campo vacio");
}
});
dlg.getBtSalir().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
dlg.dispose();
}
});
dlg.setModalityType(ModalityType.APPLICATION_MODAL);
dlg.setVisible(true);
}
public void mostrarModificar(JDialog dialog, Ingrediente in) {
dlg = new DlgIngrediente(dialog, this);
dlg.setLocationRelativeTo(null);
dlg.setTitle("Modificar Ingrediente");
ing=in;
dlg.setTxtNombre(ing.getNombre());
dlg.setTxtCantidad(String.format("%.2f", ing.getCantidad()));
dlg.getBtAceptar().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if(!dlg.getTxtNombre().equalsIgnoreCase(""))
{
ing.setNombre(dlg.getTxtNombre());
Datos.getInstancia().getIngredientes().actualizar(ing);
dlg.mostrarMensaje("MODIFICADO");
dlg.dispose();
}
else
dlg.mostrarMensaje("Campo vacio");
}
});
dlg.getBtSalir().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
dlg.dispose();
}
});
dlg.setModalityType(ModalityType.APPLICATION_MODAL);
dlg.setVisible(true);
}
}
| Java |
package controlador;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JDialog;
import javax.swing.table.AbstractTableModel;
import modelo.Datos;
import modelo.Producto;
import vista.DlgSelecProducto;
public class ContSelecProducto {
private DlgSelecProducto dlg = null;
private ArrayList<Producto> lista = null;
private AbstractTableModel tmodelo = null;
private Producto pr = null;
public ContSelecProducto() {
}
public Producto mostrar(JDialog dialog) {
dlg = new DlgSelecProducto(dialog, this);
dlg.setLocationRelativeTo(null);
lista = Datos.getInstancia().getProductos().productosGeneral();
tmodelo = new AbstractTableModel() {
private static final long serialVersionUID = 1L;
@Override
public int getColumnCount() {
return 1;
}
@Override
public String getColumnName(int col) {
switch (col) {
case 0: return "Producto";
}
return null;
}
@Override
public int getRowCount() {
return lista.size();
}
@Override
public Object getValueAt(int row, int col) {
Producto obj = lista.get(row);
switch (col) {
case 0: return obj.getNombre();
}
return null;
}
};
dlg.getTblProductos().setModel(tmodelo);
dlg.getBtAceptar().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
pr = lista.get(dlg.getTblProductos().getSelectedRow());
dlg.dispose();
}
});
dlg.getBtSalir().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
dlg.dispose();
}
});
dlg.setModalityType(ModalityType.APPLICATION_MODAL);
dlg.setVisible(true);
return pr;
}
}
| Java |
package vista;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import controlador.ContActualizarCategoria;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class DlgActualizarCategorias extends javax.swing.JDialog {
private JPanel pnlCategorias;
private JTable tblCategorias;
private JScrollPane jScrollPane1;
private JButton btModificar;
private JButton btSalir;
private JButton btAnadir;
private ContActualizarCategoria controlador;
public DlgActualizarCategorias(JFrame frame, ContActualizarCategoria controlador) {
super(frame);
this.controlador = controlador;
initGUI();
}
private void initGUI() {
try {
{
this.setTitle("Categorias");
{
pnlCategorias = new JPanel();
getContentPane().add(pnlCategorias, BorderLayout.CENTER);
pnlCategorias.setPreferredSize(new java.awt.Dimension(386, 307));
pnlCategorias.setLayout(null);
{
jScrollPane1 = new JScrollPane();
pnlCategorias.add(jScrollPane1);
jScrollPane1.setBounds(57, 39, 264, 145);
{
tblCategorias = new JTable();
jScrollPane1.setViewportView(tblCategorias);
tblCategorias.setBounds(90, 74, 193, 63);
}
}
{
btAnadir = new JButton();
pnlCategorias.add(btAnadir);
btAnadir.setText("Agregar");
btAnadir.setBounds(33, 247, 97, 26);
}
{
btModificar = new JButton();
pnlCategorias.add(btModificar);
btModificar.setText("Modificar");
btModificar.setBounds(146, 247, 105, 26);
}
{
btSalir = new JButton();
pnlCategorias.add(btSalir);
btSalir.setText("Salir");
btSalir.setBounds(269, 247, 85, 26);
}
}
}
this.setSize(396, 322);
} catch (Exception e) {
e.printStackTrace();
}
}
public JTable getTblCategorias() {
return tblCategorias;
}
public void mostrarMensaje(String mensaje) {
JOptionPane.showMessageDialog(this, mensaje);
}
public JButton getBtModificar() {
return btModificar;
}
public JButton getBtSalir() {
return btSalir;
}
public JButton getBtAnadir() {
return btAnadir;
}
}
| Java |
package vista;
import java.awt.BorderLayout;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import controlador.ContProducto;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class DlgProducto extends javax.swing.JDialog {
private JPanel PnlProducto;
private JLabel lblNombre;
private JTextField txtNombre;
private JLabel lblCategoria;
private JButton btSalir;
private JButton btAceptar;
private JButton btQuitar;
private JButton btAnadir;
private JTextField txtPrecio;
private JLabel lblPrecio;
private JScrollPane jScrollPane1;
private JTable tblIngredientes;
private JComboBox cbCategoria;
private ContProducto controlador;
public DlgProducto(JFrame frame, ContProducto controlador) {
super(frame);
this.controlador = controlador;
initGUI();
}
private void initGUI() {
try {
{
this.setTitle("Producto");
}
{
PnlProducto = new JPanel();
getContentPane().add(PnlProducto, BorderLayout.CENTER);
PnlProducto.setLayout(null);
PnlProducto.setPreferredSize(new java.awt.Dimension(408, 364));
{
lblNombre = new JLabel();
PnlProducto.add(lblNombre);
lblNombre.setText("Nombre:");
lblNombre.setBounds(34, 25, 53, 14);
}
{
txtNombre = new JTextField();
PnlProducto.add(txtNombre);
txtNombre.setBounds(111, 22, 219, 21);
}
{
lblCategoria = new JLabel();
PnlProducto.add(lblCategoria);
lblCategoria.setText("Categoria:");
lblCategoria.setBounds(34, 56, 65, 19);
}
{
ComboBoxModel cbCategoriaModel =
new DefaultComboBoxModel(
new String[] { "Item One", "Item Two" });
cbCategoria = new JComboBox();
PnlProducto.add(cbCategoria);
cbCategoria.setModel(cbCategoriaModel);
cbCategoria.setBounds(111, 55, 147, 21);
}
{
jScrollPane1 = new JScrollPane();
PnlProducto.add(jScrollPane1);
jScrollPane1.setBounds(34, 133, 351, 109);
{
tblIngredientes = new JTable();
jScrollPane1.setViewportView(tblIngredientes);
tblIngredientes.setBounds(46, 115, 345, 87);
}
}
{
lblPrecio = new JLabel();
PnlProducto.add(lblPrecio);
lblPrecio.setText("Precio:");
lblPrecio.setBounds(34, 96, 43, 14);
}
{
txtPrecio = new JTextField();
PnlProducto.add(txtPrecio);
txtPrecio.setBounds(111, 93, 69, 21);
}
{
btAnadir = new JButton();
PnlProducto.add(btAnadir);
btAnadir.setText("Agregar");
btAnadir.setBounds(118, 248, 81, 21);
}
{
btQuitar = new JButton();
PnlProducto.add(btQuitar);
btQuitar.setText("Quitar");
btQuitar.setBounds(223, 248, 81, 21);
}
{
btAceptar = new JButton();
PnlProducto.add(btAceptar);
btAceptar.setText("Aceptar");
btAceptar.setBounds(205, 309, 89, 27);
}
{
btSalir = new JButton();
PnlProducto.add(btSalir);
btSalir.setText("Salir");
btSalir.setBounds(322, 309, 63, 27);
}
}
this.setSize(418, 377);
} catch (Exception e) {
e.printStackTrace();
}
}
public JPanel getPnlProducto() {
return PnlProducto;
}
public JLabel getLblNombre() {
return lblNombre;
}
public JTextField getTxtNombre() {
return txtNombre;
}
public JLabel getLblCategoria() {
return lblCategoria;
}
public JButton getBtSalir() {
return btSalir;
}
public JButton getBtAceptar() {
return btAceptar;
}
public JButton getBtQuitar() {
return btQuitar;
}
public JButton getBtAnadir() {
return btAnadir;
}
public JTextField getTxtPrecio() {
return txtPrecio;
}
public JLabel getLblPrecio() {
return lblPrecio;
}
public JTable getTblIngredientes() {
return tblIngredientes;
}
public JComboBox getCbCategoria() {
return cbCategoria;
}
public void mostrarMensaje(String mensaje) {
JOptionPane.showMessageDialog(this, mensaje);
}
}
| Java |
package vista;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import controlador.ContSelecIngre;
import controlador.ContSelecProducto;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class DlgSelecIngre extends javax.swing.JDialog {
private JPanel PnlIngredientes;
private JScrollPane jScrollPane1;
private JButton btSalir;
private JButton btAceptar;
private JLabel lblIngrediente;
private JTable tblIngredientes;
private ContSelecIngre controlador;
public DlgSelecIngre(JFrame frame, ContSelecIngre controlador) {
super(frame);
this.controlador = controlador;
initGUI();
}
private void initGUI() {
try {
{
this.setTitle("Ingredientes");
}
{
PnlIngredientes = new JPanel();
getContentPane().add(PnlIngredientes, BorderLayout.CENTER);
PnlIngredientes.setLayout(null);
PnlIngredientes.setPreferredSize(new java.awt.Dimension(348, 254));
{
lblIngrediente = new JLabel();
PnlIngredientes.add(lblIngrediente);
lblIngrediente.setText("SELECCIONE UN INGREDIENTE");
lblIngrediente.setBounds(76, 25, 228, 14);
}
{
jScrollPane1 = new JScrollPane();
PnlIngredientes.add(jScrollPane1);
jScrollPane1.setBounds(64, 51, 256, 131);
{
TableModel tblIngredientesModel =
new DefaultTableModel(
new String[][] { { "One", "Two" }, { "Three", "Four" } },
new String[] { "Ingrediente"});
tblIngredientes = new JTable();
jScrollPane1.setViewportView(tblIngredientes);
tblIngredientes.setModel(tblIngredientesModel);
tblIngredientes.setBounds(72, 63, 243, 80);
}
}
{
btAceptar = new JButton();
PnlIngredientes.add(btAceptar);
btAceptar.setText("Aceptar");
btAceptar.setBounds(132, 221, 96, 26);
}
{
btSalir = new JButton();
PnlIngredientes.add(btSalir);
btSalir.setText("Salir");
btSalir.setBounds(264, 221, 78, 26);
}
}
this.setSize(386, 298);
} catch (Exception e) {
e.printStackTrace();
}
}
public JTable getTblIngredientes() {
return tblIngredientes;
}
public JButton getBtSalir() {
return btSalir;
}
public JButton getBtAceptar() {
return btAceptar;
}
public void mostrarMensaje(String mensaje) {
JOptionPane.showMessageDialog(this, mensaje);
}
}
| Java |
package vista;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import controlador.ContCompra;
import controlador.ContOrden;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class DlgCompra extends javax.swing.JDialog {
private JPanel pnlCompra;
private JScrollPane jScrollPane1;
private JButton btSalir;
private JButton btAceptar;
private JButton btQuitar;
private JButton btAnadir;
private JTable tblCompra;
private ContCompra controlador;
public DlgCompra(JFrame frame, ContCompra controlador) {
super(frame);
this.controlador = controlador;
initGUI();
}
private void initGUI() {
try {
{
this.setTitle("Compra");
}
{
pnlCompra = new JPanel();
getContentPane().add(pnlCompra, BorderLayout.CENTER);
pnlCompra.setLayout(null);
pnlCompra.setPreferredSize(new java.awt.Dimension(368, 261));
{
jScrollPane1 = new JScrollPane();
pnlCompra.add(jScrollPane1);
jScrollPane1.setBounds(57, 27, 265, 116);
{
tblCompra = new JTable();
jScrollPane1.setViewportView(tblCompra);
tblCompra.setBounds(59, 60, 259, 121);
}
}
{
btAnadir = new JButton();
pnlCompra.add(btAnadir);
btAnadir.setText("Agregar");
btAnadir.setBounds(81, 155, 96, 21);
}
{
btQuitar = new JButton();
pnlCompra.add(btQuitar);
btQuitar.setText("Quitar");
btQuitar.setBounds(197, 155, 92, 21);
}
{
btAceptar = new JButton();
pnlCompra.add(btAceptar);
btAceptar.setText("Aceptar");
btAceptar.setBounds(140, 223, 90, 26);
}
{
btSalir = new JButton();
pnlCompra.add(btSalir);
btSalir.setText("Salir");
btSalir.setBounds(262, 223, 75, 26);
}
}
this.setSize(378, 299);
} catch (Exception e) {
e.printStackTrace();
}
}
public JTable getTblCompra() {
return tblCompra;
}
public JButton getBtAnadir() {
return btAnadir;
}
public JButton getBtQuitar() {
return btQuitar;
}
public JButton getBtAceptar() {
return btAceptar;
}
public JButton getBtSalir() {
return btSalir;
}
public void mostrarMensaje(String mensaje) {
JOptionPane.showMessageDialog(this, mensaje);
}
}
| Java |
package vista;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import controlador.ContCategoria;
import controlador.ContIngrediente;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class DlgIngrediente extends javax.swing.JDialog {
private JPanel PnlIngrediente;
private JButton btSalir;
private JButton btAceptar;
private JTextField txtCantidad;
private JLabel lblCantidad;
private JTextField txtNombre;
private JLabel lblNombre;
private ContIngrediente controlador;
public DlgIngrediente(JDialog dialog, ContIngrediente controlador) {
super(dialog);
this.controlador = controlador;
initGUI();
}
private void initGUI() {
try {
{
this.setTitle("Ingrediente");
}
{
PnlIngrediente = new JPanel();
getContentPane().add(PnlIngrediente, BorderLayout.CENTER);
PnlIngrediente.setLayout(null);
PnlIngrediente.setPreferredSize(new java.awt.Dimension(313, 153));
{
lblNombre = new JLabel();
PnlIngrediente.add(lblNombre);
lblNombre.setText("Nombre:");
lblNombre.setBounds(23, 27, 77, 14);
}
{
txtNombre = new JTextField();
PnlIngrediente.add(txtNombre);
txtNombre.setBounds(100, 24, 186, 21);
}
{
lblCantidad = new JLabel();
PnlIngrediente.add(lblCantidad);
lblCantidad.setText("Cantidad:");
lblCantidad.setBounds(23, 67, 82, 14);
}
{
txtCantidad = new JTextField();
PnlIngrediente.add(txtCantidad);
txtCantidad.setBounds(103, 64, 72, 21);
txtCantidad.setEditable(false);
}
{
btAceptar = new JButton();
PnlIngrediente.add(btAceptar);
btAceptar.setText("Aceptar");
btAceptar.setBounds(105, 113, 99, 21);
}
{
btSalir = new JButton();
PnlIngrediente.add(btSalir);
btSalir.setText("Salir");
btSalir.setBounds(227, 113, 82, 21);
}
}
this.setSize(350, 187);
} catch (Exception e) {
e.printStackTrace();
}
}
public void setTxtNombre(String nombre) {
txtNombre.setText(nombre);
}
public String getTxtNombre() {
return txtNombre.getText();
}
public void setTxtCantidad(String nombre) {
txtCantidad.setText(nombre);
}
public String getTxtCantidad() {
return txtCantidad.getText();
}
public void mostrarMensaje(String mensaje) {
JOptionPane.showMessageDialog(this, mensaje);
}
public void setDlgTitulo(String titulo) {
this.setTitle(titulo);
}
public JButton getBtAceptar() {
return btAceptar;
}
public JButton getBtSalir() {
return btSalir;
}
}
| Java |
package vista;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.SwingUtilities;
import controlador.ContActualizarCategoria;
import controlador.ContCategoria;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class DlgCategoria extends javax.swing.JDialog {
private JPanel jPCategoria;
private JTextField txtNombre;
private JButton btSalir;
private JButton btAceptar;
private JLabel lblNombre;
private ContCategoria controlador;
public DlgCategoria(JDialog dialog, ContCategoria controlador) {
super(dialog);
this.controlador = controlador;
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.setTitle("Categoria");
{
jPCategoria = new JPanel();
getContentPane().add(jPCategoria, BorderLayout.CENTER);
jPCategoria.setPreferredSize(new java.awt.Dimension(301, 111));
jPCategoria.setLayout(null);
{
lblNombre = new JLabel();
jPCategoria.add(lblNombre);
lblNombre.setText("Nombre:");
lblNombre.setBounds(12, 25, 66, 16);
}
{
txtNombre = new JTextField();
jPCategoria.add(txtNombre);
txtNombre.setBounds(90, 25, 175, 21);
}
{
btAceptar = new JButton();
jPCategoria.add(btAceptar);
btAceptar.setText("Aceptar");
btAceptar.setBounds(49, 70, 105, 25);
}
{
btSalir = new JButton();
jPCategoria.add(btSalir);
btSalir.setText("Salir");
btSalir.setBounds(180, 70, 85, 26);
}
}
pack();
this.setSize(284, 146);
} catch (Exception e) {
//add your error handling code here
e.printStackTrace();
}
}
public void setTxtNombre(String nombre) {
txtNombre.setText(nombre);
}
public void setDlgTitulo(String titulo) {
this.setTitle(titulo);
}
public void mostrarMensaje(String mensaje) {
JOptionPane.showMessageDialog(this, mensaje);
}
public String getTxtNombre() {
return txtNombre.getText();
}
public JButton getBtAceptar() {
return btAceptar;
}
public JButton getBtSalir() {
return btSalir;
}
}
| Java |
package vista;
import java.awt.BorderLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import controlador.ContListadoIngredientes;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class DlgListadoIngredientes extends javax.swing.JDialog {
private JPanel pnlListadoIngredientes;
private JScrollPane jScrollPane1;
private ButtonGroup buttonGroup1;
private JTable tblIngredientes;
private JRadioButton rbDescendente;
private JButton btSalir;
private JRadioButton rbAscendente;
private JLabel lblOrdenar;
private ContListadoIngredientes controlador;
public DlgListadoIngredientes(JFrame frame, ContListadoIngredientes controlador) {
super(frame);
this.controlador = controlador;
initGUI();
}
private void initGUI() {
try {
{
this.setTitle("Listado de Ingredientes Mas Usados");
{
ButtonGroup grp = new ButtonGroup();
pnlListadoIngredientes = new JPanel();
getContentPane().add(pnlListadoIngredientes, BorderLayout.CENTER);
pnlListadoIngredientes.setPreferredSize(new java.awt.Dimension(439, 319));
pnlListadoIngredientes.setLayout(null);
{
lblOrdenar = new JLabel();
pnlListadoIngredientes.add(lblOrdenar);
lblOrdenar.setText("Ordenar:");
lblOrdenar.setBounds(35, 19, 70, 14);
}
{
rbAscendente = new JRadioButton();
pnlListadoIngredientes.add(rbAscendente);
rbAscendente.setText("Ascendentemente");
rbAscendente.setBounds(117, 17, 167, 18);
grp.add(rbAscendente);
}
{
rbDescendente = new JRadioButton();
pnlListadoIngredientes.add(rbDescendente);
rbDescendente.setText("Descendentemente");
rbDescendente.setBounds(117, 42, 167, 18);
grp.add(rbDescendente);
}
{
jScrollPane1 = new JScrollPane();
pnlListadoIngredientes.add(jScrollPane1);
jScrollPane1.setBounds(25, 80, 386, 156);
{
tblIngredientes = new JTable();
jScrollPane1.setViewportView(tblIngredientes);
tblIngredientes.setBounds(49, 53, 288, 113);
}
}
{
btSalir = new JButton();
pnlListadoIngredientes.add(btSalir);
btSalir.setText("Salir");
btSalir.setBounds(325, 258, 76, 28);
}
}
}
this.setSize(444, 351);
} catch (Exception e) {
e.printStackTrace();
}
}
public JTable getTblIngredientes() {
return tblIngredientes;
}
public JRadioButton getRbAscendente() {
return rbAscendente;
}
public JRadioButton getRbDescendente() {
return rbDescendente;
}
public JButton getBtSalir() {
return btSalir;
}
private ButtonGroup getButtonGroup1() {
if(buttonGroup1 == null) {
buttonGroup1 = new ButtonGroup();
}
return buttonGroup1;
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.