How to start the stream processor in Amazon Rekognition - amazon-web-services

I followed the AWS Rekognition Developer Guide and wrote a stream processor using CreateStreamProcessor in Java.
import com.amazonaws.services.rekognition.AmazonRekognition;
import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
import com.amazonaws.services.rekognition.model.*;
public class StreamProcessor {
private String streamProcessorName;
private String kinesisVideoStreamArn;
private String kinesisDataStreamArn;
private String roleArn;
private String collectionId;
private float matchThreshold;
private AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
public void createStreamProcessor() {
KinesisVideoStream kinesisVideoStream = new KinesisVideoStream().withArn(kinesisVideoStreamArn);
StreamProcessorInput streamProcessorInput = new StreamProcessorInput().withKinesisVideoStream(kinesisVideoStream);
KinesisDataStream kinesisDataStream = new KinesisDataStream().withArn(kinesisDataStreamArn);
StreamProcessorOutput streamProcessorOutput = new StreamProcessorOutput().withKinesisDataStream(kinesisDataStream);
FaceSearchSettings faceSearchSettings = new FaceSearchSettings().withCollectionId(collectionId)
.withFaceMatchThreshold(matchThreshold);
StreamProcessorSettings streamProcessorSettings = new StreamProcessorSettings().withFaceSearch(faceSearchSettings);
CreateStreamProcessorResult createStreamProcessorResult = rekognitionClient.createStreamProcessor(
new CreateStreamProcessorRequest().withInput(streamProcessorInput).withOutput(streamProcessorOutput)
.withSettings(streamProcessorSettings).withRoleArn(roleArn).withName(streamProcessorName));
System.out.println("StreamProcessorArn - " +
createStreamProcessorResult.getStreamProcessorArn());
}
public void startStreamProcessor() {
StartStreamProcessorResult startStreamProcessorResult = rekognitionClient.startStreamProcessor(
new StartStreamProcessorRequest().withName(streamProcessorName));
}
public void stopStreamProcessorSample() {
StopStreamProcessorResult stopStreamProcessorResult = rekognitionClient.stopStreamProcessor(
new StopStreamProcessorRequest().withName(streamProcessorName));
}
public void deleteStreamProcessorSample() {
DeleteStreamProcessorResult deleteStreamProcessorResult = rekognitionClient.deleteStreamProcessor(
new DeleteStreamProcessorRequest().withName(streamProcessorName));
}
public void describeStreamProcessorSample() {
DescribeStreamProcessorResult describeStreamProcessorResult = rekognitionClient.describeStreamProcessor(
new DescribeStreamProcessorRequest().withName(streamProcessorName));
System.out.println("Arn - " + describeStreamProcessorResult.getStreamProcessorArn());
System.out.println("Input kinesisVideo stream - " + describeStreamProcessorResult.getInput()
.getKinesisVideoStream().getArn());
System.out.println("Output kinesisData stream - " + describeStreamProcessorResult.getOutput()
.getKinesisDataStream().getArn());
System.out.println("RoleArn - " + describeStreamProcessorResult.getRoleArn());
System.out.println("CollectionId - " + describeStreamProcessorResult.getSettings().getFaceSearch()
.getCollectionId());
System.out.println("Status - " + describeStreamProcessorResult.getStatus());
System.out.println("Status message - " + describeStreamProcessorResult.getStatusMessage());
System.out.println("Creation timestamp - " + describeStreamProcessorResult.getCreationTimestamp());
System.out.println("Last updatClient rekognitionClient = new AmazonRekognitionClient()e timestamp - "
+ describeStreamProcessorResult.getLastUpdateTimestamp());
}
public void listStreamProcessorSample() {
ListStreamProcessorsResult listStreamProcessorsResult = rekognitionClient.listStreamProcessors(
new ListStreamProcessorsRequest().withMaxResults(100));
for (com.amazonaws.services.rekognition.model.StreamProcessor streamProcessor :
listStreamProcessorsResult.getStreamProcessors()) {
System.out.println("StreamProcessor name - " + streamProcessor.getName());
System.out.println("Status - " + streamProcessor.getStatus());
}
}
}
But I can't figure out how to start the stream processor? Do I have to simply write the main method and call createStreamProcessor() function? Or do I have to do something else: like the guide mentioned something as StartStreamProcessor?

Yes, you have to start the stream preprocessor by using following API:
https://docs.aws.amazon.com/rekognition/latest/dg/API_StartStreamProcessor.html
rekognitionClient.startStreamProcessor(name= "my-stream-1")

Related

AWS rekognition Request has invalid image format

I get this error when i try to compare two images from my s3 bucket, i follow the functions rules to get an image from S3Object with correct name and s3 bucket name but i throws the Invalid image format exception. Maybe it has to be as a base64 or bytebuffer? i dont understand then why there is a function to get from S3Object.
My code is simple and as follows:
String reference = "reference.jpg";
String target = "selfie.jpg";
String bucket = "pruebas";
CompareFacesRequest request = new CompareFacesRequest()
.withSourceImage(new Image().withS3Object(new S3Object()
.withName(reference).withBucket(bucket)))
.withTargetImage(new Image().withS3Object(new S3Object()
.withName(target).withBucket(bucket)))
.withSimilarityThreshold(similarityThreshold);
AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.standard()
.withRegion(Regions.US_EAST_1).build();
CompareFacesResult compareFacesResult= rekognitionClient.compareFaces(request);
The exception is thrown in compareFaces(request) the last line.
this is main part of the error:
Exception in thread "main" com.amazonaws.services.rekognition.model.InvalidImageFormatException: Request has invalid image format (Service: AmazonRekognition; Status Code: 400; Error Code: InvalidImageFormatException;
The images are in AWS S3 and my credentials for rekognition have permission to read from S3. So in that part is not the error.
UPDATE CODE:
public static void main(String[] args) throws FileNotFoundException {
Float similarityThreshold = 70F;
String reference = "reference.jpg";
String target = "target.jpg";
String bucket = "pruebas";
ProfileCredentialsProvider credentialsProvider = ProfileCredentialsProvider.builder().profileName("S3").build();
Region region = Region.US_EAST_1;
S3Client s3 = S3Client.builder()
.region(region)
.credentialsProvider(credentialsProvider)
.build();
byte[] sourceStream = getObjectBytes(s3, bucket,reference);
byte[] tarStream = getObjectBytes(s3, bucket, target);
SdkBytes sourceBytes = SdkBytes.fromByteArrayUnsafe(sourceStream);
SdkBytes targetBytes = SdkBytes.fromByteArrayUnsafe(tarStream);
Image souImage = Image.builder()
.bytes(sourceBytes)
.build();
Image tarImage = Image.builder()
.bytes(targetBytes)
.build();
CompareFacesRequest request = CompareFacesRequest.builder()
.sourceImage(souImage)
.targetImage(tarImage)
.similarityThreshold(similarityThreshold).build();
RekognitionClient rekognitionClient = RekognitionClient.builder()
.region(Region.US_EAST_2).build();
CompareFacesResponse compareFacesResult= rekognitionClient.compareFaces(request);
List<CompareFacesMatch> faceDetails = compareFacesResult.faceMatches();
for (CompareFacesMatch match: faceDetails){
ComparedFace face= match.face();
BoundingBox position = face.boundingBox();
System.out.println("Face at " + position.left().toString()
+ " " + position.top()
+ " matches with " + face.confidence().toString()
+ "% confidence.");
}
List<ComparedFace> uncompared = compareFacesResult.unmatchedFaces();
System.out.println("There was " + uncompared.size()
+ " face(s) that did not match");
System.out.println("Source image rotation: " + compareFacesResult.sourceImageOrientationCorrection());
System.out.println("target image rotation: " + compareFacesResult.targetImageOrientationCorrection());
}
public static byte[] getObjectBytes (S3Client s3, String bucketName, String keyName) {
try {
GetObjectRequest objectRequest = GetObjectRequest
.builder()
.key(keyName)
.bucket(bucketName)
.build();
ResponseBytes<GetObjectResponse> objectBytes = s3.getObjectAsBytes(objectRequest);
return objectBytes.asByteArray();
} catch (S3Exception e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return null;
}
Try using AWS SDK for Java V2 - not the old V1 lib. Using V2 is strongly recommended over V1 and is best practice.
Here is the V2 code that works fine to compare faces. In this example, notice that you have to get the image into a SdkBytes object. It does not matter where the image is located as long as you get it into SDKBytes. The image can be in an S3 bucket, the local file system. etc.
You can find this V2 Reckonation example in the AWS Github repo here:
https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javav2/example_code/rekognition/src/main/java/com/example/rekognition
Also - you can use S3 Java V2 Service client to read an image in an S3 bucket and get the byte[]. From there, you can create an SDKBytes object to use in CompareFaces.
https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectData.java
Here is the full Java example for Compare Faces. Notice there is an URL to the Java DEV Guide if you do not know how to get up and running with AWS SDK for Java V2 - including how to set up your creds.
package com.example.rekognition;
// snippet-start:[rekognition.java2.compare_faces.import]
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rekognition.RekognitionClient;
import software.amazon.awssdk.services.rekognition.model.RekognitionException;
import software.amazon.awssdk.services.rekognition.model.Image;
import software.amazon.awssdk.services.rekognition.model.CompareFacesRequest;
import software.amazon.awssdk.services.rekognition.model.CompareFacesResponse;
import software.amazon.awssdk.services.rekognition.model.CompareFacesMatch;
import software.amazon.awssdk.services.rekognition.model.ComparedFace;
import software.amazon.awssdk.services.rekognition.model.BoundingBox;
import software.amazon.awssdk.core.SdkBytes;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;
// snippet-end:[rekognition.java2.compare_faces.import]
/**
* Before running this Java V2 code example, set up your development environment, including your credentials.
*
* For more information, see the following documentation topic:
*
* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
*/
public class CompareFaces {
public static void main(String[] args) {
final String usage = "\n" +
"Usage: " +
" <pathSource> <pathTarget>\n\n" +
"Where:\n" +
" pathSource - The path to the source image (for example, C:\\AWS\\pic1.png). \n " +
" pathTarget - The path to the target image (for example, C:\\AWS\\pic2.png). \n\n";
if (args.length != 2) {
System.out.println(usage);
System.exit(1);
}
Float similarityThreshold = 70F;
String sourceImage = args[0];
String targetImage = args[1];
Region region = Region.US_EAST_1;
RekognitionClient rekClient = RekognitionClient.builder()
.region(region)
.credentialsProvider(ProfileCredentialsProvider.create())
.build();
compareTwoFaces(rekClient, similarityThreshold, sourceImage, targetImage);
rekClient.close();
}
// snippet-start:[rekognition.java2.compare_faces.main]
public static void compareTwoFaces(RekognitionClient rekClient, Float similarityThreshold, String sourceImage, String targetImage) {
try {
InputStream sourceStream = new FileInputStream(sourceImage);
InputStream tarStream = new FileInputStream(targetImage);
SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream);
SdkBytes targetBytes = SdkBytes.fromInputStream(tarStream);
// Create an Image object for the source image.
Image souImage = Image.builder()
.bytes(sourceBytes)
.build();
Image tarImage = Image.builder()
.bytes(targetBytes)
.build();
CompareFacesRequest facesRequest = CompareFacesRequest.builder()
.sourceImage(souImage)
.targetImage(tarImage)
.similarityThreshold(similarityThreshold)
.build();
// Compare the two images.
CompareFacesResponse compareFacesResult = rekClient.compareFaces(facesRequest);
List<CompareFacesMatch> faceDetails = compareFacesResult.faceMatches();
for (CompareFacesMatch match: faceDetails){
ComparedFace face= match.face();
BoundingBox position = face.boundingBox();
System.out.println("Face at " + position.left().toString()
+ " " + position.top()
+ " matches with " + face.confidence().toString()
+ "% confidence.");
}
List<ComparedFace> uncompared = compareFacesResult.unmatchedFaces();
System.out.println("There was " + uncompared.size() + " face(s) that did not match");
System.out.println("Source image rotation: " + compareFacesResult.sourceImageOrientationCorrection());
System.out.println("target image rotation: " + compareFacesResult.targetImageOrientationCorrection());
} catch(RekognitionException | FileNotFoundException e) {
System.out.println("Failed to load source image " + sourceImage);
System.exit(1);
}
}
// snippet-end:[rekognition.java2.compare_faces.main]
}
This code works fine too with JPG images -- as shown in the following image of an IDE debugging the code displaying the results:
UPDATE
I normally do not touch V1 code at all; however, i was curious. This code worked....
package aws.example.rekognition.image;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.rekognition.AmazonRekognition;
import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
import com.amazonaws.services.rekognition.model.Image;
import com.amazonaws.services.rekognition.model.BoundingBox;
import com.amazonaws.services.rekognition.model.CompareFacesMatch;
import com.amazonaws.services.rekognition.model.CompareFacesRequest;
import com.amazonaws.services.rekognition.model.CompareFacesResult;
import com.amazonaws.services.rekognition.model.ComparedFace;
import java.util.List;
import com.amazonaws.services.rekognition.model.S3Object;
public class CompareFacesBucket {
public static void main(String[] args) throws Exception{
Float similarityThreshold = 70F;
AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.standard()
.withRegion(Regions.US_WEST_2)
.build();
String reference = "Lam1.jpg";
String target = "Lam2.jpg";
String bucket = "<MyBucket>";
CompareFacesRequest request = new CompareFacesRequest()
.withSourceImage(new Image().withS3Object(new S3Object()
.withName(reference).withBucket(bucket)))
.withTargetImage(new Image().withS3Object(new S3Object()
.withName(target).withBucket(bucket)))
.withSimilarityThreshold(similarityThreshold);
// Call operation
CompareFacesResult compareFacesResult = rekognitionClient.compareFaces(request);
// Display results
List <CompareFacesMatch> faceDetails = compareFacesResult.getFaceMatches();
for (CompareFacesMatch match: faceDetails){
ComparedFace face= match.getFace();
BoundingBox position = face.getBoundingBox();
System.out.println("Face at " + position.getLeft().toString()
+ " " + position.getTop()
+ " matches with " + face.getConfidence().toString()
+ "% confidence.");
}
List<ComparedFace> uncompared = compareFacesResult.getUnmatchedFaces();
System.out.println("There was " + uncompared.size()
+ " face(s) that did not match");
System.out.println("Source image rotation: " + compareFacesResult.getSourceImageOrientationCorrection());
System.out.println("target image rotation: " + compareFacesResult.getTargetImageOrientationCorrection());
}
}
Output:
The last thing that i can think of as my V1 code works with JPG images and yours does not is your JPG image files may be corrupt or something. I would like to test this code with your images.

How to log HttpClient requests, response including body?

Jersey provides an excellent client-side logging facility that looks like this:
INFO: 1 * Server has received a request on thread grizzly-http-server-0
1 > GET http://localhost:9998/helloworld
1 > accept: text/plain
1 > accept-encoding: gzip,deflate
1 > connection: Keep-Alive
1 > host: localhost:9998
1 > user-agent: Jersey/3.0-SNAPSHOT (Apache HttpClient 4.5)
INFO: 1 * Server responded with a response on thread grizzly-http-server-0
1 < 200
1 < Content-Type: text/plain
Hello World!
We see the worker thread, request method, URI, headers and the response code, headers, and body.
Is there an equivalent functionality for Jetty? Or do we need to roll our own?
I ended up implementing this myself, with slight variations on the Jetty format:
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.http.HttpField;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicLong;
import static org.bitbucket.cowwoc.requirements.core.Requirements.requireThat;
/**
* Logs HttpClient request/response traffic.
*
* #author Gili Tzabari
*/
public final class RequestLogger
{
/**
* {#code true} if request values should be grouped together, and response values should be grouped together to improve readability.
* {#code false} if events should be logged as soon as they arrive (useful when diagnosing performance problems).
*/
private static final boolean IMPROVED_READABILITY = true;
private final AtomicLong nextId = new AtomicLong();
private final Logger log = LoggerFactory.getLogger(RequestLogger.class);
/**
* Attaches event listeners to a request.
*
* #param request the request to listen to
* #return the request
* #throws NullPointerException if {#code request} is null
*/
public Request listenTo(Request request)
{
requireThat("request", request).isNotNull();
if (IMPROVED_READABILITY)
improvedReadability(request);
else
correctTiming(request);
return request;
}
/**
* Group events for improved readability.
*
* #param request the request to listen to
*/
private void improvedReadability(Request request)
{
long id = nextId.getAndIncrement();
StringBuilder group = new StringBuilder();
request.onRequestBegin(theRequest -> group.append("Request " + id + "\n" +
id + " > " + theRequest.getMethod() + " " + theRequest.getURI() + "\n"));
request.onRequestHeaders(theRequest ->
{
for (HttpField header : theRequest.getHeaders())
group.append(id + " > " + header + "\n");
});
StringBuilder contentBuffer = new StringBuilder();
request.onRequestContent((theRequest, content) ->
contentBuffer.append(ByteBuffers.toString(content, getCharset(theRequest.getHeaders()))));
request.onRequestSuccess(theRequest ->
{
if (contentBuffer.length() > 0)
{
group.append("\n" +
contentBuffer.toString());
}
log.debug(group.toString());
contentBuffer.delete(0, contentBuffer.length());
group.delete(0, group.length());
});
request.onResponseBegin(theResponse ->
{
group.append("Response " + id + "\n" +
id + " < " + theResponse.getVersion() + " " + theResponse.getStatus());
if (theResponse.getReason() != null)
group.append(" " + theResponse.getReason());
group.append("\n");
});
request.onResponseHeaders(theResponse ->
{
for (HttpField header : theResponse.getHeaders())
group.append(id + " < " + header + "\n");
});
request.onResponseContent((theResponse, content) ->
contentBuffer.append(ByteBuffers.toString(content, getCharset(theResponse.getHeaders()))));
request.onResponseSuccess(theResponse ->
{
if (contentBuffer.length() > 0)
{
group.append("\n" +
contentBuffer.toString());
}
log.debug(group.toString());
});
}
/**
* Log events as they come in.
*
* #param request the request to listen to
*/
private void correctTiming(Request request)
{
long id = nextId.getAndIncrement();
request.onRequestBegin(theRequest -> log.debug(id + " > " + theRequest.getMethod() + " " + theRequest.getURI()));
request.onRequestHeaders(theRequest ->
{
for (HttpField header : theRequest.getHeaders())
log.debug(id + " > " + header);
});
request.onRequestContent((theRequest, content) -> log.debug(id + " >> " +
ByteBuffers.toString(content, getCharset(theRequest.getHeaders()))));
request.onResponseBegin(theResponse ->
{
StringBuilder line = new StringBuilder(id + " < " + theResponse.getVersion() + " " + theResponse.getStatus());
if (theResponse.getReason() != null)
line.append(" " + theResponse.getReason());
log.debug(line.toString());
});
request.onResponseHeaders(theResponse ->
{
for (HttpField header : theResponse.getHeaders())
log.debug(id + " < " + header);
});
StringBuilder responseBody = new StringBuilder();
request.onResponseContent((theResponse, content) ->
responseBody.append(ByteBuffers.toString(content, getCharset(theResponse.getHeaders()))));
request.onResponseSuccess(theResponse -> log.debug(id + " << " + responseBody));
}
/**
* #param headers HTTP headers
* #return the charset associated with the request or response body
*/
private Charset getCharset(HttpFields headers)
{
String contentType = headers.get(HttpHeader.CONTENT_TYPE);
if (contentType == null)
return StandardCharsets.UTF_8;
String[] tokens = contentType.toLowerCase(Locale.US).split("charset=");
if (tokens.length != 2)
return StandardCharsets.UTF_8;
// Remove semicolons or quotes
String encoding = tokens[1].replaceAll("[;\"]", "");
return Charset.forName(encoding);
}
}
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import static org.bitbucket.cowwoc.requirements.core.Requirements.requireThat;
/**
* ByteBuffer helper functions.
*
* #author Gili Tzabari
*/
public final class ByteBuffers
{
/**
* #param buffer a {#Code ByteBuffer}
* #param charset the character set of the bytes
* #return the {#code String} representation of the bytes
*/
public static String toString(ByteBuffer buffer, Charset charset)
{
requireThat("buffer", buffer).isNotNull();
byte[] bytes;
if (buffer.hasArray())
bytes = buffer.array();
else
{
bytes = new byte[buffer.remaining()];
buffer.get(bytes, 0, bytes.length);
}
return new String(bytes, charset);
}
/**
* Prevent construction.
*/
private ByteBuffers()
{
}
}
Usage:
Request request = new HttpClient().newRequest("http://www.test.com/");
new RequestLogger().listenTo(request).send();

How to prevent < converted to < when using web service proxy class in JDeveloper

I am calling a BPM web service that sends HTML email. I generated a web service proxy in JDeveloper 11.1.1.7. The type of the body of the email is xsd:string which should map to java String. I understand that certain characters, for example < > &, are reserved and converted during the xml document creation during the proxy operation.
Using SOAPUI to call the service, I can pass the body as <h1>My Heading</h1> and service responds correctly, sending the email with HTML as expected. When doing the same from a POJO that calls the proxy, <h1> is converted to <h1>My heading</h1>.
I have tried passing the body as a CDATA section but this makes no difference. I have tried converting the body to bytes then back to a UTF-8 string before the call but still no difference. I have access to the BPM service code. Is there a way I can send html to the service from a proxy, that retains the special characters?
I figured this out finally. While the JDeveloper web service proxy generator is useful most of the time, in this case it was not since I needed to send xml special characters to the service. Perhaps there is a way to manipulate the proxy code to do what you want but I couldn't figure it out.
Of particular help was this AMIS blog entry. And if you ever need to handle special characters during JAXB marshalling, this entry will help you too. A great summary of the steps to use the java URLConnection class is here and that answer points to a library that would probably make life even easier.
So here is the raw wrapper code below. The particular BPM email service we wrote also writes to a log and that explains the complex types in the raw xml input. Naturally I will populate the email values from a passed in POJO object in the main sendMail wrapper method.
package com.yourdomain.sendmail.methods;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import oracle.adf.model.connection.url.URLConnectionProxy;
import oracle.adf.share.ADFContext;
public class SendMailWrapper {
public SendMailWrapper() {
super();
}
public static void main(String[] args) throws MalformedURLException, IOException {
SendMailWrapper w = new SendMailWrapper();
w.sendMail();
}
public void sendMail() throws MalformedURLException, IOException {
String xmlInput =
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
"xmlns:sen=\"http://xmlns.oracle.com/bpmn/bpmnProcess/SendEmailProcess\" " +
"xmlns:ema=\"http://www.wft.com/BPM/SendEmail/Email\">\n" +
"<soapenv:Header/>" +
"<soapenv:Body>\n" +
"<sen:start>\n" +
"<ema:emailInput>\n" +
"<ema:emailContent>\n" +
"<ema:toAddr>your.name#yourdomain.com</ema:toAddr>\n" +
"<ema:fromAddr></ema:fromAddr>\n" +
"<ema:ccAddr></ema:ccAddr>\n" +
"<ema:bccAddr></ema:bccAddr>\n" +
"<ema:subject>SendMail HTML</ema:subject>\n" +
"<ema:body><h1>My Heading</h1><p>Text</p></ema:body>\n" +
"<ema:contentType>text/html</ema:contentType>\n" +
"</ema:emailContent>\n" +
"<ema:emailHistory>\n" +
"<ema:projectName>Soap Test</ema:projectName>\n" +
"<ema:reqID></ema:reqID>\n" +
"<ema:compositeID></ema:compositeID>\n" +
"<ema:processID></ema:processID>\n" +
"<ema:processName></ema:processName>\n" +
"<ema:activityName></ema:activityName>\n" +
"<ema:insertDate></ema:insertDate>\n" +
"<ema:insertByID></ema:insertByID>\n" +
"<ema:insertByName></ema:insertByName>\n" +
"<ema:commentType></ema:commentType>\n" +
"<ema:commentInfo></ema:commentInfo>\n" +
"</ema:emailHistory>\n" +
"</ema:emailInput>\n" +
"</sen:start>\n" +
"</soapenv:Body>\n" +
"</soapenv:Envelope>\n";
System.out.println(xmlInput);
String wsURL = getWsdlUrl();
URL url = new URL(wsURL);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection)connection;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buffer = new byte[xmlInput.length()];
buffer = xmlInput.getBytes();
bout.write(buffer);
byte[] b = bout.toByteArray();
String SOAPAction = "start"; //this is the method in the service
httpConn.setRequestProperty("Content-Length", String.valueOf(b.length));
httpConn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
//some other props available but don't need to be set...
//httpConn.setRequestProperty("Accept-Encoding", "gzip,deflate");
//httpConn.setRequestProperty("Host", "your.host.com:80");
//httpConn.setRequestProperty("Connection", "Keep-Alive");
//httpConn.setRequestProperty("User-Agent", "Apache-HttpClient/4.1.1 (java 1.5)");
httpConn.setRequestProperty("SOAPAction", SOAPAction);
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
OutputStream out = httpConn.getOutputStream();
out.write(b);
out.close();
//check response code...
int status = httpConn.getResponseCode();
String respMessage = httpConn.getResponseMessage();
System.out.println("RESPONSE CODE: " + status + " RESPONSE MESSAGE: " + respMessage);
//check response headers...
for (Map.Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
System.out.println(header.getKey() + "=" + header.getValue());
}
//check error stream - this helps alot when debugging...
InputStream errorStream = ((HttpURLConnection)connection).getErrorStream();
if (errorStream != null) {
System.out.println("Error Stream: " + convertStreamToString(errorStream));
}
//if there was an expected response, you need to parse it...
/* String responseString = "";
String outputString = "";
InputStreamReader isr = new InputStreamReader(httpConn.getInputStream());
BufferedReader in = new BufferedReader(isr);
while ((responseString = in.readLine()) != null) {
outputString = outputString + responseString;
}
isr.close();
System.out.println("OUT: " + outputString); */
}
static String convertStreamToString(InputStream is) {
Scanner s = new Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
private static String getWsdlUrl() {
String result = null;
try {
URLConnectionProxy wsConnection = (URLConnectionProxy)ADFContext.getCurrent().getConnectionsContext().lookup("SendMailProxyConnection");
result = wsConnection.getURL().toExternalForm();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
Happy coding.

How to fetch specific data from string using regex in python

I have following program in in that want to fetch
"planned", "not automated", "st3reporter", "functional", "report-upto3times-per2hrs", "st3-throttling-cdb"
**These value from string **
import re
string='''
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class ReportUpToTimesEveryHours {
String objective = "04 - Report up to 3 times every 2 hours";
String testName = "ReportUpToTimesEveryHours";
#BeforeMethod(alwaysRun = true)
public void beforeMethod() {
logger.info(Constants.LOGGER_SEPERATOR);
logger.info("Start -- " + testName + " - " + objective);
}
#Test(groups = { "planned", "not automated", "st3reporter", "functional", "report-upto3times-per2hrs", "st3-throttling-cdb" },
description = "04 - Report up to 3 times every 2 hours")
public void testReportUpToTimesEveryHours() {
}
#AfterMethod(alwaysRun = true)
public void afterMethod() {
logger.info("End -- " + testName + " - " + objective);
logger.info(Constants.LOGGER_SEPERATOR);
}
}
'''
pattern=re.compile(r' (\#Test\(groups\s*=\s*\{)')
m= pattern.search(string)
print m.group()
Try something like this:
pattern=re.compile(r' #Test\(groups\s*=\s*\{([^\}]+)')
result_set = [i.strip() for i in
pattern.search(string).group(1).replace('"', '').split(',')]
The value will store a list:
['planned', 'not automated', 'st3reporter', 'functional', 'report-upto3times-per2hrs', 'st3-throttling-cdb']

Refresh Jtable

I have a JTable created from Vector.
How can the JTable be refreshed to display new data that is added to the Vector?
Your JTable should update automatically when a change to the TableModel happens. I'm taking a leap here but I'm guessing that you're not using your own TableModel and just called the JTable constructor with your Vector. In this case you can get a hook on the TableModel and cast it to a DefaultTableModel and then call one its notification methods to let the JTable know of a change, something like:
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.fireTableChanged(new TableModelEvent(........));
What I would really recommend is using your own TableModel unless this is something very trivial, but the fact you're updating the data indicates it's not.
Check out the sun tutorial on working with tables, inparticular the section on listening for data changes.
It might seem like more work up front, but it will save you alot of headaches in the long run and is The Right Way to do it
I call the initTable method followed by loadTable(). I'm sure there's plenty of other ways but this works like acharm.
private void initBerkheimerTable() {
tblBerkheimer = new JTable();
tblBerkheimer.getSelectionModel().addListSelectionListener(new SelectionListener());
tblBerkheimer.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
tblBerkheimer.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"Id", "Name", "Berkheimer PSD", "Rate", "Current PSD", "Current Rate"
}
) {
Class[] columnTypes = new Class[] {
String.class, String.class, String.class, String.class, String.class, String.class
};
public Class getColumnClass(int columnIndex) {
return columnTypes[columnIndex];
}
boolean[] columnEditables=new boolean[]{false,false,false,false,false,false,false,false,false,false};
public boolean isCellEditable(int row, int column) {
return columnEditables[column];
}
});
scrollPane.setViewportView(tblBerkheimer);
add(scrollPane);
}
private void loadTable(){
PreparedStatement ps=null;
ResultSet rs=null;
try {
PayrollPsdAuditing.payroll=Database.connectToSQLServerDataBase(PayrollPsdAuditing.payrollIni);
ps=PayrollPsdAuditing.payroll.prepareStatement(
"SELECT a.EMPLOYID, " +
" a.NAME, " +
" a.PSD_CODE, " +
" a.RATE, " +
" b.STRINGS_I_2 as CURRENT_PSD, " +
" c.lcltaxrt as CURRENT_RATE " +
"FROM PYRL_PSD_VALIDATION a, " +
" EX010130 b, " +
" UPR41400 c " +
"WHERE a.employid=b.empid_i " +
" AND c.localtax=b.strings_i_2");
rs=ps.executeQuery();
while(rs.next()) {
Swing.fillJTable(tblBerkheimer,
new String[]{rs.getString("EMPLOYID").trim()
,rs.getString("NAME").trim()
,rs.getString("PSD_CODE").trim()
,String.valueOf(rs.getDouble("RATE"))
,rs.getString("CURRENT_PSD").trim()
,String.valueOf(rs.getDouble("CURRENT_RATE")/100000)});
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
Database.close(PayrollPsdAuditing.payroll);
}
}