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
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;
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?.
I have following XML string.
<Engineers>
<Engineer>
<Name>JOHN</Name>
<Position>STL</Position>
<Team>SS</Team>
</Engineer>
<Engineer>
<Name>UDAY</Name>
<Position>TL</Position>
<Team>SG</Team>
</Engineer>
<Engineer>
<Name>INDRA</Name>
<Position>Director</Position>
<Team>PP</Team>
</Engineer>
</Engineers>
I need to split this xml into smaller xml strings when Xpath is given as Engineers/Enginner.
Smaller xml strings are as follows
<Engineer>
<Name>INDRA</Name>
<Position>Director</Position>
<Team>PP</Team>
</Engineer>
<Engineer>
<Name>JOHN</Name>
<Position>STL</Position>
<Team>SS</Team>
</Engineer>
I have implemented following using saxon xpath and JDOM.
import net.sf.saxon.Configuration;
import net.sf.saxon.lib.NamespaceConstant;
import net.sf.saxon.om.DocumentInfo;
import net.sf.saxon.om.NodeInfo;
import net.sf.saxon.s9api.DocumentBuilder;
import net.sf.saxon.s9api.XPathCompiler;
import net.sf.saxon.s9api.XPathSelector;
import net.sf.saxon.s9api.XdmNode;
import net.sf.saxon.xpath.XPathFactoryImpl;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.junit.Test;
import org.xml.sax.InputSource;
import java.io.File;
import java.io.FileInputStream;
import java.io.StringReader;
import java.util.Iterator;
import java.util.List;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import javax.xml.xpath.XPathFactoryConfigurationException;
public void testXML() throws XPathFactoryConfigurationException, XPathExpressionException, Exception {
System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_JDOM,
"net.sf.saxon.xpath.XPathFactoryImpl");
XPathFactory xPathFactory = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_JDOM);
XPath xPath = xPathFactory.newXPath();
InputSource inputSource = new InputSource(new File(filename).toURI().toString());
SAXSource saxSource = new SAXSource(inputSource);
Configuration config = ((XPathFactoryImpl) xPathFactory).getConfiguration();
DocumentInfo document = config.buildDocument(saxSource);
XPathExpression xPathExpression = xPath.compile("//Engineers/Engineer");
List matches = (List) xPathExpression.evaluate(document, XPathConstants.NODESET);
if (matches != null) {
for (Iterator iter = matches.iterator(); iter.hasNext(); ) {
NodeInfo node = (NodeInfo) iter.next();
System.out.println(node.getDisplayName() + " - " + node.getStringValue());
}
}
}
It gives following result.
Engineer -
JOHN
STL
SS
Engineer -
UDAY
TL
SG
Engineer -
INDRA
Director
PP
How can I change the code so that I get my desired output?Or is there a way to get the names of child attributes(Name,Position,Team) inside Engineer
If you are using JDOM for this work, you should consider using the native JDOM methods instead of the abstraction run through Saxon.
Consider something like:
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.xpath.XPathFactory;
import org.jdom2.xpath.XPAthExpression;
import org.jdom2.output.XMLOutputter;
import org.jdom2.input.SAXBuilder;
import org.jdom2.filter.Filters;
....
XPathExpression xpe = XPathFactory.instance()
.compile("//Engineers/Engineer", Filters.element());
Document doc = new SAXBuilder().build(new File(filename));
XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
for (Element e : xpe.evaluate(doc)) {
xout.output(e, System.out);
}
I would do the splitting in XSLT:
<xsl:stylesheet ....>
<xsl:template match="Engineeers/Engineer">
<xsl:result-document href="{position()}.xml">
<xsl:copy-of select="."/>
</xsl:result-document>
</xsl:template>
</xsl:stylesheet>
If you want the result as a list of JDOM documents then you can supply Saxon with an OutputURIResolver:
Controller controller = transformer.getUnderlyingController();
final Configuration config = controller.getConfiguration();
List<Document> jdomDocuments = new ArrayLis<Document>();
Controller.setOutputURIResolver(new OutputURIResolver() {
public Result resolve(href, base) {
return new JDOM2Writer(config.makePipelineConfiguration());
}
public void close(Result result) {
jdomDocuments.add(((JDOM2Writer)result).getDocument());
}
}
and on completion the results will be in jdomDocuments.
With code:
String timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date());
I get:
cannot find symbol
symbol : class Date
String timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date());
Why?
My imports:
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import javax.imageio.ImageIO;
You're simply missing this:
import java.util.Date;
Add this import.
import java.util.Date;
It won't show any errors.
Java Doc: Date class documentation, (see link for extra info).
I need to read a XML file returned from a web service.
I was following this tutorial, and I have a error in this line:
Element firstPersonElement = (Element)firstPersonNode;
The error:
inconvertible types
required: javax.swing.text.html.parser.Element
found: org.w3c.dom.Node
What am I doing wrong?
Thanks in advance.
EDIT
My imports
import br.com.portaldeideias.model.ErroXML;
import br.com.portaldeideias.model.TributosNFe;
import java.io.StringReader;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.swing.text.html.parser.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
You have wrong imports. Make sure imports are correct.
Remove import javax.swing.text.html.parser.Element
Make sure imports are:
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
As an extra check, Make sure node is type Element Node.
if (firstPersonNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) firstPersonNode;
...................
}