Java Code Examples for fi.iki.elonen.NanoHTTPD

The following are top voted examples for showing how to use fi.iki.elonen.NanoHTTPD. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: VBrowser-Android   File: ServerRunner.java   Source Code and License 6 votes vote down vote up
public static void executeInstance(NanoHTTPD server) {
    try {
        server.start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
    } 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");
}
 
Example 2
Project: Ships   File: HttpCacheTileServer.java   Source Code and License 6 votes vote down vote up
/**
 * Start the caching tiles server
 * @return TRUE when server is available
 */
public boolean startServer(){
       final String tag="startServer - ";
	boolean result=false;

	if (!running){
           final int cleanup = cleanupOldFiles();
           Log.i(TAG, tag + "Deleted: " + cleanup + " files from caching tile server.");

           try {
			start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
			Log.i(TAG,tag+"Running! Point your browser to http://localhost:8181/ \n");
		} catch (IOException e) {
			Log.e(TAG,tag, e);
		}
		running=true;
		result=true;
	} else {
		result=true;
	}
	return result;
}
 
Example 3
Project: Biliomi   File: WebhookReceiver.java   Source Code and License 6 votes vote down vote up
private void handleSessionInput(NanoHTTPD.IHTTPSession session) {
  if (notificationHandlers.containsKey(session.getUri())) {
    NotificationHandler notificationHandler = notificationHandlers.get(session.getUri());
    String lengthHeader = session.getHeaders().getOrDefault("content-length", null);
    int contentLength = NumberConverter.asNumber(lengthHeader).withDefault(0).toInteger();
    byte[] buffer = new byte[contentLength];

    try {
      session.getInputStream().read(buffer, 0, contentLength);
      String data = new String(buffer).trim();

      if (StringUtils.isNotEmpty(data)) {
        WebhookNotification notification = notificationHandler.unmarshalNotification(data);

        if (!this.notificationIdHistory.contains(notification.getId())) {
          logger.debug("New notification on topic: " + notification.getTopic());
          this.notificationIdHistory.add(notification.getId(), 1, TimeUnit.HOURS);
          //noinspection unchecked Unchecked error can never occur, since the notification is unmarshalled by the handler
          notificationHandler.handleNotification(eventBus, notification);
        }
      }
    } catch (IOException e) {
      logger.error("Failed reading input", e);
    }
  }
}
 
Example 4
Project: r2cloud   File: StaticController.java   Source Code and License 6 votes vote down vote up
public Response doGet(IHTTPSession session) {
	String uri = session.getUri();
	String path = uri.substring(getRequestMappingURL().length());
	File result = new File(basePath, path);
	String requestCanonicalPath;
	try {
		requestCanonicalPath = result.getCanonicalPath();
	} catch (IOException e1) {
		return new503ErrorResponse();
	}
	//prevent escape from configured base directory
	if (!requestCanonicalPath.startsWith(canonicalBasePath) || !result.exists()) {
		return NanoHTTPD.newFixedLengthResponse(fi.iki.elonen.NanoHTTPD.Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "not found");
	}
	try {
		return NanoHTTPD.newFixedLengthResponse(fi.iki.elonen.NanoHTTPD.Response.Status.OK, getMimeType(uri), new FileInputStream(result), result.length());
	} catch (FileNotFoundException e) {
		return new503ErrorResponse();
	}
}
 
Example 5
Project: UIAutomatorWD   File: KeysController.java   Source Code and License 6 votes vote down vote up
@Override
public NanoHTTPD.Response get(RouterNanoHTTPD.UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) {
    String sessionId = urlParams.get("sessionId");
    Map<String, String> body = new HashMap<String, String>();
    UiDevice mDevice = Elements.getGlobal().getmDevice();
    JSONObject result = null;
    try {
        session.parseBody(body);
        String postData = body.get("postData");
        JSONObject jsonObj = JSON.parseObject(postData);
        JSONArray keycodes = (JSONArray)jsonObj.get("value");
        for (Iterator iterator = keycodes.iterator(); iterator.hasNext();) {
            int keycode = (int) iterator.next();
            mDevice.pressKeyCode(keycode);
        }
        return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(result, sessionId).toString());
    } catch (Exception e) {
        return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(Status.UnknownError, sessionId).toString());
    }
}
 
Example 6
Project: r2-streamer-java   File: ResourceHandler.java   Source Code and License 6 votes vote down vote up
@Override
public Response get(UriResource uriResource, Map<String, String> urlParams, IHTTPSession session) {
    Method method = session.getMethod();
    String uri = session.getUri();
    //Log.d(TAG, "Method: " + method + ", Url: " + uri);

    try {
        EpubFetcher fetcher = uriResource.initParameter(EpubFetcher.class);

        int offset = uri.indexOf("/", 0);
        int startIndex = uri.indexOf("/", offset + 1);
        String filePath = uri.substring(startIndex + 1);
        Link link = fetcher.publication.getResourceMimeType(filePath);
        String mimeType = link.getTypeLink();

        InputStream inputStream = fetcher.getDataInputStream(filePath);
        response = serveResponse(session, inputStream, mimeType);
    } catch (EpubFetcherException e) {
        e.printStackTrace();
        return NanoHTTPD.newFixedLengthResponse(Status.INTERNAL_ERROR, getMimeType(), ResponseStatus.FAILURE_RESPONSE);
    }
    return response;
}
 
Example 7
Project: robo-car   File: WebServer.java   Source Code and License 6 votes vote down vote up
/**
 * Handle the HTML request.
 */
@Override
public Response serve(IHTTPSession session) {
    NanoHTTPD.Response ws = mResponseHandler.serve(session);
    if (ws == null) {
        String uri = session.getUri();
        try {
            switch (uri) {
                case "/":
                    return getHTMLResponse("home.html");
                case "/css/style.css":
                    InputStream inputStream = mAssetManager.open("css/style.css");
                    return new NanoHTTPD.Response(Response.Status.OK, "text/css", inputStream);
                case "/script/script.js":
                    inputStream = mAssetManager.open("script/script.js");
                    return new NanoHTTPD.Response(Response.Status.OK, "text/javascript", inputStream);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return ws;
}
 
Example 8
Project: remotedroid   File: HTTPServer.java   Source Code and License 6 votes vote down vote up
@Override
public Response serve(IHTTPSession session) {
    Response response;
    String uri = session.getUri();

    if (uri.equals("/")){
        uri = "/index.html";
    }
    String mimetype = getMimeType(uri);
    Log.d("HTTPServer","MimeType: "+mimetype);
    if (mimetype != null) {
        //Handle text files
        if (mimetype.contains("text/") || mimetype.contains("image/")){
            response = newFixedLengthResponse(getTextFile(uri.substring(1)));
        } else { //handle binary files
            FileInputStream fcontent = getBinaryFile(uri.substring(1));
            response = NanoHTTPD.newChunkedResponse(Response.Status.OK,mimetype,fcontent);
        }
        response.setMimeType(mimetype);
    } else { //Let API Object handle the request
        response = newFixedLengthResponse(mAPI.handle(session));
        response.setMimeType("application/json");
    }

    //Allow CORS
    response.addHeader("Access-Control-Allow-Origin","*");
    response.addHeader("Access-Control-Allow-Headers","auth-user, auth-password");
    return response;
}
 
Example 9
Project: UIAutomatorWD   File: ElementController.java   Source Code and License 6 votes vote down vote up
@Override
public NanoHTTPD.Response get(RouterNanoHTTPD.UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) {
    String sessionId = urlParams.get("sessionId");
    String elementId = urlParams.get("elementId");
    try {
        Element el = Elements.getGlobal().getElement(elementId);
        JSONObject props = new JSONObject();
        props.put("text", el.element.getText());
        props.put("description", el.element.getContentDescription());
        props.put("enabled", el.element.isEnabled());
        props.put("checkable", el.element.isCheckable());
        props.put("checked", el.element.isChecked());
        props.put("clickable", el.element.isClickable());
        props.put("focusable", el.element.isFocusable());
        props.put("focused", el.element.isFocused());
        props.put("longClickable", el.element.isLongClickable());
        props.put("scrollable", el.element.isScrollable());
        props.put("selected", el.element.isSelected());
        return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(props, sessionId).toString());
    } catch (final Exception e) {
        return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(Status.UnknownError, sessionId).toString());
    }
}
 
Example 10
Project: UIAutomatorWD   File: ElementController.java   Source Code and License 6 votes vote down vote up
@Override
public NanoHTTPD.Response get(RouterNanoHTTPD.UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) {
    String sessionId = urlParams.get("sessionId");
    String elementId = urlParams.get("elementId");
    try {
        Element el = Elements.getGlobal().getElement(elementId);
        final Rect rect = el.element.getVisibleBounds();
        JSONObject res = new JSONObject();
        res.put("x", rect.left);
        res.put("y", rect.top);
        res.put("height", rect.height());
        res.put("width", rect.width());
        return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(res, sessionId).toString());
    } catch (final Exception e) {
        return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(Status.UnknownError, sessionId).toString());
    }
}
 
Example 11
Project: UIAutomatorWD   File: WindowController.java   Source Code and License 6 votes vote down vote up
@Override
public NanoHTTPD.Response get(RouterNanoHTTPD.UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) {
    String sessionId = urlParams.get("sessionId");
    try {
        UiDevice mDevice = Elements.getGlobal().getmDevice();
        Integer width = mDevice.getDisplayWidth();
        Integer height = mDevice.getDisplayHeight();
        JSONObject size = new JSONObject();
        size.put("width", width);
        size.put("height", height);
        return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(size, sessionId).toString());
    } catch(Exception e) {
        return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(Status.UnknownError, sessionId).toString());
    }
}
 
Example 12
Project: UIAutomatorWD   File: AlertController.java   Source Code and License 5 votes vote down vote up
@Override
public NanoHTTPD.Response get(RouterNanoHTTPD.UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) {
    String sessionId = urlParams.get("sessionId");
    JSONObject result = null;
    try {
        acceptAlert();
        return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(result, sessionId).toString());
    } catch (final Exception e) {
        return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(Status.UnknownError, sessionId).toString());
    }
}
 
Example 13
Project: AndroidWeb   File: WebUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 判断请求是否是下载文件
 * @param session
 * @return
 */
public static boolean isRequestFile(NanoHTTPD.IHTTPSession session){
    String uri = session.getUri();          // 获取请求连接,范例:/xxx/yyy/zz.doc
    String ext = getExt(uri);
    if(ext == null){
        return false;
    }
    if(NanoHTTPD.mimeTypes().containsKey(ext)){
        return true;
    }
    return false;
}
 
Example 14
Project: VBrowser-Android   File: ServerRunner.java   Source Code and License 5 votes vote down vote up
public static <T extends NanoHTTPD> void run(Class<T> serverClass) {
    try {
        executeInstance(serverClass.newInstance());
    } catch (Exception e) {
        ServerRunner.LOG.log(Level.SEVERE, "Cound nor create server", e);
    }
}
 
Example 15
Project: Ships   File: HttpCacheTileServer.java   Source Code and License 5 votes vote down vote up
@Override
public Response serve(IHTTPSession session) {
	final String tag = "serve - ";

	Response res = null;
	
	requestCount++;

	final String url = "http:/" + session.getUri(); // URI starts with /
	if (isAllowed(url)) {
           final File imageFile = getImage(url);
           if (imageFile!=null && imageFile.exists()){
               try {
                   res = newFixedLengthResponse(Response.Status.OK, "image/png", new FileInputStream(imageFile), (int) imageFile.length());
                   res.addHeader("Accept-Ranges", "bytes");

                   res.addHeader("Access-Control-Allow-Methods", "DELETE, GET, POST, PUT");
                   res.addHeader("Access-Control-Allow-Origin",  "*");
                   res.addHeader("Access-Control-Allow-Headers", "X-Requested-With");
               } catch (FileNotFoundException e) {
                   Log.e(TAG, tag, e);
               }
           } else {
               Log.e(TAG, tag + "Image file does not exist ("+imageFile+").");
           }
	} else {
		Log.e(TAG, tag + "URL is not allowed.");
	}
	
	if (res==null){
		notFoundCount++;
		res=newFixedLengthResponse(Response.Status.NOT_FOUND,NanoHTTPD.MIME_PLAINTEXT,"Error 404, file not found.");			
	}

	return res;
}
 
Example 16
Project: mobile-store   File: LocalHTTPD.java   Source Code and License 5 votes vote down vote up
private void enableHTTPS() {
    try {
        LocalRepoKeyStore localRepoKeyStore = LocalRepoKeyStore.get(context);
        SSLServerSocketFactory factory = NanoHTTPD.makeSSLSocketFactory(
                localRepoKeyStore.getKeyStore(),
                localRepoKeyStore.getKeyManagers());
        makeSecure(factory);
    } catch (LocalRepoKeyStore.InitException | IOException e) {
        Log.e(TAG, "Could not enable HTTPS", e);
    }
}
 
Example 17
Project: NanoMaven   File: NanoRepositoryRouter.java   Source Code and License 5 votes vote down vote up
@Override
public NanoHTTPD.Response serve(NanoHttpdServer server, NanoHTTPD.IHTTPSession session) {
    System.out.println(session.getUri() + " " + session.getMethod().name());

    try {
        return serveOrCatch(server, session);
    } catch (Exception e) {
        e.printStackTrace();
        return NanoHTTPD.newFixedLengthResponse(Status.INTERNAL_ERROR, NanoHTTPD.MIME_HTML, "Cannot serve request");
    }
}
 
Example 18
Project: android-robocar   File: DebugActivity.java   Source Code and License 5 votes vote down vote up
private void setupWebServer() {
  LocalWebServer localWebServer = new LocalWebServer(this);
  try {
    localWebServer.start(NanoHTTPD.SOCKET_READ_TIMEOUT, true);
  } catch (IOException e) {
    Timber.e(e, "Failed to start local web server.");
  }

  Timber.d("IP address: %s", LocalWebServer.getIpAddress(this));
}
 
Example 19
Project: ja-micro   File: ReadinessCheckServer.java   Source Code and License 5 votes vote down vote up
public synchronized void serveRequests() {
    boolean wasStarted = isReady.getAndSet(true);
    if (! wasStarted) {
        int port = FeatureFlags.getReadinessCheckPort(serviceProps);
        if (port > 0) {
            server = new NanoReadinessServer(port);
            try {
                server.start(NanoHTTPD.SOCKET_READ_TIMEOUT, true);
            } catch (IOException e) {
                logger.warn("Error starting readiness check server", e);
            }
        }
    }
}
 
Example 20
Project: LittleBitLouder   File: NSDSender.java   Source Code and License 5 votes vote down vote up
@Override
public Response serve(IHTTPSession session) {

    if (mNearbyListener != null)
    {
        //Neighbor neighbor = new Neighbor(session.
        //mNearbyListener.foundNeighbor(neighbor);
    }

    if (session.getUri().endsWith(SERVICE_DOWNLOAD_FILE_PATH))
    {
        try {
            return NanoHTTPD.newChunkedResponse(NanoHTTPD.Response.Status.OK, mShareMedia.mMimeType, new FileInputStream(mShareMedia.mFileMedia));
        }
        catch (IOException ioe)
        {
            return NanoHTTPD.newFixedLengthResponse(Response.Status.INTERNAL_ERROR,"text/plain",ioe.getLocalizedMessage());
        }
    }
    else if (session.getUri().endsWith(SERVICE_DOWNLOAD_METADATA_PATH))
    {
        return NanoHTTPD.newFixedLengthResponse(Response.Status.OK,"text/plain",mShareMedia.mMetadataJson);

    }
    else {
        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>";
        }
        return NanoHTTPD.newFixedLengthResponse(msg + "</body></html>\n");
    }
}
 
Example 21
Project: buffer-slayer   File: HttpReporterMetricsExporter.java   Source Code and License 5 votes vote down vote up
@Override
public Response serve(IHTTPSession session) {
  String msg = "{"
      + "\"messages\":" + metrics.messages() + ","
      + "\"messagesDropped\":" + metrics.messagesDropped() + ","
      + "\"queuedMessages\":" + metrics.queuedMessages()
      + "}";
  return newFixedLengthResponse(NanoHTTPD.Response.Status.OK, "application/json", msg);
}
 
Example 22
Project: r2cloud   File: GsonRenderer.java   Source Code and License 5 votes vote down vote up
public Response render(ModelAndView model) {
	IStatus status;
	if (model.getStatus() != null) {
		status = model.getStatus();
	} else {
		status = Status.OK;
	}
	return NanoHTTPD.newFixedLengthResponse(status, MimeType.JSON.getType(), model.getData());
}
 
Example 23
Project: NanoMaven   File: NanoTempFileManager.java   Source Code and License 5 votes vote down vote up
@Override
public NanoHTTPD.TempFile createTempFile(String s) throws Exception {
    NanoTempFile file = new NanoTempFile(NANOHTTPD_TEMP);
    file.prepare();

    return file;
}
 
Example 24
Project: jiracli   File: TestServer.java   Source Code and License 5 votes vote down vote up
private Response serve(IHTTPSession session) {
    String path = session.getUri();
    Map<String, String> parameters = session.getParms();
    LOGGER.debug("Request received: {} {}", path, parameters);
    String resource = resources.getResource(path, parameters);
    if (resource == null) {
        resource = resources.getResource("404");
    }
    if (resource == null) {
        resource = "Not found.";
    }
    return NanoHTTPD.newFixedLengthResponse(Status.OK, NanoHTTPD.MIME_PLAINTEXT, resource);
}
 
Example 25
Project: haven   File: WebServer.java   Source Code and License 5 votes vote down vote up
public WebServer(Context context) throws IOException {
    super(LOCAL_HOST, LOCAL_PORT);
    mContext = context;

    if (!TextUtils.isEmpty(mPassword)) //require a password to start the server
        start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
}
 
Example 26
Project: matrix-embedded-federation   File: JSONServant.java   Source Code and License 5 votes vote down vote up
private NanoHTTPD.Response buildResponse(Object jsonResponse) {
    if (jsonResponse instanceof Response) {
        return (Response) jsonResponse;
    }

    String json = gson.toJson(jsonResponse);
    return HttpUtils.okResponse("application/json", json);
}
 
Example 27
Project: NanoMaven   File: NanoRepositoryRouter.java   Source Code and License 5 votes vote down vote up
public NanoHTTPD.Response serveOrCatch(NanoHttpdServer server, NanoHTTPD.IHTTPSession session) throws Exception {
    switch (session.getMethod()) {
        case GET:
            return get.serve(server, session);
        case PUT:
            return put.serve(server, session);
        default:
            NanoMaven.getLogger().error("Unknown method: " + session.getUri());
            return NanoHTTPD.newFixedLengthResponse(Status.NOT_FOUND, NanoHTTPD.MIME_HTML, "Unknown method");
    }
}
 
Example 28
Project: ultra-debugger   File: HttpServer.java   Source Code and License 5 votes vote down vote up
HttpServer(int port) {
    super(port);
    try {
        start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 29
Project: neo-java   File: LocalControllerNodeCoreRpcRunnable.java   Source Code and License 5 votes vote down vote up
/**
 * the constructor.
 *
 * @param localControllerNode
 *            the local controller node to use.
 */
public LocalControllerNodeCoreRpcRunnable(final LocalControllerNode localControllerNode) {
	this.localControllerNode = localControllerNode;
	httpServer = new NanoHTTPD(localControllerNode.getLocalNodeData().getPort()) {
		@Override
		public Response serve(final IHTTPSession session) {
			return newFixedLengthResponse(processRequest(localControllerNode, session));
		}
	};
}
 
Example 30
Project: phonk   File: PhonkHttpServer.java   Source Code and License 5 votes vote down vote up
private Response serveWebIDE(IHTTPSession session) {
    Response res = null;

    String uri = session.getUri();

    // Clean up uri
    uri = uri.trim().replace(File.separatorChar, '/');
    if (uri.indexOf('?') >= 0) uri = uri.substring(0, uri.indexOf('?'));
    if (uri.length() == 1) uri = "index.html"; // We never want to request just the '/'
    if (uri.charAt(0) == '/') uri = uri.substring(1, uri.length()); // using assets, so we can't have leading '/'

    String mime = getMimeType(uri); // Get MIME type

    // Read file and return it, otherwise NOT_FOUND is returned
    AssetManager am = mContext.get().getAssets();
    try {
        MLog.d(TAG, WEBAPP_DIR + uri);
        InputStream fi = am.open(WEBAPP_DIR + uri);
        res = newFixedLengthResponse(Response.Status.OK, mime, fi, fi.available());
    } catch (IOException e) {
        e.printStackTrace();
        MLog.d(TAG, e.getStackTrace().toString());
        NanoHTTPD.newFixedLengthResponse( Response.Status.NOT_FOUND, MIME_TYPES.get("txt"), "ERROR: " + e.getMessage());
    }

    return res; //NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), inp, fontSize);
}
 
Example 31
Project: UIAutomatorWD   File: RouterNanoHTTPD.java   Source Code and License 5 votes vote down vote up
public Response process(Map<String, String> urlParams, IHTTPSession session) {
    String error = "General error!";
    if (handlerObject != null || handler != null) {
        try {
            Object object = ((handlerObject != null) ? handlerObject : handler.newInstance());
            if (object instanceof UriResponder) {
                UriResponder responder = (UriResponder) object;
                switch (this.method) {
                    case Methods.GET:
                        return responder.get(this, urlParams, session);
                    case Methods.POST:
                        return responder.post(this, urlParams, session);
                    case Methods.PUT:
                        return responder.put(this, urlParams, session);
                    case Methods.DELETE:
                        return responder.delete(this, urlParams, session);
                    default:
                        return responder.other(session.getMethod().toString(), this, urlParams, session);
                }
            } else {
                return NanoHTTPD.newFixedLengthResponse(Status.OK, "text/plain", //
                        new StringBuilder("Return: ")//
                                .append(handler.getCanonicalName())//
                                .append(".toString() -> ")//
                                .append(object)//
                                .toString());
            }
        } catch (Exception e) {
            error = "Error: " + e.getClass().getName() + " : " + e.getMessage();
            LOG.log(Level.SEVERE, error, e);
        }
    }
    return NanoHTTPD.newFixedLengthResponse(Status.INTERNAL_ERROR, "text/plain", error);
}
 
Example 32
Project: UIAutomatorWD   File: ElementController.java   Source Code and License 5 votes vote down vote up
@Override
public NanoHTTPD.Response get(RouterNanoHTTPD.UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) {
    String sessionId = urlParams.get("sessionId");
    try {
        String elementId = urlParams.get("elementId");
        Element element = Elements.getGlobal().getElement(elementId);
        return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(element.getText(), sessionId).toString());
    } catch (final Exception e) {
        return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(Status.UnknownError, sessionId).toString());
    }
}
 
Example 33
Project: Pandomium   File: PandomiumHTTPServer.java   Source Code and License 5 votes vote down vote up
@Override
public Response serve(IHTTPSession session) {
    String uri = session.getUri();

    for (Map.Entry<String, String> route : routes.entrySet()) {
        if (!uri.contains(route.getKey())) {
            continue;
        }

        return NanoHTTPD.newFixedLengthResponse(route.getValue());
    }

    return super.serve(session);
}
 
Example 34
Project: mobile-store   File: LocalHTTPD.java   Source Code and License 4 votes vote down vote up
private Response respond(Map<String, String> headers, String uri) {
    // Remove URL arguments
    uri = uri.trim().replace(File.separatorChar, '/');
    if (uri.indexOf('?') >= 0) {
        uri = uri.substring(0, uri.indexOf('?'));
    }

    // Prohibit getting out of current directory
    if (uri.contains("../")) {
        return createResponse(Response.Status.FORBIDDEN, NanoHTTPD.MIME_PLAINTEXT,
                "FORBIDDEN: Won't serve ../ for security reasons.");
    }

    File f = new File(webRoot, uri);
    if (!f.exists()) {
        return createResponse(Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT,
                "Error 404, file not found.");
    }

    // Browsers get confused without '/' after the directory, send a
    // redirect.
    if (f.isDirectory() && !uri.endsWith("/")) {
        uri += "/";
        Response res = createResponse(Response.Status.REDIRECT, NanoHTTPD.MIME_HTML,
                "<html><body>Redirected: <a href=\"" +
                        uri + "\">" + uri + "</a></body></html>");
        res.addHeader("Location", uri);
        return res;
    }

    if (f.isDirectory()) {
        // First look for index files (index.html, index.htm, etc) and if
        // none found, list the directory if readable.
        String indexFile = findIndexFileInDirectory(f);
        if (indexFile == null) {
            if (f.canRead()) {
                // No index file, list the directory if it is readable
                return createResponse(Response.Status.OK, NanoHTTPD.MIME_HTML,
                        listDirectory(uri, f));
            } else {
                return createResponse(Response.Status.FORBIDDEN, NanoHTTPD.MIME_PLAINTEXT,
                        "FORBIDDEN: No directory listing.");
            }
        } else {
            return respond(headers, uri + indexFile);
        }
    }

    Response response = serveFile(headers, f, getMimeTypeForFile(uri));
    return response != null ? response :
            createResponse(Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT,
                    "Error 404, file not found.");
}
 
Example 35
Project: mobile-store   File: LocalHTTPD.java   Source Code and License 4 votes vote down vote up
/**
 * Serves file from homeDir and its' subdirectories (only). Uses only URI,
 * ignores all headers and HTTP parameters.
 */
private Response serveFile(Map<String, String> header, File file, String mime) {
    Response res;
    try {
        // Calculate etag
        String etag = Integer
                .toHexString((file.getAbsolutePath() + file.lastModified() + String.valueOf(file.length()))
                        .hashCode());

        // Support (simple) skipping:
        long startFrom = 0;
        long endAt = -1;
        String range = header.get("range");
        if (range != null && range.startsWith("bytes=")) {
            range = range.substring("bytes=".length());
            int minus = range.indexOf('-');
            try {
                if (minus > 0) {
                    startFrom = Long.parseLong(range.substring(0, minus));
                    endAt = Long.parseLong(range.substring(minus + 1));
                }
            } catch (NumberFormatException ignored) {
            }
        }

        // Change return code and add Content-Range header when skipping is
        // requested
        long fileLen = file.length();
        if (range != null && startFrom >= 0) {
            if (startFrom >= fileLen) {
                res = createResponse(Response.Status.RANGE_NOT_SATISFIABLE,
                        NanoHTTPD.MIME_PLAINTEXT, "");
                res.addHeader("Content-Range", "bytes 0-0/" + fileLen);
                res.addHeader("ETag", etag);
            } else {
                if (endAt < 0) {
                    endAt = fileLen - 1;
                }
                long newLen = endAt - startFrom + 1;
                if (newLen < 0) {
                    newLen = 0;
                }

                final long dataLen = newLen;
                FileInputStream fis = new FileInputStream(file) {
                    @Override
                    public int available() throws IOException {
                        return (int) dataLen;
                    }
                };
                long skipped = fis.skip(startFrom);
                if (skipped != startFrom) {
                    throw new IOException("unable to skip the required " + startFrom + " bytes.");
                }

                res = createResponse(Response.Status.PARTIAL_CONTENT, mime, fis);
                res.addHeader("Content-Length", String.valueOf(dataLen));
                res.addHeader("Content-Range", "bytes " + startFrom + "-" + endAt + "/"
                        + fileLen);
                res.addHeader("ETag", etag);
            }
        } else {
            if (etag.equals(header.get("if-none-match"))) {
                res = createResponse(Response.Status.NOT_MODIFIED, mime, "");
            } else {
                res = createResponse(Response.Status.OK, mime, new FileInputStream(file));
                res.addHeader("Content-Length", String.valueOf(fileLen));
                res.addHeader("ETag", etag);
            }
        }
    } catch (IOException ioe) {
        res = createResponse(Response.Status.FORBIDDEN, NanoHTTPD.MIME_PLAINTEXT,
                "FORBIDDEN: Reading file failed.");
    }

    return res;
}
 
Example 36
Project: mobile-store   File: BluetoothServer.java   Source Code and License 4 votes vote down vote up
private Response respond(Map<String, String> headers, String uri) {
    // Remove URL arguments
    uri = uri.trim().replace(File.separatorChar, '/');
    if (uri.indexOf('?') >= 0) {
        uri = uri.substring(0, uri.indexOf('?'));
    }

    // Prohibit getting out of current directory
    if (uri.contains("../")) {
        return createResponse(NanoHTTPD.Response.Status.FORBIDDEN, NanoHTTPD.MIME_PLAINTEXT,
                "FORBIDDEN: Won't serve ../ for security reasons.");
    }

    File f = new File(webRoot, uri);
    if (!f.exists()) {
        return createResponse(NanoHTTPD.Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT,
                "Error 404, file not found.");
    }

    // Browsers get confused without '/' after the directory, send a
    // redirect.
    if (f.isDirectory() && !uri.endsWith("/")) {
        uri += "/";
        Response res = createResponse(NanoHTTPD.Response.Status.REDIRECT, NanoHTTPD.MIME_HTML,
                "<html><body>Redirected: <a href=\"" +
                        uri + "\">" + uri + "</a></body></html>");
        res.addHeader("Location", uri);
        return res;
    }

    if (f.isDirectory()) {
        // First look for index files (index.html, index.htm, etc) and if
        // none found, list the directory if readable.
        String indexFile = findIndexFileInDirectory(f);
        if (indexFile == null) {
            if (f.canRead()) {
                // No index file, list the directory if it is readable
                return createResponse(NanoHTTPD.Response.Status.NOT_FOUND, NanoHTTPD.MIME_HTML, "");
            }
            return createResponse(NanoHTTPD.Response.Status.FORBIDDEN, NanoHTTPD.MIME_PLAINTEXT,
                    "FORBIDDEN: No directory listing.");
        }
        return respond(headers, uri + indexFile);
    }

    Response response = serveFile(uri, headers, f, getMimeTypeForFile(uri));
    return response != null ? response :
            createResponse(NanoHTTPD.Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT,
                    "Error 404, file not found.");
}
 
Example 37
Project: mobile-store   File: BluetoothServer.java   Source Code and License 4 votes vote down vote up
/**
 * Serves file from homeDir and its' subdirectories (only). Uses only URI,
 * ignores all headers and HTTP parameters.
 */
Response serveFile(String uri, Map<String, String> header, File file, String mime) {
    Response res;
    try {
        // Calculate etag
        String etag = Integer
                .toHexString((file.getAbsolutePath() + file.lastModified() + String.valueOf(file.length()))
                        .hashCode());

        // Support (simple) skipping:
        long startFrom = 0;
        long endAt = -1;
        String range = header.get("range");
        if (range != null && range.startsWith("bytes=")) {
            range = range.substring("bytes=".length());
            int minus = range.indexOf('-');
            try {
                if (minus > 0) {
                    startFrom = Long.parseLong(range.substring(0, minus));
                    endAt = Long.parseLong(range.substring(minus + 1));
                }
            } catch (NumberFormatException ignored) {
            }
        }

        // Change return code and add Content-Range header when skipping is
        // requested
        long fileLen = file.length();
        if (range != null && startFrom >= 0) {
            if (startFrom >= fileLen) {
                res = createResponse(NanoHTTPD.Response.Status.RANGE_NOT_SATISFIABLE,
                        NanoHTTPD.MIME_PLAINTEXT, "");
                res.addHeader("Content-Range", "bytes 0-0/" + fileLen);
                res.addHeader("ETag", etag);
            } else {
                if (endAt < 0) {
                    endAt = fileLen - 1;
                }
                long newLen = endAt - startFrom + 1;
                if (newLen < 0) {
                    newLen = 0;
                }

                final long dataLen = newLen;
                FileInputStream fis = new FileInputStream(file) {
                    @Override
                    public int available() throws IOException {
                        return (int) dataLen;
                    }
                };
                long skipped = fis.skip(startFrom);
                if (skipped != startFrom) {
                    throw new IOException("unable to skip the required " + startFrom + " bytes.");
                }

                res = createResponse(NanoHTTPD.Response.Status.PARTIAL_CONTENT, mime, fis);
                res.addHeader("Content-Length", String.valueOf(dataLen));
                res.addHeader("Content-Range", "bytes " + startFrom + "-" + endAt + "/"
                        + fileLen);
                res.addHeader("ETag", etag);
            }
        } else {
            if (etag.equals(header.get("if-none-match"))) {
                res = createResponse(NanoHTTPD.Response.Status.NOT_MODIFIED, mime, "");
            } else {
                res = createResponse(NanoHTTPD.Response.Status.OK, mime, new FileInputStream(file));
                res.addHeader("Content-Length", String.valueOf(fileLen));
                res.addHeader("ETag", etag);
            }
        }
    } catch (IOException ioe) {
        res = createResponse(NanoHTTPD.Response.Status.FORBIDDEN, NanoHTTPD.MIME_PLAINTEXT,
                "FORBIDDEN: Reading file failed.");
    }

    return res;
}
 
Example 38
Project: UIAutomatorWD   File: KeysController.java   Source Code and License 4 votes vote down vote up
@Override
public NanoHTTPD.Response.IStatus getStatus() {
    return NanoHTTPD.Response.Status.OK;
}
 
Example 39
Project: mobile-store   File: BluetoothServer.java   Source Code and License 4 votes vote down vote up
private Response createResponse(NanoHTTPD.Response.Status status, String mimeType, InputStream content) {
    return new Response(status.getRequestStatus(), mimeType, content);
}
 
Example 40
Project: textadventurer-server   File: GameSocket.java   Source Code and License 4 votes vote down vote up
public GameSocket(NanoHTTPD.IHTTPSession handshakeRequest, GameDetails gameDetails, Path workingDir) {
    super(handshakeRequest);
    this.gameDetails = gameDetails;
    this.workingDir = workingDir;
}