Dart: How to Implement and install a simple HTTP server - dart

I have been able to run the dart-by-example http-server Hello web server.
The websocket uses port 9223 and the http server uses 8080.
After I do a build I do not find the server side code in build/bin.
What do I do next to install everything so that I could try run ws_server.dart and connect from my browser?
My Editor organization:
Server
packages
bin
packages
fireimager_server.dart (server side websocket handling code)
build
bin
web
lib
communication.dart (common code)
web
index.html
main.css
main.dart
WebsocketClient.dart (client websocket code)

If you follow the package layout convention, you server.dart should be in $PROJECT/bin and your web stuff in $PROJECT/web.
By running pub build you should get a new directory $PROJECT/build/web. Now you can use the following server.dart code to expose this build directory :
library simple_http_server;
import 'dart:io';
import 'package:http_server/http_server.dart' show VirtualDirectory;
void main() {
final MY_HTTP_ROOT_PATH = Platform.script.resolve('../build/web').toFilePath();
final virDir = new VirtualDirectory(MY_HTTP_ROOT_PATH)
..allowDirectoryListing = true;
HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 8080).then((server) {
server.listen((request) {
virDir.serveRequest(request);
});
});
}

Related

Docker: Go server does not respond

I was learning how to dockerize Go Apps. I created a simple REST API
package main
import "github.com/gin-gonic/gin"
func main() {
server := gin.Default()
server.GET("/", func(ctx *gin.Context) {
ctx.JSON(200, "HELLO SERVER")
})
server.Run("127.0.0.1:3000")
}
and here is the Dockerfile
FROM golang:1.18.3-alpine3.16
RUN mkdir /app
COPY . /app
WORKDIR /app
RUN go mod download
RUN go build -o main .
EXPOSE 3000
CMD "/app/main"
Thing is, when build and run the container, it appears the app starts normally as usual
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
- using env: export GIN_MODE=release
- using code: gin.SetMode(gin.ReleaseMode)
[GIN-debug] GET / --> main.main.func1 (3 handlers)
[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
[GIN-debug] Listening and serving HTTP on 127.0.0.1:3000
But here is the issue, when I use Postman and make a get request to 127.0.0.1:3000/, it shows it could not get any response (i.e, the response it gets when there is no such server to connect)
When I run the app using 'go run main.go' it works fine.
It would be really great if you could help me out with this
maybe you should listen on 0.0.0.0:3000
func main() {
server := gin.Default()
server.GET("/", func(ctx *gin.Context) {
ctx.JSON(200, "HELLO SERVER")
})
// server.Run("127.0.0.1:3000")
server.Run("0.0.0.0:3000")
}

.war on tomcat on docker, 404 on servlet

I finally found the motivation to work with Docker : I tried to deploy a basic "hello-world" servlet, on a tomcat running on a docker container.
This servlet works perfectly when I run it on the Tomcat started by intelliJ.
But when I use it with Docker, using this Dockerfile
FROM tomcat:latest
ADD example.war /usr/local/tomcat/webapps/
EXPOSE 8080
CMD ["/usr/local/tomcat/bin/catalina.sh", "run"]
And I build/start the image/container:
docker build -t example .
docker run -p 8090:8080 example
The index.jsp is displayed correctly at localhost:8090/example/, but I get a 404 when trying to access the servlet at localhost:8090/example/hello-servlet
At the same time, I can access localhost:8080/example/hello-servlet, when my non dockerized tomcat runs, and it works well.
Here is the servlet code :
package io.bananahammock.bananahammock_backend;
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
#WebServlet(name = "helloServlet", value = "/hello-servlet")
public class HelloServlet extends HttpServlet {
private String message;
public void init() {
message = "Hello World!";
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>" + message + "</h1>");
out.println("</body></html>");
}
public void destroy() {
}
}
What am I missing?
Since August 31, 2021 (this commit) the Docker image tomcat:latest uses Tomcat 10 (see the list of available tags).
As you are probably aware, software which uses the javax.* namespace does not work on Jakarta EE 9 servers such as Tomcat 10 (see e.g. this question). Therefore:
if it is a new project, migrate to the jakarta.* namespace and test everything on Tomcat 10 or higher,
if it is a legacy project, use another Docker image, e.g. the tomcat:9 tag.

Generate ServiceWorker using workbox 6 - how to import "registerRoute" from "workbox-routing"?

I have upgraded my project to use workbox 6 and have modified my code accordingly.
After injecting manifest (generating serviceWorker.js) my browser reports error:
Service worker error TypeError: ServiceWorker script at
http://127.0.0.1:8080/serviceWorker.js for scope
http://127.0.0.1:8080/ threw an exception during script evaluation. app.js:218:23
I have removed code to determine what causes the error and am now left with:
serviceWorker.js (generated from serviceWroker-base.js)
importScripts('workbox-sw.js');
import { registerRoute } from 'workbox-routing';
import { StaleWhileRevalidate } from 'workbox-strategies';
const CACHE_DYNAMIC_NAME = 'dynamic-DEBUG-001'
webpack.config.js
const {InjectManifest} = require('workbox-webpack-plugin')
const workboxWebpackInjectPlugin = new InjectManifest({
swSrc: './serviceWorker.js'
})
// build WEBPACK CONFIG
const config = {}
//...
config.plugins = [
nodeEnvPlugin,
firebasePlugin,
cssExtractPlugin,
workboxWebpackInjectPlugin,
]
//...
return config
If I remove the imports of registerRoute and StaleWhileRevalidate in serviceWorker.js then the service worker registers successfully - but then I cannot register routes. ;) I have installed workbox-routing and workbox-strategies.
package.json
"scripts": {
"generate:sw": "workbox injectManifest"
},
"dependencies": {
...
"workbox-routing": "^6.0.2",
"workbox-strategies": "^6.0.2"
},
"devDependencies": {
...
"webpack": "^4.41.2"
}
generate:sw is the command I run to inject manifest and create serviceWorker.js.
My suspicion is that the imoprts are not handled correctly? How can I use registerRoute and StaleWhileRevalidate in my service worker?
Kind regards /K
The info at https://developers.google.com/web/tools/workbox/guides/using-bundlers might be helpful.
You don't need to include importScripts('workbox-sw.js');
If you plan on using precaching:
You can run InjectManifest via workbox-webpack-plugin and it will take care of both compiling your service worker (i.e. inlining the ES module imports into a final, runnable service worker file) as well as replacing a self.__WB_MANIFEST inside your service worker file with the actual precache manifest based on the assets in your webpack build.
If you don't plan on using precaching:
You can add your service worker file, including the ES module imports, as a entry point in your webpack config, and that should handle inlining the ES module imports into a final, runnable service worker file.
If you're already using webpack, then your workbox injectManifest step isn't needed. See the previous two points.

when running selenium tests via jenkins on headless firefox browser the screenshots captured is of 0 bytes

I am running my selenium tests via Jenkins on Headless Firefox browser on Cent OS.
I have written a code to capture screenshots on failure which works absolutley fine on my local windows environment but when I run the same script using Jenkins on CentOS the screenshot captured is of 0 bytes
Below is the Java code to capture Screenshot:
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
public class Screen_Capture {
public static void takeDesktopScreenshot(WebDriver driver,String dateFormat,String fileFormat,String screenPath){
File src=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try{
SimpleDateFormat s=new SimpleDateFormat(dateFormat);
String d=s.format(new Date());
FileUtils.copyFile(src, new File(screenPath+d+"."+fileFormat));
}
catch (Exception e) {}
}
}
The Screenshots are captured on Test Failure:
#Override
public void onTestFailure(ITestResult arg0) {
Screen_Capture.takeDesktopScreenshot(driver,dateFormat,fileFormat,screenPath);
log.error("Test Case Failed");
}
The Images saved on Jenkins Workspace is blank(0 bytes)
[Screen File Size is 0 Bytes][1]
Please help me to overcome this issue.
I am also attaching my Build Environment Configuration on Jenkins:
[Build Environment Configuration on Jenkins][2]
[1]: https://i.stack.imgur.com/NBNUD.png
[2]: https://i.stack.imgur.com/qMxPq.png
Hi Sometimes there may be permission issue with jenkins , try giving chmod -R 777 * and also try using chown the folder which download , first try manually and try using jenkins you will know the issue easily.

How to find path to the package directory when the script is running with `pub run` command

I am writing a package that loads additional data from the lib directory and would like to provide an easy way to load this data with something like this:
const dataPath = 'mypackage/data/data.json';
initializeMyLibrary(dataPath).then((_) {
// library is ready
});
I've made two separate libraries browser.dart and standalone.dart, similar to how it is done in the Intl package.
It is quite easy to load this data from the "browser" environment, but when it comes to the "standalone" environment, it is not so easy, because of the pub run command.
When the script is running with simple $ dart myscript.dart, I can find a package path using dart:io.Platform Platform.script and Platform.packageRoot properties.
But when the script is running with $ pub run tool/mytool, the correct way to load data should be:
detect that the script is running from the pub run command
find the pub server host
load data from this server, because there could be pub transformers and we can't load data directly from the file system.
And even if I want to load data directly from the file system, when the script is running with pub run, Platform.script returns /mytool path.
So, the question is there any way to find that the script is running from pub run and how to find server host for the pub server?
I am not sure that this is the right way, but when I am running script with pub run, Package.script actually returns http://localhost:<port>/myscript.dart. So, when the scheme is http, I can download using http client, and when it is a file, load from the file system.
Something like this:
import 'dart:async';
import 'dart:io';
import 'package:path/path.dart' as ospath;
Future<List<int>> loadAsBytes(String path) {
final script = Platform.script;
final scheme = Platform.script.scheme;
if (scheme.startsWith('http')) {
return new HttpClient().getUrl(
new Uri(
scheme: script.scheme,
host: script.host,
port: script.port,
path: 'packages/' + path)).then((req) {
return req.close();
}).then((response) {
return response.fold(
new BytesBuilder(),
(b, d) => b..add(d)).then((builder) {
return builder.takeBytes();
});
});
} else if (scheme == 'file') {
return new File(
ospath.join(ospath.dirname(script.path), 'packages', path)).readAsBytes();
}
throw new Exception('...');
}

Resources