My goal is to use one of the google cloud API's, for which I need that GOOGLE_APPLICATION_CREDENTIALS is set to a .json file.
I receive this error message and a link on how to solve it:
The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.
After setting the variable through cmd (set GOOGLE_APPLICATION_CREDENTIALS=C:\...\...\File.json) to the .json file that I have just created, the same exact error continues appearing.
What am I doing wrong?
EDIT:
I'm using Eclipse JEE. I want to detect web entities from a local image using google cloud vision API. First using a html formulary I request the image and send it to a servlet class:
(index.html)
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Tittle</title>
</head>
<body>
<h1>Welcome!</h1>
<h4>Upload an image: </h4>
<div id="searchDiv">
<form id="searchForm" action="webdetection" method="get" enctype="multipart/form-data">
<div><input type="file" name="image" accept=".JPG, .JPEG, .PNG8, .PNG24, .GIF, .BMP, .WEBP, .RAW, .ICO, .PDF, .TIFF" required>
</div>
<div><input type="submit" name="searchBtn" value="Aceptar">
</div>
</form>
</div>
</body>
</html>
These are the servlets and their mappings:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<web:description></web:description>
<servlet-name>Web Detection</servlet-name>
<servlet-class>aiss.controller.google_vision.VisionServletController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Web Detection</servlet-name>
<url-pattern>/webdetection</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
This is the Servlet for cloud vision:
package aiss.controller.google_vision;
import java.io.IOException;
import java.io.PrintStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import aiss.model.CloudVision.DeteccionWeb;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletOutputStream;
public class VisionServletController extends HttpServlet {
private static final Logger log = Logger.getLogger(VisionServletController.class.getName());
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
log.log(Level.FINE, "Processing GET request");
PrintStream ps = new PrintStream(resp.getOutputStream());
try {
resp.setContentType("text/plain");
DeteccionWeb.detectWebDetectionsGcs(req.getRequestURL().toString(),ps);
}catch(Exception e) {
ps.println(e.toString());//this prints the previous error message I show
}
}
}
And the web detection class at which the servlet redirects:
(most of the imports aren't being used, but due to the class is being modified until it works, I don't know which classes I need)
package aiss.model.CloudVision;
import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.vision.v1.AnnotateFileResponse;
import com.google.cloud.vision.v1.AnnotateFileResponse.Builder;
import com.google.cloud.vision.v1.AnnotateImageRequest;
import com.google.cloud.vision.v1.AnnotateImageResponse;
import com.google.cloud.vision.v1.AsyncAnnotateFileRequest;
import com.google.cloud.vision.v1.AsyncAnnotateFileResponse;
import com.google.cloud.vision.v1.AsyncBatchAnnotateFilesResponse;
import com.google.cloud.vision.v1.BatchAnnotateImagesResponse;
import com.google.cloud.vision.v1.Block;
import com.google.cloud.vision.v1.ColorInfo;
import com.google.cloud.vision.v1.CropHint;
import com.google.cloud.vision.v1.CropHintsAnnotation;
import com.google.cloud.vision.v1.DominantColorsAnnotation;
import com.google.cloud.vision.v1.EntityAnnotation;
import com.google.cloud.vision.v1.FaceAnnotation;
import com.google.cloud.vision.v1.Feature;
import com.google.cloud.vision.v1.Feature.Type;
import com.google.cloud.vision.v1.GcsDestination;
import com.google.cloud.vision.v1.GcsSource;
import com.google.cloud.vision.v1.Image;
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.cloud.vision.v1.ImageContext;
import com.google.cloud.vision.v1.ImageSource;
import com.google.cloud.vision.v1.InputConfig;
import com.google.cloud.vision.v1.LocalizedObjectAnnotation;
import com.google.cloud.vision.v1.LocationInfo;
import com.google.cloud.vision.v1.OperationMetadata;
import com.google.cloud.vision.v1.OutputConfig;
import com.google.cloud.vision.v1.Page;
import com.google.cloud.vision.v1.Paragraph;
import com.google.cloud.vision.v1.SafeSearchAnnotation;
import com.google.cloud.vision.v1.Symbol;
import com.google.cloud.vision.v1.TextAnnotation;
import com.google.cloud.vision.v1.WebDetection;
import com.google.cloud.vision.v1.WebDetection.WebEntity;
import com.google.cloud.vision.v1.WebDetection.WebImage;
import com.google.cloud.vision.v1.WebDetection.WebLabel;
import com.google.cloud.vision.v1.WebDetection.WebPage;
import com.google.cloud.vision.v1.WebDetectionParams;
import com.google.cloud.vision.v1.Word;
import com.google.protobuf.ByteString;
import com.google.protobuf.util.JsonFormat;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DeteccionWeb {
/**
* Detects whether the remote image on Google Cloud Storage has features you would want to
* moderate.
*
* #param gcsPath The path to the remote on Google Cloud Storage file to detect web annotations.
* #param out A {#link PrintStream} to write the results to.
* #throws Exception on errors while closing the client.
* #throws IOException on Input/Output errors.
*/
public static void detectWebDetectionsGcs(String gcsPath, PrintStream out) throws Exception,
IOException {
List<AnnotateImageRequest> requests = new ArrayList<>();
ImageSource imgSource = ImageSource.newBuilder().setImageUri(gcsPath).build();
Image img = Image.newBuilder().setSource(imgSource).build();
Feature feat = Feature.newBuilder().setType(Type.WEB_DETECTION).build();
AnnotateImageRequest request =
AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
requests.add(request);
try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
List<AnnotateImageResponse> responses = response.getResponsesList();
for (AnnotateImageResponse res : responses) {
if (res.hasError()) {
out.printf("Error: %s\n", res.getError().getMessage());
return;
}
// Search the web for usages of the image. You could use these signals later
// for user input moderation or linking external references.
// For a full list of available annotations, see http://g.co/cloud/vision/docs
WebDetection annotation = res.getWebDetection();
out.println("Entity:Id:Score");
out.println("===============");
for (WebEntity entity : annotation.getWebEntitiesList()) {
out.println(entity.getDescription() + " : " + entity.getEntityId() + " : "
+ entity.getScore());
}
for (WebLabel label : annotation.getBestGuessLabelsList()) {
out.format("\nBest guess label: %s", label.getLabel());
}
}
}
}
}
My main suspect is ImageSource.newBuilder().setImageUri(gcsPath), as it seems cloud vision API may not work on http/https url's that doesn't belong to Google cloud storage. And it seems it can be solved with the credentials, but I can't pass through it.
if you're using Tomcat in eclipse, the following thread should be helpful How to set GOOGLE_APPLICATION_CREDENTIALS for Google Compute Engine?.
Related
I am using nimbus jost+jwt version 8.19 in a normal java project (not using spring). I have some claims such as iss, aud and sub and want to validate them. (I want iss, aud and sub to be a specific value). I want the parser to throw an exception when the claims dont match.
The example provided here worked fine in earlier versions , But it seems like it was changed in later versions.
Earlier (version 8.3) I used to validate using the following code
JWKSet jwkSet = new JWKSet(utils.rsakey);
JWKSource<SecurityContext> jwkSource = new ImmutableJWKSet<>(jwkSet);
ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
jwtProcessor.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("jwt")));
JWSAlgorithm expectedJWSAlg = JWSAlgorithm.RS256;
JWTClaimsSet validClaims= new JWTClaimsSet.Builder()
.issuer(InetAddress.getLocalHost().getHostName()
.subject("matchvalue")
.audience("matchvalue")
.build();
JWSKeySelector<SecurityContext> keySelector =
new JWSVerificationKeySelector<>(expectedJWSAlg, jwkSource);
jwtProcessor.setJWTClaimsSetVerifier(new DefaultJWTClaimsVerifier(
//exact match claims
validClaims,
//Required claims
new HashSet<>(Arrays.asList("exp", "sub","iss"))));
jwtProcessor.setJWSKeySelector(keySelector);
// Process the token
SecurityContext ctx = null; // optional context parameter, not required here
JWTClaimsSet tokenClaims= jwtProcessor.process(token, ctx);
but now (version 8.19) the DefaultJWTClaimsVerifier does not seem to be accepting exact match claims and Required claims parameters. Is there any way to implement the exact match and required claims?
All of my imports for refrence
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.ws.rs.FormParam;
import javax.ws.rs.core.Response;
import com.nimbusds.jose.EncryptionMethod;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JOSEObjectType;
import com.nimbusds.jose.JWEAlgorithm;
import com.nimbusds.jose.JWEHeader;
import com.nimbusds.jose.JWEObject;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.KeyLengthException;
import com.nimbusds.jose.Payload;
import com.nimbusds.jose.crypto.DirectDecrypter;
import com.nimbusds.jose.crypto.RSAEncrypter;
import com.nimbusds.jose.crypto.RSASSASigner;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.KeyUse;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.gen.RSAKeyGenerator;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.BadJOSEException;
import com.nimbusds.jose.proc.DefaultJOSEObjectTypeVerifier;
import com.nimbusds.jose.proc.JWSKeySelector;
import com.nimbusds.jose.proc.JWSVerificationKeySelector;
import com.nimbusds.jose.proc.SecurityContext;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import com.nimbusds.jwt.proc.ConfigurableJWTProcessor;
import com.nimbusds.jwt.proc.DefaultJWTClaimsVerifier;
import com.nimbusds.jwt.proc.DefaultJWTProcessor;
I am just trying out to get the documentation for my small REST API written in in spring with swagger2 inclusion. When i try to access my swagger page the following error is shown in browser console.
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Mon Sep 25 21:09:08 IST 2017
There was an unexpected error (type=Not Found, status=404).
No message available
My code snippets are below mentioned.
package com.example.demo;
import java.util.Collections;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
#RestController
#RequestMapping(value="/rooms")
#Api(value="rooms", tags=("rooms"))
public class RoomController {
#Autowired
private RoomRepositery roomRepo;
#RequestMapping(method = RequestMethod.GET)
#ApiOperation(value="Get All Rooms", notes="Get all rooms in the system", nickname="getRooms")
public List<Room> findAll(#RequestParam(name="roomNumber", required=false)String roomNumber){
if(StringUtils.isNotEmpty(roomNumber)) {
return Collections.singletonList(roomRepo.findByRoomNumber(roomNumber));
}
return (List<Room>) this.roomRepo.findAll();
}
}
App class
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import static springfox.documentation.builders.PathSelectors.any;
#SpringBootApplication
#EnableSwagger2
public class RoomServiceApp {
#Bean
public Docket api(){
return new Docket(DocumentationType.SWAGGER_2).groupName("Room").select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo"))
.paths(any()).build().apiInfo(new ApiInfo("Room Services",
"A set of services to provide data access to rooms", "1.0.0", null,
new Contact("Frank Moley", "https://twitter.com/fpmoles", null),null, null));
}
public static void main(String[] args) {
SpringApplication.run(RoomServiceApp.class, args);
}
}
I am not able to found what i am missing here. Can any one help me out?
Thanks
You have to use http://localhost:9090/swagger-ui.html for swagger UI and http://localhost:9090/v2/api-docs?group=Room for JSON API.
I used the same code and find attached screenshot.
refer to this project for more details.
Request mapping at method level should have URI path like below for findAll method. Consumes and produces also required if there is input passed to method and output returned from method.
The reason is empty mapping value at method level will result in 'host:port/contextPath/' for which swagger will return 404.
#RequestMapping(method = { RequestMethod.GET }, value = "/roomList", consumes = {
MediaType.ALL}, produces = { MediaType.ALL})
I want to add an upload function to my spring boot application;
this is my upload Rest Controller
package org.sid.web;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.sid.entities.FileInfo;
#RestController
public class UploadController {
#Autowired
ServletContext context;
#RequestMapping(value = "/fileupload/file", headers = ("content-type=multipart/*"), method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<FileInfo> upload(#RequestParam("file") MultipartFile inputFile) {
FileInfo fileInfo = new FileInfo();
HttpHeaders headers = new HttpHeaders();
if (!inputFile.isEmpty()) {
try {
String originalFilename = inputFile.getOriginalFilename();
File destinationFile = new File(
context.getRealPath("C:/Users/kamel/workspace/credit_app/uploaded") + File.separator + originalFilename);
inputFile.transferTo(destinationFile);
fileInfo.setFileName(destinationFile.getPath());
fileInfo.setFileSize(inputFile.getSize());
headers.add("File Uploaded Successfully - ", originalFilename);
return new ResponseEntity<FileInfo>(fileInfo, headers, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<FileInfo>(HttpStatus.BAD_REQUEST);
}
} else {
return new ResponseEntity<FileInfo>(HttpStatus.BAD_REQUEST);
}
}
}
but when testing this in postman with inserting http://localhost:8082/fileupload/file and adding a file to the body
i got this error: "exception": org.springframework.web.multipart.support.MissingServletRequestPartException",
"message": "Required request part 'file' is not present,
This is how your request in Postman should look like:
My sample code:
application.properties
#max file and request size
spring.http.multipart.max-file-size=10MB
spring.http.multipart.max-request-size=11MB
Main Application Class:
Application.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Rest controller class:
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
#Controller
#RequestMapping("/fileupload")
public class MyRestController {
#RequestMapping(value = "/file", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody String myService(#RequestParam("file") MultipartFile file,
#RequestParam("id") String id) throws Exception {
if (!file.isEmpty()) {
//your logic
}
return "some json";
}
}
pom.xml
//...
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
....
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
//...
In your method you have specified like this
#RequestParam("file"). Hence it is expecting the key to be file. It is quite evident in the exception message. Use this name in the Key field in Postman when you upload file.
More information here integration test case and file upload
I also had similar issue and was getting the error request part file not present.
But I later realized that I have this code in my application which was causing problem:
#Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new
CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(1000000000);
return multipartResolver;
}
I removed this and it started working for both RequestPart and RequestParam.
See the related issue below:
https://forum.predix.io/questions/22163/multipartfile-parameter-is-not-present-error.html
Except for other posted answers, the problem might be realated to missing multipart support for the servlet handling the request (spring's DispatcherServlet in case of Spring's app).
This can be fixed by adding multipart support to dispatcher servlet in web.xml declaration or during initialization (in case of annotation-based config)
a) web-xml based config
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/dispatcher-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<multipart-config>
<max-file-size>10485760</max-file-size>
<max-request-size>20971520</max-request-size>
<file-size-threshold>5242880</file-size-threshold>
</multipart-config>
</servlet>
</web-app>
b) for annotation-based configuration this would be following:
public class AppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) {
final AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
final ServletRegistration.Dynamic registration = servletContext.addServlet("dispatcher", new DispatcherServlet(appContext));
registration.setLoadOnStartup(1);
registration.addMapping("/");
File uploadDirectory = new File(System.getProperty("java.io.tmpdir"));
MultipartConfigElement multipartConfigElement = new MultipartConfigElement(uploadDirectory.getAbsolutePath(), 100000, 100000 * 2, 100000 / 2);
registration.setMultipartConfig(multipartConfigElement);
} }
Then we need to provide multipart resolver which can resolve files sent as multipart-request. For annotation config this can be done in following way:
#Configuration
public class MyConfig {
#Bean
public MultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}
}
For xml-based spring configuration you need to add this bean to the context via tag declaration declaration:
<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver" />
Alternatively to spring's standard multipart resolver you can use implementation from commons. This way however extra dependency is required:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000000"/>
</bean>
I had similar issue with error Could not resolve parameter [0] in public org.springframework.http.ResponseEntity... Required request part 'file' is not present and tried many things but one change resolved this issue.
Had to update
// old
#RequestParam("file") MultipartFile inputFile
// new
#RequestParam(value = "file") MultipartFile inputFile
In my case, i have multi module project as;
core > api > admin
Admin and api are parent of core module.
Core/ImageController:
#RequestMapping(value = "/upload/image", method = RequestMethod.POST)
public ResponseEntity uploadBanner(#RequestParam(value = "file", required =
false) MultipartFile bannerFile){...}
AdminApplicationInitializer:
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(AdminApplicationInitializer.class);
}
#Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
//100MB
resolver.setMaxUploadSize(100 * (long) 1024 * 1024);
return resolver;
}
#Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
factory.setMaxFileSize(DataSize.ofMegabytes(200L));
factory.setMaxRequestSize(DataSize.ofMegabytes(200L));
return factory.createMultipartConfig();
}
When i tried to upload file from api module with core service "/upload/image".
I had get an error : "Required request part 'file' is not present".
Cause of ApiInitializer had not configuration like AdminInitializer.
The Solution : i added multipartResolver() and multipartConfigElement() method to ApiApplicationInitializer.Then it worked.
I want to create a Soap header structure like following :
<soapenv:Header>
<wataniya:auth xmlns:wataniya="http://osb.wataniya.com">
<username> TestUser</username>
<password> TestPassword </password>
</wataniya:auth>
</soapenv:Header>
I have written a code :
QName qName = new QName("http://osb.wataniya.com", "auth", "watania");
Element authElement = doc.getDocumentElement();
Element usernameElement = doc.createElement("username");
usernameElement.setTextContent("TestUser");
Element passwordElement = doc.createElement("password");
passwordElement.setTextContent("TestPassword");
authElement.appendChild(usernameElement);
authElement.appendChild(passwordElement);
Header header = new Header(qName, authElement);
I have used following imports(for reference):
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.camel.CamelExecutionException;
import org.apache.cxf.binding.soap.SoapFault;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.MessageContentsList;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
But I am facing issue and unable to generate the header as expected.
Any leads..thanks in advance
i'm new to REST Service. i've done a small REST Webservice application and deployed in my online tomcat webserver,
My link -->
http://sample.com.au/REST/WebService/MyMethod?name=sss
but i'm getting the following message
The requested URL /REST/WebService/MyMethod was not found on this server.
when i run the similar in eclipse locally its working....
can anyone please tell me some solution for this...
my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN' 'http://java.sun.com/dtd/web-app_2_3.dtd'>
<web-app>
:
:
<servlet>
<servlet-name>ServletAdaptor</servlet-name>
<servlet-class>com.sun.jersey.server.impl.container.servlet.ServletAdaptor</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ServletAdaptor</servlet-name>
<url-pattern>/REST/*</url-pattern>
</servlet-mapping>
</web-app>
My FeedService.java
package webService;
import java.util.ArrayList;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import model.ProjectManager;
import com.google.gson.Gson;
import dto.FeedObjects;
#Path("/WebService")
public class FeedService {
#GET
#Path("/MyMethod")
#Produces("application/json")
public String names(#QueryParam("name") String name)
{
System.out.println("name----------->"+name);
String feeds = null;
try
{
ArrayList<FeedObjects> feedData = null;
ProjectManager projectManager= new ProjectManager();
feedData = projectManager.GetFeeds(name);
Gson gson = new Gson();
System.out.println(gson.toJson(feedData));
feeds = gson.toJson(feedData);
}
catch (Exception e)
{
System.out.println("Exception Error"); //Console
}
return feeds;
}
}
context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/iloadlogistics.com.au"/>
Refer here. Specifically check Example 4.1 and Example 4.5. Should you not deploy that way?