Data + VRaptor

38 respostas
J

Galera, gostaria mais uma vez da ajuda de vcs

Eu preciso enviar uma data através de um formulário, mas não sei qual a melhor forma de fazer isso, é necessário converter de String para Date?

Obrigado

38 Respostas

B

O VRaptor já possui conversores para Date e Calendar, além de LocalDate, LocalTime e LocalDateTime do JodaTime. Dá uma lida aqui que vai esclarecer mais: http://vraptor.caelum.com.br/documentacao/conversores/

J

Eu já li, mas não entendi muito bem

como a data será passada através de formulário então creio que a conversão seja necessária

vlw

L

se a data estiver no formato direitinho, o vraptor converte automaticamente, só receber um Date, ou Calendar, (ou alguém do joda-time) como parâmetro do método do controller ou como atributo do parametro do método.

R

Lucas, eu só não entendi por quê já não existe um conversor nativo do DateTime do Joda Time.

Seria essa uma possível nova implementação? Ou já houve discussão em cima disso?

EDIT: Nativo me refiro aos conversores que já estão implementados no VRaptor.

L

É possivel sim…

implementa lá e manda um pull request, plz? =)
ou pelo menos abre uma issue com isso

J

Beleza, uma coisa que tá me fazendo quebra a cabeça aqui

Eu tenho 2 datas, uma que ele pega no momento do registro e outra que é adicionada manualmente

Eu preciso da data e da hora nos dois casos, então fiz o seguinte

meu formulário

<form action="adiciona">
		<fieldset>
			<legend>Adicionar Ocorrência</legend>
			
			<label for="data">Issue's Date</label>
			<input id="data" type="text" name="servidor.dataOcorrencia"/><br/>

minha página de listagem

<tbody>
		<c:forEach items="${servidorList}" var="servidor">
			<tr>
				<td><fmt:formatDate pattern="dd/MM/yyyy HH:mm" value="${servidor.dataOcorrencia.time}" /></td>
				<td><fmt:formatDate pattern="dd/MM/yyyy HH:mm" value="${servidor.dataRegistro.time}" /></td>

meu form de edição

<form action="altera">
		<fieldset>
			<legend>Alterar Registro</legend>
			
			<input type="hidden" name="servidor.id" value="${servidor.id}"/>
			
			<label for="dataOcorrencia">Data:</label>
			<input id="dataOcorrencia" type="text" name="servidor.dataOcorrencia" value="<fmt:formatDate pattern="dd/MM/yyyy HH:mm" value="${servidor.dataOcorrencia.time}" />"/><br/>

porém, as horas e os minutos ficam 00:00, e não consigo editar, sempre que tento ele dá uma IlegalArgumentException

quando eu vo registra eu coloco a data na seguinte forma

ex - 25/04/2012 17:15

alguma pista ai??

obrigado

L

no banco a data está como date ou timestamp?

J

Tá como date

o log que sai é esse:

GRAVE: Servlet.service() for servlet [default] in context with path [/dashboard] threw exception
br.com.caelum.vraptor.InterceptionException: exception raised, check root cause for details: java.lang.IllegalArgumentException: attempt to create saveOrUpdate event with null entity
	at br.com.caelum.vraptor.interceptor.ExecuteMethodInterceptor.intercept(ExecuteMethodInterceptor.java:96)
	at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:54)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.core.LazyInterceptorHandler.execute(LazyInterceptorHandler.java:61)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.interceptor.ParametersInstantiatorInterceptor.intercept(ParametersInstantiatorInterceptor.java:87)
	at br.com.caelum.vraptor.core.LazyInterceptorHandler.execute(LazyInterceptorHandler.java:59)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.util.hibernate.HibernateTransactionInterceptor.intercept(HibernateTransactionInterceptor.java:48)
	at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:54)
L

se tá como date vai guardar só a data, e não a hora… então vc só tem que colocar no campo dd/MM/yyyy

se vc quer a hora tb precisa mudar o banco pra ser timestamp ou datetime

J

Putzz . . . . … beleza man, muito obrigado, informação nova pra mim

it’s solved =D

J

Mais uma dúvida, eu sei que o VRaptor transforma automático de string para formado de data, eu usei a seguinte anotação para isso

@Temporal(TemporalType.TIMESTAMP)
	private Calendar dataOcorrencia;

	@Temporal(TemporalType.TIMESTAMP)
	private Calendar dataRegistro = Calendar.getInstance();

Onde eu pego a data do sistema (dataRegistro) funciona perfeitamente, porém onde eu passo a data através do formulário (dataOcorrencia) ainda não está salvando a hora e os minutos,

eu tenho que formatar essa data antes de enviar para o banco??

vlw

L

esse @Temporal não é do VRaptor, é do hibernate…

o vraptor converte de string pra data pelo simples fator do objeto ser do tipo Calendar.

vc disse que ele só tá setando a data, e não a hora. Como vc está colocando no campo de texto?

26/04/2012 13:56
?

tenta também:

26/04/2012 13:56:23

J

no campo texto eu setei exatamente dessa forma, 26/04/2012 13:45:32

continuo tendo o mesmo resultado =/

Quando eu pego a data diretamente do sistema funciona tranquilo, porém quando a data vai em formato de String o time não vai.

será que não tenho que fazer alguma coisa no formulário, pq eu jogo a data em um formato de texto, ou o VRaptor já converte no momento da persistencia??

<form action="adiciona">
		<fieldset>
			<legend>Adicionar Ocorrência</legend>
			
			<label for="data">Issue's Date</label>
			<input id="data" type="text" name="servidor.dataOcorrencia"/><br/>
			
			<label for="description">Description:</label>
			<textarea id="description" name="servidor.description"></textarea><br/>
			
			<label for="ipOrNetBiosServer">Ip or NetBios Server::</label>
			<input id="ipOrNetBiosServer" type="text" name="servidor.ipOrNetBiosServer"/><br/>

detalhe, quando vou tentar editar tomo uma interception

26/04/2012 13:58:10 org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet [default] in context with path [/dashboard] threw exception
br.com.caelum.vraptor.InterceptionException: exception raised, check root cause for details: java.lang.IllegalArgumentException: attempt to create saveOrUpdate event with null entity
	at br.com.caelum.vraptor.interceptor.ExecuteMethodInterceptor.intercept(ExecuteMethodInterceptor.java:96)
	at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:54)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.core.LazyInterceptorHandler.execute(LazyInterceptorHandler.java:61)

no meu formulário de edição to fazendo assim:

<fieldset>
			<legend>Alterar Registro</legend>
			
			<input type="hidden" name="servidor.id" value="${servidor.id}"/>
			
			<label for="dataOcorrencia">Data:</label>
			<input id="dataOcorrencia" type="text" name="servidor.dataOcorrencia" value="<fmt:formatDate pattern="dd/MM/yyyy HH:mm" value="${servidor.dataOcorrencia.time}" />"/><br/>
			
			<label for="description">Description:</label>
			<textarea id="description" name="servidor.description">${servidor.description}</textarea><br/>

eu vi no banco que ele grava nesse formato: data certinho porém o horario 00:00:00

vlw

L

attempt to create saveOrUpdate event with null entity

vc tá tentando salvar algo que está null…

No banco vc mudou o tipo da coluna pra timestamp?

se vc imprimir a data no controller, ela aparece com a hora?

J

já mudei sim, porém continua vindo a mesma coisa

eu imprimi no controller a data, porém continua vindo com a hora zerada, não sei se eu fiz certo

@Restrito
	public void adiciona(Servidor servidor) {
		dao.adiciona(servidor);
		System.out.println("isso é a data da ocorrencia: "+servidor.getDataOcorrencia());
		result.redirectTo(this).lista();

ele imprimiu desse jeito

isso é a data da ocorrencia: java.util.GregorianCalendar[time=1335150000000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Sao_Paulo",offset=-10800000,dstSavings=3600000,useDaylight=true,transitions=129,lastRule=java.util.SimpleTimeZone[id=America/Sao_Paulo,offset=-10800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=9,startDay=15,startDayOfWeek=1,startTime=0,startTimeMode=0,endMode=3,endMonth=1,endDay=15,endDayOfWeek=1,endTime=0,endTimeMode=0]],firstDayOfWeek=2,minimalDaysInFirstWeek=1,ERA=1,YEAR=2012,MONTH=3,WEEK_OF_YEAR=18,WEEK_OF_MONTH=5,DAY_OF_MONTH=23,DAY_OF_YEAR=114,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=4,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=-10800000,DST_OFFSET=0]

alguma otra pista???

L

imprime com DateFormat.getDateTimeInstance().format(servidor.getDataOcorrencia().getTime());

J

opa, desculpe a demora

saiu o seguinte resultado

23/04/2012 00:00:00

o imput que eu dei foi 23/04/2012 11:15:25

L

Tem razão, a implementação padrão do VRaptor só pega a data, sem a hora.

crie essa classe:

e me dá um toque se funcionar.

[]'s

J

Beleza, está criada, mas como que eu usaria ela

onde que eu chamo ela??

vlw

L

não precisa, o próprio vraptor vai chamar a classe :wink:

só colocar ela no seu projeto, e mandar a data:

27/04/2012 13:10:54
ou
27/04/2012 13:10

J

não chamo =/

será que eu fiz algum import errado ou coloquei ela em um lugar que não está achando??

package br.com.bdp.servidor.dateConverter;

import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.ResourceBundle;

import com.google.common.base.Strings;

import br.com.caelum.vraptor.Convert;
import br.com.caelum.vraptor.converter.ConversionError;
import br.com.caelum.vraptor.converter.LocaleBasedCalendarConverter;
import br.com.caelum.vraptor.core.Localization;

@Convert(Calendar.class)
public class DateAndTimeCalendarConverter extends LocaleBasedCalendarConverter {
   private final Localization localization;

   public DateAndTimeCalendarConverter(Localization localization) {
     super(localization);
     this.localization = localization;
   }
   public Calendar convert(String value, Class<? extends Calendar> type, ResourceBundle bundle) {
      if (Strings.nullToEmpty(value).length() > "dd/mm/yyyy".length()) {
        Locale locale = localization.getLocale();
        if (locale == null) {
            locale = Locale.getDefault();
        }
        
        DateFormat format = DateFormat.getTimeInstance(DateFormat.SHORT, locale);
        try {
            Date date = format.parse(value);
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(date);
            return calendar;
        } catch (ParseException e) {
throw new ConversionError(MessageFormat.format(bundle.getString("is_not_a_valid_date"), value));
        }

      }
      return super.convert(value, type, bundle);
      
   }
}
L

dateConverter não é um nome de pacote mto válido… o certo é ser tudo minúscula…

os imports estão certos… tem certeza que não está passando por esse converter? coloca uns prints aí no meio pra ver se tá.

o objeto pra converter é um calendar mesmo né?

J

Não deu certo mesmo =/ . . . . . . o objeto é do tipo calendar sim

@Temporal(TemporalType.TIMESTAMP)
private Calendar dataOcorrencia;

continua passando time como 00:00:00

como que o VRaptor reconheceria ela sem eu faze import nenhum lucas??

L

o VRaptor procura todas as classes anotadas com @Convert e já registra automaticamente…

tá com o log do VRaptor configurado no servidor?
se não, copie esse arquivo pra sua pasta src (ou src/main/resources) https://github.com/caelum/vraptor/blob/48ab4fe5791cc7a43f200866fe5a72bb205e2ade/vraptor-blank-project/src/log4j.xml

na inicialização do sistema, veja se aparece no log que essa classe tá registrada (procure pelo nome dela)

J

já tinha o arquivo sim, man

acho que ele realmente não achou a classe:

16:42:25,339  INFO [ScannotationComponentScanner] scanning url jar:file:/C:/Users/rmolnar/Rapha/java/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/dashboard/WEB-INF/lib/vraptor-3.4.0.jar!/br/com/caelum/vraptor/util/hibernate
16:42:25,720  INFO [AnnotationConfigWebApplicationContext] Refreshing Root WebApplicationContext: startup date [Fri Apr 27 16:42:25 BRT 2012]; root of context hierarchy
16:42:26,185  INFO [DefaultListableBeanFactory] Overriding bean definition for bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor': replacing [Root bean: class [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Root bean: class [br.com.caelum.vraptor.ioc.spring.InjectionBeanPostProcessor]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
16:42:26,360  INFO [DefaultListableBeanFactory] Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@3e1bc8: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,defaultTypeNameExtractor,topologicalSortedInterceptorRegistry,hibernateProxyInitializer,cglibProxifier,defaultRoutes,interceptorListPriorToExecutionExtractor,defaultInterceptorHandlerFactory,pathAnnotationRoutesParser,defaultRestDefaults,defaultRouter,validatorFactoryCreator,javaEvaluator,messageInterpolatorFactory,objenesisInstanceCreator,defaultTypeFinder,JSR303ValidatorFactory,noRoutesConfiguration,defaultMethodNotAllowedHandler,defaultResourceTranslator,defaultAcceptHeaderToFormat,XStreamConverters.NullConverter,defaultResourceNotFoundHandler,encodingHandlerFactory,defaultDeserializers,paranamerNameProvider,defaultMultipartConfig,defaultConverters,stereotypeHandler,converterHandler,interceptorStereotypeHandler,deserializesHandler,stereotypedBeansRegistrar,defaultSpringLocator,HTMLSerialization,emptyElementsRemoval,JSR303Validator,defaultRepresentationResult,executeMethodInterceptor,defaultRefererResult,resourceLookupInterceptor,replicatorOutjector,instantiateInterceptor,jstlLocalization,outjectResult,XStreamJSONSerialization,defaultRestHeadersHandler,XStreamJSONPSerialization,defaultFormatResolver,defaultMethodInfo,emptyResult,exceptionHandlerInterceptor,defaultValidationViewsFactory,defaultExceptionMapper,servlet3MultipartInterceptor,defaultPageResult,messageConverter,flashInterceptor,deserializingInterceptor,defaultResult,XStreamXMLDeserializer,parametersInstantiatorInterceptor,XStreamConverters,defaultHttpResult,forwardToDefaultViewInterceptor,jsonDeserializer,ognlFacade,downloadInterceptor,defaultPathResolver,defaultStatus,sessionFlashScope,applicationConfiguration,XStreamXMLSerialization,defaultValidator,defaultLogicResult,ognlParametersProvider,shortConverter,stringConverter,longConverter,doubleConverter,primitiveIntConverter,characterConverter,byteConverter,booleanConverter,bigDecimalConverter,primitiveCharConverter,enumConverter,localeBasedCalendarConverter,primitiveLongConverter,primitiveDoubleConverter,primitiveBooleanConverter,primitiveFloatConverter,primitiveByteConverter,floatConverter,primitiveShortConverter,localeBasedDateConverter,integerConverter,uploadedFileConverter,bigIntegerConverter,VRaptorRequestProvider,httpServletRequestProvider,httpServletResponseProvider,httpSessionProvider,XStreamBuilderImpl,enhancedRequestExecution,defaultInterceptorStack,org.springframework.aop.config.internalAutoProxyCreator,usuarioWeb,projetoDao,loginInterceptor,loginController,hibernateTransactionInterceptor,parameterLoaderInterceptor,sessionCreator,servidorDao,sessionFactoryCreator,usuarioDao,projetoController,routineController,registroDeDesenvolvimentoController,registroDeDesenvolvimentoDao,mundo,indexController,routineDao,servidorController]; root of factory hierarchy
log4j:WARN No appenders could be found for logger (org.hibernate.type.BasicTypeRegistry).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
16:42:28,983  INFO [DefaultConverters   ] Registering bundled converters
16:42:29,015  INFO [LinkToHandler       ] Registering linkTo component
16:42:29,287  INFO [DefaultRouteBuilder ] /login                                            [POST] -> LoginController.login(Usuario)
16:42:29,288  INFO [DefaultRouteBuilder ] /logout                                           [ALL] -> LoginController.logout()
16:42:29,289  INFO [DefaultRouteBuilder ] /usuarios                                         [POST] -> LoginController.adiciona(Usuario)
L

muda o nível de log pra DEBUG (troque onde está INFO) e rode de novo

J

man, desculpe, mas é pra eu restarta o tomcat em debug ou a aplicação, nunca entendi direito essa parte =/

eu restartei o tomcat em modo debug porém as informações foram iguais

L

não, é pra abrir o log4j.xml e trocar o que tá INFO pra DEBUG…

subir o tomcat em debug e colocar um breakpoint no método convert pra ver se tá passando por lá tbm é bom.

J

hmmm . . . . . . entendi

é isso aqui que era pra sai??

18:01:38,742  INFO [DefaultConverters   ] Registering bundled converters
18:01:38,743 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.ShortConverter
18:01:38,744 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.StringConverter
18:01:38,744 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.LongConverter
18:01:38,744 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.DoubleConverter
18:01:38,744 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.PrimitiveIntConverter
18:01:38,744 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.CharacterConverter
18:01:38,744 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.ByteConverter
18:01:38,744 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.BooleanConverter
18:01:38,744 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.BigDecimalConverter
18:01:38,744 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.PrimitiveCharConverter
18:01:38,744 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.EnumConverter
18:01:38,744 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.LocaleBasedCalendarConverter
18:01:38,744 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.PrimitiveLongConverter
18:01:38,744 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.PrimitiveDoubleConverter
18:01:38,744 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.PrimitiveBooleanConverter
18:01:38,744 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.PrimitiveFloatConverter
18:01:38,745 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.PrimitiveByteConverter
18:01:38,745 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.FloatConverter
18:01:38,745 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.PrimitiveShortConverter
18:01:38,745 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.LocaleBasedDateConverter
18:01:38,745 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.IntegerConverter
18:01:38,745 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.interceptor.multipart.UploadedFileConverter
18:01:38,745 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.BigIntegerConverter
L

sim… não apareceu a sua , neh?

tenta fazer o seguinte. Tire o extends e coloque implements Converter

e como corpo, coloque o da implementação padrão:

substituindo o getDateInstance por getDateTimeInstance

J

man, desculpa a demora, mas não deu certo de novo =/

o log em debug tá assim:

13:03:14,503 DEBUG [DefaultListableBeanFactory] Returning cached instance of singleton bean 'br.com.caelum.vraptor.ioc.spring.SpringBasedContainer'
13:03:14,503 DEBUG [DefaultListableBeanFactory] Autowiring by type from bean name 'defaultConverters' via constructor to bean named 'br.com.caelum.vraptor.ioc.spring.SpringBasedContainer'
13:03:14,504  INFO [DefaultConverters   ] Registering bundled converters
13:03:14,505 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.PrimitiveShortConverter
13:03:14,505 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.ShortConverter
13:03:14,505 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.LocaleBasedDateConverter
13:03:14,505 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.CharacterConverter
13:03:14,505 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.PrimitiveFloatConverter
13:03:14,505 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.ByteConverter
13:03:14,505 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.BooleanConverter
13:03:14,505 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.BigIntegerConverter
13:03:14,505 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.PrimitiveByteConverter
13:03:14,506 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.DoubleConverter
13:03:14,506 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.interceptor.multipart.UploadedFileConverter
13:03:14,506 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.IntegerConverter
13:03:14,506 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.PrimitiveIntConverter
13:03:14,506 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.PrimitiveCharConverter
13:03:14,506 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.LongConverter
13:03:14,506 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.PrimitiveDoubleConverter
13:03:14,506 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.PrimitiveBooleanConverter
13:03:14,506 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.EnumConverter
13:03:14,506 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.PrimitiveLongConverter
13:03:14,507 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.LocaleBasedCalendarConverter
13:03:14,507 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.FloatConverter
13:03:14,507 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.StringConverter
13:03:14,507 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.BigDecimalConverter
13:03:14,507 DEBUG [DefaultListableBeanFactory] Eagerly caching bean 'defaultConverters' to allow for resolving potential circular references

aqui tá a LocaleBasedCalendarConverter como ela fico:

import static com.google.common.base.Strings.isNullOrEmpty;

import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.ResourceBundle;

import br.com.caelum.vraptor.Convert;
import br.com.caelum.vraptor.Converter;
import br.com.caelum.vraptor.converter.ConversionError;
import br.com.caelum.vraptor.core.Localization;
import br.com.caelum.vraptor.ioc.RequestScoped;

/**
 * Locale based calendar converter.
 *
 * @author Guilherme Silveira
 */
@Convert(Calendar.class)
@RequestScoped
public class LocaleBasedCalendarConverter implements Converter<Calendar> {

    private final Localization localization;
    
    public LocaleBasedCalendarConverter(Localization localization) {
        this.localization = localization;
    }

    public Calendar convert(String value, Class<? extends Calendar> type, ResourceBundle bundle) {
        if (isNullOrEmpty(value)) {
            return null;
        }
        
        Locale locale = localization.getLocale();
        if (locale == null) {
            locale = Locale.getDefault();
        }
        
        DateFormat format = DateFormat.getDateTimeInstance();
        try {
            Date date = format.parse(value);
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(date);
            return calendar;
        } catch (ParseException e) {
			throw new ConversionError(MessageFormat.format(bundle.getString("is_not_a_valid_date"), value));
        }
    }

}
L

essa sua classe está com o pacote da sua aplicação? está sendo compilada junto com as outras classes ou está em um jar?

J

tá em um pacote

será que era pra eu passa os argumentos pro getDateTimeInstance???

eu li os docsda classe dateFormat mas não entendi direito que tinha que passa como argumento

esse erro confirma que deu erro na confirmação da data não confirma??

02/05/2012 14:14:09 org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet [default] in context with path [/dashboard] threw exception
br.com.caelum.vraptor.InterceptionException: There are validation errors and you forgot to specify where to go. Please add in your method something like:
validator.onErrorUse(page()).of(AnyController.class).anyMethod();
or any view that you like.
If you didn't add any validation error, it is possible that a conversion error had happened.
	at br.com.caelum.vraptor.interceptor.ExecuteMethodInterceptor.intercept(ExecuteMethodInterceptor.java:71)
	at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:54)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
L

sim, quer dizer que deu um erro de conversão. Configure o validator pra ver qual foi o erro (validator.onErrorForwardTo(this).metodo())

J

Man, eu não consigo mais starta o meu projeto

eu tentei muda ele pra conecta no banco do servidor e não deu certo, quando fui tenta volta pra locahost começo a dar o mesmo erro

olha o que acontece

15:40:52,150  INFO [BasicConfiguration  ] Using class br.com.caelum.vraptor.ioc.spring.SpringProvider as Container Provider
15:40:52,182  INFO [DefaultSpringLocator] No application context found
15:40:52,281  INFO [WebAppBootstrapFactory] No static WebAppBootstrap found.
15:40:52,282  INFO [BasicConfiguration  ] br.com.caelum.vraptor.scanning = null
15:40:52,424  INFO [ScannotationComponentScanner] scanning url jar:file:/C:/Users/rmolnar/Rapha/java/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/dashboard/WEB-INF/lib/vraptor-3.4.0.jar!/br/com/caelum/vraptor/util/hibernate
15:40:52,712  INFO [AnnotationConfigWebApplicationContext] Refreshing Root WebApplicationContext: startup date [Mon May 07 15:40:52 BRT 2012]; root of context hierarchy
15:40:53,032  INFO [DefaultListableBeanFactory] Overriding bean definition for bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor': replacing [Root bean: class [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Root bean: class [br.com.caelum.vraptor.ioc.spring.InjectionBeanPostProcessor]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
15:40:53,175  INFO [DefaultListableBeanFactory] Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@ebf068: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,paranamerNameProvider,defaultResourceNotFoundHandler,interceptorListPriorToExecutionExtractor,javaEvaluator,defaultInterceptorHandlerFactory,validatorFactoryCreator,noRoutesConfiguration,defaultMethodNotAllowedHandler,objenesisInstanceCreator,topologicalSortedInterceptorRegistry,encodingHandlerFactory,XStreamConverters.NullConverter,JSR303ValidatorFactory,defaultConverters,pathAnnotationRoutesParser,defaultRoutes,messageInterpolatorFactory,defaultRouter,cglibProxifier,defaultTypeFinder,defaultResourceTranslator,defaultRestDefaults,hibernateProxyInitializer,defaultAcceptHeaderToFormat,defaultDeserializers,defaultTypeNameExtractor,defaultMultipartConfig,stereotypeHandler,converterHandler,interceptorStereotypeHandler,deserializesHandler,stereotypedBeansRegistrar,defaultSpringLocator,ognlFacade,defaultStatus,servlet3MultipartInterceptor,sessionFlashScope,instantiateInterceptor,JSR303Validator,replicatorOutjector,XStreamJSONPSerialization,defaultExceptionMapper,ognlParametersProvider,resourceLookupInterceptor,XStreamXMLSerialization,applicationConfiguration,defaultMethodInfo,defaultRestHeadersHandler,XStreamConverters,defaultPathResolver,forwardToDefaultViewInterceptor,deserializingInterceptor,emptyResult,jsonDeserializer,defaultResult,jstlLocalization,outjectResult,executeMethodInterceptor,defaultRepresentationResult,XStreamJSONSerialization,defaultValidator,emptyElementsRemoval,parametersInstantiatorInterceptor,downloadInterceptor,flashInterceptor,defaultPageResult,HTMLSerialization,defaultHttpResult,defaultLogicResult,defaultRefererResult,messageConverter,defaultFormatResolver,defaultValidationViewsFactory,exceptionHandlerInterceptor,XStreamXMLDeserializer,primitiveFloatConverter,localeBasedDateConverter,uploadedFileConverter,localeBasedCalendarConverter,integerConverter,floatConverter,doubleConverter,primitiveShortConverter,longConverter,primitiveCharConverter,shortConverter,bigDecimalConverter,primitiveIntConverter,bigIntegerConverter,stringConverter,characterConverter,byteConverter,booleanConverter,primitiveLongConverter,primitiveBooleanConverter,primitiveDoubleConverter,primitiveByteConverter,enumConverter,VRaptorRequestProvider,httpServletRequestProvider,httpServletResponseProvider,httpSessionProvider,XStreamBuilderImpl,defaultInterceptorStack,enhancedRequestExecution,org.springframework.aop.config.internalAutoProxyCreator,sessionFactoryCreator,rotinaController,hibernateTransactionInterceptor,projetoController,usuarioDao,loginInterceptor,registroDeDesenvolvimentoDao,usuarioWeb,indexController,parameterLoaderInterceptor,servidorController,loginController,registroDeDesenvolvimentoController,sessionCreator,projetoDao,mundo,servidorDao,routineDao]; root of factory hierarchy
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
15:40:53,831  INFO [DefaultListableBeanFactory] Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@ebf068: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,paranamerNameProvider,defaultResourceNotFoundHandler,interceptorListPriorToExecutionExtractor,javaEvaluator,defaultInterceptorHandlerFactory,validatorFactoryCreator,noRoutesConfiguration,defaultMethodNotAllowedHandler,objenesisInstanceCreator,topologicalSortedInterceptorRegistry,encodingHandlerFactory,XStreamConverters.NullConverter,JSR303ValidatorFactory,defaultConverters,pathAnnotationRoutesParser,defaultRoutes,messageInterpolatorFactory,defaultRouter,cglibProxifier,defaultTypeFinder,defaultResourceTranslator,defaultRestDefaults,hibernateProxyInitializer,defaultAcceptHeaderToFormat,defaultDeserializers,defaultTypeNameExtractor,defaultMultipartConfig,stereotypeHandler,converterHandler,interceptorStereotypeHandler,deserializesHandler,stereotypedBeansRegistrar,defaultSpringLocator,ognlFacade,defaultStatus,servlet3MultipartInterceptor,sessionFlashScope,instantiateInterceptor,JSR303Validator,replicatorOutjector,XStreamJSONPSerialization,defaultExceptionMapper,ognlParametersProvider,resourceLookupInterceptor,XStreamXMLSerialization,applicationConfiguration,defaultMethodInfo,defaultRestHeadersHandler,XStreamConverters,defaultPathResolver,forwardToDefaultViewInterceptor,deserializingInterceptor,emptyResult,jsonDeserializer,defaultResult,jstlLocalization,outjectResult,executeMethodInterceptor,defaultRepresentationResult,XStreamJSONSerialization,defaultValidator,emptyElementsRemoval,parametersInstantiatorInterceptor,downloadInterceptor,flashInterceptor,defaultPageResult,HTMLSerialization,defaultHttpResult,defaultLogicResult,defaultRefererResult,messageConverter,defaultFormatResolver,defaultValidationViewsFactory,exceptionHandlerInterceptor,XStreamXMLDeserializer,primitiveFloatConverter,localeBasedDateConverter,uploadedFileConverter,localeBasedCalendarConverter,integerConverter,floatConverter,doubleConverter,primitiveShortConverter,longConverter,primitiveCharConverter,shortConverter,bigDecimalConverter,primitiveIntConverter,bigIntegerConverter,stringConverter,characterConverter,byteConverter,booleanConverter,primitiveLongConverter,primitiveBooleanConverter,primitiveDoubleConverter,primitiveByteConverter,enumConverter,VRaptorRequestProvider,httpServletRequestProvider,httpServletResponseProvider,httpSessionProvider,XStreamBuilderImpl,defaultInterceptorStack,enhancedRequestExecution,org.springframework.aop.config.internalAutoProxyCreator,sessionFactoryCreator,rotinaController,hibernateTransactionInterceptor,projetoController,usuarioDao,loginInterceptor,registroDeDesenvolvimentoDao,usuarioWeb,indexController,parameterLoaderInterceptor,servidorController,loginController,registroDeDesenvolvimentoController,sessionCreator,projetoDao,mundo,servidorDao,routineDao]; root of factory hierarchy
07/05/2012 15:40:53 org.apache.catalina.core.StandardContext filterStart
GRAVE: Exception starting filter vraptor
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactoryCreator': Invocation of init method failed; nested exception is org.hibernate.HibernateException: Unable to get the default Bean Validation factory
	at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:133)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:394)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1413)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
	at br.com.caelum.vraptor.ioc.spring.SpringBasedContainer.start(SpringBasedContainer.java:106)
	at br.com.caelum.vraptor.ioc.spring.SpringProvider.start(SpringProvider.java:87)
	at br.com.caelum.vraptor.VRaptor.init(VRaptor.java:110)
	at br.com.caelum.vraptor.VRaptor.init(VRaptor.java:103)

socorro

L

org.hibernate.HibernateException: Unable to get the default Bean Validation factory

talvez esteja faltando o jar do bean validations (hibernate validator)

J

Era isso mesmo, tive que baixar um novo jar

assim que eu coloca essa versão em teste continuo brigando pelas horas que ele não envia

vlw =D

W
JPadawan:
man, desculpa a demora, mas não deu certo de novo =/

o log em debug tá assim:

13:03:14,503 DEBUG [DefaultListableBeanFactory] Returning cached instance of singleton bean 'br.com.caelum.vraptor.ioc.spring.SpringBasedContainer'
13:03:14,503 DEBUG [DefaultListableBeanFactory] Autowiring by type from bean name 'defaultConverters' via constructor to bean named 'br.com.caelum.vraptor.ioc.spring.SpringBasedContainer'
13:03:14,504  INFO [DefaultConverters   ] Registering bundled converters
13:03:14,505 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.PrimitiveShortConverter
13:03:14,505 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.ShortConverter
13:03:14,505 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.LocaleBasedDateConverter
13:03:14,505 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.CharacterConverter
13:03:14,505 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.PrimitiveFloatConverter
13:03:14,505 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.ByteConverter
13:03:14,505 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.BooleanConverter
13:03:14,505 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.BigIntegerConverter
13:03:14,505 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.PrimitiveByteConverter
13:03:14,506 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.DoubleConverter
13:03:14,506 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.interceptor.multipart.UploadedFileConverter
13:03:14,506 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.IntegerConverter
13:03:14,506 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.PrimitiveIntConverter
13:03:14,506 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.PrimitiveCharConverter
13:03:14,506 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.LongConverter
13:03:14,506 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.PrimitiveDoubleConverter
13:03:14,506 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.PrimitiveBooleanConverter
13:03:14,506 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.EnumConverter
13:03:14,506 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.PrimitiveLongConverter
13:03:14,507 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.LocaleBasedCalendarConverter
13:03:14,507 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.FloatConverter
13:03:14,507 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.StringConverter
13:03:14,507 DEBUG [DefaultConverters   ] bundled converter to be registered: class br.com.caelum.vraptor.converter.BigDecimalConverter
13:03:14,507 DEBUG [DefaultListableBeanFactory] Eagerly caching bean 'defaultConverters' to allow for resolving potential circular references

aqui tá a LocaleBasedCalendarConverter como ela fico:

import static com.google.common.base.Strings.isNullOrEmpty;

import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.ResourceBundle;

import br.com.caelum.vraptor.Convert;
import br.com.caelum.vraptor.Converter;
import br.com.caelum.vraptor.converter.ConversionError;
import br.com.caelum.vraptor.core.Localization;
import br.com.caelum.vraptor.ioc.RequestScoped;

/**
 * Locale based calendar converter.
 *
 * @author Guilherme Silveira
 */
@Convert(Calendar.class)
@RequestScoped
public class LocaleBasedCalendarConverter implements Converter<Calendar> {

    private final Localization localization;
    
    public LocaleBasedCalendarConverter(Localization localization) {
        this.localization = localization;
    }

    public Calendar convert(String value, Class<? extends Calendar> type, ResourceBundle bundle) {
        if (isNullOrEmpty(value)) {
            return null;
        }
        
        Locale locale = localization.getLocale();
        if (locale == null) {
            locale = Locale.getDefault();
        }
        
        DateFormat format = DateFormat.getDateTimeInstance();
        try {
            Date date = format.parse(value);
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(date);
            return calendar;
        } catch (ParseException e) {
			throw new ConversionError(MessageFormat.format(bundle.getString("is_not_a_valid_date"), value));
        }
    }

}

JPadawan, estava com exatamente o mesmo problema que o seu.

Implementei esta classe LocaleBasedCalendarConverter.java do mesmo jeito que está ai em cima e funcionou perfeitamente! :D

Tem que inserir no formato certo:
Ex: 04/08/2012 21:43:23

Se não colocar os segundos não dá certo.

Criado 24 de abril de 2012
Ultima resposta 4 de ago. de 2012
Respostas 38
Participantes 5