Restful web services with tomcat 8 - web-services

I'm trying to make a simple example of restful web services and it doesn't work for me. First, i'm using Netbeans for it, I'm using tomcat 8.5.20 and Java EE 7 web and i just have two classes. One is this:
enter image description here
And the other is this:
enter image description here
My intex.html has nothing apart the normal things and my context.xml just has this:
context.xml image
just that.
The web service works pretty nice on my computer, but, when i deploy it in a server which use Apache Tomcat 6.0.45 i have a 404 error and i don't know why because it's the same path that i use when i prove it in my computer. When i use the web service in my pc vs When i prove it in the server.
Thanks for the help, sorry for the bad english :v

Nebeans version: 8.2
Class 1:
import rest.Consumo;
import co.edu.udea.exception.OrgSistemasSecurityException;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("/semestres")
public class HistoriaAcademicaResource {
#GET
#Path("/hola")
#Produces(MediaType.TEXT_PLAIN)
public String hola() {
return "Don't give up";
}
}
Class 2:
import javax.ws.rs.core.Application;
#javax.ws.rs.ApplicationPath("prueba")
public class ApplicationConfig extends Application {
}
Index:
<html>
<head>
<title>SIRVE MALDITA SEA</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>SIRVE PLOX</div>
</body>
</html>
Context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/pruebaREST"/>

Related

Google Compute Engine aiohttp get requests recaptcha

I am trying to send a get request on Google Compute Engine (GCE) to Newegg using aiohttp. Upon doing so, I get back the webpage "Are you a human." However, when I run the same exact code on my local machine, I am able to retrieve the page just fine. Does anyone know why:
I only get the Recaptcha page with GCE, but not my local machine?
Is there any way to avoid or get around this Recaptcha page on GCE?
my code:
import asyncio from bs4 import BeautifulSoup import aiohttp
async def myDriver():
await httpReq()
async def httpReq():
async with aiohttp.ClientSession() as session:
async with session.get("https://www.newegg.com/") as page:
responseCode = page.status
print(responseCode)
pageContent = await page.text()
content = BeautifulSoup(pageContent, 'lxml')
print(content.prettify())
asyncio.run(myDriver())
page reached:
200
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
Are you a human?
</title>
.
.
.
grecaptcha.ready(function()
Notes:
"Debian GNU/Linux 10 (buster)"
python 3.7.3
aiohttp 3.6.3
I've tried similar code with the normal requests library on GCE, and everything works fine, so this is only an issue with aiohttp on GCE.
I must use aiohttp and not the normal requests library for my project

Integrating Cloudflare player into angular 7 for Cloudflare stream

I am trying to get cloudflare stream to work in angular. I have tried the solution given here: Angular attribute for HTML stream.
However, it is always a hit or a miss:
Out of 10 reloads, one loads the player.
But anytime I make a
change to the <stream> tag, and angular re-compiles, the player is
loaded. After this if I refresh the browser, it is a blank screen
again.
The component which shows the video is deep in the tree and the component belongs to a module that is lazy loaded:
In the index.html file:
<!doctype html>
<html lang="en">
<head>
...............
</head>
<body>
<app-root></app-root>
</body>
<script src="https://embed.cloudflarestream.com/embed/r4xu.fla9.latest.js" id="video_embed" defer="" async=""></script>
</html>
In the videoFile.component.ts:
<stream src="5d5bc37ffcf54c9b82e996823bffbb81" height="480px" width="240px" controls></stream>
Found a solution here: https://github.com/angular/angular/issues/13965
So everytime the component loads, the script is removed and reattached using ngOninit, like so:
document.getElementById("video_embed").remove();
let testScript = document.createElement("script");
testScript.setAttribute("id", "video_embed");
testScript.setAttribute("src", "https://embed.cloudflarestream.com/embed/r4xu.fla9.latest.js");
document.body.appendChild(testScript);
If anyone has any other solutions, please do let me know.

Changing the favicon in Flask/Dash

Trying to get the favicon to load I have followed suggestions from the internet:
server = Flask(__name__, static_folder='static')
app = dash.Dash(external_stylesheets=external_stylesheets, server=server)
app.css.config.serve_locally = False
app.scripts.config.serve_locally = True
#server.route('/favicon.ico')
def favicon():
print('Server root path', server.root_path)
return send_from_directory(os.path.join(server.root_path, 'static'),
'dice.ico', mimetype='image/vnd.microsoft.icon')
...
app.run_server(debug=True)
If I browse to the favicon, I see it:
http://www.example.com/favicon.ico
However, when I browse to
http://www.example.com
I see the dash default icon with it's own description. How do I ensure my ownfavicon loads correctly?
To simply change the favicon all you need to do is to create a folder called assets next to your app.py and place your favicon.ico inside of that folder and it will work perfectly.
app.py:
import flask
import dash
import dash_html_components as html
server = flask.Flask(__name__)
#server.route('/')
def index():
return 'Hello Flask app'
app = dash.Dash(
__name__,
server=server,
routes_pathname_prefix='/dash/'
)
app.layout = html.Div("My Dash app")
if __name__ == '__main__':
app.run_server(debug=True)
Here is the docs link for more information: Dash docs
An alternative used in Dash is:
app = dash.Dash()
app._favicon = ("path_to_folder/(your_icon).co")
You can just put title="My Title" as an argument when establishing the Dash app instance. i.e.
app = dash.Dash(
__name__,
title="My Title",
server=server,
routes_pathname_prefix='/dash/'
)
Adding for the sake of completeness. Nowadays, it's recommended to use a bundle of icons with different resolutions to please different browsers and ensure the best picture quality. You can produce such a bundle with the help of, say, realfavicongenerator.net Or you simply might want to use a non-standard .png or .svg icon.
For that, you can subclass Dash and add your much desired link rel and meta tags to its interpolate_index method:
import dash
class CustomDash(dash.Dash):
def interpolate_index(self, **kwargs):
return '''
<!DOCTYPE html>
<html>
<head>
{metas}
<title>{title}</title>
<link rel="apple-touch-icon" sizes="180x180" href="assets/favicons/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="assets/favicons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="assets/favicons/favicon-16x16.png">
<link rel="manifest" href="assets/favicons/site.webmanifest">
<link rel="mask-icon" href="assets/favicons/safari-pinned-tab.svg" color="#5bbad5">
<meta name="msapplication-TileColor" content="#da532c">
<meta name="theme-color" content="#ffffff">
{css}
</head>
<body>
{app_entry}
<footer>
{config}
{scripts}
{renderer}
</footer>
</body>
</html>
'''.format(**kwargs)
app = CustomDash()
Do not forget to place the unzipped bundle into your assets/favicons subfolder!
You should create an "assets" folden and then update the "__favicon" property in your Dash app:
app._favicon = "favico.ico"
Even if OP's accepted answer doesn't work, refer to official document which says:
It is recommended to add name to the dash init to ensure the resources in the assets folder are loaded, eg: app = dash.Dash(name, meta_tags=[...]). When you run your application through some other command line (like the flask command or gunicorn/waitress), the main module will no longer be located where app.py is. By explicitly setting name, Dash will be able to locate the relative assets folder correctly.
Include __name__ in Dash object:
app = Dash(__name__)

how to embed standalone bokeh graphs into django templates

I want to display graphs offered by the bokeh library in my web application via django framework but I don't want to use the bokeh-server executable because it's not the good way. so is that possible? if yes how to do that?
Using the Embedding Bokeh Plots documentation example as suggested by Fabio Pliger, one can do this in Django:
in the views.py file, we put:
from django.shortcuts import render
from bokeh.plotting import figure
from bokeh.resources import CDN
from bokeh.embed import components
def simple_chart(request):
plot = figure()
plot.circle([1,2], [3,4])
script, div = components(plot, CDN)
return render(request, "simple_chart.html", {"the_script": script, "the_div": div})
in the urls.py file we can put :
from myapp.views import simple_chart
...
...
...
url(r'^simple_chart/$', simple_chart, name="simple_chart"),
...
...
in the template file simple_chart.html we'll have :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Experiment with Bokeh</title>
<script src="http://cdn.bokeh.org/bokeh/release/bokeh-0.8.1.min.js"></script>
<link rel="stylesheet" href="http://cdn.bokeh.org/bokeh/release/bokeh-0.8.1.min.css">
</head>
<body>
{{ the_div|safe }}
{{ the_script|safe }}
</body>
</html>
And it works.
You don't need to use bokeh-server to embed bokeh plots. It just means you'll not be using (and probably don't need) the extra features it provides.
In fact you can embed bokeh plots in many ways like generating standalone html, by generating bokeh standalone components that you can then embed in you django app when rendering templates or with the method we call "autoloading" which makes bokeh return a tag that will replace itself with a Bokeh plot. You'll find better details looking at the documentation.
Another good source of inspiration is the embed examples you can find in the repository.
It is also possible to have it work with AJAX requests. Let's say we have a page loaded and would like to show a plot on button click without reloading the whole page. From Django view we return Bokeh script and div in JSON:
from django.http import JsonResponse
from bokeh.plotting import figure
from bokeh.resources import CDN
from bokeh.embed import components
def simple_chart(request):
plot = figure()
plot.circle([1,2], [3,4])
script, div = components(plot, CDN)
return JsonResponse({"script": script, "div": div})
When we get AJAX response in JS (in this example Jquery is used) the div is first appended to the existing page and then the script is appended:
$("button").click(function(){
$.ajax({
url: "/simple_chart",
success: function(result){
var bokeh_data = JSON.parse(result);
$('#bokeh_graph').html(bokeh_data.div);
$("head").append(bokeh_data.script);
}});
});
It must put {{the_script|safe}} inside the head tag
Here's a flask app that uses jquery to interract with a bokeh plot. Check out the templates/ for javascript you can reuse. Also search for bokeh-demos on github.

Trouble with urllib calls in Python. Getting server error

I am trying to download an XML file from the Eurostat website but I am having trouble using urllib in Python to do it. Somehow when I use my regular Chrome browser it's able to make the HTTP request and the website will generate an XML file, but when I try to do the same thing in python I get a server error. This is the code I am using:
import urllib
from xml.etree import ElementTree as ET
response = urllib.urlopen("http://ec.europa.eu/eurostat/SDMX/diss-web/rest/data/lfsq_egais/Q.T.Y_GE15.EMP..NL")
result = response.read()
print result
I have tried using urllib.urlretrieve too and that didn't work either. Any reason why this might be happening? The HTML I get back is as follows:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Draft//EN">
<HTML>
<HEAD>
<TITLE>Error 500--Internal Server Error</TITLE>
<META NAME="GENERATOR" CONTENT="WebLogic Server">
</HEAD>
<BODY bgcolor="white">
<FONT FACE=Helvetica><BR CLEAR=all>
<TABLE border=0 cellspacing=5><TR><TD><BR CLEAR=all>
<FONT FACE="Helvetica" COLOR="black" SIZE="3"><H2>Error 500--Internal Server Error</H2>
</FONT></TD></TR>
</TABLE>
<TABLE border=0 width=100% cellpadding=10><TR><TD VALIGN=top WIDTH=100% BGCOLOR=white><FONT FACE="Courier New"><FONT FACE="Helvetica" SIZE="3"><H3>From RFC 2068 <i>Hypertext Transfer Protocol -- HTTP/1.1</i>:</H3>
</FONT><FONT FACE="Helvetica" SIZE="3"><H4>10.5.1 500 Internal Server Error</H4>
</FONT><P><FONT FACE="Courier New">The server encountered an unexpected condition which prevented it from fulfilling the request.</FONT></P>
</FONT></TD></TR>
</TABLE>
</BODY>
</HTML>
This question is a few months old now, but better late than never:
The Eurostat REST API you are talking is supposed to respond with XML content, which urllib is not expecting/allowing by default. The solution is to add a header Accept: application/xml to the request.
This will do the trick in Python 2.7 (using urllib2 by the way):
import urllib2
req = urllib2.Request("http://ec.europa.eu/eurostat/SDMX/diss-web/rest/data/"
"lfsq_egais/Q.T.Y_GE15.EMP..NL")
req.add_header("Accept", "application/xml")
response = urllib2.urlopen(req)
print response.read()
See urllib2 docs for more info and examples.