I am just playing with MessageFormat but when I try to pass a String to MessageFormat format method it compiles fine but then I get a runtime classcast exception. Here is the code.
MessageFormat format = new MessageFormat("");
Object obj = Integer.toHexString(10);
format.format(obj);
Now the runtime exception I get is as follows.
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to [Ljava.lang.Object;
at java.text.MessageFormat.format(Unknown Source)
at java.text.Format.format(Unknown Source)
at JavaCore2.Codepoint.main(Codepoint.java:21)
MessageFormat.format() takes an argument of type Object[] (an Object array), whereas you are passing in a single Object.
You will have to create an array out of your Integer:
MessageFormat format = new MessageFormat("{0}");
Object[] args = { Integer.toHexString(10) };
String result = format.format(args);
Related
I am consuming data from a Kafka topic using the following consumer setup:
val consumer = {
val properties = new Properties()
properties.put(ConsumerConfig.GROUP_ID_CONFIG, "some_consumer_group")
properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, streamingConfig.getString("kafka.brokers"))
properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, classOf[StringDeserializer])
properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, classOf[KafkaJsonDeserializer[Sample]])
properties.put("json.value.type",classOf[Sample])
properties.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, streamingConfig.getInt("kafka.maxPollRecords"): java.lang.Integer)
properties.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, streamingConfig.getInt("kafka.sessionTimeoutMs"): java.lang.Integer)
properties.put(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, streamingConfig.getInt("kafka.heartbeatIntervalMs"): java.lang.Integer)
val consumer = new KafkaConsumer[String, Sample](properties)
consumer.subscribe(util.Arrays.asList(topic))
consumer
}
while the payload is represented by the following case class
case class Sample(properties: Map[String, String],eventType: String)
The problem is that during the deserialization the following errors are produced
Caused by: org.apache.kafka.common.errors.SerializationException: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `org.service.Sample` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
at [Source: (byte[])"{}"; line: 1, column: 2]
Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `org.service.Sample` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
at [Source: (byte[])"{}"; line: 1, column: 2]
If I was using Java the solution for this is straighforward: Just add a default constructor. What happens in the case of Scala case classes though? I know that the Jackson object mappers can be configured with a jackson-module-scala which takes care of case classes but due to the way the KafkaJsonSerializer is configured I cannot mess with its object mappers - this is its configure method:
protected void configure(KafkaJsonSerializerConfig config) {
boolean prettyPrint = config.getBoolean("json.indent.output");
this.objectMapper = new ObjectMapper();
this.objectMapper.configure(SerializationFeature.INDENT_OUTPUT, prettyPrint);
}
So how can I go about this error here?
I'm developing cordapp using the example-cordapp project as a reference. I've been able to commit a transaction to the ledger and even run querias on the node to see if it's really there. However, when I try to run query from my Spring Boot application, I get this error.
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request
processing failed; nested exception is
org.springframework.http.converter.HttpMessageConversionException: JSON mapping problem:
java.util.Collections$UnmodifiableRandomAccessList[0]->net.corda.core.contracts.StateAndRef["state"]-
>net.corda.core.contracts.TransactionState["data"]-
>com.mypackage.states.MyState["party"]; nested exception is
com.fasterxml.jackson.databind.JsonMappingException: object is not an instance of declaring class
(through reference chain: java.util.Collections$UnmodifiableRandomAccessList[0]-
>net.corda.core.contracts.StateAndRef["state"]->net.corda.core.contracts.TransactionState["data"]-
>com.mypackage.states.MyState["party"])] with root cause
java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_251]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_251]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~
[na:1.8.0_251]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_251]
Here's the request code
#GetMapping(value = [ "/api/v1/states" ], produces = [MediaType.APPLICATION_JSON_VALUE])
fun getMyIOUs(): ResponseEntity<List<StateAndRef<MyState>>> {
val myStates = proxy.vaultQueryBy<MyState>().states
return ResponseEntity.ok(myStates)
}
And here's the state code
#BelongsToContract(com.sentinel.contract.SharingInformationContract::class)
class SharingInformationState(
val party: Party,
val dataOwnerId: Long,
val dataBuyerId: Long,
override val linearId: UniqueIdentifier = UniqueIdentifier()) : LinearState, QueryableState {
override val participants: List<AbstractParty> = listOf(party)
override fun generateMappedObject(schema: MappedSchema): PersistentState {
return when (schema) {
SharingInformationSchemaV1 -> SharingInformationSchemaV1.PersistentSharingInformation(
party,
dataOwnerId,
dataBuyerId,
linearId.id
)
else -> throw IllegalArgumentException("Unrecognised schema $schema")
}
}
override fun supportedSchemas(): Iterable<MappedSchema> = listOf(SharingInformationSchemaV1)
}
There's little information about this issue on the internet. Some suggest it is connected to the classpath, that something is duplicated there, but I don't know how to check. Also, this error isn't connected to the Party type. I've tried to add #JsonIgnore on a party, but then it throws on the other field. Persistence of this field in mapping schema also doesn't matter. I've tried persisting and not persisting, it changes nothing. Thanks in advance!
I believe this is because you are missing Corda Jackson support library which is required to convert Corda objects to json.
Add this to your dependencies in the build.gradle
compile "net.corda:corda-jackson:$corda_release_version"
https://github.com/corda/samples-java/blob/master/Advanced/auction-cordapp/client/build.gradle#L19
Also, make sure you have a MappingJackson2HttpMessageConverter bean configured.
#Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(){
ObjectMapper mapper = JacksonSupport.createDefaultMapper(partyAProxy());
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(mapper);
return converter;
}
https://github.com/corda/samples-java/blob/master/Advanced/auction-cordapp/client/src/main/java/net/corda/samples/client/AppConfig.java#L48
The Exception java.lang.IllegalArgumentException: object is not an instance of declaring class is something that happens if a method is called by reflection on an object which is of the wrong type.
In conjunction with jackson that may happen because a generic is lying to you. Here is an example:
class A (val x: String)
class B (val y: String)
class C (val z: List<A>)
ObjectMapper().writeValueAsString(C(listOf(B("x")) as List<A>))
This causes a compile warning, but it compiles and initially runs because of type erasure. However we forcefully injected a List<B> in a place where actually a List<A> is expected. While type erasure does remove quite a bit of information, it does not do so completely. Reflection can still be used to determine that C.z is actually of type List<A>. Jackson uses this information and tries to serialize an object of type A but instead finds an object of type B in the list and fails with the given message.
Check that your data structure actually contains the types that you expect!
I have a few actions in my .NET MVC application that go through a decent amount of data and return a JSON object to my views. In order to speed things up a little bit, I've started caching the JSON objects and returning those instead of going through all of the data if only a short time has passed:
System.Web.HttpContext.Current.Cache.Insert(System.Web.HttpContext.Current.User.Identity.Name + "WB", result, null, DateTime.UtcNow.AddMinutes(1), TimeSpan.Zero);
// result is the object that gets converted to JSON
result = new
{
TopDepartures = TopDepartures.ToArray(),
YesterdayFlights = YesterdayFlights.Count(),
TodayFlights = TodayFlights.Count(),
TomorrowFlights = TomorrowFlights.Count(),
LastMonthPax = LastMonthPax.ToString("#,##0"),
YesterdayPax = YesterdayPax.ToString("#,##0"),
PaxMonthToDate = PaxMonthToDate.ToString("#,##0"),
FirstCheckInLocalTime = FirstCheckIn.EstimatedCheckIn.ToString("HH:mm"),
FirstCheckInOrigin = FirstCheckIn.OriginIATA,
FirstCheckInDestination = FirstCheckIn.DestinationIATA,
FirstCheckInSDT = FirstCheckIn.ScheduledDepartureTime.ToString("HH:mm"),
FirstCheckInSAT = FirstCheckIn.ScheduledArrivalTime.ToString("HH:mm"),
FirstCheckInFlightNo = FirstCheckIn.CarrierCode + " " + FirstCheckIn.FlightNo,
LastCheckInLocalTime = LastCheckIn.EstimatedCheckIn.ToString("HH:mm"),
LastCheckInOrigin = LastCheckIn.OriginIATA,
LastCheckInDestination = LastCheckIn.DestinationIATA,
LastCheckInSDT = LastCheckIn.ScheduledDepartureTime.ToString("HH:mm"),
LastCheckInSAT = LastCheckIn.ScheduledArrivalTime.ToString("HH:mm"),
LastCheckInFlightNo = LastCheckIn.CarrierCode + " " + LastCheckIn.FlightNo,
TomorrowFirstCheckInLocalTime = TomorrowFirstCheckIn.EstimatedCheckIn.ToString("HH:mm"),
TomorrowFirstCheckInOrigin = TomorrowFirstCheckIn.OriginIATA,
TomorrowFirstCheckInDestination = TomorrowFirstCheckIn.DestinationIATA,
TomorrowFirstCheckInSDT = TomorrowFirstCheckIn.ScheduledDepartureTime.ToString("HH:mm"),
TomorrowFirstCheckInSAT = TomorrowFirstCheckIn.ScheduledArrivalTime.ToString("HH:mm"),
TomorrowFirstCheckInFlightNo = TomorrowFirstCheckIn.CarrierCode + " " + TomorrowFirstCheckIn.FlightNo,
};
I do a check at the beginning of the Action:
var cachedResult = System.Web.HttpContext.Current.Cache.Get(System.Web.HttpContext.Current.User.Identity.Name + "WB");
if (cachedResult != null)
{
return Json(cachedResult, JsonRequestBehavior.AllowGet);
}
The problem is, ever since I implemented this, Ninject has been periodically firing OutOfMemory exceptions. I've been researching this but I haven't been able to find anything explicitly referencing a link between caching and Ninject OutOfMemory exceptions. There also doesn't appear to be a specific pattern that causes the exception to be fired. It will run fine for hours of changes and testing and then suddenly the site will stop working and I'll see the OutOfMemory exception in the logs. Then other times it'll happen immediately.
This Action is called and the object retrieved by an AJAX call on my view, if that information is relevant.
Here is the stack trace:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
at System.Collections.Generic.HashSet`1.SetCapacity(Int32 newSize, Boolean forceNewHashCodes)
at System.Collections.Generic.HashSet`1.IncreaseCapacity()
at System.Collections.Generic.HashSet`1.AddIfNotPresent(T value)
at System.Collections.Generic.HashSet`1.Add(T item)
at Ninject.Activation.Caching.ActivationCache.AddActivatedInstance(Object instance)
at Ninject.Activation.Strategies.ActivationCacheStrategy.Activate(IContext context, InstanceReference reference)
at Ninject.Activation.Pipeline.<>c__DisplayClass2.<Activate>b__0(IActivationStrategy s)
at Ninject.Infrastructure.Language.ExtensionsForIEnumerableOfT.Map[T](IEnumerable`1 series, Action`1 action)
at Ninject.Activation.Pipeline.Activate(IContext context, InstanceReference reference)
at Ninject.Activation.Context.ResolveInternal(Object scope)
at Ninject.Activation.Context.Resolve()
at Ninject.KernelBase.<>c__DisplayClass15.<Resolve>b__f(IBinding binding)
at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext()
at System.Linq.Enumerable.<CastIterator>d__94`1.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at Ninject.Infrastructure.Language.ExtensionsForIEnumerable.ToArraySlow(IEnumerable series, Type elementType)
at Ninject.Planning.Targets.Target`1.ResolveWithin(IContext parent)
at Ninject.Activation.Providers.StandardProvider.GetValue(IContext context, ITarget target)
at Ninject.Activation.Providers.StandardProvider.<>c__DisplayClass4.<Create>b__2(ITarget target)
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at Ninject.Activation.Providers.StandardProvider.Create(IContext context)
at Ninject.Activation.Context.ResolveInternal(Object scope)
at Ninject.Activation.Context.Resolve()
at Ninject.KernelBase.<>c__DisplayClass15.<Resolve>b__f(IBinding binding)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
at Ninject.Planning.Targets.Target`1.GetValue(Type service, IContext parent)
at Ninject.Planning.Targets.Target`1.ResolveWithin(IContext parent)
at Ninject.Activation.Providers.StandardProvider.GetValue(IContext context, ITarget target)
at Ninject.Activation.Providers.StandardProvider.<>c__DisplayClass4.<Create>b__2(ITarget target)
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at Ninject.Activation.Providers.StandardProvider.Create(IContext context)
at Ninject.Activation.Context.ResolveInternal(Object scope)
at Ninject.Activation.Context.Resolve()
at Ninject.KernelBase.<>c__DisplayClass15.<Resolve>b__f(IBinding binding)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
at Ninject.ResolutionExtensions.Get(IResolutionRoot root, Type service, IParameter[] parameters)
at AirlineChoiceDashboard.WebUI.Infrastructure.NinjectControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) in D:\Development\Airline Choice Dashboard\Source Code\Development\WebUI\Infrastructure\NinjectControllerFactory.cs:line 38
What should happen when the value of a property is set to undefined in a json string.
i.e:
{"Name":undefined}
The following example is using the json.net library. An exception is thrown when de-serializing the object.
JsonConvert.DeserializeObject<SimpleObject>("{\"Name\":undefined}");
public class SimpleObject
{
public string Name { get; set; }
}
Newtonsoft.Json.JsonReaderException was unhandled
Message=Error reading string. Unexpected token: Undefined. Path 'Value', line 1, position 18.
Source=Newtonsoft.Json
LineNumber=1
LinePosition=18
Path=Value
I think the error is fine.
Jsonlint.org throws an error too.
And reading the documentation on json.org the "value" element may have the following variants:
string
number
object
array
true
false
null
As you can see, undefined is NOT listed. Object does also not count as undefined.
I am using FlexJson within my play framework application but at the point I am trying to deseralize the json string it throws a java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean:
User user = new JSONDeserializer<User>()
.use(null, User.class).deserialize(body);
Body is the json string passed into the controller using standard jquery/ajax and
where User has the following boolean value declared:
public Boolean isCurrentUser;
Any ideas as to what I am doing wrong?
Thanks
In Json, Boolean is a type. Your JSon is:
{"user_id":"18","isCurrentUser":"true","title":"mr","description":"description"}
when it should be:
{"user_id":"18","isCurrentUser":true,"title":"mr","description":"description"}
Note that true is not a String, but a boolean. The parser fails because it finds a String instead of the expected boolean type. Fix the JSon generation to add a boolean, not a String.