I am trying to use NanoHTTP to serve up an HTML file with help of Android.
Currently i'm able to do display the page. I'm also new to andriod. The issue is not having a clear picture how to refer the images and css for that html file even after i have taken the files with help of AssetManager. Below i provided the entire code. Could somebody help me on this.
Note: Other permission settings are fine like InternetPermission. Only not having an idea how refer the other supported files (css, images, javascript files) for the html.
package com.web;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import java.io.*;
import java.util.*;
public class MainActivity extends Activity
{
private WebServer server;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AssetManager assetManager = getAssets();
String imagePath = "fileapp/image";
String cssPath = "fileapp/css";
String files[] = null;
try {
files = assetManager.list(imagePath);
Log.i("Image", files[0]);
Log.w("Image", files[0]);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("Image ",e.getMessage());
}
server = new WebServer();
try {
server.start();
} catch(IOException ioe) {
Log.w("Httpd", "The server could not start.");
}
Log.w("Httpd", "Web server initialized.");
}
// DON'T FORGET to stop the server
#Override
public void onDestroy()
{
super.onDestroy();
if (server != null)
server.stop();
}
private class WebServer extends NanoHTTPD {
public WebServer()
{
super(8080);
}
#Override
public Response serve(String uri, Method method,
Map<String, String> header,
Map<String, String> parameters,
Map<String, String> files) {
StringBuilder msg = new StringBuilder("<html><head><title>" + heading + "</title>" +
**"<link href=\"../../../fileapp/css/style.css\" rel=\"stylesheet\">" +**
"</head>"
+ "<body>");
msg.append("**<div class=\"jumbotron-sm\"> <img src=\"../../../fileapp/image/logo.png\">**</div>");
msg.append("<div>My Body Content go here......</div>");
msg.append("</body>"
+ "</html>");
return msg.toString();
}
}
}
Kindly let me know in case of any further details.
Thanks advance for your answers.
Related
I would like to use OpenNLP in my Android project. I imported the JAR and I can use it in my project but when I need to load a TokenizerModel (for example) I do not see how to proceed.
Cheers.
Putting my .bin model files in the assets folder and call the using getAssets() is working pretty fine.
Here is an example (originally written on Stack Overflow Documentation):
Sentence Detection using openNLP using CLI and Java API
using CLI:
$ opennlp SentenceDetector ./en-sent.bin < ./input.txt > output.txt
using API:
import static java.nio.file.Files.readAllBytes;
import static java.nio.file.Paths.get;
import java.io.IOException;
import java.util.Objects;
public class FileUtils {
/**
* Get file data as string
*
* #param fileName
* #return
*/
public static String getFileDataAsString(String fileName) {
Objects.nonNull(fileName);
try {
String data = new String(readAllBytes(get(fileName)));
return data;
} catch (IOException e) {
System.out.println(e.getMessage());
return null;
}
}
}
class sentecedetectorutil:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import opennlp.tools.sentdetect.SentenceDetectorME;
import opennlp.tools.sentdetect.SentenceModel;
public class SentenceDetectorUtil {
private SentenceModel model = null;
SentenceDetectorME sentenceDetector = null;
public SentenceDetectorUtil(String modelFile) {
Objects.nonNull(modelFile);
initSentenceModel(modelFile);
initSentenceDetectorME();
}
private void initSentenceDetectorME() {
sentenceDetector = new SentenceDetectorME(model);
}
private SentenceModel initSentenceModel(String file) {
InputStream modelIn;
try {
modelIn = new FileInputStream(file);
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
return null;
}
try {
model = new SentenceModel(modelIn);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (modelIn != null) {
try {
modelIn.close();
} catch (IOException e) {
}
}
}
return model;
}
public String[] getSentencesFromFile(String inputFile) {
String data = FileUtils.getFileDataAsString(inputFile);
return sentenceDetector.sentDetect(data);
}
public String[] getSentences(String data) {
return sentenceDetector.sentDetect(data);
}
}
}
main class:
public class Main {
public static void main(String args[]) {
SentenceDetectorUtil util = new SentenceDetectorUtil(
"path//to//your//en-sent.bin");
String data = "Welcome to Stackoverflow Documentation.This is the first example in OenNLP.";
String[] sentences = util.getSentences(data);
for (String s : sentences)
System.out.println(s +"\n");
}
}
output will be:
Welcome to Stackoverflow Documentation.
This is the first example in OpenNLP.
And you can find some basic stuff here
lot of examples are covered in the above examples. that must do the work for you.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have used the https://github.com/NanoHttpd/nanohttpd code for reference.
When i ran my simple android application. I am getting "application not supported" error. While running my android application in eclipse.
My main activity code is :
package com.example.nanoservertest;
import java.io.IOException;
import java.util.Map.Entry;
import java.util.Map;
import java.util.Properties;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
public class AndroidWebServerActivity extends Activity {
private static final int PORT = 8085;
private TextView hello;
private MyHTTPD server;
private Handler handler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// hello = (TextView) findViewById(R.id.hello);
}
#Override
protected void onResume() {
super.onResume();
System.out.println("inside resume");
try {
server = new MyHTTPD();
server.stratServer();
//server.start();
} catch (IOException e) {
e.printStackTrace();
}
}
private class MyHTTPD extends NanoHTTPD {
public MyHTTPD() throws IOException {
super(PORT);
}
//Start
public void stratServer(){
ServerRunner.run(MyHTTPD.class);
}
#Override
public Response serve(IHTTPSession session) {
Method method = session.getMethod();
String uri = session.getUri();
System.out.println(method + " '" + uri + "' ");
String msg = "<html><body><h1>Hello server</h1>\n";
Map<String, String> parms = session.getParms();
if (parms.get("username") == null)
msg +=
"<form action='?' method='get'>\n" +
" <p>Your name: <input type='text' name='username'></p>\n" +
"</form>\n";
else
msg += "<p>Hello, " + parms.get("username") + "!</p>";
msg += "</body></html>\n";
return new NanoHTTPD.Response(msg);
}
}
}
And My Server runner class is
import java.io.IOException;
public class ServerRunner {
public static void run(Class serverClass) {
try {
executeInstance((NanoHTTPD) serverClass.newInstance());
} catch (Exception e) {
e.printStackTrace();
}
}
public static void executeInstance(NanoHTTPD server) {
try {
server.start();
} catch (IOException ioe) {
System.err.println("Couldn't start server:\n" + ioe);
System.exit(-1);
}
System.out.println("Server started, Hit Enter to stop.\n");
try {
System.in.read();
} catch (Throwable ignored) {
}
server.stop();
System.out.println("Server stopped.\n");
}
}
I am unable to start my application.
Try to use this library, it seems to respond to your needs:
AndroidAsync
I would like to add a webserver to my android application for uploading small files to the phone.
The user would start the webserver from the phone by hitting a button. He would then see an ip address that can be accessed by any browser from a pc. The website behind this ip address should show a file upload opportunity.
My question is: Is there an open source project similar to my needs? Or how would you recommend doing this?
you can use NanoHttpd link it's very weight android web server that is nicely embbedible..
package .....;
import java.io.IOException;
import java.util.Map.Entry;
import java.util.Properties;
import android.app.Activity;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
public class AndroidWebServerActivity extends Activity {
private static final int PORT = 8765;
private TextView hello;
private MyHTTPD server;
private Handler handler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
protected void onResume() {
super.onResume();
try {
server = new MyHTTPD();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
if (server != null)
server.stop();
}
private class MyHTTPD extends NanoHTTPD {
public MyHTTPD() throws IOException {
super(PORT, null);
}
#Override
public Response serve(String uri, String method, Properties header, Properties parms, Properties files) {
final StringBuilder buf = new StringBuilder();
for (Entry<Object, Object> kv : header.entrySet())
buf.append(kv.getKey() + " : " + kv.getValue() + "\n");
handler.post(new Runnable() {
#Override
public void run() {
}
});
final String html = "<html><head><head><body><h1>Hello, World</h1></body></html>";
return new NanoHTTPD.Response(HTTP_OK, MIME_HTML, html);
}
}
}
I am trying to establish a chatting application between a server and a client, but the application could not run because of this line of code : message = (String) input.readObject();
because at first, inputStream is null ! any one can help please ? here is my code
package com.example.test;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OptionalDataException;
import java.net.Socket;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button send;
private Button connect;
private EditText userText;
private TextView chatWindow;
private String serverIP;
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private Socket connection;
#SuppressLint({ "NewApi", "NewApi", "NewApi" })
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
serverIP = "192.168.1.4";
//userText.setEnabled(false);
send = (Button)findViewById(R.id.button1);
connect = (Button)findViewById(R.id.button2);
chatWindow =(TextView)findViewById(R.id.textView1);
userText = (EditText)findViewById(R.id.editText1);
userText.setHint("Enter your message here");
connect.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//connect to the server
try{
connectToServer();
setupStreams();
}catch(EOFException eofException){
showMessage("\n client terminated the connection");
}catch(IOException ioException){
ioException.printStackTrace();
}
}
});
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String message = userText.getText().toString();
sendMessage(message);
userText.setText("");
}
});
while(true){
try{
message = (String) input.readObject();
showMessage("\n" + message + " NULL ");
chatWindow.refreshDrawableState();
}catch(ClassNotFoundException classNotFoundException){
showMessage("\n I don't know that object type");
}
catch(NullPointerException e){
e.printStackTrace();
}
catch (OptionalDataException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} // end of onCreate
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
//connect to the server
private void connectToServer() throws IOException {
showMessage("Attempting connection... \n");
connection = new Socket( "192.168.1.4", 6789);
showMessage("Connected to " + connection.getInetAddress().getHostName() );
}
//setup streams to send and receive messages
private void setupStreams() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\n Your streams are now good to go! \n ");
}
//whileChatting with server
private void whileChatting() throws IOException{
try{
message = (String) input.readObject();
showMessage("\n" + message + " NULL ");
chatWindow.refreshDrawableState();
}catch(ClassNotFoundException classNotFoundException){
showMessage("\n I don't know that object type");
}
}
//close the streams and sockets
private void closeCrap(){
showMessage("\n closing crap down");
ableToType(false);
try{
output.close();
input.close();
connection.close();
}catch(IOException ioException){
ioException.printStackTrace();
}
}
// gives user permission to type into the text box
private void ableToType(final boolean tof){
userText.setEnabled(tof);
}
// send messages to server
private void sendMessage(String message){
try{
output.writeObject("CLIENT - " + message);
output.flush();
showMessage("\nCLIENT - " + message);
}catch(IOException ioException){
chatWindow.append("\n somethine messed up sending message!");
}
}
//change/update chatWindow
private void showMessage(final String m){
chatWindow.append(m);
chatWindow.refreshDrawableState();
}
} // end of class MainActivity
Your code is definitely not following any good UI guidelines: You are doing network operations on the Main (UI) Thread, and you have an infinite loop in onCreate(). Android should actually offer to force close your app if nothing crashes. Now, a likely cause for the null problem you are facing:
setupStreams() is only called upon a button click. However, your while (true) loop is in the root of onCreate(). This means that as soon as the click listeners are made and set, the loop runs, attempts to read in from input and fails since setupStreams() hasn't been called.
So please don't do away with StrictMode - it's there to help, and thing about your code from an event driven standpoint ("Once X happens, then do Y"). And also get rid of loops in the Main (UI) Thread. Loops are fine for Console windows, but with UIs (which have their own complex lifecycle), you can't do this without freezing a lot of things.
Do all of your network tasks in doInBackground() ofAsyncTask then update your UI variables in onPostExecute(). Something like
public class TalkToServer extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
#Override
protected String doInBackground(String... params) {
//do your work here
return something;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// do something with data here-display it or send to mainactivity
}
Here is the documentation on AsyncTask
Another thing to consider is you are using the variable message in different places which may cause you problems. It looks like you have it defined as a member variable then as a local variable to other methods. You don't want to re-use the same variable name this way. Don't define String message multiple times in the same Activity
I am trying to integrate Minitemplator (http://www.source-code.biz/MiniTemplator/) to an application of android but i am little lost.
I can access to the template file, the template file is in asset directory and i try to get the file at this way:
Uri path = Uri.parse("file:///android_asset/index.html");
and instantiate the object at this way:
MiniTemplator t = new MiniTemplator(path.getPath());
but it send me an io exception that file or folder doesn't exists.
how is the correct way to send the file to instantiate my minitemplator object?
This is the complete code:
package com.kentverger.minitemplator;
import java.io.File;
import java.io.IOException;
import biz.source_code.miniTemplator.MiniTemplator;
import biz.source_code.miniTemplator.MiniTemplator.TemplateSyntaxException;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.webkit.WebView;
public class Template extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_template);
WebView index = (WebView) findViewById(R.id.indexWebView);
Uri path = Uri.parse("file:///android_asset/index.html");
try {
MiniTemplator t = new MiniTemplator(path.getPath());
t.setVariable("titulo", "Hola mundo generado desde java");
String html_code = t.generateOutput();
index.loadData(html_code, "text/html", null);
} catch (TemplateSyntaxException e) {
Log.d("ERROR 1", e.getMessage());
} catch (IOException e) {
Log.d("ERROR 2", e.getMessage());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_template, menu);
return true;
}
}
I solve my problem loading the template from a string instead a html file.
First I have to create a specification object that will content the template String
MiniTemplator.TemplateSpecification templateSpec = new MiniTemplator.TemplateSpecification();
Then add the template String to templateString property
templateSpec.templateText = "<html><body><h1>${hello}</h1></body></html>";
Next we have to instantiate the Minitemplator object with the speciciations object
t = new MiniTemplator(templateSpec);
And we already to change the values of the variables in the template like this:
t.setVariable("hello", "Hola Mundo!");
Thanks a lot :)
MiniTemplator miniTemplator = openHtmlFileFromAssert(activity, "test.html");
Try this method is working and is help to read html file from assert folder
public MiniTemplator openHtmlFileFromAssert(Activity activity, String fileName) {
try {
AssetManager assetManager = activity.getAssets();
InputStream inputStream = assetManager.open(fileName);
MiniTemplator.Builder templateBuilder = new MiniTemplator.Builder();
return templateBuilder.build(inputStream, Charset.defaultCharset());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}