Have a method that returns List and want it to be sent to the client as JSON. Getting an exception "A message body writer for Java class java.util.ArrayList, and Java type java.util.List, and MIME media type application/json was not found."
I've added the #XMLRootElement annotation to my class declaration and added the POJO mapping param to web.xml but it doesn't work
Using Atmosphere 2.2.3 with Atmosphere-Jersey 2.2.3
POM
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.atmosphere</groupId>
<artifactId>atmosphere-runtime</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>org.atmosphere</groupId>
<artifactId>atmosphere-jersey</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>javax.xml</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.1</version>
</dependency>
</dependencies>
RESTFul resource:
package com.foo;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("currencypairs")
#Produces(MediaType.APPLICATION_JSON)
public class CurrencyPairs {
#GET
#Path("foo")
public List<Thing> getPairs() {
List<Thing> ret = new ArrayList<Thing>();
ret.add(new Thing("CAD","USD"));
ret.add(new Thing("EUR", "USD"));
ret.add(new Thing("GBP","EUR"));
return ret;
}
}
Thing class:
package com.foo;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Thing {
#XmlElement
private String a;
#XmlElement
private String b;
public Thing(String a, String b)
{
this.setA(a);
this.setB(b);
}
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:j2ee="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2.5.xsd">
<description>AtmosphereServlet</description>
<display-name>AtmosphereServlet</display-name>
<context-param>
<param-name>resteasy.scan</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>resteasy.scan.providers</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>resteasy.scan.resources</param-name>
<param-value>false</param-value>
</context-param>
<servlet>
<description>AtmosphereServlet</description>
<servlet-name>AtmosphereServlet</servlet-name>
<servlet-class>org.atmosphere.cpr.AtmosphereServlet</servlet-class>
<!-- If you want to use Servlet 3.0 -->
<async-supported>true</async-supported>
<!-- List of init-param -->
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.foo</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>AtmosphereServlet</servlet-name>
<!-- Any mapping -->
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
Add jersey-json-1.6.jar to your dependencies.
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.6</version>
</dependency>
Related
I'm trying to use junit to test a Spigot plugin, but I get the following error:
java.lang.NoSuchMethodError: org.yaml.snakeyaml.LoaderOptions.setMaxAliasesForCollections(I)V
at org.bukkit.configuration.file.YamlConfiguration.loadFromString(YamlConfiguration.java:56)
at org.bukkit.configuration.file.FileConfiguration.load(FileConfiguration.java:160)
at org.bukkit.configuration.file.YamlConfiguration.loadConfiguration(YamlConfiguration.java:217)
at tests.MessengerTests.conf(MessengerTests.java:24)
at tests.MessengerTests.msr(MessengerTests.java:19)
at tests.MessengerTests.testBasic(MessengerTests.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
I've tried searching for this error on DuckDuckGo, but haven't found a solution. I've tried updating spigot-api to 1.16.5, but get the same error. Is this a bug with Spigot, or could it be solved another way? I don't know what else to try here.
MessengerTests.java
package tests;
import me.rubyjay.bukkit.core.api.messenger.Messenger;
import me.rubyjay.bukkit.core.api.zconfig.ZConfigFile;
import org.bukkit.configuration.file.YamlConfiguration;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.io.StringReader;
public class MessengerTests {
private static Messenger msr(ZConfigFile conf) {
return new Messenger(new TestModule(), conf);
}
private static Messenger msr(String contents) {
return msr(conf(contents));
}
private static ZConfigFile conf(String contents) {
StringReader reader = new StringReader(contents);
YamlConfiguration conf = YamlConfiguration.loadConfiguration(reader);
return ZConfigFile.wrap(new File("test.yml"), conf);
}
#Test
public void testBasic() {
Messenger msr = msr("hello: '&9Hello&7, &2World&d!!'").cfg("hello");
Assert.assertEquals("§9Hello§7, §2World§d!!", msr.outString());
}
#Test
public void testLink() {
Messenger msr = msr("test: 'If you like cheese, [click here](https://duckduckgo.com/?q=cheese), but not here.'").cfg("test");
Assert.assertEquals("§9Hello§7, §2World§d!!", msr.outComponent());
}
// #Test
// public void testData() {
// Messenger msr = msr("hello: '&9Hello&7, &2World&d!! '");
// Assert.assertEquals("§9Hello§7, §2World§d!!", msr.getString());
// }
//
// #Test
// public void testList() {
// Messenger msr = msr("{\"cmd\":{\"list\":{\"head\":\"&9--- Header ---\",\"item\":\"&b - <item>\",\"foot\":\"&9--------------\"}}}");
// Assert.assertEquals("§9Hello§7, §2World§d!!", msr.getString());
// }
#Test
public void testMissingConfigPathAbsolute() {
Messenger msr = msr("").cfg("this.message.does.not.exist");
Assert.assertEquals("§cMissing config message: this.message.does.not.exist", msr.outString());
}
#Test
public void testMissingConfigPathRelative() {
Messenger msr = msr("{\"this\":{\"message\":{\"exists\":\"but we're not using it.\"}}}")
.path("this.message").cfg(".does.not.exist");
Assert.assertEquals("§cMissing config message: this.message.does.not.exist", msr.outString());
}
}
ZConfigFile.java
package me.rubyjay.bukkit.core.api.zconfig;
import org.bukkit.configuration.file.FileConfiguration;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Ruby jay
*/
public class ZConfigFile extends ZConfigWrapper {
private final File file;
private ZConfigFile(File file, FileConfiguration config) {
super(config);
this.file = file;
}
#Override
public FileConfiguration unwrap() {
return (FileConfiguration)super.unwrap();
}
public static ZConfigFile wrap(File file, FileConfiguration config) {
if (file == null || config == null) {
return null;
} else {
return new ZConfigFile(file, config);
}
}
/**
* #return the file
*/
public File getFile() {
return file;
}
public boolean save() {
try {
unwrap().save(file);
return true;
} catch (IOException ex) {
Logger.getLogger(ZConfigFile.class.getName()).log(Level.SEVERE, "Failed to save zconfig " + file.getName(), ex);
return false;
}
}
public boolean backup() {
String name = file.getName();
try {
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd.HH-mm-ss");
name += "." + dateFormat.format(date) + ".old";
unwrap().save(new File(file.getParentFile(), name));
return true;
} catch (IOException ex) {
Logger.getLogger(ZConfigFile.class.getName()).log(Level.SEVERE, "Failed to backup zconfig " + name, ex);
return false;
}
}
}
ZConfigWrapper.java
package me.rubyjay.bukkit.core.api.zconfig;
import org.bukkit.Color;
import org.bukkit.OfflinePlayer;
import org.bukkit.configuration.Configuration;
import org.bukkit.configuration.ConfigurationOptions;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.MemoryConfiguration;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* #inheritDoc
*
* #author Ruby jay
*/
public class ZConfigWrapper implements ZConfig {
private final ConfigurationSection config;
private String rootPath;
protected ZConfigWrapper(ConfigurationSection config) {
this.config = config;
}
public ConfigurationSection unwrap() {
return config;
}
public static ZConfig newEmpty() {
return new ZConfigWrapper(new MemoryConfiguration());
}
#Contract("null -> null")
public static ZConfig wrap(ConfigurationSection conf) {
if (conf == null) {
return null;
} else if (conf instanceof ZConfig) {
return (ZConfig) conf;
} else {
return new ZConfigWrapper(conf);
}
}
// (Redacted) Implemented methods
// Example:
#NotNull
#Override
public Set<String> getKeys(boolean deep) {
return config.getKeys(deep);
}
// End Example
#NotNull
#Override
public ZConfig getRoot() {
return ZConfigWrapper.wrap(Objects.requireNonNull(config.getRoot()));
}
#Override
public String toString() {
return getValues().toString();
}
}
Zonfig is an interface that extends org.bukkit.configuration.Configuration and adds a lot of custom methods.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>me.rubyjay.bukkit</groupId>
<artifactId>ruby-core</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>RubyCore</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<minecraft.version>1.16.5</minecraft.version>
<minecraft_version>1_16_R1</minecraft_version>
<spigot.version>1.16.5-R0.1-SNAPSHOT</spigot.version>
</properties>
<repositories>
<repository>
<id>spigotmc-repo</id>
<url>https://hub.spigotmc.org/nexus/content/groups/public/</url>
</repository>
<repository>
<id>vault-repo</id>
<url>http://nexus.hc.to/content/repositories/pub_releases</url>
</repository>
<repository>
<id>sk89q-repo</id>
<url>http://maven.sk89q.com/repo/</url>
</repository>
<repository>
<id>dmulloy2-repo</id>
<url>http://repo.dmulloy2.net/nexus/repository/public/</url>
</repository>
<repository>
<id>placeholderapi</id>
<url>http://repo.extendedclip.com/content/repositories/placeholderapi/</url>
</repository>
<repository>
<id>codemc-repo</id>
<url>https://repo.codemc.org/repository/maven-public/</url>
<layout>default</layout>
</repository>
<repository>
<id>skullcreator-repo</id>
<url>https://dl.bintray.com/deanveloper/SkullCreator</url>
</repository>
</repositories>
<dependencies>
<!--<editor-fold desc="org.jetbrains:annotations">-->
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>LATEST</version>
</dependency>
<!--</editor-fold>-->
<!--<editor-fold desc="junit">-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<!--</editor-fold>-->
<!--<editor-fold desc="ninja.leaping.configurate">-->
<dependency>
<groupId>ninja.leaping.configurate</groupId>
<artifactId>configurate-gson</artifactId>
<version>3.3</version>
</dependency>
<dependency>
<groupId>ninja.leaping.configurate</groupId>
<artifactId>configurate-hocon</artifactId>
<version>3.3</version>
</dependency>
<dependency>
<groupId>ninja.leaping.configurate</groupId>
<artifactId>configurate-yaml</artifactId>
<version>3.3</version>
</dependency>
<!--</editor-fold>-->
<!--<editor-fold desc="net.sourceforge.htmlunit">-->
<dependency>
<groupId>net.sourceforge.htmlunit</groupId>
<artifactId>htmlunit</artifactId>
<version>2.30</version>
</dependency>
<!--</editor-fold>-->
<!--<editor-fold desc="org.spigotmc">-->
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>${spigot.version}</version>
<scope>provided</scope>
</dependency>
<!--<dependency>-->
<!--<groupId>org.spigotmc</groupId>-->
<!--<artifactId>minecraft-server</artifactId>-->
<!--<version>${minecraft.version}-SNAPSHOT</version>-->
<!--<type>jar</type>-->
<!--<scope>provided</scope>-->
<!--</dependency>-->
<!--</editor-fold>-->
<!--<editor-fold desc="net.milkbowl.vault">-->
<dependency>
<groupId>net.milkbowl.vault</groupId>
<artifactId>VaultAPI</artifactId>
<version>LATEST</version>
<scope>provided</scope>
</dependency>
<!--</editor-fold>-->
<!--<editor-fold desc="me.clip:placeholderapi">-->
<dependency>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
<version>2.8.2</version>
<scope>provided</scope>
</dependency>
<!--</editor-fold>-->
<!--<editor-fold desc="de.tr7zw:item-nbt-api">-->
<dependency>
<groupId>de.tr7zw</groupId>
<artifactId>item-nbt-api</artifactId>
<version>LATEST</version>
<scope>compile</scope>
</dependency>
<!--</editor-fold>-->
<!--<editor-fold desc="com.deanveloper:skullcreator">-->
<dependency>
<groupId>dev.dbassett</groupId>
<artifactId>skullcreator</artifactId>
<version>3.0.0</version>
<scope>compile</scope>
</dependency>
<!--</editor-fold>-->
<!--<editor-fold desc="com.sk89q:worldedit">-->
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldedit</artifactId>
<version>6.0.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<!--</editor-fold>-->
<!--<editor-fold desc="com.sk89q.worldguard">-->
<dependency>
<groupId>com.sk89q.worldguard</groupId>
<artifactId>worldguard-core</artifactId>
<version>7.0.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sk89q.worldguard</groupId>
<artifactId>worldguard-legacy</artifactId>
<version>7.0.0-SNAPSHOT</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>com.sk89q</groupId>
<artifactId>commandbook</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--</editor-fold>-->
</dependencies>
<!--<editor-fold defaultstate="collapsed" desc="build">-->
<build>
<defaultGoal>clean package</defaultGoal>
<sourceDirectory>src</sourceDirectory>
<testSourceDirectory>test</testSourceDirectory>
<finalName>${project.name}</finalName>
<plugins>
<plugin>
<version>3.6.1</version>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<minimizeJar>true</minimizeJar>
</configuration>
</execution>
</executions>
<configuration>
<relocations>
<relocation>
<pattern>de.tr7zw.changeme.nbtapi</pattern>
<shadedPattern>de.tr7zw.nbtapi.rubycore</shadedPattern>
</relocation>
</relocations>
</configuration>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
<executions>
<execution>
<id>copy-resources</id>
<!-- here the phase you need -->
<phase>install</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>libraries/</outputDirectory>
<resources>
<resource>
<!-- Get main artifact -->
<directory>target</directory>
<!-- Don't filter binary files -->
<filtering>false</filtering>
<includes>
<include>${project.build.finalName}.jar</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<groupId>org.codehaus.mojo</groupId>
<executions>
<execution>
<id>Distribution script</id>
<phase>install</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>bash</executable>
<commandlineArgs>/home/ruby/AppData/minecraft/server/bin/mcdist</commandlineArgs>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<resources>
<resource>
<directory>resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<!--</editor-fold>-->
</project>
So I've had this happen before on my IDE, mostly when I was editing the main projects API. And then going into the second project, not syncing the maven repo between it, and then compiling it, since I added/changed a class file in the API, the class "technically" doesn't exist, because it's now using different methods. This might not be helpful, cause I had to both sync and restart my IDE multiple times to fix the issue. But I got it working after a while.
I am trying to create a RESTful web-service and I created one but I am getting a
MessageBodyWriter not found for media type=application/json error
My Todo class:
package com.jersey.jaxb;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.pojomatic.Pojomatic;
import org.pojomatic.annotations.AutoProperty;
#XmlRootElement
#XmlType(name = "todo")
#XmlAccessorType(XmlAccessType.FIELD)
#AutoProperty
public class Todo {
#XmlElement(name = "summary")
private final String summary;
#XmlElement(name = "description")
private final String description;
public String getSummary() {
return summary;
}
public String getDescription() {
return description;
}
public Todo() {
this(new Builder());
}
public Todo(Builder builder) {
this.summary = builder.summary;
this.description = builder.description;
}
#Override
public boolean equals(Object o) {
return Pojomatic.equals(this, o);
}
#Override
public int hashCode() {
return Pojomatic.hashCode(this);
}
#Override
public String toString() {
return Pojomatic.toString(this);
}
public static class Builder {
private String description;
private String summary;
public Builder summary(String summary) {
this.summary = summary;
return this;
}
public Builder description(String description) {
this.description = description;
return this;
}
public Todo build() {
return new Todo(this);
}
}
}
And my Resource:-
package com.jersey.jaxb;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.Produces;
import javax.ws.rs.GET;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
#Path("/todo")
public class TodoResource {
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response getTodo(){
Todo todo = new Todo.Builder().description("My Todo Object").summary("Created").build();
return Response.status(Status.OK).entity(todo).build();
}
}
My web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<display-name>MyFirstWebService</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.jersey.jaxb</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
My Libraries:
aopalliance-repackaged-2.4.0-b10.jar
asm-debug-all-5.0.2.jar
hk2-api-2.4.0-b10.jar
hk2-locator-2.4.0-b10.jar
hk2-utils-2.4.0-b10.jar
jackson-jaxrs-json-provider-2.2.3.jar
javassist-3.18.1-GA.jar
javax.annotation-api-1.2.jar
javax.inject-2.4.0-b10.jar
javax.servlet-api-3.0.1.jar
javax.ws.rs-api-2.0.1.jar
jaxb-api-2.2.7.jar
jersey-client.jar
jersey-common.jar
jersey-container-servlet.jar
jersey-container-servlet-core.jar
jersey-guava-2.17.jar
jersey-media-jaxb.jar
jersey-server.jar
org.osgi.core-4.2.0.jar
osgi-resource-locator-1.0.1.jar
persistence-api-1.0.jar
validation-api-1.1.0.Final.jar
When I run this application on Tomcat server and run this :
http://localhost:8080/MyFirstWebService/rest/todo
I get the error:
SEVERE: MessageBodyWriter not found for media type=application/json,
type=class com.jersey.jaxb.Todo, genericType=class
com.jersey.jaxb.Todo.
You have jackson-jaxrs-json-provider which is a start..
But...
that artifact is still dependent on Jacskon itself, which includes all these artifacts
That's why we use Maven[1] (so we don't have to worry about this kind of thing :-). So go find these.
Then just add the package to the web.xml, and it should work
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>
com.jersey.jaxb,
com.fasterxml.jackson.jaxrs.json
</param-value>
1. Maven dependency
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.2.3</version>
</dependency>
Or use the below Jersey "wrapper" for the above dependency. It will register the Jackson providers (so we don't need to explicitly register like above), and the Jackson exception mappers, and start from version 2.17, provides support for Entity Data Filtering.
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey2.version}</version>
</dependency>
Note: The fact that we don't have to register anything with the above dependency, is made possible through the Auto-discovery feature of Jersey. If we for some reason disable the auto-discovery, you will want to explicitly register the JacksonFeature.
The solution may be to make ensure that the model classes have a no-argument constructor.
And add this dependency on your pom.XML:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
I had the same issue, i solved it by addind a empty constructor to the class
public SandBoxClass(){} //-> solved the issue**
public SandBoxClass(Integer arg1, Integer arg2) {
this.arg1=arg1;
this.arg2=arg2;
}
If you already have the jersey-media-moxy dependency added into your pom.xml. Make sure your entity class has the default constructor.
I got this issue when I introduced a paramatrized constructor in the model class. Adding the default constructor again worked for me.
As for me, it helped to register JacksonFeature:
public class App extends ResourceConfig {
public App() {
packages("info.ernestas.simplerest");
register(new JacksonFeature()); // This magical line helped
}
}
Update Library Jax-RS 2.0 and Jersey 2.5.1(JAX-RS-RI) only
Return Bean object(todo) not response because while auto generating json or xml it response create issue.
Answered here: Obtaining "MessageBodyWriter not found for media type=application/json" trying to send JSON object through JAX-RS web service
As stated above:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
For me I also had to add:
ClientConfig config = new ClientConfig();
config.register(JacksonJsonProvider.class);
return ClientBuilder.newClient(config)
Has anyone managed to get wildfly's undertow to work with Primefaces push 2.0? Wildfly's native websockets (jee7) works great on it's own. I'm not sure how to integrate with primefaces. Any examples would be helpful.
I got this working on WildFly 8.1.0.Final with:
pom.xml:
<dependency>
<groupId>org.atmosphere</groupId>
<artifactId>atmosphere-runtime</artifactId>
<version>2.1.6</version>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>5.0</version>
</dependency>
web.xml:
<servlet>
<servlet-name>PrimePushServlet</servlet-name>
<servlet-class>org.primefaces.push.PushServlet</servlet-class>
<init-param>
<param-name>org.atmosphere.cpr.broadcasterCacheClass</param-name>
<param-value>org.atmosphere.cache.UUIDBroadcasterCache</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>PrimePushServlet</servlet-name>
<url-pattern>/primepush/*</url-pattern>
</servlet-mapping>
in .xhtml:
<p:socket onMessage="handleMessage" channel="/#{request.remoteUser}" />
<script type="text/javascript">
function handleMessage(facesmessage) {
var msgdetail = $.base64.decode(facesmessage.detail);
facesmessage.detail = msgdetail;
PF('growlWidget').show([ facesmessage ]);
}
</script>
My Resource:
#PushEndpoint("/{user}")
#Singleton
public class UserResource {
#PathParam("user")
private String user;
#OnMessage(encoders = { JSONEncoder.class }, decoders = { JSONDecoder.class })
public FacesMessage onMessage(FacesMessage message) {
return message;
}
The javascript-part should be modified to match your demand.
Wildfly 9.0.2
pom.xml
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.atmosphere</groupId>
<artifactId>atmosphere-runtime</artifactId>
<version>2.3.5</version>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>5.2</version>
</dependency>
web.xml
<servlet>
<servlet-name>PrimePushServlet</servlet-name>
<servlet-class>org.primefaces.push.PushServlet</servlet-class>
<init-param>
<param-name>org.atmosphere.cpr.broadcasterCacheClass</param-name>
<param-value>org.atmosphere.cache.UUIDBroadcasterCache</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>PrimePushServlet</servlet-name>
<url-pattern>/primepush/*</url-pattern>
xhtml
<p:socketonMessage="handleMessage" channel="/counter" />
js
function handleMessage(data) {
console.log(data);
}
Java
import org.primefaces.push.annotation.OnMessage;
import org.primefaces.push.annotation.PushEndpoint;
import org.primefaces.push.impl.JSONEncoder;
#PushEndpoint("/counter")
public class MessageResources {
#OnMessage(encoders = {JSONEncoder.class})
public String onMessage(String count) {
return count;
}
}
More java
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.primefaces.push.EventBus;
import org.primefaces.push.EventBusFactory;
#ManagedBean
#SessionScoped
public class GlobalMessageControler implements Serializable {
private static final long serialVersionUID = -4507223739929042795L;
private volatile int count;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public void increment() {
count++;
EventBus eventBus = EventBusFactory.getDefault().eventBus();
eventBus.publish("/counter", String.valueOf(count));
}
}
I have an issue with Spring JPA, Hibernate, MySQL.
I have an Entity (Nom.java) and repository (public interface NomRepository extends JpaRepository). They are created and injected just fine.
The issue is that when I'm trying to save a record via repository's save method spring complaines that "Table '' doesn't exist".
Indeed I do not see this table in MySQL. U've tried different values of hibernate.hbm2ddl.auto but it did not help.
I use XML-less configuration BTW.
Here's the config file:
package ru.interosite.awp.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
#Configuration
#ComponentScan("ru.interosite.awp")
#EnableAutoConfiguration
public class AppConfiguration {
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/awp");
dataSource.setUsername("root");
dataSource.setPassword("password");
return dataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
lef.setPersistenceUnitName("my_pu");
lef.setPackagesToScan("ru.interosite.awp.data");
lef.setDataSource(dataSource);
lef.setJpaVendorAdapter(jpaVendorAdapter);
lef.setJpaProperties(getJpaProperties());
return lef;
}
#Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setDatabase(Database.MYSQL);
jpaVendorAdapter.setGenerateDdl(true);
jpaVendorAdapter.setShowSql(true);
jpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQL5Dialect");
return jpaVendorAdapter;
}
private Properties getJpaProperties() {
return new Properties() {
{
setProperty("hibernate.hbm2ddl.auto", "update");
setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
setProperty("hibernate.show_sql", "true");
setProperty("hibernate.format_sql", "true");
}
};
}
}
Here's how I start the app:
package ru.interosite.awp;
import java.awt.Font;
import javax.swing.UIManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import ru.interosite.awp.config.AppConfiguration;
import ru.interosite.awp.gui.UIUtils;
public class Boot {
private static final Logger LOGGER = LoggerFactory.getLogger(Boot.class);
public static void main( String[] args )
{
UIUtils.setUIFont(new javax.swing.plaf.FontUIResource(Font.SANS_SERIF, Font.PLAIN, 16));
try {
String lafClassName = UIManager.getSystemLookAndFeelClassName();
UIManager.setLookAndFeel(lafClassName);
} catch (Exception e) {
LOGGER.debug(e.getMessage());
}
ApplicationContext ctx = SpringApplication.run(AppConfiguration.class, args);
((Runner)ctx.getBean("runner")).start();
}
}
This is my pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>ru.interosite</groupId>
<artifactId>AWP</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>AWP</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<start-class>ru.interosite.awp.Runner</start-class>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>0.5.0.M4</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>http://repo.spring.io/libs-snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>http://repo.spring.io/libs-milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>org.jboss.repository.releases</id>
<name>JBoss Maven Release Repository</name>
<url>https://repository.jboss.org/nexus/content/repositories/releases</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>http://repo.spring.io/libs-snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>http://repo.spring.io/libs-milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
you need to change two method and delete getProperties() method:
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
lef.setDataSource(dataSource);
lef.setJpaVendorAdapter(jpaVendorAdapter);
lef.setPackagesToScan("com.spring.domain");
return lef;
}
#Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
hibernateJpaVendorAdapter.setShowSql(true);
hibernateJpaVendorAdapter.setGenerateDdl(true); //Auto creating scheme when true
hibernateJpaVendorAdapter.setDatabase(Database.H2);//Database type
return hibernateJpaVendorAdapter;
}
the point is:
hibernateJpaVendorAdapter.setGenerateDdl(true);
In the latest version [spring boot].Include the below in application.properties
spring.jpa.generate-ddl=true
Ok, finally I have found how to fix it.
1) First, I moved AppConfiguration class to top-level package, ru.interosite.awp in my case
2) Second, I changed annotations to be:
#Configuration
#ComponentScan
#EnableJpaRepositories
public class AppConfiguration {...
Seems that #EnableAutoConfiguration annotation messed things up.
I dunno if it is a bug or feature. Looks like a bug of spring-boot actually.
I swapped to the M5 spring-boot-starter-xxx jars and now I'm seeing my tables get created
Here's my Application class (this is my first attempt at spring boot so...)
import static org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType.H2;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder().setType(H2).build();
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
lef.setDataSource(dataSource);
lef.setJpaVendorAdapter(jpaVendorAdapter);
lef.setPackagesToScan("org.home.wtw.domain");
return lef;
}
#Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
hibernateJpaVendorAdapter.setShowSql(true);
hibernateJpaVendorAdapter.setGenerateDdl(true);
hibernateJpaVendorAdapter.setDatabase(Database.H2);
return hibernateJpaVendorAdapter;
}
#Bean
public PlatformTransactionManager transactionManager(
EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
If you want the tables to be created, you must set hibernate.hbm2ddl.auto property to create. Here are the possible values for hibernate.hbm2ddl.auto :
validate: validate the schema, makes no changes to the database.
update: update the schema.
create: creates the schema, destroying previous data.
create-drop: drop the schema at the end of the session.
Also, check that you are your database url is correct.
[Update]And don't forget to define a transaction manager for spring.
#Bean
public PersistenceAnnotationBeanPostProcessor persistenceAnnotationBeanPostProcessor()
{
PersistenceAnnotationBeanPostProcessor persistenceAnnotationBeanPostProcessor = new PersistenceAnnotationBeanPostProcessor();
return persistenceAnnotationBeanPostProcessor;
}
Trying giving spring.jpa.hibernate.ddl-auto=create in application.properties file.
I'm creating a REST service which accepts input as PathParam and produces JSON Response. The code is working fine and I can able to build the response. After returning the response, REST is throwing an error like "COULD NOT FIND WRITER OR DATASOURCEPROVIDER FOR (ResponseClass) and MediaType application/json". Thanks.
This is how I got jackson 2.1.3 working with Wink as a JSON provider.
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;
//see http://www.ibm.com/developerworks/web/library/wa-aj-jackson/
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import com.fasterxml.jackson.databind.AnnotationIntrospector;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;
import com.fasterxml.jackson.databind.type.TypeFactory;
/**
* #see https://cwiki.apache.org/WINK/jax-rs-getting-started.html
*/
public class JaxrsApp extends Application {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> classes = new HashSet<Class<?>>();
classes.add(YourJaxRSAnnotated.class);
//...
return classes;
}
#Override
public Set<Object> getSingletons() {
Set<Object> s = new HashSet<Object>();
// See http://wiki.fasterxml.com/JacksonJAXBAnnotations for more information
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector primary = new JaxbAnnotationIntrospector( TypeFactory.defaultInstance() );
AnnotationIntrospector secondary = new JacksonAnnotationIntrospector();
AnnotationIntrospector pair = AnnotationIntrospector.pair(primary, secondary);
mapper.getDeserializationConfig().with(pair);
mapper.getSerializationConfig().with(pair);
// Set up the provider
JacksonJaxbJsonProvider jaxbProvider = new JacksonJaxbJsonProvider();
jaxbProvider.setMapper(mapper);
s.add(jaxbProvider);
return s;
}
}
then, in web.xml
<servlet>
<servlet-name>JAX-RS Servlet</servlet-name>
<servlet-class>org.apache.wink.server.internal.servlet.RestServlet</servlet-class>
<!-- this param tells the RestServlet which custom Application sub-class
will return a list of our classes that have JAX-RS annotations -->
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.example.JaxrsApp</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
I suppose you use Jersey.
First of all, check the dependencies: http://jersey.java.net/nonav/documentation/latest/chapter_deps.html#d4e1716
Here is my pom.xml:
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.15</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.15</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
<version>1.15</version>
</dependency>
I myself found that the WinkApplication is not loaded properly. The restsdkservice configuration in web.xml was incorrect and because of that JacksonJaxbJsonProvider was not loaded into the Wink. Finally got it after 2 days. Thanks everyone!!