Apache Camel: prevent trimming the space character after passing the property to the bean - apache-camel

I am trying to search for a regex in the text and seperate the substrings by the delimiter ", ". Currently I am facing the problem that the second delimiter character " " space
is being trimed after passing it to the bean. Regarding the Apache Camel docu there is 5 bean method options (ref, method, beanType, scope and trim) to use.
How can I set the trim option to prevent removing the space character from the delimiter in the bean?
DSL code
static final String DELIMITER = ", ";
.setProperty("regex", simple(REGEX))
.setProperty("delimiter", simple(DELIMITER))
.bean("regexAgrsMessageBean", "searchRegexInText") //how can I set the trim option here
Bean
#Component
public class RegexAgrsMessageBean {
public static String searchRegexInText(#Body String text, #ExchangeProperty("regex") String regex,
#ExchangeProperty("delimiter") String delimiter) {
LOGGER.info("delimiter: '"+delimiter+"'");
return "";
}
}
https://camel.apache.org/components/3.15.x/languages/bean-language.html
enter image description here
camel.version: 3.15.0

Have you tried
// 2nd param to constant() is trim
.setProperty("delimiter", constant(DELIMITER, false))

Related

Spring's URIComponentsBuilder converts colon (:) for port number into slash (/)

In a test, I am injecting an example URL with a colon for a port number ("http://example.com:port") into my configuration, which is then used by my production code to construct a UriComponentsBuilder which ultimately creates a URI String.
However, that colon character is being converted into a forward slash by the UriComponentsBuilder, as demonstrated in this MCVE:
#Test
public void portNumberFromHttpUrl() {
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://example.com:port");
String uriString = builder.toUriString();
assertThat(uriString).isEqualTo("http://example.com:port");
}
This test fails as follows:
org.junit.ComparisonFailure:
Expected :"http://example.com:port"
Actual :"http://example.com/port"
Why is the : being converted to a /?
The MCVE helped me answer this myself almost immediately, but I'll leave the question here because I couldn't find the same question here or anywhere else online, and I guess it might save someone else some time:
It seems that UriComponentsBuilder recognises that a port should be a number, so this (more realistic) case passes:
#Test
public void portNumberFromHttpUrl() {
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://example.com:123");
String uriString = builder.toUriString();
assertThat(uriString).isEqualTo("http://example.com:123");
}
From a little more investigation it seems that it puts a / before the first non-numeric character that it encounters after a :, so:
http://example.com:a123 -> http://example.com/a123
http://example.com:12a3 -> http://example.com:12/a3
http://example.com:123a -> http://example.com:123/a
Not immediately obvious, but makes sense, I guess.

TextEncodings.Base64Url.Decode vs Convert.FromBase64String

I was working on creating a method that would generate a JWT token. Part of the method reads a value from my web.config that services as the "secret" used to generate the hash used to create the signature for the JWT token.
<add key="MySecret" value="j39djak49H893hsk297353jG73gs72HJ3tdM37Vk397" />
Initially I tried using the following to convert the "secret" value to a byte array.
byte[] key = Convert.FromBase64String(ConfigurationManager.AppSettings["MySecret"]);
However, an exception was thrown when this line was reached ...
The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.
So I looked into the OAuth code and so another method being used to change a base64 string into a byte array
byte[] key = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["MySecret"]);
This method worked without issue. To me it looks like they are doing the same thing. Changing a Base64 text value into an array of bytes. However, I must be missing something. Why does Convert.FromBase64String fail and TextEncodings.Base64Url.Decode work?
I came across the same thing when I migrated our authentication service to .NET Core. I had a look at the source code for the libraries we used in our previous implementation, and the difference is actually in the name itself.
The TextEncodings class has two types of text encoders, Base64TextEncoder and Base64UrlEncoder. The latter one modifies the string slightly so the base64 string can be used in an url.
My understanding is that it is quite common to replace + and / with - and _. As a matter of fact we have been doing the same with our handshake tokens. Additionally the padding character(s) at the end can also be removed. This leaves us with the following implementation (this is from the source code):
public class Base64UrlTextEncoder : ITextEncoder
{
public string Encode(byte[] data)
{
if (data == null)
{
throw new ArgumentNullException("data");
}
return Convert.ToBase64String(data).TrimEnd('=').Replace('+', '-').Replace('/', '_');
}
public byte[] Decode(string text)
{
if (text == null)
{
throw new ArgumentNullException("text");
}
return Convert.FromBase64String(Pad(text.Replace('-', '+').Replace('_', '/')));
}
private static string Pad(string text)
{
var padding = 3 - ((text.Length + 3) % 4);
if (padding == 0)
{
return text;
}
return text + new string('=', padding);
}
}

character encoding issue while reading email using java mail api

Hi I am reading emil's from a mailbox using Java mail Api.
For an email ,The from Address has Chinese characters and looks as below
(krishna 国际快 <12139#ty.com> ).
After reading the email , When I get the from Address from message using message.getFromAddress();
The from address is some thing like below
?utf-8?Q?Kris=EF=BC=88=E4=BF=9E=E7=94=9F=EF=BC=89?= <12139#ty.com>
How can I get the original from address.
The email address encoding issue while reading the email from a mail box is fixed.
StringBuffer sbFrom =null;
sbFrom = new StringBuffer();
Address[] in = msg.getFrom();
for (Address address : in) {
System.out.println("FROM: " + address.toString());
sbFrom.append(address.toString());
}
I created two solutions for this . Please find them below.
Solution 1:
Created a regular expression and checking the regular expression , If email address matches the regular expression then we decode the email address.
Please check the code below.
String ENCODED_PART_REGEX_PATTERN="=\\?([^?]+)\\?([^?]+)\\?([^?]+)\\?=";
Pattern pattern=Pattern.compile(ENCODED_PART_REGEX_PATTERN);
Matcher m =pattern.matcher(sbFrom.toString());
if(m.find()){
System.out.println("FROM: " +MimeUtility.decodeWord( sbFrom.toString()));
}else{
System.out.println("FROM: " + sbFrom.toString());
}
Solution 2: Written a method which decodes the given email address. If we get javax.mail.internet.ParseException while decoding then it means the email Address do not have any encoded characters , so we return normal string.
Please observe the below method.
public String decodeAddress(String emailId) throws UnsupportedEncodingException{
String string = "";
try{
string = MimeUtility.decodeWord(emailId);
}catch(ParseException e){
System.out.println("ParseException occured so return the same string");
string =emailId;
}
return string;
}

Need to check whether any extension is present before query string

I have written the code to check the query string
Logic::if query string is "?" should remove all the characters from the query string and print the vailid URL.
char str[] = "http://john.org/test.mp4?iufjdlwle";
char *pch;
pch = strtok(str,"?");
printf("%s\n",pch);
Output::
bash-3.2$ ./querystring
http://john.com/test.mp4
But i have to check one more case
Need to get the URL only if there is any extensions present before query string?
if No extensions are present before the query string,need to skip.
I have tried this way,
continuation of the code
char *final;
final = pch+(strlen(pch)-3);
printf("%s\n",final);
if(strcasecmp(p,"mp4"))
printf("falure case\n");
else
printf("Success case\n");
It will work for .mp4 extension alone.
Incase if i'm getting *.mpeg or *.m3u8 or *.flv as an extensions,it will fail.
Can someone guide me how to solve this problem and make it working?
A query string is what starts after a question mark ?, fine.
You should try to define what an extension is. For me, it is what can happen after a dot (.) in the last component of the url, where the components are delimited with slashes (/)
So you should do:
first remove the possible query string including the initial ?
then locate the last /
then locate the last . that occurs after the last /
If you find one, it is the starting point of the extension.
So assuming pch contains the url without any query string, you can do:
char * ix = strrchr(pch, '/');
if (ix == NULL) {
// an URL without / is rather weird, better report and abort
...
}
ix = strrchr(ix, '.');
if (ix == NULL) {
// no extension here: ignore the url
...
}
else {
// found an URL containing an extension: process it
// ix+1 points to the extension
...
}

Splitting a text file where the information are separated in different lines

So, I have a text file where the information are separated by the enter key (I don't know how to explain, I will paste the code and some stuff).
cha-cha
Fruzsina
Ede
salsa
Szilvia
Imre
Here's how the text file looks like, and I need to split it into three parts, the first being the type of the dance, and then dancer 1 and dancer 2.
using System;
using System.Collections.Generic;
using System.IO;
namespace tanciskola
{
struct tanc
{
public string tancnev;
public string tancos1;
public string tancos2;
}
class Program
{
static void Main(string[] args)
{
#region 1.feladat
StreamReader sr = new StreamReader("tancrend.txt");
tanc[] tanc = new tanc[140];
string[] elv;
int i = 0;
while (sr.Peek() != 0)
{
elv = sr.ReadLine().Split('I don't know what goes here');
tanc[i].tancnev = elv[0];
tanc[i].tancos1 = elv[1];
tanc[i].tancos2 = elv[2];
i++;
}
#endregion
Console.ReadKey();
}
}
}
Here is how I tried to solve it, although I don't really get how I should do it. The task is would be to display the first dance and the last dance, but for that I need to split it somehow.
As mentioned in my comments, you seem to have a text file where each item is on a new line, and a set of 3 lines constitutes a single 'record'. In that case, you can simply read all the lines of the file, and then create your records, like so:
var v = File.ReadLines("file path");
tancr[] tanc = new tancr[140];
for (int i = 0; i < v.Count(); i += 3)
{
tanc[i/3].tancnev= v.ElementAt(i);
tanc[i/3].tancos1 = v.ElementAt(i + 1);
tanc[i/3].tancos2 = v.ElementAt(i + 2);
}
Note: ReadLines() is better when the file size is large. If your file is small, you could use ReadAllLines() instead.
To split by the "enter character" you can use Environment.NewLine in .NET:
https://msdn.microsoft.com/en-us/library/system.environment.newline(v=vs.110).aspx
elv = sr.ReadAllText().Split(new string[] {Environment.NewLine}, StringSplitOptions.None);
This constant will contain the sequence that is specific to your OS (I'm guessing Windows).
You should be aware that the characters used for newlines is different for Windows vs. Linux/Unix. So in the rare event that someone edits your file on a different OS, you can run into problems.
On Windows, newline is a two character sequence: carriage-return + line-feed (ASCII 13 + 10). On Linux it is just line-feed. So if you wanted to be extra clever, you could first check for CRLF and if you only get one element back from Split() then try just LF.

Resources