How do I make a WebDav call using resttemplate? - java

How do I make a WebDav call using resttemplate if I am trying to get file from a webdav server.
I used to do that using HttpClient like this:
public byte[] getFileAsBytes( String location ) throws FileNotFoundException, IOException {
GetMethod method = new GetMethod( baseUrl + "/" + location );
client.executeMethod( method );
if ( method.getStatusCode() == HttpStatus.SC_NOT_FOUND ) {
throw new FileNotFoundException( "Got error " + method.getStatusCode() + " : " + method.getStatusText()
+ " retrieving file from webdav server at path " + location );
} else if ( method.getStatusCode() != HttpStatus.SC_OK ) {
throw new IOException( "Got error " + method.getStatusCode() + " : " + method.getStatusText()
+ " retrieving file from webdav server at path " + location );
}
return method.getResponseBody();
}

I was able to hit the WebDav server using restTemplate as the following:
/**
* This method copies the file from webdav to local system
*
* #param documentMetadata
* #return
*/
#Override
public Document downloadFile( DocumentMetadata documentMetadata ) {
Document document = new Document();
String fileUrl = baseUrl + documentMetadata.getFilepath();
ResponseEntity<byte[]> result = restTemplate.exchange(fileUrl, HttpMethod.GET, new HttpEntity<>( createHeaders( username, password )), byte[].class );
return document;
}
private Void prepareDocument( ClientHttpResponse response, Document document, DocumentMetadata meta ) throws IOException {
document.setName( meta.getFilename() );
document.setFilePath( meta.getFilepath() );
document.setFile( IOUtils.toByteArray( response.getBody() ) );
return null;
}
public static HttpHeaders createHeaders( final String userName, final String password ) {
log.debug( "SlateUtil.createHeaders" );
return new HttpHeaders(){{
String auth = userName + ":" + password;
byte[] encodedAuth = Base64.encodeBase64(
auth.getBytes( Charset.forName( "US-ASCII" )));
String authHeader = "Basic " + new String( encodedAuth );
set( "Authorization", authHeader );
}};
}
For other people reference if they ever get this question:
here is how my models look like.
public class Document {
private String name;
private byte[] file;
private String filePath;
private String contentType;
// getters and setters
}
public class DocumentMetadata {
private String id;
private String filename;
private String filepath;
private String extension;
private String createdBy;
private Date createDate;
private String size;
private String documentType;
private String displayName;
// getters and setters
}

Related

Getting java.net.ConnectException: Connection refused (Connection refused) while creating object using fake-gcs-server image

I am getting java.net.ConnectException:connection refused error while trying to write junit for creating object in gcs using fake-gcs-server image. Please find the below code. Bucket name is test and consider, it is already created.
#TempDir
private static File directory;
private static final GenericContainer<?> GCS_CONTAINER = new GenericContainer<>(DockerImageName.parse("fsouza/fake-gcs-server:1.33.1"))
.withExposedPorts(4443).withCreateContainerCmdModifier(cmd -> cmd.withEntrypoint(
"/bin/fake-gcs-server",
"-scheme", "http"
));
String fakeGcsExternalUrl = "http://" + GCS_CONTAINER.getContainerIpAddress() + ":" + GCS_CONTAINER.getFirstMappedPort();
private static final Storage storage = new Storage.Builder(getTransport(), GsonFactory.getDefaultInstance(), null).setRootUrl(fakeGcsExternalUrl).setApplicationName("test").build();
void test() {
final File localFile1 = new File(directory.getAbsolutePath() + File.separator + "testFile.txt");
localFile1.createNewFile();
try (final FileWriter fileWriter = new FileWriter(localFile1.getPath())) {
fileWriter.write("Test gs file content");
}
final InputStream stream = FileUtils.openInputStream(localFile1);
Path path = localFile1.toPath();
String contentType = Files.probeContentType(path);
uploadFile("test", "/sampleFiles/newFile.txt", contentType, stream, null);
}
public String uploadFile(final Storage storage, final String bucketName, final String filePath,
final String contentType, final InputStream inputStream, final Map<String, String> metadata)
throws IOException {
final InputStreamContent contentStream = new InputStreamContent(contentType, inputStream);
final StorageObject objectMetadata = new StorageObject().setName(filePath);
objectMetadata.setMetadata(GoogleLabels.manageLabels(metadata));
final Storage.Objects.Insert insertRequest = storage.objects().insert(bucketName, objectMetadata,
contentStream);
return insertRequest.execute().getName();
}
This problem might be related to you omitting to set the fake-gcs-server's external URL property to the container's address. Make sure you follow guide in the official repo https://github.com/fsouza/fake-gcs-server/blob/cf3fcb083e19553636419818e29f84825bd1e13c/examples/java/README.md, particularly, that you execute the following code:
private static void updateExternalUrlWithContainerUrl(String fakeGcsExternalUrl) throws Exception {
String modifyExternalUrlRequestUri = fakeGcsExternalUrl + "/_internal/config";
String updateExternalUrlJson = "{"
+ "\"externalUrl\": \"" + fakeGcsExternalUrl + "\""
+ "}";
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create(modifyExternalUrlRequestUri))
.header("Content-Type", "application/json")
.PUT(BodyPublishers.ofString(updateExternalUrlJson))
.build();
HttpResponse<Void> response = HttpClient.newBuilder().build()
.send(req, BodyHandlers.discarding());
if (response.statusCode() != 200) {
throw new RuntimeException(
"error updating fake-gcs-server with external url, response status code " + response.statusCode() + " != 200");
}
}
before using the container.

How to read values from properties file and use it in final class

Here is my final class "Constants"
#Component
public final class Constants {
#Value("${db2.schema}")
private static String Schema;
public static final String STUDENT_TABLE = Schema + ".Student";
}
I have db2.schema in my properties file :
db2.schema = ${DB2_SCHEMA}
DB2_SCHEMA = D5677ESB
#Value can not be used with static fields
You can use like:
...
public class Constants {
public static final String NewOrder = "neworder";
public static final String POST = "POST";
public static final String CONTENT_TYPE = "Content-Type";
public static final String APPLICATION_TYPE = "application/json";
public static final String ACCEPT = "Accept";
public static final String CART_URL = PropsUtil.get("order.inquiry.search.insertCartDataURL");
}
...
** or check this code:**
...
public String getPropValues() throws IOException {
try {
Properties prop = new Properties();
String propFileName = "config.properties";
inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
}
Date time = new Date(System.currentTimeMillis());
// get the property value and print it out
String user = prop.getProperty("user");
String company1 = prop.getProperty("company1");
String company2 = prop.getProperty("company2");
String company3 = prop.getProperty("company3");
result = "Company List = " + company1 + ", " + company2 + ", " + company3;
System.out.println(result + "\nProgram Ran on " + time + " by user=" + user);
} catch (Exception e) {
System.out.println("Exception: " + e);
} finally {
inputStream.close();
}
return result;
} ...

How to store result of exchange.getRequestURI().getQuery() in variable and use it to get authorization code

I'm trying to implement this stage of project - https://hyperskill.org/projects/62/stages/337/implement.
I need to store result of String code = exchange.getRequestURI().getQuery(); in a variable and use it in POST request.
POST(HttpRequest.BodyPublishers.ofString("client_id=" + CLIENT_ID + "&client_secret=" + CLIENT_SECRET+ "&grant_type=" + GRANT_TYPE + "&code=" + CODE + "&redirect_uri=" + REDIRECT_URI))
But I can't do that, because of it doesn't store in a vairable outside of server.createContext.
Maybe I'm trying to do wrong thing? Can anyone help me?
private static final String CLIENT_ID = "da072c60fcee469e8b0f4140aa4480d5";
private static final String CLIENT_SECRET = "8ada13093c704487b57c3a660448884e";
private static final String AUTHORIZE_ADDRESS = "https://accounts.spotify.com/authorize";
private static final String RESPONSE_TYPE = "code";
private static final String TOKEN_ADDRESS = "https://accounts.spotify.com/api/token";
private static final String GRANT_TYPE = "authorization_code";
private static final String CODE = "";
private static final String REDIRECT_URI = "http://localhost:8080";
private static final String ANSWER_DENIED_ACCESS = "Please, provide access for application.";
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
boolean successfulAccess = false;
while (sc.hasNext()) {
String input = sc.next();
switch (input) {
case "auth":
server();
request();
successfulAccess = true;
System.out.println("---SUCCESS---");
break;
}
}
}
private static void server() throws IOException {
HttpServer server = HttpServer.create();
server.bind(new InetSocketAddress(8080), 0);
server.start();
System.out.println("use this link to request the access code:");
System.out.println(AUTHORIZE_ADDRESS
+ "?client_id=" + CLIENT_ID
+ "&redirect_uri=" + REDIRECT_URI
+ "&response_type=" + RESPONSE_TYPE);
System.out.println("waiting for code...");
server.createContext("/",
exchange -> {
String code = exchange.getRequestURI().getQuery();
String result = "";
String answer = "";
if (code.contains("code")) {
result = "Got the code. Return back to your program.";
answer = "code received";
} else {
result = "Not found authorization code. Try again.";
answer = "code didn't received";
}
exchange.sendResponseHeaders(200, result.length());
exchange.getResponseBody().write(result.getBytes());
exchange.getResponseBody().close();
System.out.println(answer);
}
);
server.stop(10);
}
private static void request() throws IOException, InterruptedException {
System.out.println("making http request for access_token...");
HttpRequest request = HttpRequest.newBuilder()
.POST(HttpRequest.BodyPublishers.ofString(
"client_id=" + CLIENT_ID
+ "&client_secret=" + CLIENT_SECRET
+ "&grant_type=" + GRANT_TYPE
+ "&code=" + CODE
+ "&redirect_uri=" + REDIRECT_URI))
.header("Content-Type", "application/x-www-form-urlencoded")
.uri(URI.create(TOKEN_ADDRESS))
.build();
HttpClient client = HttpClient.newBuilder().build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("response:");
System.out.println(response.body());
}
}```
I need while cycle with Thread.sleep, than you can normally store code in variable. Like this:
exchange -> {
String code = exchange.getRequestURI().getQuery();
String result = "";
String answer = "";
if (code != null && code.contains("code")) {
CODE = code.substring(5);
result = "Got the code. Return back to your program.";
answer = "code received";
} else {
result = "Not found authorization code. Try again.";
answer = "code not received";
}
exchange.sendResponseHeaders(200, result.length());
exchange.getResponseBody().write(result.getBytes());
exchange.getResponseBody().close();
System.out.println(answer);
}
);
while (CODE.equals("")) {
Thread.sleep(10);
}
server.stop(10);```

Executing a java class in Eclipse

I have a java project in Eclipse which was written by some other developer. I am very new to Java and have made some modifications in the source code. Now i want to test the code by executing it in eclipse. How can I create a main class and execute the modified code.
Following is the class file which I want to run
public class Bio_Verify extends AbstractOutboundServiceProvider
{
public static String EndPointURL = null;
public static String ApiKey = null;
public static String Version = null;
public static String EntityId = null;
public static String requestId = null;
public static String EncryptionKey = null;
public static String SignatureKey = null;
public static String SignAlgorithm = null;
public String requestData = null;
public String requestXML = null;
public String response = null;;
public String errorMsg;
public void preprocess(IUsbMessage inputMsg)
{
LogManager.logDebug("Bio_Verify: preprocess():: inside preprocess");
LogManager.logDebug("Bio_Verify: executeOutboundRequest():: START");
}
public IUsbMessage executeOutboundRequest(String inputMsg)
{
int i = 0;
int j = 0;
String resolution = null;
String key = null;
String criteria = null;
String position = null;
String format = null;
String data = null;
String intent = null;
String resBodyXML = null;
String outputXMLMsg = null;
String[] responseMsg = new String[2];
IUsbMessage outMsg = null;
Verify verify = new Verify();
Fingerprint fingerprint = new Fingerprint();
requestData = "CN01473|cif|UNKNOWN_FINGER|508|BMP|Qk12WeoAAAA=|verify";
//Forming requestId for Bio
Date date = Calendar.getInstance().getTime();
DateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
requestId = dateFormat.format(date);
EndPointURL = OutboundConstants.Bio_Endpoint;
ApiKey = OutboundConstants.ApiKey;
Version = OutboundConstants.Version;
EntityId = OutboundConstants.EntityId;
EncryptionKey = OutboundConstants.EncryptionKey;
SignAlgorithm = OutboundConstants.SignAlgorithm;
SignatureKey = OutboundConstants.SignatureKey;
LogManager.logDebug("Bio_Verify: executeOutboundRequest():: Bio_Endpoint URL is " + EndPointURL);
LogManager.logDebug("Bio_Verify: executeOutboundRequest():: Api Key is " + ApiKey);
LogManager.logDebug("Bio_Verify: executeOutboundRequest():: Version is " + Version);
LogManager.logDebug("Bio_Verify: executeOutboundRequest():: EntityId is " + EntityId);
LogManager.logDebug("Bio_Verify: executeOutboundRequest():: EncryptionKey is " + EncryptionKey);
LogManager.logDebug("Bio_Verify: executeOutboundRequest():: SignatureKey is " + SignatureKey);
LogManager.logDebug("Bio_Verify: executeOutboundRequest():: SignAlgorithm is " + SignAlgorithm);
LogManager.logDebug("Bio_Verify: executeOutboundRequest():: Request Id is " + requestId);
//Extraction data from the request XML
for(i=0;i<7;i++){
int x = requestData.indexOf("|");
int y = requestData.length();
if(i==0){
key = requestData.substring(0, x);
LogManager.logDebug("Key: "+key);
requestData = requestData.substring(x+1,y);
}
if(i==1){
criteria = requestData.substring(0, x);
LogManager.logDebug("Criteria: "+criteria);
requestData = requestData.substring(x+1,y);
}
if(i==2){
position = requestData.substring(0, x);
LogManager.logDebug("Position: "+position);
requestData = requestData.substring(x+1,y);
}
if(i==3){
format = requestData.substring(0, x);
LogManager.logDebug("Format: "+format);
requestData = requestData.substring(x+1,y);
}
if(i==4){
resolution = requestData.substring(0, x);
LogManager.logDebug("Resolution: "+resolution);
requestData = requestData.substring(x+1,y);
}
if(i==5){
data = requestData.substring(0, x);
requestData = requestData.substring(x+1,y);
}
if(i==6){
intent = requestData;
LogManager.logDebug("Intent: "+intent);
}
}
FingerprintImage fingerprintimage = new FingerprintImage(format,resolution,data);
fingerprint.image = fingerprintimage;
fingerprint.position = position;
responseMsg = verify.verify(key, criteria, fingerprint, intent);
this.errorMsg = responseMsg[0];
this.response = responseMsg[1];
LogManager.logDebug("Back in bio verify - array element1"+this.errorMsg);
LogManager.logDebug("Back in bio verify - array element2"+this.response);
outMsg = UsbMessageFactory.createUbusMessage();
outMsg.setMsgType("XML");
outMsg.setMsgSubType("FIXML");
LogManager.logDebug("Bio: executeOutboundRequest():: errorMsg=" + errorMsg);
if (errorMsg.toString().trim().length() > 0)
{
LogManager.logDebug("Bio_Verify: executeOutboundRequest():: Inside FAILURE");
outMsg.setBackEndTranStatus("FAILURE");
outMsg.setErrMsgFlg(1);
outMsg.setPayload(new Object[] { new CIFatalException(errorMsg.toString()) });
}
else
{
LogManager.logDebug("Bio_Verify: executeOutboundRequest():: Inside SUCCESS");
outMsg.setBackEndTranStatus("SUCCESS");
outMsg.setErrMsgFlg(0);
resBodyXML = this.response.toString();
LogManager.logDebug("Bio_Verify: executeOutboundRequest():: outputXMLMsg XML:" + outputXMLMsg);
outMsg.setPayload(new Object[] { outputXMLMsg });
}
LogManager.logDebug("Bio_Verify: executeOutboundRequest():: outMsg:" + outMsg);
LogManager.logDebug("Bio_Verify: executeOutboundRequest():: END");
return outMsg;
}
Can you follow the steps , this will help to you
There are 6 steps are below added ( I think you will get idea how to archive your problem )
1.Right click inside package and you can see CLASS then it will pop up this attached window
2. Insight Main method you can crate some object like I have created and pass parameter what you want (You just understand what method you have to call )
You have to write main function into Bio_Verify class.
main function is boot function.
So if you write main function, you can execute this class.
ex)
public class BioVerify extends AbstractOutboundServiceProvider {
public static void main(String[] args) {
// TODO: Write a code....
}
}
write the main function below to the code and create object for BIO_verify class and it's function

Testing the existence of a File using Apache Camel

I want to test if a given file exists at a remote SFTP server using Apache Camel.
The method has to return true if exists, false if not and an Exception in case
the client cannot get connected (timeout, wrong username/password, etc).
In fact to test if I can get logged in to the server is not a major problem
to test if the given file exists. Just send a request to the SFTP server, download=false and noop=true
and this is pretty much what it has to be done. An empty file will be downloaded to my TMP directory
in case the file exists, no file will be downloaded. In case I cannot logged in to the server an own Exception is thrown
(CannotConnectException).
My point is that I cannot catch this exception at my client.
I am pretty sure I am doing something wrong, but I do not know what.
I was thinking as a work around to set some error value in returned file is case I cannot get connected, but
this looks like a "hack" to me. Is there any way to catch the thrown exception? If not, what is the best way to
get an Exception my client in case I cannot get connected?
My code is as follows:
public final class MyFtpClient {
private static final Logger LOG = LoggerFactory.getLogger(MyFtpClient.class);
// Client settings
static String localPath = File.separator + "tmp";
public enum Existence{
EXIST, NOT_EXIST, UNKNOWN
}
private MyFtpClient() {
}
private static Existence doesFileExistAtServer(Main main, String protocol, String user, String password,
String server, int port, String filePathAtServer, String filenameAtServer, String localPath)
{
boolean fileExist = false;
try {
main.addRouteBuilder(new MyFtpClientRouteBuilder(protocol, user, password, server, port, filePathAtServer,
filenameAtServer, localPath));
main.start();
Thread.sleep(5000);
main.stop();
String filePath = localPath + File.separator + filenameAtServer;
File f = new File(filePath);
fileExist = f.exists();
if (fileExist) {
f.delete(); // Just delete it.
return Existence.EXIST;
} else {
return Existence.NOT_EXIST;
}
// I CANNOT CATCH THIS EXCEPTION
} catch (Exception e) {
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Cannot Connect to the Sftp Server " + server);
LOG.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Cannot Connect to the Sftp Server " + server);
LOG.info(e.getMessage());
return Existence.UNKNOWN;
}
}
public static void main(String[] args) throws Exception {
String protocol = "sftp";
int port = 22;
String server;
String user;
String password;
String filePathAtServer;
String filenameAtServer;
boolean fileExist;
Main main = new Main();
server = "unknown.com";
user = "demo";
password = "password";
filePathAtServer = "/";
filenameAtServer = "readme.txt";
doesFileExistAtServer(main, protocol, user, password, server, port, filePathAtServer, filenameAtServer, localPath);
LOG.info("\nThe accesibility of the file 1 " + filenameAtServer + " at the server " + server + " is " + fileExist + "\n")
}
Whereas my RouteBuilder looks as follows:
public class MyFtpClientRouteBuilder extends RouteBuilder {
private static final Logger LOG =
LoggerFactory.getLogger(MyFtpClientRouteBuilder.class);
String protocol = "sftp";
int port = 22;
String server;
String user;
String password;
String filePathAtServer;
String filenameAtServer;
String localPath;
boolean fileExist;
public MyFtpClientRouteBuilder(String protocol, String user, String password, String server, int port,
String filePathAtServer, String filenameAtServer, String localPath) {
super();
this.protocol = protocol;
this.user = user;
this.password = password;
this.server = server;
this.port = port;
this.filePathAtServer = filePathAtServer;
this.filenameAtServer = filenameAtServer;
this.localPath = localPath;
}
private static String generateFromUri(String protocol, String user, String password, String server, int port,
String path, String filename) {
final String downloadFalse = "download=false"; // NO, DO NOT Download the file
final String fastExistsCheck = "fastExistsCheck=true";
final String doNothing = "noop=true"; // Just connect, but DO NOTHING
final String connectFail = "throwExceptionOnConnectFailed=true"; // Just in case a connection fails
final String maxReconnect = "maximumReconnectAttempts=0";
final String bridgeError = "consumer.bridgeErrorHandler=true";
return protocol + "://" + user + "#" + server + ":" + port + path + "?" + "fileName=" + filename + "&"
+ downloadFalse + "&"
+ "password=" + password
+ "&" + fastExistsCheck
+ "&" + connectFail
+ "&" + doNothing
+ "&" + maxReconnect
+ "&" + bridgeError;
}
private static String generateLocalUri(String path) {
final String protocol = "file";
final String allowNullBody = "allowNullBody=true";
final String doNothing = "noop=true";
final String fileExist = "fileExist=move";
final String moveExisting = "moveExisting=oldFile";
return protocol + ":" + path + "?" + allowNullBody + "&" + doNothing + "&" + fileExist + "&" + moveExisting;
}
#Override
public void configure() throws CannotConnectException {
final String fromSftpServer = generateFromUri(protocol, user, password, server, port, filePathAtServer, filenameAtServer);
LOG.info("From: " + fromSftpServer);
final String toLocal = generateLocalUri(localPath);
LOG.info("To: " + toLocal);
onException(GenericFileOperationFailedException.class, JSchException.class)
//.handled(true)
.throwException(new CannotConnectException("Cannot connect to the remote SFTP server " + server))
.log("Cannot connect to the remote SFTP server " + server)
.maximumRedeliveries(0)
.to(toLocal)
.continued(false) // Either handled(true) or continue(false) but NOT both together
.end();
from(fromSftpServer).to(toLocal);
}
}

Categories