How to use Apache camel RAW(value) for password - apache-camel

When we configure Camel endpoints using URIs then the parameter values gets url encoded by default. This can be a problem when we want to configure passwords as is.
To do that we can tell Camel to use the raw value, by enclosing the value with RAW(value).
http://camel.apache.org/how-do-i-configure-endpoints.html
But this is not working for mail endpoint URI.
Here is the code.
public String getURL()
{
String url = "";
try{
URI uri = new URI(this.emailServer.toString());
url = "imaps://"+uri.getHost()+"?username="+this.username+"&password=RAW("+this.password+")&folderName="+this.getMailBox()+"&copyTo="+this.getMailBox()";
} catch (Exception ex){
ex.printStackTrace();
}
return url;
}
But it is working fine aws endpoint
public String getURL(){
String fromURL = "";
fromURL = "aws-sqs://" + getQueueName() + "?accessKey=" + getS3AccessKey() + "&secretKey=RAW(" + getS3SecretKey() + ")&region=" + getQueueRegion() + "&queueOwnerAWSAccountId=" + getS3SQSAWSClientID();
return fromURL;
}
Any idea?

Related

Forbidden 403 response from Google Calendar API while calling from Salesforce Using Server-to-Server

I'm trying to insert an event on Google Calendar using REST API, I'm using JWT to get the access token as I don't want user to login into google account to get token. I'd performed below steps, but still getting the error:
I've created one service account
I'm getting a Token from google to send the request
I've shared the calendar with Service Account email address as well.
Please see below code:
public class GoogleCalendarSynchronization {
public static void addEvent (){
String accessToken = GenerateJWTBearerToken.generateTokenforGoogleCalendarServices();
system.debug(accessToken);
String createEventEndPoint = 'https://www.googleapis.com/calendar/v3/calendars/primary/events/';
String createEventBody = '{' +
'"attendees": ['+
'{'+
'"email": "abc#gmail.com"'+
'},'+
'{'+
'"email": "abc#gmail.com"'+
'}'+
'],'+
'"end": {'+
'"dateTime": "2019-12-27T03:30:00-07:00"'+
'},'+
'"start": {'+
'"dateTime": "2019-12-27T03:30:00-06:00"'+
'},'+
'"summary": "Appointment has been confirmed..!!",'+
'"location": "TEST",'+
'"sendUpdates": "all"'+
'}';
//system.debug(createEventBody);
Http http = new Http();
HttpRequest httpReq = new HttpRequest();
HttpResponse HttpRes = new HttpResponse();
httpReq.setEndpoint(createEventEndPoint);
httpReq.setMethod('POST');
httpReq.setBody(createEventBody);
httpReq.setHeader('Content-Type', 'application/json');
httpReq.setHeader('Authorization','Bearer ' + accessToken);
try{
HttpRes = http.send(httpReq);
if(HttpRes.getStatusCode() == 200){
String response = HttpRes.getBody();
system.debug(response);
Map<String, Object> responseMap = (Map<String, Object>)JSON.deserializeUntyped(response);
system.debug(responseMap.get('id'));
system.debug('calendar is saved successfully..!!');
}else{
String errorMessage = 'Unexpected Error while communicating with Google Calendar API. '
+'Status '+HttpRes.getStatus()+' and Status Code '+HttpRes.getStatuscode();
system.debug(errorMessage);
}
} catch(system.Exception e){
System.debug('#### Exception Executed : '+e.getMessage() + ' ' + e.getStackTraceString() + ' ' +e.getLineNumber());
}
}
}

Spring Boot endpoint for downloading File automatically

I want to make a Spring Boot endpoint for downloading file. I Have tried this things but the file does not download automatically... I get only file content in the body...
#RequestMapping(value = "/files", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
#ResponseBody
public ResponseEntity<FileSystemResource> getFile(#RequestParam(name = "start") String start) {
return new ResponseEntity<>(new FileSystemResource(myService.makeFile(start)),
HttpStatus.OK);
}
Another one that I have tried is this:
#RequestMapping(value = "/download", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public String download(HttpServletResponse response, #RequestParam(name = "start") String start)
{
response.setContentType("application/force-download");
FileReader fr = new FileReader(myService.makeFile(start));
return IOUtils.toString(fr);
}
I have read that MediaType.APPLICATION_OCTET_STREAM_VALUE will force it to download but nothing happened in my case.
You are on the right track, you just need to set one response header Content-Disposition to attachment; filename=YOUR_FILE_NAME.
Try This:
#RequestMapping(value = "/files", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public FileSystemResource getFile(#RequestParam(name = "start") String start, HttpServletResponse response) {
response.setHeader("Content-Disposition", "attachment; filename=" + "YOUR_FILE_NAME");
return new FileSystemResource(myService.makeFile(start));
}

Salesforce test web service call

Here is the code for a helper function
public class SalesforceHelper {
public static void waitCall(String timeout){
System_Settings__c lnpSetting = System_Settings__c.getValues('System Properties');
String endpoint=lnpSetting.Base_Endpoint_URL__c + 'salesforceHelper/wait?timeout=' + timeout;
system.debug('====endpoint======'+endpoint);
HttpRequest httpReq=new HttpRequest();
HttpResponse httpResp = new HttpResponse();
Http http = new Http();
httpReq.setMethod('GET');
httpReq.setEndpoint(endpoint);
String username=lnpSetting.Endpoint_Username__c;
String password=lnpSetting.Endpoint_Password__c;
Blob headerValue = Blob.valueOf(username + ':' + password);
String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);
httpReq.setHeader('Authorization', authorizationHeader);
httpReq.setHeader('content-type','application/json; charset=utf-8');
httpReq.setTimeout(120000);
try{
httpResp = http.send(httpReq);
System.debug('Wait response' + httpResp);
} catch (Exception e) {
system.debug(LoggingLevel.Error, 'Error HTTP response code = ' + httpResp.getStatusCode() + '; calling '+endpoint );
}
}
}
Basically this method just using HttpRequest and HttpResponse to call the endpoint URL, and the endpoint URL is web service, and it will just return 200 after the timeout that specified in the parameter.
Now the question is, I need to write a test case to cover this method, and I don't know how to write it.. I don't know how to mock the httpcallout properly, because this method doesn't return HttpResponse, and since the code is freeze right now, I cannot modified my class to make the test case work.
So any other way I can create the test class for this method?
You should definitely be able to use standard Http Callout Mock:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing_httpcalloutmock.htm
The only difference would be that you'd only set stats code:
// Create a fake response
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
return res;
and check for response code:
System.assertEquals(200, res.getStatusCode());

AngularJS/ Spring Boot application - automatically navigate to signin page after an idle time

I use AngularJS in frontend and Spring Boot/Spring Security in backend.
The backend looks like this:
#Component
public class TokenUtils {
public static final String MAGIC_KEY = "obfuscate";
public String createToken(final UserDetails userDetails) {
final long expires = System.currentTimeMillis() + 1000L * 60 * 60;
return userDetails.getUsername() + ":" + expires + ":" + computeSignature(userDetails, expires);
}
public String computeSignature(UserDetails userDetails, long expires) {
final StringBuilder signatureBuilder = new StringBuilder();
signatureBuilder.append(userDetails.getUsername()).append(":");
signatureBuilder.append(expires).append(":");
signatureBuilder.append(userDetails.getPassword()).append(":");
signatureBuilder.append(TokenUtils.MAGIC_KEY);
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("No MD5 algorithm available!");
}
return new String(Hex.encode(digest.digest(signatureBuilder.toString().getBytes())));
}
public String getUserNameFromToken(final String authToken) {
if (null == authToken) {
return null;
}
final String[] parts = authToken.split(":");
return parts[0];
}
public boolean validateToken(final String authToken, final UserDetails userDetails) {
final String[] parts = authToken.split(":");
final long expires = Long.parseLong(parts[1]);
final String signature = parts[2];
final String signatureToMatch = computeSignature(userDetails, expires);
return expires >= System.currentTimeMillis() && signature.equals(signatureToMatch);
}
}
If user does not use the frontend for awhile and returns to frontend by e.g. a bottonclick, he is moved to the signin page.
My intention is that the application moves to signin page automatically after expiration time.
Is there a possibility to do this with AngularJS in frontend?
you may wanna use ng-idle plugin
how to configure ?
myApp.config(['KeepaliveProvider', 'IdleProvider', function(KeepaliveProvider, IdleProvider) {
IdleProvider.idle(5);
IdleProvider.timeout(5);
KeepaliveProvider.interval(10);
}]);
how to implement and listen timeouts in any scope ?
it is emitting some events at $rootScope. you can listen to it at any scope with
$scope.$on('IdleStart',fn) like functions
so you can call logout api endpoints & change route to login page

Get the Ip Info from Client to Web Api

fist at all sorry for my bad English.
I'm trying to get the IP in the login option to save them as a "Session" in the database and register who and where is using the app.
I try this, but it obvious that it isn't going to work.
var ip = new System.Net.WebClient().DownloadString("http://ipinfo.io/json");
It Gets the IP Client. So it logical that I need to do this get in the Client side. But the problem is that the Client can change this values before its send to the Web API
$http.get("http://ipinfo.io/json").then(function (response) {
return response.data;
}).catch(function (response) {
console.log(response.data);
});
The users can change this value to send me a false data in the login and I don't have how to validate if this information is valid or real. So, the question is ¿How can I do this without let the user manipulate this data?
Create a method in web API, and we can save all the information needed directly to database.
public static string UserIp()
{
string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
{
ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
try
{
string url1 = "http://geoip.nekudo.com/api/" + ip.ToString(); // passing IP address will return location information.
WebClient client = new WebClient(); // Intialize the webclient
string jsonstring = client.DownloadString(url1);
dynamic dynObj = JsonConvert.DeserializeObject(jsonstring); // De-serialize the JSON string
string filePath = AppDomain.CurrentDomain.BaseDirectory + "\\App_Data\\Logs\\" + "Ip.txt";
using (System.IO.StreamWriter writer = new StreamWriter(filePath, true))
{
// you can save the information to database instead of writing to a file
writer.WriteLine("UserIp:" + ip);
writer.WriteLine("Date:" + DateTime.Now);
writer.WriteLine("JsonString:" + jsonstring);
writer.WriteLine("Country name:" + dynObj.country.code);
}
return dynObj;
}
catch (Exception ex)
{
string filePath = AppDomain.CurrentDomain.BaseDirectory + "\\App_Data\\Logs\\" + "I.txt";
string url1 = "http://geoip.nekudo.com/api/" + ip.ToString();
WebClient client = new WebClient(); // Intialize the webclient
string jsonstring = client.DownloadString(url1);
dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);
// string a = dynObj.country.code;
using (System.IO.StreamWriter writer = new StreamWriter(filePath, true))
{
writer.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" +
ex.StackTrace +
"" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
writer.WriteLine("UserIp:" + ip);
writer.WriteLine("Dynamic obj:" + dynObj);
}
return null;
}
}

Resources