Identify whether I've received an HttpRequest or HttpResponse? - sockets

I have a netty server that listens on a port. It can either receive HttpResponses or HttpRequests on this port. How can I set up a pipeline to handle both and distinguish between the two? Is this possible? Connections are initiated to this server and not from it.
Thank you!

You could use the isHttp method from the PortUnification example. It examines the first two unsigned bytes of a received message to determine if it is likely an HTTP verb, therefore identifying the message as an HTTP request. You might need to modify it slightly, depending on the likely content of any responses.
private static boolean isHttp(int magic1, int magic2) {
return
magic1 == 'G' && magic2 == 'E' || // GET
magic1 == 'P' && magic2 == 'O' || // POST
magic1 == 'P' && magic2 == 'U' || // PUT
magic1 == 'H' && magic2 == 'E' || // HEAD
magic1 == 'O' && magic2 == 'P' || // OPTIONS
magic1 == 'P' && magic2 == 'A' || // PATCH
magic1 == 'D' && magic2 == 'E' || // DELETE
magic1 == 'T' && magic2 == 'R' || // TRACE
magic1 == 'C' && magic2 == 'O'; // CONNECT
}

Related

mismatched input '.' in rule

I am new to drools .I am writing a new rule.But i am getting Error as follow:
mismatched input '.' in rule "StopTextRule" in pattern
My rule is
package com.******.*****;
import java.lang.Number;
rule "StopTextRule"
dialect "mvel"
salience 20
lock-on-active true
when
RoutingData( messageBody != null && (
(messageBody.trim().equalsIgnoreCase("stop") || messageBody.trim().equalsIgnoreCase("\"stop\"") || messageBody.trim().equalsIgnoreCase("stop.") || messageBody.trim().equalsIgnoreCase("\"stop.\""))
|| (messageBody.trim().equalsIgnoreCase("quit")|| messageBody.trim().equalsIgnoreCase("\"quit\"") || messageBody.trim().equalsIgnoreCase("quit.")|| messageBody.trim().equalsIgnoreCase("\"quit.\""))
|| (messageBody.trim().equalsIgnoreCase("cancel")|| messageBody.trim().equalsIgnoreCase("\"cancel\"") || messageBody.trim().equalsIgnoreCase("cancel.")|| messageBody.trim().equalsIgnoreCase("\"cancel.\""))
|| (messageBody.trim().equalsIgnoreCase("UNSUBSCRIBE")|| messageBody.trim().equalsIgnoreCase("\"UNSUBSCRIBE\"") || messageBody.trim().equalsIgnoreCase("UNSUBSCRIBE.")|| messageBody.trim().equalsIgnoreCase("\"UNSUBSCRIBE.\"")))
&& incomingMessageProtocol != null && incomingMessageProtocol.trim().equalsIgnoreCase("X"))
routingResp : RoutingRuleResponse( isStop == false )
then
modify( routingResp ) {
setIsStop( true )
}
end
This compiles using Drools 6.4.0. I think that you are using an older version where Java expressions had to be enclosed in eval.
It would be simpler in any case to rewrite this pattern like so:
rule x
when
X( messageBody != null &&
messageBody matches "\\s*(\"?)(?i:stop|quit|cancel|unsubscribe)\\.?\\1\\s*" &&
incomingMessageProtocol != null &&
incomingMessageProtocol matches "\\s*(?i:X)\\s*") )
then
// ...
end

Syntax error when map() returns LIST

This works,
print map { $_." x" => $_ } 1..5;
print map { ("$_ x" => $_) } 1..5;
print map { ("$_ x") => $_ } 1..5;
but this throws syntax error,
print map { "$_ x" => $_ } 1..5;
Is this documented bug, undocumented bug, or I can't see why this should not compile?
Why perl thinks this should be map EXPR, LIST instead of map BLOCK LIST
From perlref
Because curly brackets (braces) are used for several other things including BLOCKs, you may occasionally have to disambiguate braces at the beginning of a statement by putting a + or a return in front so that Perl realizes the opening brace isn't starting a BLOCK. The economy and mnemonic value of using curlies is deemed worth this occasional extra hassle.
To make your intentions clearer and to help the parser,
Say +{...} to unambiguously specify a hash reference
#list_of_hashrefs = map +{ "$_ x" => $_ }, 1..5;
Say {; ...} to unambiguously specify a code block
%mappings = map {; "$_ x" => $_ } 1..5;
Why perl thinks this should be map EXPR, LIST instead of map BLOCK LIST?
The relevant section of code is in toke.c, Perl's lexer (the below is from Perl 5.22.0):
/* This hack serves to disambiguate a pair of curlies
* as being a block or an anon hash. Normally, expectation
* determines that, but in cases where we're not in a
* position to expect anything in particular (like inside
* eval"") we have to resolve the ambiguity. This code
* covers the case where the first term in the curlies is a
* quoted string. Most other cases need to be explicitly
* disambiguated by prepending a "+" before the opening
* curly in order to force resolution as an anon hash.
*
* XXX should probably propagate the outer expectation
* into eval"" to rely less on this hack, but that could
* potentially break current behavior of eval"".
* GSAR 97-07-21
*/
t = s;
if (*s == '\'' || *s == '"' || *s == '`') {
/* common case: get past first string, handling escapes */
for (t++; t < PL_bufend && *t != *s;)
if (*t++ == '\\')
t++;
t++;
}
else if (*s == 'q') {
if (++t < PL_bufend
&& (!isWORDCHAR(*t)
|| ((*t == 'q' || *t == 'x') && ++t < PL_bufend
&& !isWORDCHAR(*t))))
{
/* skip q//-like construct */
const char *tmps;
char open, close, term;
I32 brackets = 1;
while (t < PL_bufend && isSPACE(*t))
t++;
/* check for q => */
if (t+1 < PL_bufend && t[0] == '=' && t[1] == '>') {
OPERATOR(HASHBRACK);
}
term = *t;
open = term;
if (term && (tmps = strchr("([{< )]}> )]}>",term)))
term = tmps[5];
close = term;
if (open == close)
for (t++; t < PL_bufend; t++) {
if (*t == '\\' && t+1 < PL_bufend && open != '\\')
t++;
else if (*t == open)
break;
}
else {
for (t++; t < PL_bufend; t++) {
if (*t == '\\' && t+1 < PL_bufend)
t++;
else if (*t == close && --brackets <= 0)
break;
else if (*t == open)
brackets++;
}
}
t++;
}
else
/* skip plain q word */
while (t < PL_bufend && isWORDCHAR_lazy_if(t,UTF))
t += UTF8SKIP(t);
}
else if (isWORDCHAR_lazy_if(t,UTF)) {
t += UTF8SKIP(t);
while (t < PL_bufend && isWORDCHAR_lazy_if(t,UTF))
t += UTF8SKIP(t);
}
while (t < PL_bufend && isSPACE(*t))
t++;
/* if comma follows first term, call it an anon hash */
/* XXX it could be a comma expression with loop modifiers */
if (t < PL_bufend && ((*t == ',' && (*s == 'q' || !isLOWER(*s)))
|| (*t == '=' && t[1] == '>')))
OPERATOR(HASHBRACK);
if (PL_expect == XREF)
{
block_expectation:
/* If there is an opening brace or 'sub:', treat it
as a term to make ${{...}}{k} and &{sub:attr...}
dwim. Otherwise, treat it as a statement, so
map {no strict; ...} works.
*/
s = skipspace(s);
if (*s == '{') {
PL_expect = XTERM;
break;
}
if (strnEQ(s, "sub", 3)) {
d = s + 3;
d = skipspace(d);
if (*d == ':') {
PL_expect = XTERM;
break;
}
}
PL_expect = XSTATE;
}
else {
PL_lex_brackstack[PL_lex_brackets-1] = XSTATE;
PL_expect = XSTATE;
}
Explanation
If the first term after the opening curly is a string (delimited by ', ", or `) or a bareword beginning with a capital letter, and the following term is , or =>, the curly is treated as the beginning of an anonymous hash (that's what OPERATOR(HASHBRACK); means).
The other cases are a little harder for me to understand. I ran the following program through gdb:
{ (x => 1) }
and ended up in the final else block:
else {
PL_lex_brackstack[PL_lex_brackets-1] = XSTATE;
PL_expect = XSTATE;
}
Suffice it to say, the execution path is clearly different; it ends up being parsed as a block.

Allow only a-Z, 0-9 using preg_match, preg_replace

Could somebody please help out with this line? How to modify it so it only allows a-Z, 0-9?
Thanks.
if (preg_match('~[<>&"\'=\\\]~', preg_replace('~&#(?:\\d{1,7}|x[0-9a-fA-F]{1,6});~', '', $context['checked_username'])) != 0 || $context['checked_username'] == '_' || $context['checked_username'] == '|' || strpos($context['checked_username'], '[code') !== false || strpos($context['checked_username'], '[/code') !== false)
$context['valid_username'] = false;
following code checks [[:alnum:]] (alnum stands for alpha numeric)
if (!preg_match("/^[[:alnum:]]+$/", $context['checked_username']))
{
$context['valid_username'] = false;
}

Big Entity Framework Query, How to pregenerate, or precompile this query

I Have a Big Linq-to-entity Query and it's seem to be very long to convert that linq query into SQL.
How can I Precompiled this query.
Is there a way to do that?.
here is my query.
var ListLocation = from s in repLocation.GetLocationByPermision()
.Where(p => (ViewModel.BaseSearchViewModel.IsActive == -1 || p.IsActive == bIsActive) &&
(ViewModel.LocationTypeID < 0 || ViewModel.LocationTypeID == p.LocationTypeID) &&
(ViewModel.ListUsageID.Count() == 0 || p.Premises.Select(gs => gs.UsageID).Intersect(ViewModel.ListUsageID).Any()) &&
(ViewModel.BaseSearchViewModel.City == null || p.Address.City.CityName.Contains(ViewModel.BaseSearchViewModel.City)) &&
(ViewModel.BaseSearchViewModel.ListCountryID.Count() == 0 || ViewModel.BaseSearchViewModel.ListCountryID.Any(pl => pl == p.Address.City.Province.Country.CtryID)) &&
(ViewModel.BaseSearchViewModel.ListStateID.Count() == 0 || ViewModel.BaseSearchViewModel.ListStateID.Any(pl => pl == p.Address.City.Province.PrvID)) &&
(ViewModel.BaseSearchViewModel.Street == null || p.Address.Street.Contains(ViewModel.BaseSearchViewModel.Street)) &&
(ViewModel.BaseSearchViewModel.CivicNumber == null || p.Address.CivicNumber.Contains(ViewModel.BaseSearchViewModel.CivicNumber)) &&
(ViewModel.BaseSearchViewModel.ListGrpDescID1.Count() == 0 || p.GroupLocations.Select(sg => sg.GrpDescID).Intersect(ViewModel.BaseSearchViewModel.ListGrpDescID1).Any()) &&
(ViewModel.BaseSearchViewModel.ListGrpDescID2.Count() == 0 || p.GroupLocations.Select(sg => sg.GrpDescID).Intersect(ViewModel.BaseSearchViewModel.ListGrpDescID2).Any()) &&
(ViewModel.BaseSearchViewModel.ListGrpDescID3.Count() == 0 || p.GroupLocations.Select(sg => sg.GrpDescID).Intersect(ViewModel.BaseSearchViewModel.ListGrpDescID3).Any()) &&
(ViewModel.BaseSearchViewModel.ListGrpDescID4.Count() == 0 || p.GroupLocations.Select(sg => sg.GrpDescID).Intersect(ViewModel.BaseSearchViewModel.ListGrpDescID4).Any())
)
select new LocationViewModel()
{
LocationID = s.LocationID,
LocationTypeID = s.LocationTypeID,
Long = s.Address.Longitude,
Lat = s.Address.Latitude,
FileNumber = s.LocationFile,
State = s.Address.City.Province.PrvName,
City = s.Address.City.CityName,
Address = s.Address.CivicNumber + " " + s.Address.Street,
Status = s.LocationType.LocationTypeTexts.FirstOrDefault(p => p.LangID == lang).Txt,
DefaultImgPath = s.LocationPictures.FirstOrDefault(p => p.IsDefault == true && p.IsActive == true).FilePath,
Location = s,
HasPremises = s.Premises.Any(p => p.IsActive == true && p.IsDelete == false),
ListGrpDescID = s.GroupLocations.Select(g => g.GrpDescID)
};
What you want is to pre-compile the linq. There is a decent MSDN article on the topic here:
http://msdn.microsoft.com/en-us/magazine/ee336024.aspx
I've found the process a little cumbersome, and find myself reverting to Stored Procedures for the handfull of queries I need to write that rise to your level of complexity.
The guidance on pre-compiling views from Microsoft is probably your best bet:
How to: Pre-Generate Views to Improve Query Performance

What is wrong with this if-elsif-else block in my Perl script?

I'm trying to write a condition for a nested if statement, but haven't found a good example of using or in if statements. The following elsif condition fails and allows the code nested beneath it to fire if $status == 6:
if ($dt1 > $dt2 ) {do one thing}
elsif(($status != 3) || ($status != 6)) { do something else}
else {do something completely different}
I'd like to avoid having another elsif for each condition as the code that actually resides here is several lines long.
Your logic is wrong and your elseif block will always return true. I think you mean to use an AND instead of an OR. Given the following snippet
foreach $status (1 .. 10) {
if (($status != 3) && ($status != 6)) {
print "$status => if\n";
} else {
print "$status => else\n";
}
}
This will output
1 => if
2 => if
3 => else
4 => if
5 => if
6 => else
7 => if
8 => if
9 => if
10 => if
If it helps your thinking, a conditional that is !something || !somethingElse can always be rewritten as !(something && somethingElse). If you apply this to your case above you'd say !(3 && 6), and seeing as a number cannot be 3 and 6 at the same time, it's always false
You said you're asking this because the code is several lines long. Fix that problem. :)
if( $dt1 > $dt2 ) { do_this_thing() }
elsif( ($status != 3) || ($status != 6) ) { do_this_other_thing() }
else { do_something_completely_different() }
Now you don't have several lines in the block and everything is next to each other. You have to figure out what those conditions will be because any value is either not 3 or not 6. :)
Perhaps you meant to use and:
if( $dt1 > $dt2 ) { do_this_thing() }
elsif( $status != 3 and $status != 6 ) { do_this_other_thing() }
else { do_something_completely_different() }
Putting print statements with var names/values into each branch can be helpful.
You could see that the elsif branch is always run, because $status != 3 || $status != 6 is true for any value of $status.