run jetty and display a folder content - android

I have made a working web server with jetty on an android device, but it only displays a static website, does any one know how to display a folder content of the android device? can it be done with a web page or there is a simpler way to do it? I want it similar to when you connect to a tcp server

Serving static content with Jetty can be done using a ResourceHandler.
A simple example
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ResourceHandler;
public class FolderContents {
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
ContextHandler requestContext = new ContextHandler("/filelist");
ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setResourceBase("/path/to/directory/");
resourceHandler.setDirectoriesListed(true);
requestContext.setHandler(resourceHandler);
server.setHandler(requestContext);
server.start();
server.join();
}
}
So, on a request to /filelist/, the directory contents will be printed.

Related

Sendgrid Android plugin init error "java.lang.NoSuchFieldError: No static field INSTANCE of type .../AllowAllHostnameVerifier"

I'm trying the Sendgrid plugin API for Android. I'm following the step on Sendgrid website, which ends with:
import com.sendgrid.*;
import java.io.IOException;
public class Example {
public static void main(String[] args) throws IOException {
Email from = new Email("test#example.com");
String subject = "Sending with SendGrid is Fun";
Email to = new Email("test#example.com");
Content content = new Content("text/plain", "and easy to do anywhere, even with Java");
Mail mail = new Mail(from, subject, to, content);
SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY"));
Request request = new Request();
try {
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
Response response = sg.api(request);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());
System.out.println(response.getHeaders());
} catch (IOException ex) {
throw ex;
}
}
}
This code produce error on:
SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY"));
of:
java.lang.NoSuchFieldError: No static field INSTANCE of type Lorg/apache/http/conn/ssl/AllowAllHostnameVerifier; in class Lorg/apache/http/conn/ssl/AllowAllHostnameVerifier; or its superclasses (declaration of 'org.apache.http.conn.ssl.AllowAllHostnameVerifier' appears in /system/framework/framework.jar!classes3.dex)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.<clinit>(SSLConnectionSocketFactory.java:144)
at org.apache.http.impl.client.HttpClientBuilder.build(HttpClientBuilder.java:966)
at org.apache.http.impl.client.HttpClients.createDefault(HttpClients.java:58)
at com.sendgrid.Client.<init>(Client.java:56)
at com.sendgrid.SendGrid.<init>(SendGrid.java:52)
...
From other answer, I discovered that AllowAllHostnameVerifier has been deprecated since API v22. But I don't have enough knowledge in Android to be able to toying around with third party library and change it into HTTPUrlConnection.
I also stumble upon this sendgrid library that change that particular networking library to Http library, but when I tried to run, I got tons of "duplicate class" error between httpclient-android-4.3.5.1.jar (org.apache.httpcomponents:httpclient-android:4.3.5.1) and httpcore-4.3.2.jar (org.apache.httpcomponents:httpcore:4.3.2).
How can I resolve or work around this problem? I have used the latest Sendgrid plugins (4.4.1), and the same problem still popped up.

Limit access to my endpoints to my Android app only

I'm new to the Google App Engine, and I'm trying to make my first engine and connect it to my Android app. I have walked through this tutorial in order to learn about it:
https://cloud.google.com/endpoints/docs/frameworks/legacy/v1/java/helloendpoints-android-studio
I got it to work fine. I can access my app engine from my android app, and get the wanted response. The problem is, I want to restrict the endpoints of my API to my app's users only.
This is my API method (from the tutorial), and as for now, everyone can access my api's explorer and execute methods in it, as long as they are logged in to any Google account.
I want the users to be able to execute this method from my app only.
This is my app engine java file:
package com.example.Barda.myapplication.backend;
import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.ApiNamespace;
import com.google.api.server.spi.response.UnauthorizedException;
import com.google.appengine.api.users.User;
import javax.inject.Named;
/**
* An endpoint class we are exposing
*/
#Api(
name = "myApi",
version = "v1",
clientIds = {Constants.ANDROID_CLIENT_ID},
audiences="firebase-wiki-race.appspot.com",
namespace = #ApiNamespace(
ownerDomain = "backend.myapplication.Barda.example.com",
ownerName = "backend.myapplication.Barda.example.com",
packagePath = ""
)
)
public class MyEndpoint {
/**
* A simple endpoint method that takes a name and says Hi back
*/
#ApiMethod(name = "sayHi")
public MyBean sayHi(#Named("name") String name) throws UnauthorizedException {
// if (user == null) throw new UnauthorizedException("User is Not Valid");
MyBean response = new MyBean();
response.setData("Hi, " + name);
return response;
}
}
This is constants class:
package com.example.Barda.myapplication.backend;
/**
* Contains the client IDs and scopes for allowed clients consuming your API.
*/
public class Constants {
public static final String ANDROID_CLIENT_ID = "*********************.apps.googleusercontent.com";
}
I have generated using my app's SH-1 and package name the ANDROID_CLIENT_ID.
I have searched online a lot, and read blogs and threads, but I couldn't make it work. Is this a possible thing to do? What am I doing wrong?
You'll want to follow the documentation's guide on adding authorization to the API backend. In this process you define a list of clients that are authorized to use your Endpoint.
Once that's done you can follow the guide on making authenticated calls from Android.

How do I send a serialized object over network stream to a tcp listener in Xamarin?

Can someone show me a code example of how to send serialized objects back and forth from a Xamarin Android application using a BinaryFormatter instead of Json? It's going to be over WiFi inside the Server Farm.
I'm currently trying to port a simple administrative console application over to an Xamarin Android forms application. I don't understand PCL yet or it's lack of [serializable] attribute. I've heard from the guys at Xamarin that I should probably try Android specific Xamarin instead of forms. I'm new to this so I'm not sure. This will be connecting to a custom Windows Service using standard TCPListeners. Any help would be greatly appreciated. Thanks.
This is an example of the type of console code that I am trying to port over.
public static void HeartBeatPulseListener()
{
Int32 hbPort = 8002;
Console.WriteLine("\nStarting Heart Beat Listener on Port: {0}", hbPort.ToString());
TcpListener heartBeatListener = new TcpListener(IPAddress.Any, hbPort);
heartBeatListener.Start();
while (true)
{
using (TcpClient client = heartBeatListener.AcceptTcpClient())
{
Console.BackgroundColor = ConsoleColor.DarkRed;
Console.ForegroundColor = ConsoleColor.Yellow;
NetworkStream netStream = client.GetStream();
IFormatter formater = new BinaryFormatter();
HeartBeatPulse pulseMSG = (HeartBeatPulse)formater.Deserialize(netStream);
if (pulseMSG != null) Console.WriteLine("\nPulse:{0} \n tStamp:{1}\n FROM:{2}\n Instance:{3} \n Original Unique:{4} \n Type: {5}", pulseMSG.Id.ToString(), pulseMSG.TimeStamp.ToString(), pulseMSG.A.ToString(), pulseMSG.ServerCoreInstanceId, pulseMSG.OriginalUnique, pulseMSG.Type);
if (pulseMSG.Roles.Count() > 1)
{
Console.WriteLine("\nRoles:");
foreach (string role in pulseMSG.Roles)
{
Console.WriteLine("\n{0}", role);
}
}
else Console.WriteLine("\nSum Ting Wong");
Console.ResetColor();
}
}
}

How to connect an Android Chat Application to Openfire server

I am trying to connect an Android chat app in Eclipse to my own Openfire server. The code I am using is from the Samsung developers site (http://developer.samsung.com/android/technical-docs/Building-a-Chat-Application) and I am having difficulty in connecting the app to my server.
The problem comes from declaring the connections:
public static final String HOST = "talk.google.com";
public static final int PORT = 5222;
public static final String SERVICE = "gmail.com";
public static final String USERNAME = "userid#gmail.com";
public static final String PASSWORD = "password";
This is the example provided by the site, but I am unsure of what the fields should contain if I am using my own openfire server, as opposed to the example above. If someone could give an example of what I should do to connect to my own server, I would really appreciate it.
Thank you for your time.

Android: Simple way to upload a picture to an image host

I d like to upload a picture to a host like: http://imagerz.com/ .
Any sample for this? I can do a simple POST request, but how I can add the image content to my POST request?
Here is a tutorial that tells you how to send a file via FTP to a server. File upload and download using Java
It shouldn't be very hard to "port" that code into android. (You may have to change some of the classes/methods as some of them may not be implemented in Android's lightweight VM).
There are also other image hosting services that should have an api that you could follow.
EDIT:
As you stated, you wanted to do this with a post request.
I found this great tutorial with the following code:
package com.commonsbook.chap9;
import java.io.File;
import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.MultipartPostMethod;
public class HttpMultiPartFileUpload {
private static String url =
"http://localhost:8080/HttpServerSideApp/ProcessFileUpload.jsp";
public static void main(String[] args) throws IOException {
HttpClient client = new HttpClient();
MultipartPostMethod mPost = new MultipartPostMethod(url);
client.setConnectionTimeout(8000);
// Send any XML file as the body of the POST request
File f1 = new File("students.xml");
File f2 = new File("academy.xml");
File f3 = new File("academyRules.xml");
System.out.println("File1 Length = " + f1.length());
System.out.println("File2 Length = " + f2.length());
System.out.println("File3 Length = " + f3.length());
mPost.addParameter(f1.getName(), f1);
mPost.addParameter(f2.getName(), f2);
mPost.addParameter(f3.getName(), f3);
int statusCode1 = client.executeMethod(mPost);
System.out.println("statusLine>>>" + mPost.getStatusLine());
mPost.releaseConnection();
}
}
Source: http://www.theserverside.com/news/1365153/HttpClient-and-FileUpload
The same issues about porting this code to android as I stated above apply.

Categories

Resources