Replacing files with WebClient - webclient

I'm testing the following code for replacing files on a https site via C# code, but it has no effect and
generates no exception. (Downloading files works fine).
try
{
using (System.Net.WebClient client = new System.Net.WebClient())
{
client.Credentials = new System.Net.NetworkCredential(username, password);
//www.testsite.com is just an example - testing is done with an actual site:
client.UploadFile("https://www.testsite.com/testfolder/testpage.html", #"C:\testuploads\testpage.html");
//same effect using the 3-param version - no effect + no exception:
//client.UploadFile("https://www.testsite.com/testfolder/testpage.html", System.Net.WebRequestMethods.Ftp.UploadFile, #"C:\testuploads\testpage.html");
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}
This post mentioned the need for server-side code:
WebClient UploadFile Does Not Work
But how does an FTP client tool such as FileZilla Client accomplish this? Surely it doesn't install server-side
code. (FileZilla Client replaces the file without issue).

Related

Hosting a web server in a local enviroment using only Flutter

Is it possible to host a Flutter web app on a local environment using a Flutter desktop-based app?
The google-search for a solution like this can be difficult, since it involves many keywords that lead to similar situations (online hosting when you need a local solution, command-line only solution, and so on).
After some digging, I ended up using the shelf package to deploy my own Flutter web app on a local network. I developed this for Windows only, so I can't guarantee it will work on other platforms.
First thing to do is obviously adding the shelf package in your pubspec.yaml: after that, this is how my main method looks like
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf/shelf.dart' as shelf;
import 'package:shelf_router/shelf_router.dart' as shelf_router;
[...]
void main() async{
[...]
var secureContext = SecurityContext();
try {
//privKey and cert are the String names of the two files for the SSL connection,
//placed in the root directory of the flutter project or along with the .exe file (when released)
secureContext.usePrivateKey(privKey);
secureContext.useCertificateChain(cert);
} catch (error) {
logger.e("Error on init SecurityContext");
}
try {
//this is the handler that deploys the files contained in 'webAppFolder': I just simply pasted the result of
//the flutter webapp building inside (the index.html file is the default one for flutter web)
//and put the folder in the root of the flutter project (or, again, in the same folder with the .exe file when released)
final _staticHandler = createStaticHandler("webAppFolder", defaultDocument: 'index.html');
//this I kept just for a reminder on how to deploy a static page, if needed
final _router = shelf_router.Router()
..get(
'/time',
(request) => shelf.Response.ok(DateTime.now().toUtc().toIso8601String()),
);
final cascade = shelf.Cascade()
.add(_staticHandler)
.add(_router);
try {
var server = await shelf_io.serve(
cascade.handler,
InternetAddress.anyIPv4,
mainPort, //this is the number of the port on which the webapp is deployed (I load this from a .ini file beforehand
securityContext: secureContext,
);
// Enable content compression
server.autoCompress = true;
logger.i("Serving at https://${server.address.host}:${server.port}");
} catch (err) {
logger.e("Error while serving");
logger.e(err.toString());
}
} catch (err) {
logger.e("Error while creating handler");
logger.e(err.toString());
}
runApp(MaterialApp(
[...]
This is the part related to the deploy of a web app: since the flutter desktop app already provides a GUI, I used that to add some maintenance and testing utilities to check if everything is working fine.
For more details regarding shelf, refer to their API on their pub.dev page.

Embedded Jetty Server giving Same response for different urls , without restarting its not working,

I have developed the embedded jetty server to implement the rest service.
I have setup the eclipse project in the eclipse.
I have written the sample program which returns some details through rest url,
I was successfully compiled the program and created a Runnable jar.
I was successfully able to run the Jar files and the server started and running on the port which i gave ,
I have the testing url
http://localhost:1234/getuser/1
it gave me the user details in the response
<username>test1</username>
I ran the same url with different id no
http://localhost:1234/getuser/2
Again it gave me the same result,
`<username>test1</username>`
So i have restarted the server and then it got me the proper details,
<username>test2</username>
public static void main(String[] args) {
// TODO Auto-generated method stub
ServletContextHandler context = new
ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
Server jettyServer = new Server(1234);
jettyServer.setHandler(context);
ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);
jerseyServlet.setInitParameter("jersey.config.server.provider.classnames", org.test.test.getuser.class.getCanonicalName());
try {
jettyServer.start();
jettyServer.join();
} catch (Exception e) {
e.printStackTrace();
} finally{
jettyServer.destroy();
}
}
Without restarting the jetty web server how to get the proper results.
Is there any thing i need to add in the code to get it worked.
or any settings i need to do for this auto refresh?
I have found the answer, jetty server was able to refresh automatically, there was a object refresh didnt happened in the back end, resolved it from myside and it worked

How to receive messages in a GWT App using Kaazing Websockets <type>proxy</type> configuration?

I'm trying to build a GWT (2.4.0) application that can communicate (full-duplex) with a server using a text-based protocol. To accomplish this I'm using Kaazing Websocket Gateway Version 3.3.2 to act as a proxy.
GWT App <-----[websocket]-----> Kaazing <-----[tcp]-----> Backend Server
This is my Kaazing configuration:
<service>
<accept>ws://127.0.0.1:9444/foobar</accept>
<connect>tcp://localhost:50189</connect>
<type>proxy</type>
<cross-site-constraint>
<allow-origin>http://127.0.0.1:8888</allow-origin>
</cross-site-constraint>
</service>
This setup works with the Java implementation of the Kaazing client. Now I want to use this service in a GWT application.
This is my Code for the GWT client implementation:
WebSocket ws;
try {
ws = new WebSocket("ws://127.0.0.1:9444/foobar");
ws.addCloseHandler(new CloseHandler() {
#Override
public void onClose(CloseEvent ev) {
}
});
ws.addMessageHandler(new MessageHandler() {
#Override
public void onMessage(MessageEvent ev) {
System.out.println(ev.getData());
}
});
ws.addOpenHandler(new OpenHandler() {
#Override
public void onOpen(OpenEvent ev) {
}
});
} catch (WebSocketException e) {
e.printStackTrace();
}
The GWT client can successfully send text to the backend server. It just can't process any response from the server. A JavaScript Exception is thrown as soon as ev.getData() is called.
Uncaught JavaScript exception [Uncaught java.lang.ClassCastException: com.google.gwt.core.client.JavaScriptObject$ cannot be cast to java.lang.String]
If I change the WebSocket address in the code above to ws://127.0.0.1:9444/echo to use the Kaazing echo service, any text I send is successfully received by the GWT application. If I change the service back to proxy (or broadcast) the above JavaScript exception is thrown every time a message from the server is received.
The same code in a Java program (using the Kaazing java client) works just fine.
As I am no GWT expert, is there any way I can further debug the problem or is there a simple solution I just fail to see?
I believe I've seen that issue before, do you mind sharing your gwtclient.gwt.xml file content? Or, maybe, try adding '' or '' depending on whether you are using ByteSocket or WebSocket in the 'gwtclient.gwt.xml' of the GWT client.
Hope this helps,
-Marcelo

Eclipse base HTML5 Websocket and GlassFish

Env for project: -
Eclipse 3.6 (Eclipse-jee-helios) + HTML5 + JavaScript + Websocket + (grizzly) Glassfish 3.1.1
I have deployed sample project and able to run using GF.
When i try to connect websocket it always call onClose.
I tried: -
asadmin set configs.config.server-config.network-config.protocols.protocol.http-listener-1.http.websockets-support-enabled=true
GF 3.1.1 supports web socket (Downloaded from http://glassfish.java.net/downloads/3.1.1-final.html)
Browser like safari and Google Chrome supports websocket (i am using latest browser and checked with http://websocket.org/echo.html URL)
Java Script:-
var webSocket;
$(document).ready(
function() {
**var URL = "ws://localhost:8080/SampleGF/WebSocketChatServlet";**
//Tried using and lot of combination of URLS
var URL = "ws://localhost:8080/";
var URL = "ws://localhost:8080/SampleGF";
var URL = "ws://localhost:8080/SampleGF/WebSocketChatServlet";
webSocket = new WebSocket(URL);
//alert("WebSockets are " + (window.WebSocket ? "" : "not ") + "supported");
webSocket.onopen = function(event) {
alert("OPEN")
}
webSocket.onmessage = function(event) {
var $textarea = $('#messages');
$textarea.val($textarea.val() + event.data + "\n");
$textarea.animate({
scrollTop : $textarea.height()
}, 1000);
}
webSocket.onclose = function(event) {
alert("CLOSE")
}
});
function sendMessage() {
var message = $('#username').val() + ":" + $('#message').val();
webSocket.send(message);
$('#message').val('');
}
i have used ChatSocket.java, WebSocketChatServlet.java, ChatApplication.java as it is from below link: -
http://java.dzone.com/articles/creating-websocket-chat
i have added servlet-api.jar in my project library.
Ref. Link: - http://tech.amikelive.com/node-269/eclipse-quick-tip-resolving-error-the-import-javaxservlet-cannot-be-resolved/
Web.xml: -
I have added servlet and servlet-mapping as below:
servlet
description WebSocketChatServlet description
servlet-name WebSocketChatServlet servlet-name
servlet-class org.trivadis.websocket.servlet.WebSocketChatServlet servlet-class
servlet
servlet-mapping
servlet-name WebSocketChatServlet servlet-name
url-pattern /WebSocketChatServlet url-pattern
servlet-mapping
I am not sure what i am doing wrong....
How can i check URL i am using is correct or not for websocket.
GF location is D:\glassfish3\glassfish for my project.
Project location D:\workspace\SampleGF
Another reason: -
Even I tried WAR sample from below link: -
http://jarvana.com/jarvana/search?search_type=project&project=grizzly-websockets-chat
WAR File Name: -grizzly-websockets-chat-1.9.45.war
I have imported above war file in Eclipse and deployed it on glassfish 3.1.1 server. After running it application always call onclose event.
I have executed below command: -
asadmin set configs.config.server-config.network-config.protocols.protocol.http-listener-1.http.websockets-support-enabled=true
and I am using browser like safari and Google Chrome supports websocket (i have tested it with below link http://websocket.org/echo.html URL)
Can anyone help me out…..
It's been months since I tried to run published sample-code against grizzly. I may be out of date, but it didn't work when I tried it. The guy who published the sample eventually admitted problems in the discussion posts below his article. Since I haven't tried it since, I don't know whether it's been fixed yet; i.e. I don't have confirmation that grizzly works yet. (If someone knows of a working sample, I'm as interested as you are.)
In the mean time, you can try this alternative for running your client code. You can even check what you're doing against the free downloadable JavaScript code if you wish.
http://highlevellogic.blogspot.com/2011/09/websocket-server-demonstration_26.html
If you get your code to work against this server, then try again with grizzly. I'll be interested in the results.

Has anyone successfully deployed a GWT app on Heroku?

Heroku recently began supporting Java apps. Looking through the docs, it seems to resemble the Java Servlet Standard. Does anyone know of an instance where a GWT app has been successfully deployed on Heroku? If so, are there any limitations?
Yes, I've got a successful deployment using the getting started with Java instructions here:
http://devcenter.heroku.com/articles/java
I use the Maven project with appassembler plugin approach but added gwt-maven-plugin to compile a GWT app during the build.
When you push to heroku you see the GWT compile process running, on one thread only so quite slow but it works fine.
The embedded Jetty instance is configured to serve up static resources at /static from src/main/resources/static and I copy the compiled GWT app to this location during the build and then reference the .nocache.js as normal.
What else do you want to know?
You've got a choice, either build the Javascript representation of your GWT app locally into your Maven project, commit it and the read it from your app, or to generate it inside Heroku via the gwt-maven-plugin as I mentioned.
The code to serve up files from a static location inside your jar via embedded Jetty is something like this inside a Guice ServletModule:
(See my other answer below for a simpler and less Guice-driven way to do this.)
protected void configureServlets() {
bind(DefaultServlet.class).in(Singleton.class);
Map<String, String> initParams = new HashMap<String, String>();
initParams.put("pathInfoOnly", "true");
initParams.put("resourceBase", staticResourceBase());
serve("/static/*").with(DefaultServlet.class, initParams);
}
private String staticResourceBase() {
try {
return WebServletModule.class.getResource("/static").toURI().toString();
}
catch (URISyntaxException e) {
e.printStackTrace();
return "couldn't resolve real path to static/";
}
}
There's a few other tricks to getting embedded Jetty working with guice-servlet, let me know if this isn't enough.
My first answer to this turned out to have problems when GWT tried to read its serialization policy. In the end I went for a simpler approach that was less Guice-based. I had to step through the Jetty code to understand why setBaseResource() was the way to go - it's not immediately obvious from the Javadoc.
Here's my server class - the one with the main() method that you point Heroku at via your app-assembler plugin as per the Heroku docs.
public class MyServer {
public static void main(String[] args) throws Exception {
if (args.length > 0) {
new MyServer().start(Integer.valueOf(args[0]));
}
else {
new MyServer().start(Integer.valueOf(System.getenv("PORT")));
}
}
public void start(int port) throws Exception {
Server server = new Server(port);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setBaseResource(createResourceForStatics());
context.setContextPath("/");
context.addEventListener(new AppConfig());
context.addFilter(GuiceFilter.class, "/*", null);
context.addServlet(DefaultServlet.class, "/");
server.setHandler(context);
server.start();
server.join();
}
private Resource createResourceForStatics() throws MalformedURLException, IOException {
String staticDir = getClass().getClassLoader().getResource("static/").toExternalForm();
Resource staticResource = Resource.newResource(staticDir);
return staticResource;
}
}
AppConfig.java is a GuiceServletContextListener.
You then put your static resources under src/main/resources/static/.
In theory, one should be able to run GWT using the embedded versions of Jetty or Tomcat, and bootstrap the server in main as described in the Heroku Java docs.