Apache freemarker will not import with gradle - java

I have a java web app, which I am using cloud9 for, and I have set up Apache freemarker as a templating engine. To import the package I used gradle, but when I run gradle build, I get exceptions due to references to the freemarker package in my code. When I comment out all uses of freemarker aside from the import statement, my gradle will build my code, but it will throw errors when I run it (freemarker package does not exist). How can I fix this?
App.java
import freemarker.template.*;
import com.sun.net.httpserver.HttpServer;
import java.net.*;
import java.util.*;
public class App{
public static Configuration cfg = new Configuration(Configuration.VERSION_2_3_27);
int port;
public static void main(String[] args){
App app = new App(8081);
try{
app.init();
app.templateConfig();
}catch(Exception e){
System.out.println(e);
}
}
public App(int port){
this.port = port;
}
public void init() throws Exception{
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
System.out.println("server started at " + port);
server.createContext("/", new HomeController.Index());
server.createContext("/echoHeader", new HomeController.EchoHeaderHandler());
server.createContext("/echoGet", new HomeController.EchoGetHandler());
server.createContext("/echoPost", new HomeController.EchoPostHandler());
server.setExecutor(null);
server.start();
}
public void templateConfig() throws Exception{
cfg.setDirectoryForTemplateLoading(new File("../templates"));
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHanlder.HTML_DEBUG_HANDLER);
cfg.setLogTemplateExceptions(false);
cfg.setWrapUncheckedExceptions(true);
}
}
HomeController.java
import freemarker.template.*;
import com.sun.net.httpserver.*;
import java.net.*;
import java.io.*;
import java.util.*;
public class HomeController{
public static class Index implements HttpHandler{
public void handle(HttpExchange exchange) throws IOException{
//String response = "<h1>Server start success if you see this message</h1><h1>Port: " + 8081 + "</h1>";
exchange.sendResponseHeaders(200, response.length());
OutputStream os = exchange.getResponseBody();
//os.write(response.getBytes());
Map<String, Object> root = new HashMap<>();
root.put("port", 3000);
Template home = App.cfg.getTemplate("home.ftlh");
home.process(root, os);
os.close();
}
}
public static class EchoHeaderHandler implements HttpHandler{
public void handle(HttpExchange exchange){
}
}
public static class EchoGetHandler implements HttpHandler{
public void handle(HttpExchange exchange){
}
}
public static class EchoPostHandler implements HttpHandler{
public void handle(HttpExchange exchange){
}
}
}
build.gradle
repositories {
mavenCentral()
}
apply plugin: "java"
dependencies {
compile "org.freemarker:freemarker:2.3.28"
}
sourceSets {
main.java.srcDir "src/main"
}
jar {
from configurations.compile.collect { zipTree it }
manifest.attributes "Main-Class":"com.isaackrementsov.app.App"
}
My directory structure
workspace
build
classes
java
main
//Source code compiles here
libs
tmp
compileJava
jar
src
main
com
isaackrementsov
app
//Source code here
My whole project is here: Cloud9 Project

Related

JNDI Reference+RMI, load remote .class failed

my java version is: 1.8.0_282
this is client:
import java.rmi.registry.*;
import javax.naming.*;
public class RegistryClient {
public static void main(String[] args) throws Exception {
System.setProperty("com.sun.jndi.rmi.object.trustURLCodebase", "true");
Context registry = new InitialContext();
registry.lookup("rmi://127.0.0.1:1099/Demo");
System.out.println("done");
}
}
this is server:
import java.rmi.registry.*;
import javax.naming.*;
import com.sun.jndi.rmi.registry.ReferenceWrapper;
public class RegistryServer {
public static void main(String[] args) throws Exception {
Registry registry = LocateRegistry.createRegistry(1099);
Reference refObj = new Reference(
"xxx",
"RMIRegistryDemoRemote",
"http://127.0.0.1:8000/"
);
ReferenceWrapper hello = new ReferenceWrapper(refObj);
registry.bind("Demo", hello);
System.out.println("[!] server is ready");
}
}
this is the interface and implement of RMIRegistryDemo:
import java.rmi.*;
public interface RMIRegistryDemo extends Remote {
String sayHello(String name) throws Exception;
}
import java.rmi.server.*;
import java.rmi.*;
public class RMIRegistryDemoImpl extends UnicastRemoteObject implements RMIRegistryDemo {
public RMIRegistryDemoImpl() throws Exception {}
String id = "10";
#Override
public String sayHello(String name) {
System.out.println(id);
return "Hi, " + name;
}
}
this is the remote .class:
import java.io.IOException;
public class RMIRegistryDemoRemote {
public RMIRegistryDemoRemote() throws IOException {
final Process process = Runtime.getRuntime().exec("/System/Applications/Calculator.app/Contents/MacOS/Calculator");
}
}
after:
run RegistryServer
deployed a web server to send RMIRegistryDemoRemote.class
run RegistryClient
the client just prints "done", and no access log in my weblog:
# overflow in ~/Downloads/test [16:16:44]
» javac RegistryClient.java && java RegistryClient
done
# overflow in ~/Downloads/test/remote [16:20:05]
» python -m http.server 8000
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
what causes it?

How to download zip files from webdav server using sardine?

I am using below java class which uses sardine , i am getting only resources or zip files list in the directory, what should i use to download zip files?
package com.download;
import java.util.List;
import org.mule.api.MuleEventContext;
import org.mule.api.lifecycle.Callable;
import com.github.sardine.DavResource;
import com.github.sardine.Sardine;
import com.github.sardine.SardineFactory;
public class filesdownload implements Callable{
#Override
public Object onCall(MuleEventContext eventContext) throws Exception {
Sardine sardine = SardineFactory.begin("***","***");
List<DavResource> resources = sardine.list("http://hfus.com/vsd");
for (DavResource res : resources)
{
System.out.println(res);
}
return sardine;
}
You need to use sardine.get() method. Method documentation
Don't forget to use absolute path to your file. For example: http://hfus.com/vsd/file.zip.
Code sample:
package com.download;
import java.util.List;
import org.mule.api.MuleEventContext;
import org.mule.api.lifecycle.Callable;
import com.github.sardine.DavResource;
import com.github.sardine.Sardine;
import com.github.sardine.SardineFactory;
//TODO: add missing imports
public class filesdownload implements Callable{
#Override
public Object onCall(MuleEventContext eventContext) throws Exception {
Sardine sardine = SardineFactory.begin("***","***");
List<DavResource> resources = sardine.list(serverUrl()+"/vsd");
for (DavResource res : resources) {
if(res.getName().endsWith(".zip")) {
downloadFile(res);
}
}
return sardine;
}
private void downloadFile(DavResource resource) {
try {
InputStream in = sardine.get(serverUrl()+resource.getPath());
// TODO: handle same file name in subdirectories
OutputStream out = new FileOutputStream(resource.getName());
IOUtils.copy(in, out);
in.close();
out.close();
} catch(IOException ex) {
// TODO: handle exception
}
}
private String serverUrl() {
return "http://hfus.com";
}
}

Websockets Tomcat 7 does not work in existing project

I try to run a websocket server in a Java project that was running on Tomcat6. I have set up a Tomcat 7 server where the project now is running on.
First I tried to run the socket example of Tomcat7. This run perfectly. I copied this class to my old project. When I run the old project again all the functionalities are working like before but only the websocket server doe not work.
This is the ChatAnnotation class that I have copied from the examples from Tomcat to my old project.
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.apache.log4j.Logger;
#ServerEndpoint(value = "/websocket/chat")
public class ChatAnnotation {
private static Logger logger = Logger.getLogger(ChatAnnotation.class);
private static final String GUEST_PREFIX = "Guest";
private static final AtomicInteger connectionIds = new AtomicInteger(0);
private static final Set<ChatAnnotation> connections = new CopyOnWriteArraySet<ChatAnnotation>();
private final String nickname;
private Session session;
public ChatAnnotation() {
nickname = GUEST_PREFIX + connectionIds.getAndIncrement();
logger.info("ws instance");
}
#OnOpen
public void start(Session session) {
this.session = session;
connections.add(this);
String message = String.format("* %s %s", nickname, "has joined.");
broadcast(message);
}
#OnClose
public void end() {
connections.remove(this);
String message = String.format("* %s %s", nickname, "has disconnected.");
broadcast(message);
}
#OnMessage
public void incoming(String message) {
// Never trust the client
String filteredMessage = String.format("%s: %s", nickname, message.toString());
broadcast(filteredMessage);
}
#OnError
public void onError(Throwable t) throws Throwable {
logger.error("Chat Error: " + t.toString(), t);
}
private static void broadcast(String msg) {
for (ChatAnnotation client : connections) {
try {
synchronized (client) {
client.session.getBasicRemote().sendText(msg);
}
} catch (IOException e) {
logger.debug("Chat Error: Failed to send message to client", e);
connections.remove(client);
try {
client.session.close();
} catch (IOException e1) {
// Ignore
}
String message = String.format("* %s %s", client.nickname, "has been disconnected.");
broadcast(message);
}
}
}
}
I have noting added in my web.xml. In my old project are also tcpsockets used can this be the problem?
Can anyone help me with this problem?
EDIT
Class added:
import java.util.HashSet;
import java.util.Set;
import javax.websocket.Endpoint;
import javax.websocket.server.ServerApplicationConfig;
import javax.websocket.server.ServerEndpointConfig;
import org.apache.log4j.Logger;
public class ExamplesConfig implements ServerApplicationConfig {
private static Logger log = Logger.getLogger(ChatAnnotation.class);
public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> endpointClasses) {
Set<ServerEndpointConfig> result = new HashSet<ServerEndpointConfig>();
log.info("getEndpointConfigs");
return result;
}
public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scanned) {
log.info("getAnnotatedEndpointClasses");
return scanned;
}
}
Java websocket server use return value of ServerApplicationConfig interface to deploy programmatic endpoints and for annotated endpoints.
For Tomcat example, if you change the package name of ChatAnnotation. You have to modify websocket.ExamplesConfig too.
public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scanned) {
// Deploy all WebSocket endpoints defined by annotations in the examples
// web application. Filter out all others to avoid issues when running
// tests on Gump
Set<Class<?>> results = new HashSet<>();
for (Class<?> clazz : scanned) {
String name = clazz.getPackage().getName();
boolean ok = name.startsWith("websocket.");
if (ok) {
results.add(clazz);
}
}
return scanned;
}
The getAnnotatedEndpointClasses(scanned) only return classes which package name start with websocket. Unmatched classes will not deployed even they have #ServerEndpoint declarations.

Start elasticsearch within gradle build for integration tests

Is there a way to start elasticsearch within a gradle build before running integration tests and afterwards stop elasticsearch?
My approach so far is the following, but this blocks the further execution of the gradle build.
task runES(type: JavaExec) {
main = 'org.elasticsearch.bootstrap.Elasticsearch'
classpath = sourceSets.main.runtimeClasspath
systemProperties = ["es.path.home":"$buildDir/elastichome",
"es.path.data":"$buildDir/elastichome/data"]
}
For my purpose i have decided to start elasticsearch within my integration test in java code.
I've tried out ElasticsearchIntegrationTest but that didn't worked with spring, because it didn't harmony with SpringJUnit4ClassRunner.
I've found it easier to start elasticsearch in the before method:
My test class testing some 'dummy' productive code (indexing a document):
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.ImmutableSettings.Builder;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.indices.IndexAlreadyExistsException;
import org.elasticsearch.node.Node;
import org.elasticsearch.node.NodeBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class MyIntegrationTest {
private Node node;
private Client client;
#Before
public void before() {
createElasticsearchClient();
createIndex();
}
#After
public void after() {
this.client.close();
this.node.close();
}
#Test
public void testSomething() throws Exception {
// do something with elasticsearch
final String json = "{\"mytype\":\"bla\"}";
final String type = "mytype";
final String id = index(json, type);
assertThat(id, notNullValue());
}
/**
* some productive code
*/
private String index(final String json, final String type) {
// create Client
final Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", "mycluster").build();
final TransportClient tc = new TransportClient(settings).addTransportAddress(new InetSocketTransportAddress(
"localhost", 9300));
// index a document
final IndexResponse response = tc.prepareIndex("myindex", type).setSource(json).execute().actionGet();
return response.getId();
}
private void createElasticsearchClient() {
final NodeBuilder nodeBuilder = NodeBuilder.nodeBuilder();
final Builder settingsBuilder = nodeBuilder.settings();
settingsBuilder.put("network.publish_host", "localhost");
settingsBuilder.put("network.bind_host", "localhost");
final Settings settings = settingsBuilder.build();
this.node = nodeBuilder.clusterName("mycluster").local(false).data(true).settings(settings).node();
this.client = this.node.client();
}
private void createIndex() {
try {
this.client.admin().indices().prepareCreate("myindex").execute().actionGet();
} catch (final IndexAlreadyExistsException e) {
// index already exists => we ignore this exception
}
}
}
It is also very important to use elasticsearch version 1.3.3 or higher. See Issue 5401.

Using JAVA RMI in Android application

I've read lots of threads about this issue, and i couldnt see a 'real' solution for it.
I made a java project - which is a rmi server and i have an android application which suppose to be also a rmi client.
When i checked if the server works I wasn't wise enough to test the client on an android project and i made a test client on a simple java project.
Now when i'm trying to connect my android application to server i fail because the android project doesn't recognize the java rmi package.
Why that happen? what should I do?
You can also use the following library LipeRMI
Here is an example of a Android client interacting with Java Server via LipeRMI.
Create the Following 2 classes and a interface for Java application.
//TestService.java
package test.common;
public interface TestService {
public String getResponse(String data);
}
//TestServer.java
import java.io.IOException;
import java.net.Socket;
import test.common.TestService;
import lipermi.exception.LipeRMIException;
import lipermi.handler.CallHandler;
import lipermi.net.IServerListener;
import lipermi.net.Server;
public class TestServer implements TestService {
public TestServer() {
try {
CallHandler callHandler = new CallHandler();
callHandler.registerGlobal(TestService.class, this);
Server server = new Server();
server.bind(7777, callHandler);
server.addServerListener(new IServerListener() {
#Override
public void clientDisconnected(Socket socket) {
System.out.println("Client Disconnected: " + socket.getInetAddress());
}
#Override
public void clientConnected(Socket socket) {
System.out.println("Client Connected: " + socket.getInetAddress());
}
});
System.out.println("Server Listening");
} catch (LipeRMIException | IOException e) {
e.printStackTrace();
}
}
#Override
public String getResponse(String data) {
System.out.println("getResponse called");
return "Your data: " + data;
}
}
//TestMain.java
public class TestMain {
public static void main(String[] args) {
TestServer testServer = new TestServer();
}
}
Android client:
//MainActivity.java
package com.example.lipermidemoandroidclient;
import java.io.IOException;
import test.common.TestService;
import lipermi.handler.CallHandler;
import lipermi.net.Client;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private String serverIP = "192.168.1.231";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnGet = (Button) findViewById(R.id.btnGet);
btnGet.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
new Conn().execute();
}
});
}
class Conn extends AsyncTask<Void, Void, MainActivity> {
#Override
protected MainActivity doInBackground(Void... params) {
Looper.prepare();
try {
CallHandler callHandler = new CallHandler();
Client client = new Client(serverIP, 7777, callHandler);
TestService testService = (TestService) client.getGlobal(TestService.class);
String msg = testService.getResponse("qwe");
//Toast.makeText(MainActivity.this, testService.getResponse("abc"), Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
client.close();
} catch (IOException e) {
e.printStackTrace();
}
Looper.loop();
return null;
}
}
}
//TestService.java
package test.common;
public interface TestService {
public String getResponse(String data);
}
Add the LipeRMI library to both the projects
Make sure you add INTERNET permission in Android project
Also make sure you have the TestService.java file placed in same package name at both places for eg. test.common package here
Also change value of serverIP variable in Android MainActivity.java to the IP of the machine running the Java code.
I had the same problem and changed my communication to socket communication!
As far as I could figure out Java.rmi unfortunately does not come with Android and therefore it's not possible to use it.
However there are some more disucssions in this post.
Android doesn't support RMI. You should change to socket or raw TCP communication.

Categories