java unit test mock HttpClient and webdav - java

Hello I have a class for doing webdav related operations such as creating a directory, Implementatiion can be seen below (the createDir method). The question is how to test it nicely, perhaps using EasyMock or a similar lib. Any ideas? thanks!
package foobar;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.jackrabbit.webdav.client.methods.DavMethod;
import org.apache.jackrabbit.webdav.client.methods.MkColMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import mypackage.httpdclient.util.URLHandler;
public class WebDavImpl{
private static final String SEPARATOR = " ----- ";
private HttpClient httpClient;
public StorageSpaceClientImpl() {
httpClient = new HttpClient();
}
public String createDir(String dirName) {
String response = null;
String url = URLHandler.getInstance().getDirectoryUrl(dirName);
DavMethod mkcol = new MkColMethod(url);
try {
httpClient.executeMethod(mkcol);
response = mkcol.getStatusCode() + SEPARATOR + mkcol.getStatusText();
} catch (IOException ex) {
} finally {
mkcol.releaseConnection();
}
return response;
}
}

Related

Prometheus 'expected label name, got "BCLOSE"' error

I have an application running on port 7070 on my local. It exposes and endpoint /metrics and shows all the tags that are available. Prometheus is not able to get these data and it says 'expected label name, got "BCLOSE"'.
I have been trying to figure this out but not sure why this code doesn't work:
import io.micrometer.prometheus.PrometheusMeterRegistry;
import io.prometheus.client.exporter.common.TextFormat;
import metrics.PrometheusRegistry;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
#Path("/metrics")
public class MetricsController {
private final PrometheusMeterRegistry prometheusRegistry = PrometheusRegistry.INSTANCE();
#GET
public Response getMetrics(#Context HttpHeaders headers) {
Writer writer = new StringWriter();
try {
TextFormat.write004(writer, prometheusRegistry.getPrometheusRegistry().metricFamilySamples());
} catch (IOException e) {
e.printStackTrace();
}
return writer.toString();
}
}
Also, the application is neither a sprintboot nor a spring project.
Tried this:
#GET
public Response getMetrics(#Context HttpHeaders headers) {
String accept = headers.getRequestHeader("Accept").get(0);
System.out.println("Accept Header --------------------------> " + accept);
return Response.ok(prometheusRegistry.scrape(), "application/openmetrics-text").build();
}
Even then the same error as above SS.
This worked for me:
#GET
public Response getMetrics() {
return Response.ok(prometheusRegistry.scrape(), TextFormat.CONTENT_TYPE_004).build();
}

Braintree webhooks: Error: payload contains illegal characters

I am trying to consume Braintree webhooks in a java microservice (Micronaut fwiw).
The issue that I'm having is that when I try to parse the webhook body, I get an error: " Error: payload contains illegal characters", which it does. So I'm wondering if maybe I'm casting the request body to something thats inserting the characters...? (the body is x-www-form-urlencoded)
package com.autonomy;
import com.braintreegateway.*;
import event_broker.BrokerServiceGrpc;
import event_broker.EventBroker;
import events.Events;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.micronaut.context.annotation.Value;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Body;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Post;
import io.micronaut.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.Normalizer;
import java.time.Clock;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
#Controller("/webhooks")
public class WebhooksController {
private final Logger logger = LoggerFactory.getLogger("BraintreeServiceJava");
#Value("${env}") String env;
#Value("${braintree.merchant.id}") String braintreeMerchantId;
#Value("${braintree.public.key}") String braintreePublicKey;
#Value("${braintree.private.key}") String braintreePrivateKey;
#Post(consumes = MediaType.APPLICATION_FORM_URLENCODED)
public HttpResponse<?> consumeWebhook(#Body String body) {
BraintreeGateway gateway =
new BraintreeGateway(determineEnv(env),
braintreeMerchantId,
braintreePublicKey,
braintreePrivateKey
);
logger.info(body);
try {
String decodedBody = body; // was doing a decode here that didn't do anything
logger.info(decodedBody);
Map<String, String> map = new HashMap<>();
Arrays.stream(decodedBody.split("&")).toList().forEach(pair -> {
String[] param = pair.split("=");
map.put(param[0], param[1]);
});
WebhookNotification webhookNotification = gateway.webhookNotification().parse(
map.get("bt_signature"),
map.get("bt_payload")
);
..... Do stuff
} catch (Exception e) {
logger.error(String.format("Braintree webhook failed for %s. Error: %s", kind, e.getMessage()), e);
return HttpResponse.status(HttpStatus.BAD_REQUEST);
}
return HttpResponse.status(HttpStatus.OK);
}
private Environment determineEnv(String env) {
if (env.equals("beta") || env.equals("prod")) {
return Environment.PRODUCTION;
} else {
return Environment.SANDBOX;
}
}
}
Try:
#Post(consumes = MediaType.APPLICATION_FORM_URLENCODED)
public HttpResponse<?> consumeWebhook(String bt_signature, String bt_payload)
BTW: What 'illegal characters' were in the body that was logged?

How to get Soap header without SOAP handler

I am trying edit my soap header using my java code before running the request. I am not using handler or jax-rs. I saw WsdlUtils but am not able figure how to use this in my code. please someone help me in this
Here's my code;
package soap.impl;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.xmlbeans.XmlException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.eviware.soapui.SoapUI;
import com.eviware.soapui.StandaloneSoapUICore;
import com.eviware.soapui.config.impl.TestStepConfigImpl;
import com.eviware.soapui.impl.wsdl.WsdlHeaderPart;
import com.eviware.soapui.impl.wsdl.WsdlProject;
import com.eviware.soapui.impl.wsdl.WsdlTestSuite;
import com.eviware.soapui.impl.wsdl.submit.filters.SoapHeadersRequestFilter;
import com.eviware.soapui.impl.wsdl.support.wsdl.WsdlUtils;
import com.eviware.soapui.impl.wsdl.support.wsdl.WsdlUtils.SoapHeader;
import com.eviware.soapui.impl.wsdl.testcase.WsdlTestCase;
import com.eviware.soapui.impl.wsdl.testcase.WsdlTestCaseRunner;
import com.eviware.soapui.model.TestPropertyHolder;
import com.eviware.soapui.model.iface.MessageExchange;
import com.eviware.soapui.model.propertyexpansion.PropertyExpansionUtils;
import com.eviware.soapui.model.support.PropertiesMap;
import com.eviware.soapui.model.support.TestPropertyUtils;
import com.eviware.soapui.model.testsuite.TestCase;
import com.eviware.soapui.model.testsuite.TestProperty;
import com.eviware.soapui.model.testsuite.TestRunner;
import com.eviware.soapui.model.testsuite.TestStepResult;
import com.eviware.soapui.model.testsuite.TestRunner.Status;
import com.eviware.soapui.model.testsuite.TestSuite;
import com.eviware.soapui.support.SoapUIException;
import com.eviware.soapui.support.types.StringToObjectMap;
import com.eviware.soapui.support.types.StringToStringsMap;
public class RunTestImpl{
static Logger logger = LoggerFactory.getLogger(RunTestImpl.class);
public static void main(String[] args) throws XmlException, IOException, SoapUIException {
logger.info("Into the Class for running test cases");
String suiteName = "";
String reportStr = "";
InputData input=new InputData();
TestPropertyHolder holder = PropertyExpansionUtils.getGlobalProperties();
String testCaseName="";
holder.setPropertyValue("CRK", "CRK987909000000000075");
// variables for getting duration
WsdlTestCaseRunner runner = null;
List<TestSuite> suiteList = new ArrayList<TestSuite>();
List<TestCase> caseList = new ArrayList<TestCase>();
SoapUI.setSoapUICore(new StandaloneSoapUICore(true));
// specified soapUI project
WsdlProject project1 = new WsdlProject("D://my-project.xml");
WsdlTestSuite testSuite1= project1.getTestSuiteByName("my TestSuite");
WsdlTestCase testCase1= testSuite1.getTestCaseByName("myTestCase");
suiteList.add(testSuite1);
runner= testCase1.run(new StringToObjectMap(), false);
List<TestStepResult> list= runner.getResults();
StringToStringsMap headers1=null;
for (TestStepResult testStepResult : list) {
testStepResult).getRequestContent();
byte[] rawReq=((MessageExchange)testStepResult).getRawRequestData();
headers1 = ((MessageExchange)testStepResult).getRequestHeaders();
String response = ((MessageExchange)testStepResult).getResponseContent();
StringBuilder build=new StringBuilder();
for (byte b : rawReq) {
build.append((char)b);
}
System.out.println("build "+build.toString());
}
for (Map.Entry<String,List< String>> entry : headers1.entrySet()) {
System.out.println("key"+entry.getKey());
for (String string:entry.getValue()) {
System.out.println("value "+string);
}
}
// }
// string of the results
System.out.println(reportStr);
}
}

UIMA Pipeline with Stanford NER

I have integrated Stanford NER in UIMA and developed a pipeline.
The pipeline contains a FileSystemCollectionReader,an NERAnnotator and a CasConsumer but the output so come isn't desired. In my input directory i have two files and after running the pipeline, i get two files as ouput but the second file is getting merged with the first file in second ouput. I don't know what's happening here.
The code for CasConsumer:
`
package org.gds.uima;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import org.apache.uima.UimaContext;
import org.apache.uima.analysis_component.AnalysisComponent_ImplBase;
import org.apache.uima.analysis_component.CasAnnotator_ImplBase;
import org.apache.uima.analysis_component.JCasAnnotator_ImplBase;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.cas.CAS;
import org.apache.uima.cas.CASException;
import org.apache.uima.cas.Type;
import org.apache.uima.cas.text.AnnotationFS;
import org.apache.uima.fit.component.CasConsumer_ImplBase;
import org.apache.uima.fit.component.JCasConsumer_ImplBase;
import org.apache.uima.fit.descriptor.ConfigurationParameter;
import org.apache.uima.fit.util.CasUtil;
import org.apache.uima.jcas.JCas;
import org.apache.uima.resource.ResourceInitializationException;
public class CasConsumer extends JCasConsumer_ImplBase
{
public final static String PARAM_OUTPUT="outputDir";
#ConfigurationParameter(name = PARAM_OUTPUT)
private String outputDirectory;
public final static String PARAM_ANNOTATION_TYPES = "annotationTypes";
enter code here
#ConfigurationParameter(name = PARAM_ANNOTATION_TYPES,defaultValue="String")
public List<String> annotationTypes;
public void initialize(final UimaContext context) throws ResourceInitializationException
{
super.initialize(context);
}
#Override
public void process(JCas jcas)
{
String original = jcas.getDocumentText();
try
{
String onlyText="";
JCas sofaText = jcas.getView(NERAnnotator.SOFA_NAME);
onlyText = sofaText.getDocumentText();
String name = UUID.randomUUID().toString().substring(20);
File outputDir = new File(this.outputDirectory+"/"+name);
System.out.print("Saving file to "+outputDir.getAbsolutePath());
FileOutputStream fos = new FileOutputStream(outputDir.getAbsoluteFile());
PrintWriter pw = new PrintWriter(fos);
pw.println(onlyText);
pw.close();
}
catch(CASException cae)
{
System.out.println(cae);
}
catch(FileNotFoundException fne)
{
System.out.print(fne);
}
}
}
`
}

Consume Java weblogic web service having usernametoken and client certificate in ASP.Net

i need to consume a web service developed with java web logic server, usernametoken and client certificate are used to invoke the service.
and i got the java code to call web service as below
import javax.ejb.CreateException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.rmi.RemoteException;
import weblogic.wtc.jatmi.TPException;
import weblogic.wtc.jatmi.TypedString;
import weblogic.wtc.jatmi.Reply;
import weblogic.wtc.jatmi.TuxedoReply;
import weblogic.wtc.jatmi.TPServiceInformation;
import weblogic.wtc.jatmi.TypedFML32;
import weblogic.wtc.jatmi.TuxedoService;
import weblogic.wtc.jatmi.TypedBuffer;
import java.util.StringTokenizer;
import java.io.IOException;
import javax.xml.rpc.ServiceException;
import MMSWbSrv.*;
import java.util.Properties;
import java.text.SimpleDateFormat;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.security.cert.X509Certificate;
import weblogic.security.SSL.TrustManager;
import weblogic.xml.crypto.wss.provider.CredentialProvider;
import weblogic.xml.crypto.wss.WSSecurityContext;
import weblogic.wsee.security.bst.ClientBSTCredentialProvider;
import weblogic.wsee.security.unt.ClientUNTCredentialProvider;
import java.security.cert.X509Certificate;
import weblogic.wsee.security.util.CertUtils;
import javax.xml.rpc.Stub;
import java.util.List;
import java.util.ArrayList;
import java.util.regex.*;
import weblogic.wtc.jatmi.TypedFML32;
public class MMSTest
{
public static void main(String args[]) throws Throwable
{
Properties sysProps = System.getProperties();
sysProps.setProperty("http.proxyHost","XXX.XX.X.XX");
sysProps.setProperty("http.proxyPort","XXXX");
sysProps.setProperty("weblogic.webservice.transport.http.proxy.host", "XXX.XX.X.XX");
sysProps.setProperty("weblogic.webservice.transport.http.proxy.port", "XXXX");
sysProps.setProperty("http.proxySet","true");
sysProps.setProperty("weblogic.webservice.verbose","true");
sysProps.setProperty("javax.net.ssl.trustStore","D:/weblogic92/server/lib/DemoTrust.jks");
System.out.println("proxyHost::"+ sysProps.getProperty("http.proxyHost"));
System.out.println("proxyPort::"+ sysProps.getProperty("http.proxyPort"));
MMSService service = null;
MMSPortType port = null;
try{
System.out.println("before..");
service = new MMSService_Impl("http://XXX.XX.X.XX/MMS/Service?wsdl");
System.out.println("after..");
if(service==null)
System.out.println("NULL SERVICE");
System.out.println("got service...");
port = service.getMMSServicePort();
if(port==null)
System.out.println("NULL PORT");
}
catch(ServiceException svcEx)
{
System.out.println("In ServiceXexception");
}
List credProviders = new ArrayList();
System.out.println("After cred");
String clientCertFile = "F:/client-cert.der";
String keyFile = "F:/client-key-pkcs8.der";
String username = "userName" ;
String password = "Password" ;
CredentialProvider cp = new ClientBSTCredentialProvider(clientCertFile, keyFile);
credProviders.add(cp);
System.out.println("credProviders:"+credProviders);
System.out.println("cp:"+cp+":");
String strret= "";
try{
cp = new ClientUNTCredentialProvider(username, password);
credProviders.add(cp);
Stub stub = (Stub)port;
System.out.println("before");
stub._setProperty(WSSecurityContext.CREDENTIAL_PROVIDER_LIST, credProviders);
System.out.println("after");
stub._setProperty(WSSecurityContext.TRUST_MANAGER,
new TrustManager()
{
public boolean certificateCallback(X509Certificate[] chain, int validateErr)
{
return true;
}
}
);
String strArg = "Parameters";
strret = port.sendData(strArg);
}
catch(Exception e)
{
System.out.println("JJJ");
e.printStackTrace();
}
System.out.println("strret:"+strret);
}
}
and also .pfx format client certificate and .key file .
So using WSE3.0 i try to consume the service like below
WebReference.MMSServiceWse wse = new MMSServiceWse();
UsernameToken token = new UsernameToken("XXXX", "XXXX", PasswordOption.SendPlainText);
wse.RequestSoapContext.Security.Tokens.Add(token);
X509Certificate2 cert = new X509Certificate2(#"D:\\certificate.pfx","",X509KeyStorageFlags.MachineKeySet);
wse.ClientCertificates.Add(cert);
wse.SetPolicy("ClientPolicy");
//System.Net.ServicePointManager.CertificatePolicy =new TrustAllCertificatePolicy();
String strArg = "Param";
strArg= wse.sendData(strArg);
but i have got exception.
When this happens to me, it is usually because the time on the server and the client are too different. The security token has a validity period and if you're not in sync, it seems expired or worse, in the future.

Categories