How can blueimp communicate with a Java REST service, if possible - angularjs

$scope.$on('fileuploadadd', function(e,data) {
$http({
method: 'POST',
}).success().error();
}
i know writing above code for single simple file upload, but with blueimp,
can i manage progress with my rest service? also is above the right approach?
i know there is a data.submit function, but i do not know how can it know to call which server side action.

You can use annotations to map request method on a restful function according to the Javax RS Api. So it depends of which Restful Java Api you use.
An example from the oracle documentation:
package com.sun.jersey.samples.helloworld.resources;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.Path;
// The Java class will be hosted at the URI path "/helloworld"
#Path("/helloworld")
public class HelloWorldResource {
// The Java method will process HTTP POST requests
#POST
// The Java method will produce content identified by the MIME Media
// type "text/plain"
#Produces("text/plain")
public String getClichedMessage() {
// Return some cliched textual content
return "Hello World";
}
}
The Javascript :
$('#fileupload').fileupload({
url: 'http://yourSite/helloworld',
type: 'POST',
...

Related

How to send image from React app to api server

I need help with implementation send image from React app to server api.
In React I use library FilePond for send image, and that work great, but I dont know how to get this image on server, I use NETTE framework and also apitte library for request. If you know how to send and get images another way, write please. Thank you very much!
For example how I use FilePond in react
<FilePond allowMultiple={true} server={"http://localhost:3000" + this.baseProperties.uploadUrl}/>
and part of php code
/**
* #Path("/upload")
* #Method("POST")
* #param ApiRequest $request
* #return string
*/
public function uploadImage(ApiRequest $request)
{
return 'check';
}
It is not very clearly document but file pond will hit whatever API you specified (http://localhost:3000 in your case) simply using the HTTP verb that corresponds to the REST action being taken. so for example if you set this. (note this in react)
server={
{
'url': 'localhost:3000/filepondBackend',
Then file pond would hit the localhost:3000/filepondBackend endpoint with the follow HTTP verbs: POST, GET, DELETE
Here's an example of how the backend would be mapped in spring
#RequestMapping("/filepondBackend")
#DeleteMapping(produces = "application/json")
#ApiOperation(value = "Deletes file from DataBase")
public ResponseEntity<ResponseDTO> deleteFile(
#RequestHeader HttpHeaders headers
{
delete logic
});
#PostMapping(produces = "application/json")
#ApiOperation(value = "Inserts file into DataBase")
public ResponseEntity<ResponseDTO> postFile(
#RequestHeader HttpHeaders headers, #RequestParam("filepond") MultipartFile file
{
post logic
});
#GetMapping(produces = "application/json")
#ApiOperation(value = "Retrieve file from DataBase")
public ResponseEntity<ResponseDTO> getFile(
#RequestHeader HttpHeaders headers
)
{
get logic
});
Hope that helps.

How to call App Engine Endpoints with the JavaScript library in promises mode

I have a web application which calls several App Engine Endpoints with the Google API JavaScript client library.
I am currently changing this application from callback mode to promises mode, as recommended by Google (https://developers.google.com/api-client-library/javascript/features/promises#using-promises) and I am encountering a problem. Note that the app works well with the callback mode.
My problem with the promises mode is to find what is the correct path argument to use when calling the request method:
JavaScrit code:
var params = {'webSafeKeyParent’: ‘neN4fm15xW52b2ljZXMtb19saW5lmlYLEglBY1NFwpRpdHkYgICAgQj97AoM’};
gapi.client.request({
'path': 'https://myappenginename.appspot.com/_ah/api/customerApi/v1/?????????',
'params': params
}).then(function(response) {
// Handle response
}, function(reason) {
// Handle error
});
Endpoint definition in "customerApi":
#ApiMethod(
name = "listByParent",
path = "customerByParent/{webSafeKeyParent}",
httpMethod = ApiMethod.HttpMethod.GET,
scopes = {Constants.EMAIL_SCOPE},
clientIds = {Constants.WEB_CLIENT_ID, com.google.api.server.spi.Constant.API_EXPLORER_CLIENT_ID},
audiences = {Constants.ANDROID_AUDIENCE})
public List<Customer> listByParent(final User user, #Named("webSafeKeyParent") final String webSafeKeyParent, #Nullable #Named("cursor") String cursor, #Nullable #Named("limit") Integer limit) throws UnauthorizedException {
For few of my endpoints it works by including in the path argument of the JavaScript request method, the values of "path" and "name" as declared in the #ApiMethod annotation.
i.e. for the above endpoint, the following path works:
https://myappenginename.appspot.com/_ah/api/customerApi/v1/customerByParent/listByParent
Strangely enough this does NOT work for some other endpoints of the same kind. I receive either a 404 HTTP error or a 503 one.
I've also tried with the paths displayed under "Request" when you query the endpoints with the APIs Explorer but without success....
Is there any detailed documentation on how to call App Engine Endpoints with promises, with the Google API JavaScript client library? I have not found any. Do you have some advice to share please?
Thanks in advance
Actually the request method DOES work ALL THE TIME with the "path" argument composed of the values of "path" and "name" as declared in the #ApiMethod annotation...
It was a mistake on my side if it didn't work for some endpoints. Don't know which mistake, however.
Note that I have noticed that it is very important to pass to the JavaScript request method the correct httpMethod of the App Engine Endpoints. By default the request methid assumes that it is a GET. In case your Endpoint has httpMethod= ApiMethod.HttpMethod.POST in the #ApiMethod annotation, you shall pass the argument 'method': 'POST', as detailed in the doc: https://developers.google.com/api-client-library/javascript/reference/referencedocs#gapiclientrequestargs

Is there any other way except POJO to send response in form of JSON from server side to angular?

Hi i am at my elementary stage in learning dropwizard with angularjs, my problem is that when i send response from my resource at server side as POJO, it gets parsed into JSON, but if i send any String, angular throws me error, please help me out how can i send my custom response to angular.
First step is to set the response type to plain text. This could be done like this:
#Path("/example")
#Produces(MediaType.TEXT_PLAIN)
public class EndPoint{
#GET
public Response saySomething() {
return Response.ok("plain text response").type(MediaType.TEXT_PLAIN).build();
}
}
once you have that covered you can use angular's $http service to read the plain text response:
$http({method: "GET", url: "/example"})
.success(function(data){
alert(data) // alert: plain text response
}
);

Accessing Jenkins API from AngularJS

I'm trying to retrieve information about one job build from the api rest provided by Jenkins with Angularjs.
Jsonp is actually disabled on Jenkins:
Jenkins Security Advisory 2013-02-16
so this piece of code can't work:
var url = 'http://jenkins-server:8080/job/job-name/api/json?jsonp=callback';
$http.jsonp(url).success(function (data) {
console.log(data);
});
throw:
Uncaught SyntaxError: Unexpected token :
Cors is not enabled by default... to be honest I can't find the way to install this plugins:
https://github.com/algal/cors
https://github.com/jhinrichsen/cors-plugin
and this code can't work as well
var url = 'http://jenkins-server:8080/job/job-name/api/json'
$http({url: url, method: 'GET'}).success(function(data){console.log(data)})
You can use this CORS filter plugin:
https://wiki.jenkins-ci.org/display/JENKINS/Cors+Filter+Plugin
Or you can host your Angular app on the Jenkins server using the User Content mechanism:
https://wiki.jenkins-ci.org/display/JENKINS/User+Content
There seems to be a plugin now for whitelisting JSON requests...Just go to the plugins, and search for JSON.
The Secure Access plugin.
#Mauro, starting with Jenkins 1.537 you can implement "jenkins.security.SecureRequester" and allow the json request to work.
You just have to implement the method permit(StaplerRequest req, Object bean) and have your validations there and just return true (based on your validation result) to allow the request.
Once you done that you can simply use the first code snipped you have mentioned in your question.
Example SecureRequester Implementation : -
import hudson.Extension;
import jenkins.security.SecureRequester;
import org.kohsuke.stapler.StaplerRequest;
#Extension
public class AllowRequest implements SecureRequester {
public boolean permit(StaplerRequest req, Object bean) {
// A method to validate the request and return the appropriate result
return YOUR_VALIDATION_METHOD(req,bean);
}
private boolean YOUR_VALIDATION_METHOD(StaplerRequest req, Object bean) {
// validation goes here
}
}
You need to build this as a plugin and install it in you Jenkins setup to work.

Jax-Rs service is not getting invoked

I am developing JAX-RS Rest service using Apache CXF. After deploying it to Tomcat 7 server, if I type the URL http://localhost:8080/Rest/rest?_wadl it shows me the WADL. but if I enter the URL http://localhost:8080/Rest/rest/retrieve it gives me 404 error.
In above URLs: Rest is the name of my project
/rest is the url-pattern for my CXFServlet which is specified in web.xml
/ is the address of jaxrs:server which is specified in beans.xml
retrieve is the path of service which is specified in my interface with #Path annotation.
(My apologies: I can't provide the XML documents referred to above.)
I think this is a CXF bug which get the incorrect base URL for restful web services.
The class "org.apache.cxf.transport.servlet.ServletController" invokes the method "getBaseURL" of the class "org.apache.cxf.transport.servlet.BaseUrlHelper".
It gets the base URL from request URL, and it ignores the parameters part.
This is correct for SOAP web servcies, because SOAP web services URL is just like: http://host:port/basepath?para=a. Unfortunately, for restful web services, the URL is just like http://host:port/basepath/method/parameter. The correct base URL should be http://host:port/basepath, but actually, the BaseUrlHelper gives you http://host:port/basepath/method/parameter. It just gives the URL before "?". It's why the result is correct when you access http://localhost:8080/Rest/rest?_wadl, in this case, it gives the correct base URL http://localhost:8080/Rest.
If you access http://localhost:8080/Rest/rest?_wadl at first then you access http://localhost:8080/Rest/rest/retrieve, it would be correct. Because, CXF set the base URL as the address of EndpointInfo only at the first time. It means, you MUST access the correct base URL at the first time! :(
The solution is: override the method "getBaseURL(HttpServletRequest request)" of "org.apache.cxf.transport.servlet.ServletController", let it return correct base URL.
For example, step1: extends the ServletController.
public class RestfulServletController extends ServletController {
private final String basePath;
public RestfulServletController(DestinationRegistry destinationRegistry, ServletConfig config,
HttpServlet serviceListGenerator, String basePath) {
super(destinationRegistry, config, serviceListGenerator);
this.basePath = basePath;
}
#Override
protected String getBaseURL(HttpServletRequest request) {
// Fixed the bug of BaseUrlHelper.getBaseURL(request) for restful service.
String reqPrefix = request.getRequestURL().toString();
int idx = reqPrefix.indexOf(basePath);
return reqPrefix.substring(0, idx + basePath.length());
}
}
step2: extends CXFNonSpringServlet and use the RestfulServletController in the subclass
public class RestfulCXFServlet extends CXFNonSpringServlet {
... ...
private ServletController createServletController(ServletConfig servletConfig) {
HttpServlet serviceListGeneratorServlet = new ServiceListGeneratorServlet(destinationRegistry, bus);
ServletController newController = new RestfulServletController(destinationRegistry, servletConfig,
serviceListGeneratorServlet, basePath);
return newController;
}
}
step3: instead of CXFNonSpringServlet , you use the derived class RestfulServletController.
Don't forget, you should config the "basePath" as /Rest/rest.
Hope this can help you.

Resources