BarcodeBean.java 15.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
/*
 * Copyright Codecrew Ry
 * 
 * All rights reserved.
 * 
 * This license applies to any software containing a notice placed by the 
 * copyright holder. Such software is herein referred to as the Software. 
 * This license covers modification, distribution and use of the Software. 
 * 
 * Any distribution and use in source and binary forms, with or without 
 * modification is not permitted without explicit written permission from the 
 * copyright owner. 
 * 
 * A non-exclusive royalty-free right is granted to the copyright owner of the 
 * Software to use, modify and distribute all modifications to the Software in 
 * future versions of the Software. 
 * 
 */
package fi.codecrew.moya.beans;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;

import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import fi.codecrew.moya.facade.PlaceFacade;
import fi.codecrew.moya.facade.PrintedCardFacade;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.Place;
import fi.codecrew.moya.model.PrintedCard;
import fi.codecrew.moya.model.Product;
import fi.codecrew.moya.utilities.BarcodeUtils;

/**
 * Session Bean implementation class BarcodeBean
 */
@Stateless
@LocalBean
public class BarcodeBean implements BarcodeBeanLocal {

	private static final String PRINTED_CARD_BARCODEPREFIX = "277"; //2M
	private static final String EVENTUSER_BARCODEPREFIX = "279"; //2O
	private static final String PLACE_BARCODEPREFIX = "289"; //2Y
	
	private static final String PRINTED_CARD_TEXTCODEPREFIX = "10"; 
	private static final String PLACE_TEXTCODEPREFIX = "11";
	private static final String EVENTUSER_TEXTCODEPREFIX = "12";


	// DO NOT ACCIDENTLY ADD '=' -char to this list
	private static final String TEXTCODE_CHARACTER_MAP = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
	private static final int  TEXTCODE_ROTATE_COUNT = 500;
	
	//private static final String NEXT_PREFIX = "265";			//2A

	private static final Logger logger = LoggerFactory.getLogger(BarcodeBean.class);

	@EJB
	PrintedCardFacade printedCardFacade;

	@EJB
	PlaceFacade placeFacade;

	@EJB
	UserBeanLocal userBean;
	
	@EJB
	ProductBeanLocal productBean;
	

	/**
	 * Default constructor.
	 */
	public BarcodeBean() {
		// TODO Auto-generated constructor stub
	}

	public InputStream getUserBarcode(EventUser user) throws IOException {
		
		String barcode = generateBarcodeNumbers(EVENTUSER_BARCODEPREFIX, user.getId());
		
		logger.debug("Geneating barcode for user {} : {}", user, barcode);

		return BarcodeUtils.getBarcodeEAN(barcode);
	}

	public InputStream getCardBarcode(PrintedCard printedCard) throws IOException {
		
		String barcode = generateBarcodeNumbers(PRINTED_CARD_BARCODEPREFIX, printedCard.getId());
		
		logger.debug("Geneating barcode for card {} : {}", printedCard, barcode);

		return BarcodeUtils.getBarcodeEAN(barcode);
	}

	@Override
	public String getUserLongTextCode(EventUser user) {
		return getUserTextCode(user,38,16);
	}

	@Override
	public EventUser getUserFromLongTextCode(String textcode) {

		// check if it is some url
		if(textcode.lastIndexOf("=") > 6) {
			textcode = textcode.substring(textcode.lastIndexOf("=")+1);
		}

		return getUserFromTextCode(textcode,38,16);
	}

	@Override
	public String getUserTextCode(EventUser user) {
		return getUserTextCode(user, 12, 5);
	}


	@Override
	public EventUser getUserFromTextCode(String textcode) {

		return getUserFromTextCode(textcode,12,5);
	}


	private String getUserTextCode(EventUser user, int lenght, int bytecount) {

		int barcodeLenght = 12;

		if(lenght < barcodeLenght)
			barcodeLenght = lenght;

		// barcode is still only 12 marks long
		String barcode = generateBarcodeNumbers(EVENTUSER_TEXTCODEPREFIX, user.getId(), barcodeLenght);

		// add some random -stuff to start of string
		for (int i = lenght - barcode.length(); i > 0; --i) {
			barcode = ((int) (Math.random() * 10.0)) + barcode;
		}

		logger.debug(barcode);


		BigInteger intCode;
		try {
			intCode = new BigInteger(barcode);
		} catch(NumberFormatException x)
		{
			return "GenFail";
		}

		String textCode = generateTextcode(intCode, bytecount);

		BigInteger checkCode = textcodeToNumber(textCode, bytecount);


		if(checkCode.compareTo(intCode) != 0) {
			logger.error("CheckCode {} : Original {}", checkCode, intCode);
			return "GenError"; // different error messages, so we can tell where the error was
		}

//		logger.debug("Geneating hexcode for place {} : {}", place.getId(), textCode);

		return textCode;
	}

	private EventUser getUserFromTextCode(String textcode, int lenght, int bytecount) {

		BigInteger numbercode = textcodeToNumber(textcode, bytecount);
		String barcode = numbercode.toString();

		// remove random prefix
		int barcodeLenght = 12;
		if(lenght < barcodeLenght)
			barcodeLenght = lenght;

		// remove some random -stuff to start of string
		for (int i = lenght - barcodeLenght; i > 0; --i) {

			// barcode was shorter than random stuff, I think that it does not match
			if(barcode.length() <= 0)
				return null;

			barcode = barcode.substring(1);
		}


		try {
			if (barcode.startsWith(EVENTUSER_TEXTCODEPREFIX)) {
				int id = Integer.parseInt(barcode.substring(PLACE_TEXTCODEPREFIX.length(), barcode.length()));
				EventUser user = userBean.findByEventUserId(id);

				return user;
			}
		} catch (NumberFormatException x) {
		}

		return null;
	}



	public String getPlaceTextCode(Place place) {
	
		String barcode = generateBarcodeNumbers(PLACE_TEXTCODEPREFIX, place.getId(), 8);
		
		BigInteger intCode;
		try {
			intCode = new BigInteger(barcode);
		} catch(NumberFormatException x)
		{
			return "GenFail";
		}
		
		String textCode = generateTextcode(intCode, 3);
		
		BigInteger checkCode = textcodeToNumber(textCode, 3);

		
		if(checkCode.compareTo(intCode) != 0) {
			logger.error("CheckCode {} : Original {}", checkCode, intCode);
			return "GenError"; // different error messages, so we can tell where the error was
		}

//		logger.debug("Geneating hexcode for place {} : {}", place.getId(), textCode);

		return textCode;
	}

	public String getVrAuthCodeForCard(PrintedCard printedCard) {
		StringBuilder sb = new StringBuilder();
		sb.append(PRINTED_CARD_BARCODEPREFIX);
		if (printedCard == null)
			return "";
		String idStr = printedCard.getId().toString();

		for (int i = 8 - idStr.length() - sb.length(); i > 0; --i) {
			sb.append("0");
		}
		sb.append(idStr);
		String code = sb.toString();

		String hexcode = Integer.toHexString(Integer.parseInt(code));
		String checksum = Integer.toHexString(hexcode.hashCode());
		checksum = checksum.substring(checksum.length() - 3);
		hexcode += checksum;
		//hexcode = Integer.toString(hexcode.hashCode());

		logger.debug("Geneating VrAuthcode for card {} : {}", printedCard.getId(), hexcode);

		return hexcode;
	}

	public String checkVrAuthCode(String code) {
		String checksumNew = code.substring(code.length() - 3);
		code = code.substring(0, (code.length() - 3));
		String checksumOld = Integer.toHexString(code.hashCode());
		checksumOld = checksumOld.substring(checksumOld.length() - 3);
		if (checksumNew.equals(checksumOld)) {
			int decimal = Integer.decode(code);
			code = Integer.toString(decimal);
			String prefix = code.substring(0, 2);
			int id = Integer.parseInt(code.substring(3, code.length() - 1));
			if (prefix.equals(PRINTED_CARD_BARCODEPREFIX) && id != 0) {
				PrintedCard printedCard = printedCardFacade.find(id);
				if (printedCard != null)
					return printedCard.getUser().getNick();
				else
					return "Invalid";
			}
		} else {
			return "Invalid";
		}
		return "Invalid";
	}

	@Override
	public Place getPlaceFromTextCode(String textcode) {

		BigInteger numbercode = textcodeToNumber(textcode, 3);
		String barcode = numbercode.toString();

		try {
			if (barcode.startsWith(PLACE_TEXTCODEPREFIX)) {
				int id = Integer.parseInt(barcode.substring(PLACE_TEXTCODEPREFIX.length(), barcode.length()));
				Place place = placeFacade.find(id);

				return place;
			}
		} catch (NumberFormatException x) {
		}

		return null;
	}

	public PrintedCard getPrintedCard(String barcode) {
		if (barcode == null || barcode.isEmpty())
			return null;

		// it's our special front barcode
		try {
			if (barcode.startsWith(PRINTED_CARD_BARCODEPREFIX)) {
				int id = Integer.parseInt(barcode.substring(3, barcode.length() - 1));
				PrintedCard card = printedCardFacade.find(id);

				if (card != null)
					return card;
			}
		} catch (NumberFormatException x) {
		}

		return printedCardFacade.findByCode(barcode);
	}

	public EventUser getUser(String barcode) {
		if (barcode == null || barcode.isEmpty())
			return null;

		// trim zeros off from barcode
		String stripped = barcode;
		while (stripped.length() > 0 && stripped.charAt(0) == '0') {
			stripped = stripped.substring(1);
		}

		if (stripped.length() > 0)
			barcode = stripped;

		try {
			// it's our special front barcode
			if (barcode.startsWith(EVENTUSER_BARCODEPREFIX)) {
				int id = Integer.parseInt(barcode.substring(3, barcode.length() - 1));
				logger.debug("finding user with barcode {} and id {}", barcode, id);
				EventUser user = userBean.findByEventUserId(id);

				return user;
			}

			// try if it is our Eticket -code
			EventUser user = getUserFromTextCode(barcode);

			if(user != null)
				return user;

			// not eticket, then there is our other eticket, the one sent via email.
			user = getUserFromLongTextCode(barcode);

			if(user != null)
				return user;


		} catch (NumberFormatException x) {
		}

		return null;
	}

	@Override
	public Product getProduct(String barcode) {
		return productBean.findByBarcode(barcode);
	}

	@Override
	public Place getPlaceFromBarcode(String barcode) {
		//throw new UnsupportedOperationException();
		return null;
	
		// TODO: tarttee hakea se paikkakoodi, ja sen avulla paikka. Toivon että se on ny tämä eikä placecodehäsmäkkä, mikä se oikeasti on. Vittu lisää refactorointia
	}
	
	private String generateBarcodeNumbers(String prefix, Integer id) {
		return generateBarcodeNumbers(prefix,id,12);
	}
	
	
	/**
	 * Reverse for generateTextcode
	 * @param original
	 * @param bytecount
	 * @return
	 */
	private BigInteger textcodeToNumber(String original, int bytecount) {
		

		BigInteger number = BigInteger.ZERO;
		BigInteger divnumber = BigInteger.valueOf(TEXTCODE_CHARACTER_MAP.length());
		int curExponent = 0;
		int curIndex = original.length() -1;
		do {
			
			char curChar = original.charAt(curIndex);
			BigInteger curNumber = BigInteger.valueOf(TEXTCODE_CHARACTER_MAP.indexOf(curChar));
			
			number = number.add(curNumber.multiply(divnumber.pow(curExponent++)));
			
		} while(--curIndex >= 0);
		
		BigInteger convertedNumber = new BigInteger(reverseLinearFeedbackShiftRegister(number.toByteArray(),bytecount, TEXTCODE_ROTATE_COUNT));
		
		
		return convertedNumber;
	}
	
	
	
	
	/**
	 * 
	 * @param original Original code to convert
	 * @param bytecount Code width in bytes
	 * @return
	 */
	private String generateTextcode(BigInteger original, int bytecount) {
		
	
		
		if(original == null || original.compareTo(BigInteger.ZERO) <= 0) {
			return "GenFail";
		}
		
		
		BigInteger numbersLeft = new BigInteger(linearFeedbackShiftRegister(original.toByteArray(),bytecount, TEXTCODE_ROTATE_COUNT)); 
		
		String converted = "";
		BigInteger divnumber = BigInteger.valueOf(TEXTCODE_CHARACTER_MAP.length());
		
		do {
			
			BigInteger div = numbersLeft.divide(divnumber);
			
			converted = TEXTCODE_CHARACTER_MAP.charAt(numbersLeft.subtract(div.multiply(divnumber)).intValue()) + converted;
			
			numbersLeft = div;
			
			if(numbersLeft.compareTo(divnumber) < 0) {
				converted = TEXTCODE_CHARACTER_MAP.charAt(numbersLeft.intValue()) + converted;
				numbersLeft = BigInteger.ZERO;
			}
			
		} while(numbersLeft.compareTo(BigInteger.ZERO) > 0);
		
		
		return converted;
	}
	
	private String generateBarcodeNumbers(String prefix, Integer id, int lenght) {
		StringBuilder sb = new StringBuilder();
		sb.append(prefix);
		String idStr = id.toString();

		for (int i = lenght - idStr.length() - sb.length(); i > 0; --i) {
			sb.append("0");
		}
		sb.append(idStr);
		return sb.toString();
	}

	
	
	
	/**
	 * http://en.wikipedia.org/wiki/Linear_feedback_shift_register
	 * 
	 * @param bytes bytes to rotate
	 * @param bytecount How many bytes we rotate from array, counting from right side
	 * @param times how many times we do lfsr-rotate
	 * @return rotated bytearray, this does not touch original array
	 */
	private byte[] reverseLinearFeedbackShiftRegister(byte[] bytes,int bytecount, int times) {
		
		
		// remove empty bytes from bytearray, this way this number wont bloat
		int emptySize = bytes.length - bytecount;
				
		if(emptySize < 0) emptySize = 0;

		
		byte[] convertedBytes = new byte[bytes.length - emptySize];
		
		int y = emptySize;
		for(int n = 0; n < convertedBytes.length; n++) {
			convertedBytes[n] = bytes[y++];
		}
		
		
		// empty part removed, let's do some lfsr-magic
		
		for(int n = 0; n < times; n++) {
			
			boolean curbit = (convertedBytes[0] & 0b10000000) != 0;
			
			
			curbit = curbit ^ ((convertedBytes[convertedBytes.length-1] & 0b10) != 0); // 2. bit from right
			curbit = curbit ^ ((convertedBytes[convertedBytes.length-1] & 0b100) != 0); // 3. bit from right
			curbit = curbit ^ ((convertedBytes[convertedBytes.length-1] & 0b10000) != 0); // 5. bit from right
			
			// sift left one
			for(int z = convertedBytes.length-1; z >= 0; z--) {
				boolean overflowBit = ((convertedBytes[z] & 0b10000000) != 0);
				
				convertedBytes[z] = (byte) (convertedBytes[z] << 1);
				
				if(curbit) {
					convertedBytes[z] = (byte) (convertedBytes[z] | 0b00000001);
				} else {
					convertedBytes[z] = (byte) (convertedBytes[z] & 0b11111110);
				}
				
				curbit = overflowBit;
			}
			
			
		}
		
		// add 1 zerobyte to the start, just to be sure that this number is now bigger than 0
		byte[] returnBytes = new byte[convertedBytes.length+1];
		
		for(int n = 0; n < convertedBytes.length; n++) {
			returnBytes[n+1] = convertedBytes[n];
		}
				
		
		return returnBytes;
	}
	
	
	
	
	/**
	 * http://en.wikipedia.org/wiki/Linear_feedback_shift_register
	 * 
	 * @param bytes bytes to rotate
	 * @param bytecount How many bytes we rotate from array, counting from right side
	 * @param times how many times we do lfsr-rotate
	 * @return rotated bytearray, this does not touch original array
	 */
	private byte[] linearFeedbackShiftRegister(byte[] bytes, int bytecount, int times) {
		
		
		// remove empty bytes from bytearray, this way this number wont bloat
		int emptySize = bytes.length - bytecount;
		
		if(emptySize < 0) emptySize = 0;
		
		byte[] convertedBytes = new byte[bytes.length - emptySize];
		
		int y = emptySize;
		for(int n = 0; n < convertedBytes.length; n++) {
			convertedBytes[n] = bytes[y++];
		}
		
		
		// empty part removed, let's do some lfsr-magic
		
		for(int n = 0; n < times; n++) {
			
			boolean curbit =  (convertedBytes[convertedBytes.length-1] & 0b1) != 0; // rightmost byte
			curbit = curbit ^ ((convertedBytes[convertedBytes.length-1] & 0b100) != 0); // 3. bit from right
			curbit = curbit ^ ((convertedBytes[convertedBytes.length-1] & 0b1000) != 0); // 4. bit from right
			curbit = curbit ^ ((convertedBytes[convertedBytes.length-1] & 0b100000) != 0); // 6. bit from right
			
			// sift right one
			for(int z = 0; z < convertedBytes.length; z++) {
				boolean overflowBit = ((convertedBytes[z] & 0b1) != 0);
				
				// >> uses leftmost bit as filler >>> uses 0 as filler
				convertedBytes[z] = (byte) (convertedBytes[z] >>> 1);
				
				if(curbit) {
					convertedBytes[z] = (byte) (convertedBytes[z] | 0b10000000);
				} else {
					convertedBytes[z] = (byte) (convertedBytes[z] & 0b01111111);
				}
				
				curbit = overflowBit;
			}
			
			
		}
		
		// add 1 zerobyte to the start, just to be sure that this number is now bigger than 0
		byte[] returnBytes = new byte[convertedBytes.length+1];
		
		for(int n = 0; n < convertedBytes.length; n++) {
			returnBytes[n+1] = convertedBytes[n];
		}
		
		return returnBytes;
		
	}

}