Java Code Examples for fi.iki.elonen.NanoHTTPD#Response

The following examples show how to use fi.iki.elonen.NanoHTTPD#Response . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TorrentRequestProcesser.java    From TVRemoteIME with GNU General Public License v2.0 6 votes vote down vote up
@Override
public NanoHTTPD.Response doResponse(NanoHTTPD.IHTTPSession session, String fileName, Map<String, String> params, Map<String, String> files) {
    if(session.getMethod() == NanoHTTPD.Method.POST){
        switch (fileName){
            case "/torrent/upload":
                saveTorrent(params, files);
                break;
            case "/torrent/play":
                return RemoteServer.createPlainTextResponse(NanoHTTPD.Response.Status.OK, playTorrent(params) ? "ok" : "fail");
        }
    }
    if(RemoteServerFileManager.getPlayTorrentFile().exists()){
        return responseTorrentFileList();
    }else {
        return RemoteServer.createJSONResponse(NanoHTTPD.Response.Status.OK,  "{\"success\":false}");
    }
}
 
Example 2
Source File: ElementController.java    From UIAutomatorWD with MIT 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 3
Source File: UploadRequestProcesser.java    From TVRemoteIME with GNU General Public License v2.0 6 votes vote down vote up
@Override
public NanoHTTPD.Response doResponse(NanoHTTPD.IHTTPSession session, String fileName, Map<String, String> params, Map<String, String> files) {
    String uploadFileName  = params.get("file");
    Boolean autoInstall = "true".equalsIgnoreCase(params.get("autoInstall"));
    String localFilename = files.get("file");
    if(!TextUtils.isEmpty(uploadFileName)) {
        if (!TextUtils.isEmpty(localFilename)) {
            if(autoInstall) {
                if (localFilename.endsWith(".apk")) {
                    //执行安装
                    AppPackagesHelper.installPackage(new File(localFilename), this.context);
                }
                else if (FileUtils.isMediaFile(localFilename)){
                    //执行播放
                    VideoPlayHelper.playUrl(this.context, localFilename, 0, "true".equalsIgnoreCase(params.get("useSystem")));
                }
            }
        }
    }
    if(TextUtils.isEmpty(localFilename)){
        return RemoteServer.createJSONResponse(NanoHTTPD.Response.Status.OK,  "{\"success\":false}");
    }else{
        return RemoteServer.createJSONResponse(NanoHTTPD.Response.Status.OK,  String.format("{\"success\":true, \"filePath\":\"%s\"}", localFilename.replaceAll("\\\\", "\\\\")));
    }
}
 
Example 4
Source File: PlayRequestProcesser.java    From TVRemoteIME with GNU General Public License v2.0 6 votes vote down vote up
@Override
public NanoHTTPD.Response doResponse(NanoHTTPD.IHTTPSession session, String fileName, Map<String, String> params, Map<String, String> files) {
    switch (fileName) {
        case "/play":
            if (!TextUtils.isEmpty(params.get("playUrl"))) {
                VideoPlayHelper.playUrl(this.context, params.get("playUrl"), 0, "true".equalsIgnoreCase(params.get("useSystem")));
            }
            return RemoteServer.createPlainTextResponse(NanoHTTPD.Response.Status.OK,"ok");
        case "/playStop":
            xllib.DownloadManager.instance().taskInstance().stopTask();
            return RemoteServer.createPlainTextResponse(NanoHTTPD.Response.Status.OK,"ok");
        case "/changePlayFFI":
            if(!TextUtils.isEmpty(params.get("speedInterval"))){
                try{
                    GlobalSettings.FastForwardInterval = Integer.valueOf(params.get("speedInterval")) * 1000;
                }catch (NumberFormatException ignored) {
                }
            }
            return RemoteServer.createPlainTextResponse(NanoHTTPD.Response.Status.OK,"ok");
        default:
            return RemoteServer.createPlainTextResponse(NanoHTTPD.Response.Status.NOT_FOUND, "Error 404, file not found.");
    }
}
 
Example 5
Source File: AgentStatusHttpdTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
void shouldRouteToIsConnectedToServerHandler() throws Exception {
    when(session.getMethod()).thenReturn(NanoHTTPD.Method.GET);
    when(session.getUri()).thenReturn("/health/latest/isConnectedToServer");
    when(agentHealthHolder.hasLostContact()).thenReturn(false);

    NanoHTTPD.Response response = this.agentStatusHttpd.serve(session);
    assertThat(response.getStatus()).isEqualTo(NanoHTTPD.Response.Status.OK);
    assertThat(response.getMimeType()).isEqualTo("text/plain; charset=utf-8");
    assertThat(IOUtils.toString(response.getData(), StandardCharsets.UTF_8)).isEqualTo("OK!");
}
 
Example 6
Source File: HttpHandler.java    From gocd with Apache License 2.0 5 votes vote down vote up
NanoHTTPD.Response process() {
    if (isPassed()) {
        return NanoHTTPD.newFixedLengthResponse(Status.OK, "text/plain; charset=utf-8", "OK!");
    } else {
        return NanoHTTPD.newFixedLengthResponse(Status.SERVICE_UNAVAILABLE, "text/plain; charset=utf-8", "Bad!");
    }
}
 
Example 7
Source File: AlertController.java    From UIAutomatorWD with MIT 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 {
        dismissAlert();
        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 8
Source File: FileRequestProcesser.java    From TVRemoteIME with GNU General Public License v2.0 5 votes vote down vote up
@Override
public NanoHTTPD.Response doResponse(NanoHTTPD.IHTTPSession session, String fileName, Map<String, String> params, Map<String, String> files) {
    if(session.getMethod() == NanoHTTPD.Method.GET){
        if(fileName.startsWith("/file/dir/")) {
            return responseDirData(fileName.substring("/file/dir/".length()));
        }else if(fileName.startsWith("/file/download/")){
            return downloadFileData(fileName.substring("/file/download/".length()));
        }
    }
    else if(session.getMethod() == NanoHTTPD.Method.POST) {
        String paths = params.get("paths");
        switch (fileName) {
            case "/file/copy":
                if (!TextUtils.isEmpty(paths)) {
                    batchCopyFile(params.get("targetPath"), paths);
                }
                return RemoteServer.createPlainTextResponse(NanoHTTPD.Response.Status.OK, "ok");
            case "/file/cut":
                if (!TextUtils.isEmpty(paths)) {
                    batchCutFile(params.get("targetPath"),paths);
                }
                return RemoteServer.createPlainTextResponse(NanoHTTPD.Response.Status.OK, "ok");
            case "/file/delete":
                if (!TextUtils.isEmpty(paths)) {
                    batchDeleteFile(paths);
                }
                return RemoteServer.createPlainTextResponse(NanoHTTPD.Response.Status.OK, "ok");
            case "/file/upload":
                return uploadFile(params, files);
        }
    }
    return RemoteServer.createPlainTextResponse(NanoHTTPD.Response.Status.NOT_FOUND, "Error 404, file not found.");
}
 
Example 9
Source File: AgentStatusHttpdTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
void shouldRouteToIsConnectedToServerV1Handler() throws Exception {
    when(session.getMethod()).thenReturn(NanoHTTPD.Method.GET);
    when(session.getUri()).thenReturn("/health/v1/isConnectedToServer");
    when(agentHealthHolder.hasLostContact()).thenReturn(false);

    NanoHTTPD.Response response = this.agentStatusHttpd.serve(session);
    assertThat(response.getStatus()).isEqualTo(NanoHTTPD.Response.Status.OK);
    assertThat(response.getMimeType()).isEqualTo("text/plain; charset=utf-8");
    assertThat(IOUtils.toString(response.getData(), StandardCharsets.UTF_8)).isEqualTo("OK!");
}
 
Example 10
Source File: OtherGetRequestProcesser.java    From TVRemoteIME with GNU General Public License v2.0 5 votes vote down vote up
private NanoHTTPD.Response getSDCardStatResponse(){
    File path = Environment.getExternalStorageDirectory();
    StatFs stat = new StatFs(path.getPath());
    long totalBytes, availableBytes;
    if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2){
        totalBytes = (long)stat.getBlockCount() * stat.getBlockSize();
        availableBytes = (long)stat.getAvailableBlocks() * stat.getBlockSize();
    }else{
        totalBytes = stat.getTotalBytes();
        availableBytes = stat.getAvailableBytes();
    }
    return RemoteServer.createJSONResponse(NanoHTTPD.Response.Status.OK,
            "{\"totalBytes\":" + totalBytes + ", \"availableBytes\":" + availableBytes + "}");
}
 
Example 11
Source File: MBTilesServer.java    From OpenMapKitAndroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Response serve(IHTTPSession session) {
    NanoHTTPD.Response response;
    Method method = session.getMethod();
    String uri = session.getUri();
    Log.d(TAG, method + " '" + uri + "' ");

    Matcher matcher = TILE_PATTERN.matcher(uri);
    if(!matcher.find()) {
        response = new NanoHTTPD.Response(NanoHTTPD.Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "Not found");
    } else {
        String layerName = matcher.group(1);
        int z = Integer.parseInt(matcher.group(2));
        int x = Integer.parseInt(matcher.group(3));
        int y = Integer.parseInt(matcher.group(4));

        MBTiles mbTiles = layers.get(layerName);

        if (mbTiles != null) {
            try {
                byte[] tile = mbTiles.getTile(z, x, y);
                if (tile != null) {
                    response = new NanoHTTPD.Response(NanoHTTPD.Response.Status.OK, "image/png", new ByteArrayInputStream(tile));
                } else {
                    response = new NanoHTTPD.Response(NanoHTTPD.Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "Tile not found");
                }
            } catch(Exception ex) {
                Log.e(TAG, ex.toString());
                response = new NanoHTTPD.Response(NanoHTTPD.Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, ex.toString());
            }
        } else {
            response = new NanoHTTPD.Response(NanoHTTPD.Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "Layer not found");
        }
    }

    return response;
}
 
Example 12
Source File: SessionController.java    From UIAutomatorWD with MIT License 4 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");
    return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(Status.NoSuchElement, sessionId).toString());
}
 
Example 13
Source File: ContextController.java    From UIAutomatorWD with MIT License 4 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");
    return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(Status.NoSuchElement, sessionId).toString());
}
 
Example 14
Source File: HttpDConnectSDKTest.java    From DeviceConnect-Android with MIT License 4 votes vote down vote up
private NanoHTTPD.Response newJsonResponse(final String message) {
    return newFixedLengthResponse(NanoHTTPD.Response.Status.OK, "application/json", message);
}
 
Example 15
Source File: FileBroadcastServer.java    From physical-web with Apache License 2.0 4 votes vote down vote up
@Override
public NanoHTTPD.Response serve(IHTTPSession session) {
  InputStream fis = new ByteArrayInputStream(mFile);
  return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.OK,
      mType, fis, mFile.length);
}
 
Example 16
Source File: SessionController.java    From UIAutomatorWD with MIT License 4 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");
    return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(Status.NoSuchElement, sessionId).toString());
}
 
Example 17
Source File: ContextController.java    From UIAutomatorWD with MIT License 4 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");
    return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(Status.NoSuchElement, sessionId).toString());
}
 
Example 18
Source File: UrlController.java    From UIAutomatorWD with MIT License 4 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");
    return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(Status.NoSuchElement, sessionId).toString());
}
 
Example 19
Source File: RequestProcesser.java    From TVRemoteIME with GNU General Public License v2.0 2 votes vote down vote up
/**
 * doResponse
 * @param session
 * @param fileName
 * @param params
 * @param files
 * @return
 */
NanoHTTPD.Response doResponse(NanoHTTPD.IHTTPSession session, String fileName, Map<String, String> params, Map<String, String> files);
 
Example 20
Source File: WebServerPlugin.java    From CameraV with GNU General Public License v3.0 votes vote down vote up
NanoHTTPD.Response serveFile(String uri, Map<String, String> headers, File file, String mimeType);