Reading an email string from a cookie in java - java

My application needs to store the users email address in a cookie so that I can pre-populate a login form (username == email address). I set the cookie value in JavaScript. If I read it from JavaScript, I get foo#bar.com. If I look at it in the cookie viewer in Firefox I get foo#bar.com.
When I try to read it on the server-side in Java however, I only get foo.
Do I need to do some sort of encoding/decoding here? If so, how do I do it in a way that can be decoded by both JavaScript and Java?
Thanks in advance!
-Michael

From the javax.servlet.http.Cookie doco for setValue(String):
Assigns a new value to a cookie after
the cookie is created. If you use a
binary value, you may want to use
BASE64 encoding.
With Version 0
cookies, values should not contain
white space, brackets, parentheses,
equals signs, commas, double quotes,
slashes, question marks, at signs,
colons, and semicolons. Empty values
may not behave the same way on all
browsers.
I'm guessing you need to BASE64 encode it on the way in (via JavaScript) and on the way out (via Java)

You need to escape the value part of your cookie.
document.cookie = name + "=" +escape( value )
+ ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" )
+ ( ( path ) ? ";path=" + path : "" )
+ ( ( domain ) ? ";domain=" + domain : "" )
+ ( ( secure ) ? ";secure" : "" );

I have found two solutions to this. Here is the first one.
Add back in padding to Base64 encoded strings. Inspiration for this came from http://fi.am/entry/urlsafe-base64-encodingdecoding-in-two-lines/
In this solution, the JavaScript stays the same (base64 encode everything) and the server side looks like:
public class CookieDecoder {
private static final Log log = LogFactory.getLog(CookieDecoder.class);
/**
* #param cookieValue The value of the cookie to decode
* #return Returns the decoded string
*/
public String decode(String cookieValue) {
if (cookieValue == null || "".equals(cookieValue)) {
return null;
}
if (!cookieValue.endsWith("=")) {
cookieValue = padString(cookieValue);
}
if (log.isDebugEnabled()) {
log.debug("Decoding string: " + cookieValue);
}
Base64 base64 = new Base64();
byte[] encodedBytes = cookieValue.getBytes();
byte[] decodedBytes = base64.decode(encodedBytes);
String result = new String(decodedBytes);
if (log.isDebugEnabled()) {
log.debug("Decoded string to: " + result);
}
return result;
}
private String padString(String value) {
int mod = value.length() % 4;
if (mod <= 0) {
return value;
}
int numEqs = 4 - mod;
if (log.isDebugEnabled()) {
log.debug("Padding value with " + numEqs + " = signs");
}
for (int i = 0; i < numEqs; i++) {
value += "=";
}
return value;
}
}
On the JavaScript side, you just need to make sure you base64 encode the values:
var encodedValue = this.base64.encode(value);
document.cookie = name + "=" + encodedValue +
"; expires=" + this.expires.toGMTString() +
"; path=" + this.path;

The second solution is just to URLEncode the Base64 encoded string. I'm using commons codec to do the encoding here. Java Code:
public class CookieDecoder {
private static final Log log = LogFactory.getLog(CookieDecoder.class);
/**
* #param cookieValue The value of the cookie to decode
* #return Returns the decoded string
*/
public String decode(String cookieValue) {
if (cookieValue == null || "".equals(cookieValue)) {
return null;
}
if (log.isDebugEnabled()) {
log.debug("Decoding string: " + cookieValue);
}
URLCodec urlCodec = new URLCodec();
String b64Str;
try {
b64Str = urlCodec.decode(cookieValue);
}
catch (DecoderException e) {
log.error("Error decoding string: " + cookieValue);
return null;
}
Base64 base64 = new Base64();
byte[] encodedBytes = b64Str.getBytes();
byte[] decodedBytes = base64.decode(encodedBytes);
String result = new String(decodedBytes);
if (log.isDebugEnabled()) {
log.debug("Decoded string to: " + result);
}
return result;
}
}
But now I have to decode it on the JavaScript side as well...
Encode:
var encodedValue = this.base64.encode(value);
document.cookie = name + "=" + escape(encodedValue) +
"; expires=" + this.expires.toGMTString() +
"; path=" + this.path;
Decode:
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1,c.length);
}
if (c.indexOf(nameEQ) == 0) {
var encodedValue = c.substring(nameEQ.length,c.length);
return this.base64.decode(unescape(encodedValue));
}
}
return null;

Related

Appending arguments to url with Java

I am using the following method to add url encoded (the encoding occurs inside another method) name/value pairs to the end of a url represented by the variable mUrl using the following code
public void addArgument(String name, String value){
String encName = urlEncode ( name ) ;
String encValue = urlEncode( value ) ;
String urlenc;
if ( argCount++ == 0 ){
urlenc = "?" + encName + "=" + encValue + "&";
mUrl = mUrl + urlenc;
argCount++;
} else {
urlenc = encName + "=" + encValue + "&";
mUrl = mUrl + urlenc;
}
}
The code works fine however the resulting url ends in "&". For example:
http://www.amazon.com?name=sam&age=5&
Is there a way I can adjust my code to get rid of the "&" on the end of the url?
Thanks
Add the & at the beginning instead of at the end:
public void addArgument(String name, String value) {
mUrl += (argCount++ == 0 ? "?" : "&") + urlEncode(name) + "=" + urlEncode(value);
}

Issue in masking XML tag value in java

I have an XML file shown below:
<Envelope>
<Body>
<user1>
<userId>userName</userId>
<password>password</password>
<creditCard>
<creditCardNumber>12345678901234</creditCardNumber>
<cvv>123</cvv>
</creditCard>
</user1>
<user2>
<userId>userName</userId>
<password>password</password>
<creditCard>
<creditCardNumber>12345678901234</creditCardNumber>
<cvv>123</cvv>
</creditCard>
</user2>
</Body>
</Envelope>
I have a java code used to log the xml transactions on to some server for future reference. This java code has methods to mask some characters or whole value of tag before logging as the credit card details are not to be disclosed.
Here are the methods:
public static String mask( String input, String[] tags, String maskPattern, String namespacePattern)
throws Throwable
{
StringBuffer sb = new StringBuffer( input );
encodedXML = false;
if (sb.indexOf( ">" ) > 0) {
// XML is encoded
gt = ">";
lt = "<";
encodedXML = true;
// modify patterns for encoded xml
maskPattern = "(>)" + alphaNumericStuff + "+(<)/";
if (sb.indexOf( """ ) >= 0) {
// There is a mix of double quotes and " in this xml
namespacePattern = mixedEncodingAlphaNumericStuff + "*";
}
}
for (int i = 0; i < tags.length; i++) {
// do a quick check to see if the tag is in the string to reduce excessive string creation
if (sb.indexOf( tags[i] ) < 0) {
continue;
} else {
sb = maskElementValue( sb, tags[i],maskPattern, namespacePattern );
}
}
return sb.toString();
}
private static StringBuffer maskElementValue( StringBuffer sb, String tag, String maskPattern,String namespacePattern)
{
// Pattern p = Pattern.compile( tag + maskPattern ); doesn't take namespace into account
Pattern p = Pattern.compile( tag + namespacePattern + maskPattern );
Matcher m = p.matcher( sb.toString() );
StringBuffer tempSB = new StringBuffer();
String namespaceStr = "";
while (m.find()) {
namespaceStr = m.group().substring( tag.length(), m.group().indexOf( gt ) );
// Added full masking for username and password including last 4 characters
if (tag.equalsIgnoreCase( "username" ) || tag.equalsIgnoreCase( "password" )) {
m.appendReplacement( tempSB, tag + namespaceStr + gt + xOut( new StringBuffer( m.group().substring( tag.length() + namespaceStr.length() + gt.length() ) ), true ) );
} else {
m.appendReplacement( tempSB, tag + namespaceStr + gt + xOut( new StringBuffer( m.group().substring( tag.length() + namespaceStr.length() + gt.length() ) ), false ) );
}
}
m.appendTail( tempSB );
return tempSB;
}
private static String xOut( StringBuffer sb, boolean maskAll )
{
int dataSize = sb.toString().trim().length() - 1 - lt.length();
if (!maskAll && dataSize > 4) {
if (sb.indexOf( "<" ) > 0 || sb.indexOf( "<" ) > 0) {
StringBuffer tempmaskSB = new StringBuffer( sb.substring( 0, sb.indexOf( "<" ) ) );
dataSize = tempmaskSB.length();
}
// Don't mask last 4 digit
for (int i = 0; i < dataSize - 4; i++) {
sb.setCharAt( i, 'X' );
}
} else {
if (sb.indexOf( "<" ) > 0 || sb.indexOf( "<" ) > 0) {
StringBuffer tempmaskSB = new StringBuffer( sb.substring( 0, sb.indexOf( "<" ) ) );
dataSize = tempmaskSB.length();
}
// Mask all
for (int i = 0; i < dataSize; i++) {
sb.setCharAt( i, 'X' );
}
}
return sb.toString();
}
I am passing the xml as string to the method and an array of tags that are to be masked. If it is username and password they should be masked completely and other tags in the array should be masked except the last 4 characters.
Now the problem is that masking is not happening for some of the transactions. when we have done a load testing, 12 out of 18000 transactions are not masked the protected data.
In some cases, user1 details are getting masked but user2 details are not masked in the same transaction.
Could any one help me in understanding why this is happening? Has anybody faced such issue before?
Thanks in advance.
Not sure if this is helpful. But i would do the masking part with jsoup
Example:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;
public class Mask {
static String xml = "<Envelope>\n" +
"<Body>\n" +
" <user1>\n" +
" <userId>userName</userId>\n" +
" <password>password</password>\n" +
" <creditCard>\n" +
" <creditCardNumber>12345678901234</creditCardNumber>\n" +
" <cvv>123</cvv>\n" +
" </creditCard>\n" +
" </user1>\n" +
" <user2>\n" +
" <userId>userName</userId>\n" +
" <password>password</password>\n" +
" <creditCard>\n" +
" <creditCardNumber>12345678901234</creditCardNumber>\n" +
" <cvv>123</cvv>\n" +
" </creditCard>\n" +
" </user2>\n" +
"</Body>\n" +
"</Envelope>";
public static void main (String[]args){
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
Elements toMaskCompletely = doc.select("userId,password");
Elements toMaskPartially = doc.select("creditCardNumber");
for(Element ele : toMaskCompletely){
ele.text("XXXXX");
}
for(Element ele : toMaskPartially){
ele.text("XXXXXXXX"+ele.text().substring(ele.text().length()-4));
}
System.out.println(doc.toString());
}
}

How to split URL?

This is my code to split URL, but that code have problem. All link appear with double word, example www.utem.edu.my/portal/portal . the words /portal/portal always double in any link appear. Any suggestion to me extract links in the webpage?
public String crawlURL(String strUrl) {
String results = ""; // For return
String protocol = "http://";
// Assigns the input to the inURL variable and checks to add http
String inURL = strUrl;
if (!inURL.toLowerCase().contains("http://".toLowerCase()) &&
!inURL.toLowerCase().contains("https://".toLowerCase())) {
inURL = protocol + inURL;
}
// Pulls URL contents from the web
String contectURL = pullURL(inURL);
if (contectURL == "") { // If it fails, then try with https
protocol = "https://";
inURL = protocol + inURL.split("http://")[1];
contectURL = pullURL(inURL);
}
// Declares some variables to be used inside loop
String aTagAttr = "";
String href = "";
String msg = "";
// Finds A tag and stores its href value into output var
String bodyTag = contectURL.split("<body")[1]; // Find 1st <body>
String[] aTags = bodyTag.split(">"); // Splits on every tag
//To show link different from one another
int index = 0;
for (String s: aTags) {
// Process only if it is A tag and contains href
if (s.toLowerCase().contains("<a") && s.toLowerCase().contains("href")) {
aTagAttr = s.split("href")[1]; // Split on href
// Split on space if it contains it
if (aTagAttr.toLowerCase().contains("\\s"))
aTagAttr = aTagAttr.split("\\s")[2];
// Splits on the link and deals with " or ' quotes
href = aTagAttr.split(((aTagAttr.toLowerCase().contains("\""))? "\"" : "\'"))[1];
if (!results.toLowerCase().contains(href))
//results += "~~~ " + href + "\r\n";
/*
* Last touches to URl before display
* Adds http(s):// if not exist
* Adds base url if not exist
*/
if(results.toLowerCase().indexOf("about") != -1) {
//Contains 'about'
}
if (!href.toLowerCase().contains("http://") && !href.toLowerCase().contains("https://")) {
// http:// + baseURL + href
if (!href.toLowerCase().contains(inURL.split("://")[1]))
href = protocol + inURL.split("://")[1] + href;
else
href = protocol + href;
}
System.out.println(href);//debug
consider to use the URL class...
Use it as suggested by the documentation :
)
public static void main(String[] args) throws Exception {
URL aURL = new URL("http://example.com:80/docs/books/tutorial"
+ "/index.html?name=networking#DOWNLOADING");
System.out.println("protocol = " + aURL.getProtocol());
System.out.println("authority = " + aURL.getAuthority());
System.out.println("host = " + aURL.getHost());
System.out.println("port = " + aURL.getPort());
System.out.println("path = " + aURL.getPath());
System.out.println("query = " + aURL.getQuery());
System.out.println("filename = " + aURL.getFile());
System.out.println("ref = " + aURL.getRef());
}
}
the output:
protocol = http
authority = example.com:80
host = example.com
port = 80
etc
after this you can take the elements you need an create a new one string/URL :)

How to remove whitespace in String imported from Excel

I need to remove all white character from a string and I am not able to do so.
Anyone has an idea on how to do it?
Here is my string retrieved from an excel file via jxl API :
"Destination à gauche"
And here are its bytes :
6810111511610511097116105111110-96-32321039711799104101
There is the code I use to remove whitespaces :
public static void checkEntetes(Workbook book) {
String sheetName = "mysheet";
System.out.print(sheetName + " : ");
for(int i = 0; i < getColumnMax(book.getSheet(sheetName)); i++) {
String elementTrouve = book.getSheet(sheetName).getCell(i, 0).getContents();
String fileEntete = new String(elementTrouve.getBytes()).replaceAll("\\s+","");
System.out.println("\t" + elementTrouve + ", " + bytesArrayToString(elementTrouve.getBytes()));
System.out.println("\t" + fileEntete + ", " + bytesArrayToString(fileEntete.getBytes()));
}
System.out.println();
}
And this outputs :
"Destination à gauche", 6810111511610511097116105111110-96-32321039711799104101
"Destination àgauche", 6810111511610511097116105111110-96-321039711799104101
I even tried to make it myself and it still leaves a space before the 'à' char.
public static String removeWhiteChars(String s) {
String retour = "";
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c != (char) ' ') {
retour += c;
}
}
return retour;
}
regular expressions to the rescue:
str = str.replaceAll("\\s+", "")
will remove any sequence of whitespace characters. for example:
String input = "Destination à gauche";
String output = input.replaceAll("\\s+","");
System.out.println("output is \""+output+"\"");
outputs Destinationàgauche
if youre starting point is indeed the raw bytes (byte[]) you will first need to make them into a String:
byte[] inputData = //get from somewhere
String stringBefore = new String(inputData, Charset.forName("UTF-8")); //you need to know the encoding
String withoutSpaces = stringBefore.replaceAll("\\s+","");
byte[] outputData = withoutSpaces.getBytes(Charset.forName("UTF-8"));
If you would like to use a formula, the TRIM function will do exactly what you're looking for:
+----+------------+---------------------+
| | A | B |
+----+------------+---------------------+
| 1 | =TRIM(B1) | value to trim here |
+----+------------+---------------------+
So to do the whole column.
1) Insert a column
2) Insert TRIM function pointed at cell you are trying to correct.
3) Copy formula down the page
4) Copy inserted column
5) Paste as "Values"
Reference: Question number 9578397 on stackoverflow.com

Using 2 QueryParams to return an object requiring 2 different variables

I'm writing a special permission forms program using MySQL, Javascript, and HTML code, which both respond to. I'm doing all of this using singleton pattern access and facade code(s) in java, and a services code, which responds to the singleton pattern codes.
I'm trying To retrieve a form (AKA 1 Result) by the variables, courseDept & courseNm.
This is a snippet of code I'm using to do all this:
FormDataFacade.java code snippet:
#Path("/specialPermissions/sp")
#GET
#Produces("text/plain")
public Response getSpecialPermissionFormByDeptAndRoomNm(#QueryParam("courseDept") String theDept, #QueryParam("courseNm") String theNm)
throws NamingException, SQLException, ClassNotFoundException
{
//Referenciation to FormDataFacade class.
FormDataFacade iFacade = FormDataFacade.getInstance();
int intNm = 0;
try {
intNm = Integer.parseInt(theNm);
}catch (NumberFormatException FAIL) {
intNm = 1;
}
//Aiming for forms with matching departments & room numbers by calling FormDataFacade
//method, getSpecialPermissionFormByDeptAndRoomNm.
SpecialPermissionForms[] orgaForm = iFacade.getSpecialPermissionFormByDeptAndRoomNm(theDept, intNm);
//Json String Representation...
if (orgaForm != null)
{
Gson neoArcadia = new Gson();
String result = neoArcadia.toJson(orgaForm);
//Json String added to response message body...
ResponseBuilder rb = Response.ok(result, MediaType.TEXT_PLAIN);
rb.status(200); //HTTP Status code has been set!
return rb.build(); //Creating & Returning Response.
}
else
{ //In case of finding no form data for the procedure...
return Response.status(700).build();
}
}
FormDataServices.java code snippet:
public SpecialPermissionForms[] getSpecialPermissionFormByDeptAndRoomNm(String theDept, int theNm) throws SQLException, ClassNotFoundException
{
Connection con = zeon.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT formID, studentName, courseDept, courseNm, semester, year, reasonCode FROM spforms WHERE courseDept = ? & courseNm = ?");
pstmt.setString(1, theDept);
pstmt.setInt(2, theNm);
ResultSet rs = pstmt.executeQuery();
SpecialPermissionForms[] neoForm = new SpecialPermissionForms[50];
int current = 0;
while (rs.next())
{
int formID3 = rs.getInt("formID");
String studentName3 = rs.getString("studentName");
String courseDept3 = rs.getString("courseDept");
String courseNm3 = rs.getString("courseNm");
String semester3 = rs.getString("semester");
int year3 = rs.getInt("year");
String reasonCode3 = rs.getString("reasonCode");
SpecialPermissionForms neo = new SpecialPermissionForms(formID3, studentName3, courseDept3, courseNm3, semester3, year3, reasonCode3);
neoForm[current] = neo;
current++;
}
if (current > 0)
{
neoForm = Arrays.copyOf(neoForm, current);
return neoForm;
}
else
{
return null;
}
}
Forms.html code snippet which both pieces of java code respond to:
$("#btnOneName").click(function() {
alert("clicked");
var inputId1=document.getElementById("t_specialFormCourseDept").value;
var inputId2=document.getElementById("t_specialFormCourseNm").value;
var theData = "courseDept=" + inputId1 + "&" + "courseNm=" + inputId2;
alert("Sending: " + theData);
var theUrl = "http://localhost:8080/onlineforms/services/enrollment/specialPermissions/sp?courseDept=&courseNm="+ theData;
$.ajax( {
url: theUrl,
type: "GET",
dataType: "text",
success: function(result) {
alert("success");
var neoForm = JSON.parse(result);
alert(neoForm);
var output="<h3>Current Form Lists:</h3>";
output += "<ul>";
for (var current = 0; current < neoForm.length; current++)
{
output += "<li>" + neoForm[current].formID + ": " + neoForm[current].studentName + " (" + neoForm[current].courseDept + " - " + neoForm[current].courseNm + ") " +
" (" + neoForm[current].semester + " - " + neoForm[current].year + ") " + " - " + neoForm[current].reasonCode + "</li>";
}
output += "</ul>";
alert(output);
$("#p_retrieveOneName").html(output);
},
error:function(xhr) {
alert("error");
$("#p_retrieveOneName").html("Error:"+xhr.status+" "+xhr.statusText);}
} );
});
});
Now, when I go test this code in my webservice after successfully compiling it, it does work, however it retrieves everything, including the specific results I was searching for - I only want to return the results I have specifically searched for and nothing else. What exactly am I doing wrong here in these snippets of code?
Any suggestions or steps in the right direction are highly welcome.

Categories

Resources