DHL Webservice Security issue - java

I'm trying to connect DHL Webservice searchLocations DHL wsdl:https://standorte.deutschepost.de/webservice/?wsdl
Here the code I'm using (just trying to test it ), I always get this exception :
de.dpag.postfinder.webservice.ServiceException_Exception: Access denied. Access key is not valid.
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.handler.MessageContext;
import de.dpag.postfinder.webservice.AutomatWS;
import de.dpag.postfinder.webservice.InputAddress;
import de.dpag.postfinder.webservice.WebServiceImpl;
import de.dpag.postfinder.webservice.WebServiceImplService;
public class DHLWebService {
public static void main(String[] args) throws Exception {
InputAddress request = new InputAddress();
request.setCountryCode("DE");
request.setCity("Bonn");
request.setStreet("harles-de-Gaulle-Str");
request.setStreetNo("20");
request.setZip("53113");
List<AutomatWS> packstationsByAddress = new ArrayList<AutomatWS>();
String wsdlLocation = "https://standorte.deutschepost.de/webservice/?wsdl";
try {
URL wsdlUrl = new URL(wsdlLocation);
QName qName = new QName("http://postfinder.dpag.de/webservice", "WebServiceImplService");
WebServiceImplService dhlClientService = new WebServiceImplService(wsdlUrl, qName);
WebServiceImpl webServiceImplPort = dhlClientService.getWebServiceImplPort();
Map<String, Object> req_ctx = ((BindingProvider) webServiceImplPort).getRequestContext();
req_ctx.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "https://standorte.deutschepost.de/webservice/?wsdl");
Map<String, List<String>> headers = new HashMap<String, List<String>>();
//sample username and password
headers.put("Username", Collections.singletonList("test"));
headers.put("Password", Collections.singletonList("test"));
req_ctx.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
packstationsByAddress = webServiceImplPort.getPackstationsByAddress("", request);
} catch (Exception e) {
e.printStackTrace();
}
for (AutomatWS automatWS : packstationsByAddress) {
System.out.println(automatWS.getAddress());
}
}
}

I figure out the problem,the end point need to be at the end of the wsdl file as the following :
<service name="WebServiceImplService">
<port name="WebServiceImplPort" binding="tns:WebServiceImplPortBinding">
<soap:address location="https://cig.dhl.de/services/sandbox/soap" />
</port>
</service>
Then the code should be as the following :
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import de.dpag.postfinder.webservice.AutomatWS;
import de.dpag.postfinder.webservice.InputAddress;
import de.dpag.postfinder.webservice.WebServiceImpl;
import de.dpag.postfinder.webservice.WebServiceImplService;
public class DHLWebService {
//wsdl path
private static final String RELATIVE_WSDL_PATH = "";
public static void main(String[] args) throws Exception {
InputAddress request = new InputAddress();
request.setCountryCode("DE");
request.setCity("Bonn");
request.setStreet("harles-de-Gaulle-Str");
request.setStreetNo("20");
request.setZip("53113");
List<AutomatWS> packstationsByAddress = new ArrayList<>();
try {
URL wsdlLocalURL = DHLWebService.class.getResource(RELATIVE_WSDL_PATH);
QName qName = new QName("http://postfinder.dpag.de/webservice", "WebServiceImplService");
WebServiceImplService dhlClientService = new WebServiceImplService(wsdlLocalURL,qName);
WebServiceImpl webServiceImplPort = dhlClientService.getWebServiceImplPort();
Map<String, Object> req_ctx = ((BindingProvider) webServiceImplPort).getRequestContext();
// replace it with your username and password
req_ctx.put(BindingProvider.USERNAME_PROPERTY, "test");
req_ctx.put(BindingProvider.PASSWORD_PROPERTY, "test");
packstationsByAddress = webServiceImplPort.getPackstationsByAddress("", request);
} catch (Exception e) {
e.printStackTrace();
}
for (AutomatWS automatWS : packstationsByAddress) {
System.out.println(automatWS.getAddress());
}
}
}

Related

Springboot - Save entity in 'normal' class

I'm pretty new to Springboot and Java in general and because we got this in school I'm fiddeling arround.
I'm now trying to save an entity outside of the Springboot Entities, Repositories or RestController with the following code:
InfMApplication.java:
package com.domain.springboot;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.domain.springboot.repositories.MovieRepository;
import com.domain.springboot.services.MovieImport;
#SpringBootApplication
public class InfMApplication {
public static void main(String[] args) {
SpringApplication.run(InfMApplication.class, args);
MovieImport movieImport = new MovieImport();
movieImport.saveToDb();
}
}
MovieImport.java:
package com.domain.springboot.services;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.CrossOrigin;
import java.io.*;
import java.net.URL;
import com.google.gson.Gson;
import com.domain.omdbapi.entities.Movie;
import com.domain.omdbapi.entities.SearchResponse;
import com.domain.omdbapi.entities.SearchResult;
import com.domain.springboot.repositories.ComplexRepository;
import com.domain.springboot.repositories.DocumentRepository;
import com.domain.springboot.repositories.MovieRepository;
import com.domain.springboot.repositories.SimpleRepository;
#Service
public class MovieImport {
private final MovieRepository movieRepository;
public MovieImport(MovieRepository movieRepository){
this.movieRepository = movieRepository;
}
public void main() {
String randomImdbId = fetchRandomMovie();
Movie movie = fetchMovieDetails(randomImdbId);
saveToDb(movie);
}
public void saveToDb(Movie movie) {
com.domain.springboot.entities.Movie springbootMovie = new com.domain.springboot.entities.Movie(movie.Title, movie.imdbID);
this.movieRepository.save(springbootMovie);
}
public String fetchRandomMovie() {
String randomWord = getRandomWord();
String url = "https://www.omdbapi.com/?apikey=<API_KEY>&type=movie&s=" + randomWord;
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(
URI.create(url))
.header("accept", "application/json")
.build();
HttpResponse<String> response = null;
try {
response = client.send(request, BodyHandlers.ofString());
} catch (Exception e) {
System.out.println(e);
}
Gson gson = new Gson();
SearchResponse searchResponse = gson.fromJson(response.body(), SearchResponse.class);
int randomIndex = new Random().nextInt(0, searchResponse.getSearch().length);
SearchResult randomResult = searchResponse.getSearch()[randomIndex];
return randomResult.getImdbID();
}
public Movie fetchMovieDetails(String imdbId) {
String url = "https://www.omdbapi.com/?apikey=<API_KEY>&type=movie&plot=full&i=" + imdbId;
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(
URI.create(url))
.header("accept", "application/json")
.build();
HttpResponse<String> response = null;
try {
response = client.send(request, BodyHandlers.ofString());
} catch (Exception e) {
System.out.println(e);
}
Gson gson = new Gson();
Movie movie = gson.fromJson(response.body(), Movie.class);
return movie;
}
public String getRandomWord() {
URL resource = getClass().getClassLoader().getResource("Wordlist.txt");
List<String> words = new ArrayList<>();
try {
File file = new File(resource.toURI());
words = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
}
int randomIndex = new Random().nextInt(0, words.size());
return words.get(randomIndex);
}
}
If I use "this.movieRepository.save(movieObject);" to save a movie in the MovieRestController the same way, it works. I also tried adding the "#Autowire" annotation, but this didn't work.
I always get the error
java.lang.NullPointerException: Cannot invoke "com.domain.springboot.repositories.MovieRepository.save(Object)" because "this.movieRepository" is null
How can I get to use the movieRepository in other Java classes like in the RestControllers?
java.lang.NullPointerException: Cannot invoke
"com.domain.springboot.repositories.MovieRepository.save(Object)"
because "this.movieRepository" is null
Above is perfectly valid if we look at your following shared code.
public class MovieImport {
private MovieRepository movieRepository;
public void saveToDb() {
// Create movie
com.domain.springboot.entities.Movie springbootMovie = new com.domain.springboot.entities.Movie("Iron Man", "284cb8fgf");
this.movieRepository.save(springbootMovie);
}
}
You've to correct certain things in your code base.
First you're not initializing the movieRepository and therefore, you're getting the null pointer exception. As you've been using the springboot you can use construction injection to initialized the field by spring container. Also. this class should be scanned by spring and you should also put some annotation such as Component or Service on top of it.
Following will work if your MovieImport and MovieRepository classess will scan by springboot.
package com.domain;
import com.domain.omdbapi.entities.Movie;
import com.domain.springboot.repositories.MovieRepository;
#Service
public class MovieImport {
private final MovieRepository movieRepository;
public MovieImport(MovieRepository movieRepository){
this.movieRepository = movieRepository;
}
public void saveToDb() {
// Create movie
com.domain.springboot.entities.Movie springbootMovie = new com.domain.springboot.entities.Movie("Iron Man", "284cb8fgf");
this.movieRepository.save(springbootMovie);
}
}
Updated
#SpringBootApplication
public class InfMApplication implements CommandLineRunner {
#Autowired
private MovieImport movieImport;
public static void main(String[] args) {
SpringApplication.run(InfMApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
movieImport.saveToDb();
}
}

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?

Java soap web service header authentication call from windows application c#

I was create a soap web service at java. When called from java working fine, but when called from c# its not working, would you please help me? How to call getHelloWorldAsString method from c# with header authentication. Thanks in advance
Here is the java code:
package com.mkyong.ws;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.jws.WebService;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
//Service Implementation Bean
#WebService(endpointInterface = "com.mkyong.ws.HelloWorld")
public class HelloWorldImpl implements HelloWorld{
#Resource
WebServiceContext wsctx;
#Override
public String getHelloWorldAsString() {
MessageContext mctx = wsctx.getMessageContext();
//get detail from request headers
Map<?,?> http_headers = (Map<?,?>) mctx.get(MessageContext.HTTP_REQUEST_HEADERS);
List<?> userList = (List<?>) http_headers.get("Username");
List<?> passList = (List<?>) http_headers.get("Password");
String username = "";
String password = "";
if(userList!=null){
//get username
username = userList.get(0).toString();
}
if(passList!=null){
//get password
password = passList.get(0).toString();
}
//Should validate username and password
if (username.equals("abcd") && password.equals("abcd123")){
return "Hello World JAX-WS - Valid User!";
}else{
return "Unknown User!";
}
}
#Override
public String getSum() {
return "10";
}
}
Here is the java calling (this is working):
package com.mkyong.client;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import javax.xml.ws.handler.MessageContext;
import com.mkyong.ws.HelloWorld;
public class HelloWorldClient{
private static final String WS_URL ="http://localhost:8080/ws/HelloWorld?wsdl";
public static void main(String[] args) throws Exception {
try {
URL url = new URL(WS_URL);
QName qname = new QName("http://ws.mkyong.com/", "HelloWorldImplService");
Service service = Service.create(url, qname);
HelloWorld hello = service.getPort(HelloWorld.class);
/*******************UserName & Password ******************************/
Map<String, Object> req_ctx = ((BindingProvider)hello).getRequestContext();
req_ctx.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, WS_URL);
Map<String, List<String>> headers = new HashMap<String, List<String>>();
headers.put("Username", Collections.singletonList("abcd"));
headers.put("Password", Collections.singletonList("abcd123"));
req_ctx.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
/**********************************************************************/
System.out.println(hello.getHelloWorldAsString());
System.out.println(hello.getSum());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
C# Client Call:
After adding wsdl to the windows application web service,written following C# code,
webService.HelloWorldImplService ws = new webService.HelloWorldImplService(); Console.WriteLine(ws.getHelloWorldAsString());

AWS Lambda Java "Failed to connect to service endpoint:" despite supplying the endpoint with .withEndpointConfiguration

Please help me diagnose the error message "Failed to connect to service endpoint:". That is the complete error message. Kind of looks like it can't find the endpoint, but as you can see below, I do supply the endpoint with the ".withEndpointConfiguration" method.
Here is my code:
package xyz.bombchu;
import java.util.HashMap;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.InstanceProfileCredentialsProvider;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
public class LambdaFunctionHandler implements RequestHandler<Object, String> {
DynamoDB ddb;
#Override
public String handleRequest(Object input, Context context) {
Regions REGION = Regions.AP_SOUTHEAST_2;
HashMap<String, AttributeValue> item_values =
new HashMap<String, AttributeValue>();
String relativeTime = "02000001";
item_values.put("dateTime", new AttributeValue().withN(relativeTime));
item_values.put("cID", new AttributeValue("TEST"));
AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.standard()
.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("dynamodb.ap-southeast-2.amazonaws.com", "ap-southeast-2"))
.withCredentials(new InstanceProfileCredentialsProvider())
.withClientConfiguration(new ClientConfiguration())
.build();
try {
ddb.putItem("myTableTest", item_values);
} catch (Exception e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
}

JAVA XmlRpcClient

I am using this code to connect server, but get error:
pms.java:25: error: cannot find symbol
server.setconfig(config);
enter code here ^
symbol: method setconfig(XmlRpcClientConfigImpl)
location: variable server of type XmlRpcClient
import java.util.*;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
//import org.apache.xmlrpc.client.XmlRpcClientConfig;
import org.apache.xmlrpc.common.*;
import org.apache.xmlrpc.*;
import java.net.*;
public class pms {
public static void main (String [] args) {
try {
String UserName = "123";
String Password = "123";
String pKey = "123";
Vector params = new Vector();
params.addElement(UserName);
params.addElement(Password);
params.addElement(pKey);
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(new URL(" https://wubook.net/xrws/"));
XmlRpcClient server = new XmlRpcClient();
server.setconfig(config);
Object result = server.execute("acquire_token",params);
System.out.println(result);
System.out.println("Hello World");
} catch (Exception e) {
}
}
}
Your code server.setcongfig should be setConfig (capitlization)
i think it should be server.setConfig(config)notserver.setconfig(config)
you can import
import java.net.URL;
import java.util.Vector;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
only
and here is the dependancy
<dependency>
<groupId>org.apache.xmlrpc</groupId>
<artifactId>xmlrpc-client</artifactId>
<version>3.1.3</version>
it work fine and the output

Categories