I want to create and publish simple WebService using Java.
Everything compiles.
When I run
>java -cp . ts.TimeServerPublisher
I am getting error
Error: Could not find or load main class ts.TimeServerPublisher
Any idea why it is a problem?
My code looks like following
TimeServerPublisher
package ts;
import javax.xml.ws.Endpoint;
public class TimeServerPublisher {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Endpoint.publish("http://127.0.0.1:9876/ts", new TimeServerImpl());
}
}
TimeServerImpl.java
package ts;
import java.util.Date;
import javax.jws.WebService;
#WebService(endpointInterface = "ts.TimeServer")
public class TimeServerImpl implements TimeServer {
public String getTimeAsString() { return new Date().toString(); }
public long getTimeAsElapsed() { return new Date().getTime(); }
}
TimeServer.java
package ts;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
#WebService
#SOAPBinding(style = Style.RPC)
public interface TimeServer {
#WebMethod String getTimeAsString();
#WebMethod long getTimeAsElapsed();
}
The class you are tryin to run is in the package ts.
So if you have this file tree:
/bin/ts/TimeServerPublisher
You have to run the following command
java -cp /bin ts/TimeServerPublisher
Related
I am trying to make a basic mod for minecraft and am following a tutorial for the same. When I run runClient, it gives me the following error
Reference to undefined variable MC_VERSION
Here is my main.java for reference:
package rattandeep.basicmod;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import rattandeep.basicmod.proxy.CommonProxy;
import rattandeep.basicmod.util.Reference;
#Mod(modid = Reference.MOD_ID, name = Reference.NAME, version = Reference.VERSION)
public class Main {
#Instance
public static Main instance;
#SidedProxy(clientSide = Reference.CLIENT_PROXY_CLASS, serverSide = Reference.COMMON_PROXY_CLASS)
public static CommonProxy proxy;
#EventHandler
public static void PreInit(FMLPreInitializationEvent event) {
}
#EventHandler
public static void init(FMLInitializationEvent event) {
}
#EventHandler
public static void Postinit(FMLPostInitializationEvent event) {
}
}
I have searched for a solution but found none. How do I solve this?
I found out how to solve it. I just needed to change the variable value of MC_VERSION in my runClient launch file to my minecraft version.
I'm refactoring a legacy Java codebase to provide Guice-powered dependency injection to Jersey resource classes.
Here is a stripped down application that uses the legacy Jetty/Jersey setup (see Main & Application) along with my attempts to wire up Guice using their wiki article on servlets:
build.gradle
plugins {
id 'java'
}
repositories {
mavenCentral()
}
dependencies {
compile 'org.projectlombok:lombok:1.16.18'
compile 'com.google.inject:guice:4.1.0'
compile 'com.google.inject.extensions:guice-servlet:4.1.0'
compile 'com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:2.9.3'
compile 'org.eclipse.jetty:jetty-server:9.4.8.v20171121'
compile 'org.eclipse.jetty:jetty-servlet:9.4.8.v20171121'
compile 'org.glassfish.jersey.media:jersey-media-sse:2.26'
compile 'com.sun.jersey:jersey-servlet:1.19.4'
}
Main.java
package org.arabellan.sandbox;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.servlet.ServletModule;
import java.util.ArrayList;
import java.util.List;
public class Main {
static Injector injector;
public static void main(String[] args) throws Exception {
List<AbstractModule> modules = new ArrayList<>();
modules.add(new ExistingModule());
modules.add(new ServletModule());
injector = Guice.createInjector(modules);
injector.getInstance(Application.class).run();
}
}
Application.java
package org.arabellan.sandbox;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import com.google.inject.servlet.GuiceFilter;
import com.sun.jersey.spi.container.servlet.ServletContainer;
import org.glassfish.jersey.message.DeflateEncoder;
import org.glassfish.jersey.message.GZipEncoder;
import org.glassfish.jersey.server.ResourceConfig;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.glassfish.jersey.server.filter.EncodingFilter;
class Application {
void run() throws Exception {
Server jettyServer = new Server(8080);
ServletContextHandler httpContext = new ServletContextHandler(jettyServer, "/");
httpContext.addEventListener(new GuiceServletConfig());
httpContext.addFilter(GuiceFilter.class, "/*", null);
httpContext.addServlet(new ServletHolder(new ServletContainer(buildResourceConfig())), "/*");
jettyServer.setHandler(httpContext);
jettyServer.start();
}
private ResourceConfig buildResourceConfig() {
ResourceConfig config = new ResourceConfig();
config.register(JacksonJsonProvider.class);
config.registerClasses(EncodingFilter.class, GZipEncoder.class, DeflateEncoder.class);
config.packages("org.arabellan.sandbox");
return config;
}
}
ExistingModule.java
package org.arabellan.sandbox;
import com.google.inject.AbstractModule;
public class ExistingModule extends AbstractModule {
protected void configure() {
bind(FooDao.class).to(DynamoDBFooDao.class);
}
}
GuiceServletConfig.java
package org.arabellan.sandbox;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceServletContextListener;
public class GuiceServletConfig extends GuiceServletContextListener {
#Override
protected Injector getInjector() {
return Main.injector;
}
}
FooResource.java
package org.arabellan.sandbox;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
#Path("/foo")
public class FooResource {
private final FooDao dao;
#Inject
public FooResource(FooDao dao) {
this.dao = dao;
}
#GET
#Path("/{id}")
public Response getById(#PathParam("id") String id) {
return Response.ok(dao.getById(id)).build();
}
}
DynamoDBFooDao.java
package org.arabellan.sandbox;
import javax.inject.Singleton;
#Singleton
public class DynamoDBFooDao implements FooDao {
public String getById(String id) {
return id;
}
}
FooDao.java
package org.arabellan.sandbox;
interface FooDao {
String getById(String id);
}
I'm failing to understand the various components and how they work together. As such I keep getting the following error:
SEVERE: The following errors and warnings have been detected with resource and/or provider classes:
SEVERE: Missing dependency for constructor public org.arabellan.sandbox.FooResource(org.arabellan.sandbox.FooDao) at parameter index 0
If I access the Guice injector directly in FooResource's constructor then it works. This tells me the Jetty/Jersey stuff is setup properly to serve the resource and Guice is able to build it's dependency tree correctly. I believe this means the problem lies in getting Jersey to use Guice when constructing the resource.
As pointed out in the comments, I needed to settle on either version 1 or 2 of Jersey before trying to hook up Guice. I went with Jersey 2.
My original assumption however was correct, the linkage between Guice and Jersey (or rather HK2) needed to be setup. I facilitated this with the GuiceToHK2 class. I didn't want to define DI bindings in two places so this solution loops through all of the Guice bindings, filters them to a specific package (optional), and then binds them within HK2.
build.gradle
plugins {
id 'java'
}
repositories {
mavenCentral()
}
dependencies {
compile 'org.projectlombok:lombok:1.16.18'
compile 'com.google.inject:guice:4.1.0'
compile 'com.google.inject.extensions:guice-servlet:4.1.0'
compile 'com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:2.9.3'
compile 'org.eclipse.jetty:jetty-server:9.4.8.v20171121'
compile 'org.eclipse.jetty:jetty-servlet:9.4.8.v20171121'
compile 'org.glassfish.jersey.containers:jersey-container-jetty-servlet:2.26'
compile 'org.glassfish.jersey.media:jersey-media-sse:2.26'
compile 'org.glassfish.jersey.inject:jersey-hk2:2.26'
}
Application.java
package org.arabellan.sandbox;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.glassfish.jersey.message.DeflateEncoder;
import org.glassfish.jersey.message.GZipEncoder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.filter.EncodingFilter;
import org.glassfish.jersey.servlet.ServletContainer;
class Application {
void run() throws Exception {
ServletContextHandler httpContext = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
ServletContainer container = new ServletContainer(buildResourceConfig());
ServletHolder holder = new ServletHolder(container);
httpContext.setContextPath("/");
httpContext.addServlet(holder, "/*");
Server jettyServer = new Server(8080);
jettyServer.setHandler(httpContext);
jettyServer.start();
}
private ResourceConfig buildResourceConfig() {
ResourceConfig config = new ResourceConfig();
config.register(new GuiceToHK2(Main.injector));
config.register(JacksonJsonProvider.class);
config.registerClasses(EncodingFilter.class, GZipEncoder.class, DeflateEncoder.class);
config.packages("org.arabellan.sandbox");
return config;
}
}
GuiceToHK2.java
package com.flightstats.hub.app;
import com.google.inject.Injector;
import com.google.inject.Key;
import lombok.extern.slf4j.Slf4j;
import org.glassfish.hk2.api.Factory;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
#Slf4j
class GuiceToHK2 extends AbstractBinder {
private final Injector injector;
GuiceToHK2(Injector injector) {
this.injector = injector;
}
#Override
protected void configure() {
injector.getBindings().forEach((key, value) -> {
if (isNamedBinding(key)) {
bindNamedClass(key);
} else {
bindClass(key);
}
});
}
private boolean isNamedBinding(Key<?> key) {
return key.getAnnotationType() != null && key.getAnnotationType().getSimpleName().equals("Named");
}
private void bindClass(Key<?> key) {
try {
String typeName = key.getTypeLiteral().getType().getTypeName();
log.info("mapping guice to hk2: {}", typeName);
Class boundClass = Class.forName(typeName);
bindFactory(new ServiceFactory<>(boundClass)).to(boundClass);
} catch (ClassNotFoundException e) {
log.warn("unable to bind {}", key);
}
}
private void bindNamedClass(Key<?> key) {
try {
String typeName = key.getTypeLiteral().getType().getTypeName();
Method value = key.getAnnotationType().getDeclaredMethod("value");
String name = (String) value.invoke(key.getAnnotation());
log.info("mapping guice to hk2: {} (named: {})", typeName, name);
Class boundClass = Class.forName(typeName);
bindFactory(new ServiceFactory<>(boundClass)).to(boundClass).named(name);
} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
log.warn("unable to bind {}", key);
}
}
private class ServiceFactory<T> implements Factory<T> {
private final Class<T> serviceClass;
ServiceFactory(Class<T> serviceClass) {
this.serviceClass = serviceClass;
}
public T provide() {
return injector.getInstance(serviceClass);
}
public void dispose(T versionResource) {
// do nothing
}
}
}
It's not a bulletproof solution but it solved my issue. It assumes that everything that needs to be injected into my resources is in the org.arabellan.sandbox package and isn't #Named.
UPDATE: Made the solution more generic by removing assumptions.
hmmn for me it looks like you execute one of the following URLs:
http://localhost/foo
http://localhost/foo/
so that the string-parameter "id" of this function: "public Response getById(#PathParam("id") String id)" is null. which results in your error.
It's just an assumption. Could you check it if i'm right, please
My application is written with Spring, Hibernate (JPA), JBOSS 9.0.0.GA & JBOSS EAP 6.4. In POM.xml I have specified the packaging to WAR.
I have 2 functions which I'd like to automate:
a. CSV reader - Read from CSV file and update table in DB
package com.fwd.pmap.memberInterfaceFile;
/* all imports */
public class CsvReader
{
public void importInterfaceFile() throws Exception
{
// do processing here
}
}
b. CSV Writer - Read from DB and output to CSV file
package com.fwd.pmap.memberInterfaceFile;
/* all imports */
public class CsvWriter
{
public void generateInterfaceFile() throws Exception
{
// do processing here
}
}
How can I automate both functions above to run on a specific time every day? For example:
CSV Reader to run daily # 05:00 AM
CSV Writer to run daily # 07:00 AM
Project Structure
Finally decided to use Spring Scheduling as it does not involve lots of coding as well as XML.
This is the bean class where I schedule 2 jobs to run at 5AM & 6AM daily:
package com.fwd.pmap.scheduler;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.fwd.pmap.memberInterfaceFile.CsvReader;
import com.fwd.pmap.memberInterfaceFile.CsvWriter;;
#Component
public class MyBean {
#Scheduled(cron="0 0 5 * * *")
public void importInterfaceFile()
{
CsvReader reader = new CsvReader();
try {
reader.importInterfaceFile();
} catch (Exception e) {
e.printStackTrace();
}
}
#Scheduled(cron="0 0 6 * * *")
public void generateInterfaceFile()
{
CsvWriter writer = new CsvWriter();
try {
writer.generateInterfaceFile();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here's the config class:
package com.fwd.pmap.scheduler;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import com.fwd.pmap.scheduler.MyBean;
#Configuration
#EnableScheduling
public class SchedulerConfig implements SchedulingConfigurer {
#Bean
public MyBean bean() {
return new MyBean();
}
#Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(taskExecutor());
}
#Bean(destroyMethod="shutdown")
public Executor taskExecutor() {
return Executors.newScheduledThreadPool(4);
}
}
And the main class to execute the above:
package main;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import com.fwd.pmap.scheduler.SchedulerConfig;
public class Main {
static Logger LOGGER = LoggerFactory.getLogger(Main.class);
#SuppressWarnings({ "unused", "resource" })
public static void main(String[] args) {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(SchedulerConfig.class);
}
}
I am going through the Play Framework tutorial. I am getting this error:
error: cannot find symbol
In /Users/hseritt/devel/todolist/app/controllers/Application.java at line 12.
import views.html.*;
public class Application extends Controller {
static Form<Task> taskForm = Form.form(Task.class); // ERROR IS HIGHLIGHTED AS Form.form
public static Result index() {
return redirect(routes.Application.tasks());
}
My full code for Application.java:
package controllers;
import play.*;
import play.data.*;
import play.mvc.*;
import models.*;
import views.html.*;
public class Application extends Controller {
static Form<Task> taskForm = Form.form(Task.class);
public static Result index() {
return redirect(routes.Application.tasks());
}
public static Result tasks() {
return ok(
views.html.index.render(Task.all(), taskForm)
);
}
public static Result newTask() {
return TODO;
}
public static Result deleteTask(Long id) {
return TODO;
}
}
I am wondering if I missed something in the tutorial or put something in the wrong place.
Thanks!
I think you should import the following:
import static play.data.Form.*;
As per jnoob, just change import to import play.data.Form, then do static Form<Task> taskForm = form(Task.class);, worked for me.
I am trying to create a job in java play2 using akka.
I always get the same error error: cannot find symbol
And it points to system.actorOf() Intellij and Eclipse don't give me an error msg.
But I can not find this method. I used the following imports
import play.libs.Akka;
import akka.actor.ActorSystem;
import akka.actor.ActorRef;
import akka.actor.UntypedActorFactory;
import akka.actor.UntypedActor;
import akka.actor.Props;
import akka.actor.ActorRefFactory;
Maybe the docs are outdated and they have removed the system.actorOf() ?
public class Global extends GlobalSettings {
ActorRef tickActor = system.actorOf(new Props().withCreator(new UntypedActorFactory() {
public UntypedActor create() {
return new UntypedActor() {
public void onReceive(Object message) {
if (message.equals("Log")) {
controllers.Application.log();
} else {
unhandled(message);
}
}
};
}
}));
#Override
public void onStart(Application app) {
Cancellable cancellable = system.scheduler().schedule(Duration.Zero(), Duration.create(10, TimeUnit.SECONDS),
tickActor, "Log");
}
}
EDIT:
.
oh... google redirected me to the outdated documentation. It's Akka.System() now..
Can anyone give me an example on how to create the tickActor with up2date code?
http://www.playframework.org/documentation/2.0.2/JavaAkka
I strongly suggest that you take a look at the Akka documentation about actors and schedulers.
You can also take a look at this question: Play Framework 2.0 schedules an Akka Actor at server launch
solved it.
Btw there are some typos in the documentation.
import java.util.concurrent.TimeUnit;
import play.*;
import play.mvc.*;
import play.mvc.Http.RequestHeader;
import static play.mvc.Results.*;
import play.libs.Akka;
import akka.actor.ActorSystem;
import akka.actor.ActorRef;
import akka.actor.UntypedActorFactory;
import akka.actor.UntypedActor;
import akka.actor.Props;
import akka.actor.ActorRefFactory;
import akka.util.*;
public class Global extends GlobalSettings {
ActorRef tickActor;
#Override
public void onStart(Application app) {
Logger.info("D");
tickActor = Akka.system().actorOf((new Props().withCreator(new UntypedActorFactory() {
public UntypedActor create() {
return new UntypedActor() {
public void onReceive(Object message) {
if (message.equals("Log")) {
//Do something
// controllers.Application.log();
} else {
unhandled(message);
}
}
};
}
})));
Akka.system().scheduler().schedule(
Duration.create(0, TimeUnit.MILLISECONDS),
Duration.create(30, TimeUnit.MINUTES),
tickActor,
"Log"
);
}
}