I have a modal Window implemented in SmartGWT - how can I close it when someone clicks off of the window? - user-interface

I've created a class that extends the Window SmartGWT class, and it is set to be modal. I am trying to make the Window close when a user clicks off the window. I have tried to link it up to a FocusChangedHandler with no luck. Has anyone done something like this before?
/**
* Sets up a modal Dialog box that lets the user edit attributes associated
* with the properties of the {#link LabElement} that are given.
*
* #author Therin Irwin
*/
public class EditorDialog extends Window {
final DynamicForm dyn = new DynamicForm();
final RichTextEditor richTextEditor = new RichTextEditor();
final List attrItems = new ArrayList();
/**
* Creates a new EditorDialog with a RichTextEditor and a list of
* attributes for the element.
*
* #param name the name of the element being edited.
* #param attr the List of String attributes of the element that can be
* edited.
* #param hasText true if the element supports text inside, false if not.
*/
public EditorDialog(String name, List attr, boolean hasText) {
super();
VLayout vert = new VLayout();
this.setShowMinimizeButton(false);
this.setIsModal(true);
this.setShowModalMask(true);
this.setTitle(name + " Editor");
richTextEditor.setWidth(550);
richTextEditor.setHeight(100);
richTextEditor.setPadding(5);
richTextEditor.setCanDragResize(true);
richTextEditor.setResizeFrom("B");
richTextEditor.setShowEdges(true);
if (attr == null || attr.size() == 0) {
richTextEditor.setHeight(300);
}
else {
int i = 0;
FormItem[] fi = new FormItem[attr.size()];
for (String at : attr) {
TextItem temp = new TextItem(at, at);
attrItems.add(temp);
fi[i++] = temp;
}
dyn.setFields(fi);
dyn.setPadding(5);
dyn.setTop(100);
}
if (hasText)
vert.addMember(richTextEditor);
if (!(attr == null || attr.size() == 0))
vert.addMember(dyn);
this.addItem(vert);
this.centerInPage();
this.setAutoSize(true);
}
/**
* Returns the text of the RichTextEditor.
*
* #return the text entered into the RichTextEditor.
*/
public String getRichText() {
return richTextEditor.getValue();
}
/**
* Sets the text in the RichTextEditor to String value.
*
* #param value the String to put as the contents of the RichTextEditor.
*/
public void setRichText(String value) {
richTextEditor.setValue(value);
}
/**
* Returns the List of TextItems that hold the user-entered values for
* attributes.
*
* #return the TextItems associated with each attribute, in order.
*/
public DynamicForm getFormItems() {
return dyn;
}
public TextItem getFormItem(int item) {
return (TextItem) dyn.getFields()[item];
}
}

#Therin
I guess according to your requirement, you need to implement this property of Window:
this.setDismissOnOutsideClick(true);

Related

ES6 inherited function returns wrong type when invoked on subclass

When a function is inherited by a subclass, I want the return type to be as if the function were defined directly on the subclass.
To be clear, the code works fine at run-time. But I want to take advantage of static type-checking. I'm getting red squiggly lines in VScode and warnings from Google-Closure-Compiler. I'm not sure if this is an issue with my ES6 code or with my type annotations.
My trivial example ES6 classes:
// #ts-check
"use strict";
export class db_row {
/**
* #param {number} id
*/
constructor(id) {
/** #type {number} */
this.id = id;
}
clone() {
return new db_row(this.id);
}
}
export class Channel_row extends db_row {
/**
* Constructor
* #param {*=} init
* #param {string=} name
* #param {string=} value
*/
constructor(init, name, value = '') {
let id = -1;
if (typeof init == 'object') {
id = init.id;
name = init.name;
value = init.value;
} else if (typeof init == 'number') {
id = init;
}
super(id);
this.name = name;
this.value = value;
}
clone() {
return new Channel_row(this.id, this.name, this.value);
}
}
export class db_table {
/**
* Constructor
* #param {Array<db_row>} table
*/
constructor(table) {
/**#type {Array<db_row>} */
this.table = table;
}
/**
*/
get_table_copy() { return this.table.map(item => item.clone()) }
/**
* #param {?number=} id
*/
get_row_by_id(id) {
const row = this.table.filter(item => item.id === id)[0];
if (row) return row.clone();
return null;
}
}
export class Channel_table extends db_table {
constructor() {
/**#type {Array<Channel_row>} */
let table = [];
super(table);
}
}
// Test code below:
/**
*
* #param {Channel_row} chan_row
*/
function print_chan_row(chan_row) {
console.log(chan_row.name);
}
let channel_table = new Channel_table();
let channel_row = channel_table.get_row_by_id(0); // hover reports that the type of channel_row is db_row, when it should be type Channel_row
print_chan_row(channel_row); // Red squiggly line error: Argument of type 'db_row' is not assignable to parameter of type 'Channel_row'. Type 'db_row' is missing the following properties from type 'Channel_row': name, valuets(2345)
console.log(channel_row.name); // Red squiggly line error: Property 'name' does not exist on type 'db_row'.ts(2339)
let channel_table_2 = channel_table.get_table_copy(); // hover reports that the type of channel_row is db_row[], when it should be type Channel_row[]
print_chan_row(channel_table_2[0]); // Red squiggly line error: Argument of type 'db_row' is not assignable to parameter of type 'Channel_row'.ts(2345)
Now, if I move or copy the get_row_by_id() and get_table_copy() functions into the subclass, the type errors go away. But I don't want to duplicate code unnecessarily.
How can I declare the functions in the parent class so it can be reused in child classes, but maintain the static type checking?
As a bonus, can I also generalize the clone() function so it doesn't need to be over-ridden in subclasses of db_row?

How to get random words of a give length (L) from a dictionary which has been implemented using a trie?

How to retrieve a random word of a given length from a Trie
The answer above explains how to select the first character but I am confused how we will proceed after that. I want words of Length L but when I start traversing the tree, I wouldn't know if the branch that is being traversed has depth L.
Dictionary
package com.FastDictionary;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import sun.rmi.runtime.Log;
/**
* Dictionary implementation.
* Uses Trie Data Structure
* Creates a singleton object
*/
public class FastDictionary {
private int nineWordCount;
private int totalWordCount;
// Root Node
private DictionaryNode root;
// Singleton object
private static FastDictionary fastDictionary;
// Flag; True if words.txt has been processed once
private boolean isProcessed;
private FastDictionary() {
this.root = new DictionaryNode();
isProcessed = false;
this.nineWordCount = 0;
this.totalWordCount = 0;
}
private boolean sanitiseSearch(String text) {
if (text == null) {
return false;
}
else {
return text.matches("[a-zA-Z]");
}
}
/**
* Add a word to Dictionary
* #param word word to be added
*/
public void addWord(String word) {
if (word == null) {
throw new IllegalArgumentException("Word to be added to Dictionary can't be null");
}
// Sanitise input
if (word.contains(" ")) {
throw new IllegalArgumentException(
"Word to be added to Dictionary can't contain white spaces");
}
DictionaryNode currentNode = this.root;
for (char c: word.toCharArray()) {
DictionaryNode child = currentNode.getChild(c);
if (child == null) {
currentNode = currentNode.addChild(c);
}
else {
currentNode = child;
}
}
// Last node contains last character of valid word
// Set that node as Leaf Node for valid word
currentNode.setLeaf();
}
/**
*
* #param word String to be checked if it is a valid word
* #return True if valid word
*/
public boolean isWord(String word) {
if (word == null) {
throw new IllegalArgumentException("Word to be added to Dictionary can't be null");
}
// Sanitise input
if (word.contains(" ")) {
throw new IllegalArgumentException(
"Word to be added to Dictionary can't contain white spaces");
}
DictionaryNode currentNode = this.root;
for (char c: word.toCharArray()) {
DictionaryNode child = currentNode.getChild(c);
if (child == null) {
return false;
}
currentNode = child;
}
// Returns true if Last Character was leaf
return currentNode.isLeaf();
}
/**
*
* #param text String that needs to be searched
* #return List of Strings which are valid words searched using 'text'
*
*/
public ArrayList<String> getWords(String text) {
ArrayList<String> words = new ArrayList<String>();
DictionaryNode currentNode = this.root;
for (int i = 0; i < text.length() ; i++) {
DictionaryNode child = currentNode.getChild(text.charAt(i));
if (child == null) {
return words;
}
if (child.isLeaf()) {
words.add(text.substring(0,i+1));
}
currentNode = child;
}
return words;
}
/**
*
* #param inputFileStream Text file containing list of valid words
* Switches Flag isProcessed to True
*/
public void processFile(InputStream inputFileStream) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(inputFileStream));
String line;
while((line = br.readLine()) != null) {
line = line.trim();
this.addWord(line);
// Nine Word test
if (line.length() == 9) {
this.nineWordCount++;
}
this.totalWordCount++;
}
}
catch(Exception e){
System.out.print(e);
}
this.isProcessed = true;
}
/**
*
* #return True if valid words text file has been processed
* Word file needs to be processed just once
*/
public boolean isProcessed() {
return this.isProcessed;
}
/**
* Factory method to create Singleton Object
* #return Singleton object
*/
public static FastDictionary getInstance() {
if (fastDictionary == null) {
fastDictionary = new FastDictionary();
}
return fastDictionary;
}
public int getNineWordCount() {
return this.nineWordCount;
}
}
**Node**
package com.FastDictionary;
import java.util.HashMap;
/**
* Node of the Trie Data Structure used for FastDictionary
*/
public class DictionaryNode {
// Character which the Node represents
private char nodeChar;
// Points to children
private HashMap<Character, DictionaryNode> children = new HashMap<Character,DictionaryNode>();
// Is Node the last character for a valid word
private boolean isLeaf;
/**
* To create Root Node
*/
DictionaryNode() {
this.nodeChar = '.';
this.isLeaf = false;
}
/**
* To create Child Node
* #param c Character that Node represents
*/
DictionaryNode(char c) {
this.nodeChar = c;
isLeaf = false;
}
/**
*
* #param c Character that Node represents
* #return Child Node which was created
*/
public DictionaryNode addChild(char c) {
DictionaryNode child = new DictionaryNode(c);
this.children.put(c, child);
return child;
}
/**
*
* #return true if Node is the last character for a valid word; default is false
*/
public boolean isLeaf() {
return this.isLeaf;
}
/**
* Set Node as Leaf Node for a valid word
*/
public void setLeaf() {
this.isLeaf = true;
}
/**
*
* #param c the character which the Child Node represnts
* #return Child Node representing character c; null if no such Child exists
*/
public DictionaryNode getChild(char c) {
DictionaryNode child = this.children.get(c);
return child;
}
}
Yes, he only shows how to choose first character from root node. However, after you update your currentNode following that character, you can apply exact same principal to find next character from the new node. Another way of viewing what his algorithm did is, given a node, an integer L(5 in his example), finds i'th (1234 in his example) word which is in the subtree of that node and is exactly L depth away from it.
So after you have made your first move, you can recursively call that algorithm from new node, with L-1 as depth. This is basic idea. Of course,some details need to be filled.
Firstly, updating i before next recursive call. Say algorithm chose first character to be d. And first 3 letters i.e a b c combinedly had 1000 5-letter words. So now, you need to find (1234-1000)=234th word from this new node.
Secondly, instead of having lengthFrequencyByLetter and totalLengthFrequency for entire tree,now you need to have them for every single node, which will require lots of ram. (you can optimize that by using HashMap though.)
A very high level implementation could be:
String randomWord(Node currentNode,int L,int index){
if(L==0) return node.wordContainedWithin();
char ch = find_next_character(node,L,index); //'d' in our example
newNode = currentNode.getChild(ch); //node following d
//following example, words_before = 1000
int words_before = sum(lengthFrequencyByLetter[x][L] of all x before ch)
int new_index = index - words_before;
return randomWord(newNode,L-1,new_index);
}
Now to get a random L-letter word, look up root's totalLengthFrequency[L], generate a number i (1234 here) between 0 to that value, and call randomWord as:
randomWord(tree.root,L,i)

Fatal error: Call to a member function setFinalPrice() on a non-object in /app/code/core/Mage/Sales/Model/Quote/Item/Abstract.php on line 89

I had installed an custom extension. Its running successfully and had all files at its place. But I am getting this error on my listing page
Fatal error: Call to a member function setFinalPrice() on a non-object in /var/zpanel/hostdata/zadmin/public_html/unisport_com/app/code/core/Mage/Sales/Model/Quote/Item/Abstract.php on line 89.
I google this error but did'nt found any proper solution. One solution is to copy the original Abstract.php file may be because extension had overwrite this file. But I checked the code from the backup its the same and also copied original file but nothing worked for me.
What is wrong with this file? Can anybody help?
below is the code of Abstract.php file:
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license#magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* #category Mage
* #package Mage_Sales
* #copyright Copyright (c) 2013 Magento Inc. (http://www.magentocommerce.com)
* #license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Quote item abstract model
*
* Price attributes:
* - price - initial item price, declared during product association
* - original_price - product price before any calculations
* - calculation_price - prices for item totals calculation
* - custom_price - new price that can be declared by user and recalculated during calculation process
* - original_custom_price - original defined value of custom price without any convertion
*
* #category Mage
* #package Mage_Sales
* #author Magento Core Team <core#magentocommerce.com>
*/
abstract class Mage_Sales_Model_Quote_Item_Abstract extends Mage_Core_Model_Abstract
implements Mage_Catalog_Model_Product_Configuration_Item_Interface
{
/**
* Parent item for sub items for bundle product, configurable product, etc.
*
* #var Mage_Sales_Model_Quote_Item_Abstract
*/
protected $_parentItem = null;
/**
* Children items in bundle product, configurable product, etc.
*
* #var array
*/
protected $_children = array();
/**
*
* #var array
*/
protected $_messages = array();
/**
* Retrieve Quote instance
*
* #return Mage_Sales_Model_Quote
*/
abstract function getQuote();
/**
* Retrieve product model object associated with item
*
* #return Mage_Catalog_Model_Product
*/
public function getProduct()
{
$product = $this->_getData('product');
if ($product === null && $this->getProductId()) {
$product = Mage::getModel('catalog/product')
->setStoreId($this->getQuote()->getStoreId())
->load($this->getProductId());
$this->setProduct($product);
}
/**
* Reset product final price because it related to custom options
*/
$product->setFinalPrice(null);
if (is_array($this->_optionsByCode)) {
$product->setCustomOptions($this->_optionsByCode);
}
return $product;
}
/**
* Returns special download params (if needed) for custom option with type = 'file'
* Needed to implement Mage_Catalog_Model_Product_Configuration_Item_Interface.
* Return null, as quote item needs no additional configuration.
*
* #return null|Varien_Object
*/
public function getFileDownloadParams()
{
return null;
}
/**
* Specify parent item id before saving data
*
* #return Mage_Sales_Model_Quote_Item_Abstract
*/
protected function _beforeSave()
{
parent::_beforeSave();
if ($this->getParentItem()) {
$this->setParentItemId($this->getParentItem()->getId());
}
return $this;
}
/**
* Set parent item
*
* #param Mage_Sales_Model_Quote_Item $parentItem
* #return Mage_Sales_Model_Quote_Item
*/
public function setParentItem($parentItem)
{
if ($parentItem) {
$this->_parentItem = $parentItem;
$parentItem->addChild($this);
}
return $this;
}
/**
* Get parent item
*
* #return Mage_Sales_Model_Quote_Item
*/
public function getParentItem()
{
return $this->_parentItem;
}
/**
* Get chil items
*
* #return array
*/
public function getChildren()
{
return $this->_children;
}
/**
* Add child item
*
* #param Mage_Sales_Model_Quote_Item_Abstract $child
* #return Mage_Sales_Model_Quote_Item_Abstract
*/
public function addChild($child)
{
$this->setHasChildren(true);
$this->_children[] = $child;
return $this;
}
/**
* Adds message(s) for quote item. Duplicated messages are not added.
*
* #param mixed $messages
* #return Mage_Sales_Model_Quote_Item_Abstract
*/
public function setMessage($messages)
{
$messagesExists = $this->getMessage(false);
if (!is_array($messages)) {
$messages = array($messages);
}
foreach ($messages as $message) {
if (!in_array($message, $messagesExists)) {
$this->addMessage($message);
}
}
return $this;
}
/**
* Add message of quote item to array of messages
*
* #param string $message
* #return Mage_Sales_Model_Quote_Item_Abstract
*/
public function addMessage($message)
{
$this->_messages[] = $message;
return $this;
}
/**
* Get messages array of quote item
*
* #param bool $string flag for converting messages to string
* #return array|string
*/
public function getMessage($string = true)
{
if ($string) {
return join("\n", $this->_messages);
}
return $this->_messages;
}
/**
* Removes message by text
*
* #param string $text
* #return Mage_Sales_Model_Quote_Item_Abstract
*/
public function removeMessageByText($text)
{
foreach ($this->_messages as $key => $message) {
if ($message == $text) {
unset($this->_messages[$key]);
}
}
return $this;
}
/**
* Clears all messages
*
* #return Mage_Sales_Model_Quote_Item_Abstract
*/
public function clearMessage()
{
$this->unsMessage(); // For older compatibility, when we kept message inside data array
$this->_messages = array();
return $this;
}
/**
* Retrieve store model object
*
* #return Mage_Core_Model_Store
*/
public function getStore()
{
return $this->getQuote()->getStore();
}
/**
* Checking item data
*
* #return Mage_Sales_Model_Quote_Item_Abstract
*/
public function checkData()
{
$this->setHasError(false);
$this->clearMessage();
$qty = $this->_getData('qty');
try {
$this->setQty($qty);
} catch (Mage_Core_Exception $e) {
$this->setHasError(true);
$this->setMessage($e->getMessage());
} catch (Exception $e) {
$this->setHasError(true);
$this->setMessage(Mage::helper('sales')->__('Item qty declaration error.'));
}
try {
$this->getProduct()->getTypeInstance(true)->checkProductBuyState($this->getProduct());
} catch (Mage_Core_Exception $e) {
$this->setHasError(true)
->setMessage($e->getMessage());
$this->getQuote()->setHasError(true)
->addMessage(Mage::helper('sales')->__('Some of the products below do not have all the required options.'));
} catch (Exception $e) {
$this->setHasError(true)
->setMessage(Mage::helper('sales')->__('Item options declaration error.'));
$this->getQuote()->setHasError(true)
->addMessage(Mage::helper('sales')->__('Items options declaration error.'));
}
if ($this->getProduct()->getHasError()) {
$this->setHasError(true)
->setMessage(Mage::helper('sales')->__('Some of the selected options are not currently available.'));
$this->getQuote()->setHasError(true)
->addMessage($this->getProduct()->getMessage(), 'options');
}
if ($this->getHasConfigurationUnavailableError()) {
$this->setHasError(true)
->setMessage(Mage::helper('sales')->__('Selected option(s) or their combination is not currently available.'));
$this->getQuote()->setHasError(true)
->addMessage(Mage::helper('sales')->__('Some item options or their combination are not currently available.'), 'unavailable-configuration');
$this->unsHasConfigurationUnavailableError();
}
return $this;
}
/**
* Get original (not related with parent item) item quantity
*
* #return int|float
*/
public function getQty()
{
return $this->_getData('qty');
}
/**
* Get total item quantity (include parent item relation)
*
* #return int|float
*/
public function getTotalQty()
{
if ($this->getParentItem()) {
return $this->getQty()*$this->getParentItem()->getQty();
}
return $this->getQty();
}
/**
* Calculate item row total price
*
* #return Mage_Sales_Model_Quote_Item
*/
public function calcRowTotal()
{
$qty = $this->getTotalQty();
// Round unit price before multiplying to prevent losing 1 cent on subtotal
$total = $this->getStore()->roundPrice($this->getCalculationPriceOriginal()) * $qty;
$baseTotal = $this->getStore()->roundPrice($this->getBaseCalculationPriceOriginal()) * $qty;
$this->setRowTotal($this->getStore()->roundPrice($total));
$this->setBaseRowTotal($this->getStore()->roundPrice($baseTotal));
return $this;
}
/**
* Get item price used for quote calculation process.
* This method get custom price (if it is defined) or original product final price
*
* #return float
*/
public function getCalculationPrice()
{
$price = $this->_getData('calculation_price');
if (is_null($price)) {
if ($this->hasCustomPrice()) {
$price = $this->getCustomPrice();
} else {
$price = $this->getConvertedPrice();
}
$this->setData('calculation_price', $price);
}
return $price;
}
/**
* Get item price used for quote calculation process.
* This method get original custom price applied before tax calculation
*
* #return float
*/
public function getCalculationPriceOriginal()
{
$price = $this->_getData('calculation_price');
if (is_null($price)) {
if ($this->hasOriginalCustomPrice()) {
$price = $this->getOriginalCustomPrice();
} else {
$price = $this->getConvertedPrice();
}
$this->setData('calculation_price', $price);
}
return $price;
}
/**
* Get calculation price used for quote calculation in base currency.
*
* #return float
*/
public function getBaseCalculationPrice()
{
if (!$this->hasBaseCalculationPrice()) {
if ($this->hasCustomPrice()) {
$price = (float) $this->getCustomPrice();
if ($price) {
$rate = $this->getStore()->convertPrice($price) / $price;
$price = $price / $rate;
}
} else {
$price = $this->getPrice();
}
$this->setBaseCalculationPrice($price);
}
return $this->_getData('base_calculation_price');
}
/**
* Get original calculation price used for quote calculation in base currency.
*
* #return float
*/
public function getBaseCalculationPriceOriginal()
{
if (!$this->hasBaseCalculationPrice()) {
if ($this->hasOriginalCustomPrice()) {
$price = (float) $this->getOriginalCustomPrice();
if ($price) {
$rate = $this->getStore()->convertPrice($price) / $price;
$price = $price / $rate;
}
} else {
$price = $this->getPrice();
}
$this->setBaseCalculationPrice($price);
}
return $this->_getData('base_calculation_price');
}
/**
* Get whether the item is nominal
* TODO: fix for multishipping checkout
*
* #return bool
*/
public function isNominal()
{
if (!$this->hasData('is_nominal')) {
$this->setData('is_nominal', $this->getProduct() ? '1' == $this->getProduct()->getIsRecurring() : false);
}
return $this->_getData('is_nominal');
}
/**
* Data getter for 'is_nominal'
* Used for converting item to order item
*
* #return int
*/
public function getIsNominal()
{
return (int)$this->isNominal();
}
/**
* Get original price (retrieved from product) for item.
* Original price value is in quote selected currency
*
* #return float
*/
public function getOriginalPrice()
{
$price = $this->_getData('original_price');
if (is_null($price)) {
$price = $this->getStore()->convertPrice($this->getBaseOriginalPrice());
$this->setData('original_price', $price);
}
return $price;
}
/**
* Set original price to item (calculation price will be refreshed too)
*
* #param float $price
* #return Mage_Sales_Model_Quote_Item_Abstract
*/
public function setOriginalPrice($price)
{
return $this->setData('original_price', $price);
}
/**
* Get Original item price (got from product) in base website currency
*
* #return float
*/
public function getBaseOriginalPrice()
{
return $this->_getData('base_original_price');
}
/**
* Specify custom item price (used in case whe we have apply not product price to item)
*
* #param float $value
* #return Mage_Sales_Model_Quote_Item_Abstract
*/
public function setCustomPrice($value)
{
$this->setCalculationPrice($value);
$this->setBaseCalculationPrice(null);
return $this->setData('custom_price', $value);
}
/**
* Get item price. Item price currency is website base currency.
*
* #return decimal
*/
public function getPrice()
{
return $this->_getData('price');
}
/**
* Specify item price (base calculation price and converted price will be refreshed too)
*
* #param float $value
* #return Mage_Sales_Model_Quote_Item_Abstract
*/
public function setPrice($value)
{
$this->setBaseCalculationPrice(null);
$this->setConvertedPrice(null);
return $this->setData('price', $value);
}
/**
* Get item price converted to quote currency
* #return float
*/
public function getConvertedPrice()
{
$price = $this->_getData('converted_price');
if (is_null($price)) {
$price = $this->getStore()->convertPrice($this->getPrice());
$this->setData('converted_price', $price);
}
return $price;
}
/**
* Set new value for converted price
* #param float $value
* #return Mage_Sales_Model_Quote_Item_Abstract
*/
public function setConvertedPrice($value)
{
$this->setCalculationPrice(null);
$this->setData('converted_price', $value);
return $this;
}
/**
* Clone quote item
*
* #return Mage_Sales_Model_Quote_Item
*/
public function __clone()
{
$this->setId(null);
$this->_parentItem = null;
$this->_children = array();
$this->_messages = array();
return $this;
}
/**
* Checking if there children calculated or parent item
* when we have parent quote item and its children
*
* #return bool
*/
public function isChildrenCalculated()
{
if ($this->getParentItem()) {
$calculate = $this->getParentItem()->getProduct()->getPriceType();
} else {
$calculate = $this->getProduct()->getPriceType();
}
if ((null !== $calculate) && (int)$calculate === Mage_Catalog_Model_Product_Type_Abstract::CALCULATE_CHILD) {
return true;
}
return false;
}
/**
* Checking can we ship product separatelly (each child separately)
* or each parent product item can be shipped only like one item
*
* #return bool
*/
public function isShipSeparately()
{
if ($this->getParentItem()) {
$shipmentType = $this->getParentItem()->getProduct()->getShipmentType();
} else {
$shipmentType = $this->getProduct()->getShipmentType();
}
if ((null !== $shipmentType) &&
(int)$shipmentType === Mage_Catalog_Model_Product_Type_Abstract::SHIPMENT_SEPARATELY) {
return true;
}
return false;
}
/**
* Calculate item tax amount
*
* #deprecated logic moved to tax totals calculation model
* #return Mage_Sales_Model_Quote_Item
*/
public function calcTaxAmount()
{
$store = $this->getStore();
if (!Mage::helper('tax')->priceIncludesTax($store)) {
if (Mage::helper('tax')->applyTaxAfterDiscount($store)) {
$rowTotal = $this->getRowTotalWithDiscount();
$rowBaseTotal = $this->getBaseRowTotalWithDiscount();
} else {
$rowTotal = $this->getRowTotal();
$rowBaseTotal = $this->getBaseRowTotal();
}
$taxPercent = $this->getTaxPercent()/100;
$this->setTaxAmount($store->roundPrice($rowTotal * $taxPercent));
$this->setBaseTaxAmount($store->roundPrice($rowBaseTotal * $taxPercent));
$rowTotal = $this->getRowTotal();
$rowBaseTotal = $this->getBaseRowTotal();
$this->setTaxBeforeDiscount($store->roundPrice($rowTotal * $taxPercent));
$this->setBaseTaxBeforeDiscount($store->roundPrice($rowBaseTotal * $taxPercent));
} else {
if (Mage::helper('tax')->applyTaxAfterDiscount($store)) {
$totalBaseTax = $this->getBaseTaxAmount();
$totalTax = $this->getTaxAmount();
if ($totalTax && $totalBaseTax) {
$totalTax -= $this->getDiscountAmount() * ($this->getTaxPercent() / 100);
$totalBaseTax -= $this->getBaseDiscountAmount() * ($this->getTaxPercent() / 100);
$this->setBaseTaxAmount($store->roundPrice($totalBaseTax));
$this->setTaxAmount($store->roundPrice($totalTax));
}
}
}
if (Mage::helper('tax')->discountTax($store) && !Mage::helper('tax')->applyTaxAfterDiscount($store)) {
if ($this->getDiscountPercent()) {
$baseTaxAmount = $this->getBaseTaxBeforeDiscount();
$taxAmount = $this->getTaxBeforeDiscount();
$baseDiscountDisposition = $baseTaxAmount/100*$this->getDiscountPercent();
$discountDisposition = $taxAmount/100*$this->getDiscountPercent();
$this->setDiscountAmount($this->getDiscountAmount()+$discountDisposition);
$this->setBaseDiscountAmount($this->getBaseDiscountAmount()+$baseDiscountDisposition);
}
}
return $this;
}
/**
* Get item tax amount
*
* #deprecated
* #return decimal
*/
public function getTaxAmount()
{
return $this->_getData('tax_amount');
}
/**
* Get item base tax amount
*
* #deprecated
* #return decimal
*/
public function getBaseTaxAmount()
{
return $this->_getData('base_tax_amount');
}
/**
* Get item price (item price always exclude price)
*
* #deprecated
* #return decimal
*/
protected function _calculatePrice($value, $saveTaxes = true)
{
$store = $this->getQuote()->getStore();
if (Mage::helper('tax')->priceIncludesTax($store)) {
$bAddress = $this->getQuote()->getBillingAddress();
$sAddress = $this->getQuote()->getShippingAddress();
$address = $this->getAddress();
if ($address) {
switch ($address->getAddressType()) {
case Mage_Sales_Model_Quote_Address::TYPE_BILLING:
$bAddress = $address;
break;
case Mage_Sales_Model_Quote_Address::TYPE_SHIPPING:
$sAddress = $address;
break;
}
}
if ($this->getProduct()->getIsVirtual()) {
$sAddress = $bAddress;
}
$priceExcludingTax = Mage::helper('tax')->getPrice(
$this->getProduct()->setTaxPercent(null),
$value,
false,
$sAddress,
$bAddress,
$this->getQuote()->getCustomerTaxClassId(),
$store
);
$priceIncludingTax = Mage::helper('tax')->getPrice(
$this->getProduct()->setTaxPercent(null),
$value,
true,
$sAddress,
$bAddress,
$this->getQuote()->getCustomerTaxClassId(),
$store
);
if ($saveTaxes) {
$qty = $this->getQty();
if ($this->getParentItem()) {
$qty = $qty*$this->getParentItem()->getQty();
}
if (Mage::helper('tax')->displayCartPriceInclTax($store)) {
$rowTotal = $value*$qty;
$rowTotalExcTax = Mage::helper('tax')->getPrice(
$this->getProduct()->setTaxPercent(null),
$rowTotal,
false,
$sAddress,
$bAddress,
$this->getQuote()->getCustomerTaxClassId(),
$store
);
$rowTotalIncTax = Mage::helper('tax')->getPrice(
$this->getProduct()->setTaxPercent(null),
$rowTotal,
true,
$sAddress,
$bAddress,
$this->getQuote()->getCustomerTaxClassId(),
$store
);
$totalBaseTax = $rowTotalIncTax-$rowTotalExcTax;
$this->setRowTotalExcTax($rowTotalExcTax);
}
else {
$taxAmount = $priceIncludingTax - $priceExcludingTax;
$this->setTaxPercent($this->getProduct()->getTaxPercent());
$totalBaseTax = $taxAmount*$qty;
}
$totalTax = $this->getStore()->convertPrice($totalBaseTax);
$this->setTaxBeforeDiscount($totalTax);
$this->setBaseTaxBeforeDiscount($totalBaseTax);
$this->setTaxAmount($totalTax);
$this->setBaseTaxAmount($totalBaseTax);
}
$value = $priceExcludingTax;
}
return $value;
}
}

ITextSharp - get image at a particular location

What I need to do is extract a 2D DataMatrix (bitmap) bar code and read it. I can make this work however, I have to loop through all the images on every page. This is taking a long time when I have 1000’s of pages, so I was wondering if it was possible to define a location(rectangle)of where the image(barcode) was and just extract that image?
The bar code is always i the same location.
note: I'm using Spire.Barcode from e-IceBlue
Thank you for any help.
CODE RenderFilter snippet:
public class MyRegionTextRenderFilter : RenderFilter {
/** the region to allow text from */
private RectangleJ filterRect;
public PdfImageObject image;
/**
* Constructs a filter
* #param filterRect the rectangle to filter text against. Note that this is a java.awt.Rectangle !
*/
public MyRegionTextRenderFilter(RectangleJ filterRect) {
this.filterRect = filterRect;
}
/**
* Constructs a filter
* #param filterRect the rectangle to filter text against.
*/
public MyRegionTextRenderFilter(iTextSharp.text.Rectangle filterRect)
{
this.filterRect = new RectangleJ(filterRect);
}
/**
* #see com.itextpdf.text.pdf.parser.RenderFilter#allowText(com.itextpdf.text.pdf.parser.TextRenderInfo)
*/
public override bool AllowImage(ImageRenderInfo renderInfo)
{
var matrix = renderInfo.GetImageCTM();
float left = matrix[6];
float top = matrix[7];
float width = matrix[0];
float height = matrix[4];
return filterRect.IntersectsLine(left, top, width, height);
}
}
Code calling :
RectangleJ rect = new RectangleJ(518.0f, 18.0f, 23.0f, 23.0f);
PdfReaderContentParser parser2 = new PdfReaderContentParser(pdfReader);
RenderFilter[] renderFilter = new RenderFilter[1];
renderFilter[0] = new MyRegionTextRenderFilter(rect);
FilteredTextRenderListener listener2 = new FilteredTextRenderListener(new LocationTextExtractionStrategy(), renderFilter);
parser2.ProcessContent(3, listener2);
The parser namespace of iText(Sharp) allows filtering of information digested by an IRenderListener implementation by using a RenderFilter:
public abstract class RenderFilter {
/**
* #param renderInfo
* #return true if the text render operation should be performed
*/
public virtual bool AllowText(TextRenderInfo renderInfo){
return true;
}
/**
*
* #param renderInfo
* #return true is the image render operation should be performed
*/
public virtual bool AllowImage(ImageRenderInfo renderInfo){
return true;
}
}
For filtering by area there already is a textual render filter, the RegionTextRenderFilter.
For your task simply copy it and add an AllowImage(ImageRenderInfo renderInfo) implementation similar to the existing AllowText(TextRenderInfo renderInfo) method.

Why isn't my RCP application splash showing in Windows?

I've created an RCP application with an interactive splash for logging onto my system. I built it on a Mac, and the application works perfectly, but when I created a new product configuration for Windows and run the application, it launches without the splash and there are no errors appearing in the console.
The splash handler code is as follows
/**
* The splash screen controller for the RCP application. This has been modified to also act as a login screen for the
* application. Failure to correctly authenticate results in the application termination.
*/
package com.myproject.plugins.core.splashHandlers;
import java.net.MalformedURLException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.splash.AbstractSplashHandler;
/**
* The splash handler overrides the default RCP splash handler.
* #since 3.3
*/
public class InteractiveSplashHandler extends AbstractSplashHandler {
/**
* Composite container for login form.
*/
private Composite loginComposite;
/**
* Text box input for login username.
*/
private Text usernameTextBox;
/**
* Text box input for login password.
*/
private Text passwordTextBox;
/**
* OK button for submission of the login form.
*/
private Button okButton;
/**
* Cancel button for cancelling the login attempt and exiting the application.
*/
private Button cancelButton;
/**
* Simple boolean flag to store login success/status.
*/
private boolean isAuthenticated;
/**
* SWT form label for username.
*/
private Label usernameLabel;
/**
* SWT form label for password.
*/
private Label passwordLabel;
/**
* Form/layout data for username label.
*/
private FormData usernameLabelFormData;
/**
* Form/layout data for password label.
*/
private FormData passwordLabelFormData;
/**
* Form/layout data for username text box.
*/
private FormData usernameTextBoxFormData;
/**
* Form/layout data for password text box.
*/
private FormData passwordTextBoxFormData;
/**
* Form/layout data for OK button.
*/
private FormData okButtonFormData;
/**
* Constructor for the splash handler.
*/
public InteractiveSplashHandler() {
passwordTextBox = null;
cancelButton = null;
isAuthenticated = false;
}
/**
* Initialiser for the splash screen.
* #see org.eclipse.ui.splash.AbstractSplashHandler#init(org.eclipse.swt.widgets.Shell)
*/
public void init(final Shell splash) {
/**
* Initialising the parent SplashHandler with the splash shell.
*/
super.init(splash);
/**
* Configure the shell UI layout.
*/
configureUISplash();
/**
* Create UI components.
*/
createUI();
/**
* Create UI listeners.
*/
createUIListeners();
/**
* Force the splash screen to layout.
*/
splash.layout(true);
/**
* Keep the splash screen visible and prevent the RCP application from loading until the close button is
* clicked.
*/
doEventLoop();
}
/**
* Create the event loop for the splash to prevent the application load from completion, and hold it at the splash
* until the login event is successful.
*/
private void doEventLoop() {
Shell splash = getSplash();
while (isAuthenticated == false) {
if (splash.getDisplay().readAndDispatch() == false) {
splash.getDisplay().sleep();
}
}
}
/**
* Create the UI listeners for all the form components.
*/
private void createUIListeners() {
/**
* Create the OK button listeners.
*/
createUIListenersButtonOK();
/**
* Create the cancel button listeners.
*/
createUIListenersButtonCancel();
}
/**
* Listeners setup for the cancel button.
*/
private void createUIListenersButtonCancel() {
cancelButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleButtonCancelWidgetSelected();
}
});
}
/**
* Handles the cancel action by shutting down the RCP application.
*/
private void handleButtonCancelWidgetSelected() {
/**
* Abort the loading of the RCP application.
*/
getSplash().getDisplay().close();
System.exit(0);
}
/**
* Listeners setup for the OK button.
*/
private void createUIListenersButtonOK() {
okButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleButtonOKWidgetSelected();
}
});
}
/**
* Handles the OK button being pressed and the login attempted.
*/
private void handleButtonOKWidgetSelected() {
String username = usernameTextBox.getText();
String password = passwordTextBox.getText();
AuthenticationClient client = new AuthenticationClient();
if (username.equals("") || password.equals("")) {
MessageDialog.openError(getSplash(),
"Authentication Failed", //$NON-NLS-1$
"A username and password must be specified to login."); //$NON-NLS-1$
} else {
try {
if (client.authenticate(username, password)) {
isAuthenticated = true;
} else {
MessageDialog.openError(getSplash(),
"Authentication Failed", //$NON-NLS-1$
"The details you entered could not be verified."); //$NON-NLS-1$
}
} catch (MalformedURLException e) {
MessageDialog.openError(getSplash(),
"Authentication Failed", //$NON-NLS-1$
"Service responded with an error."); //$NON-NLS-1$
}
}
}
/**
* Calls the individual UI component creation functions.
*/
private void createUI() {
/**
* Create the login panel.
*/
createUICompositeLogin();
/**
* Create the user name label.
*/
createUILabelUserName();
/**
* Create the user name text widget.
*/
createUITextUserName();
/**
* Create the password label.
*/
createUILabelPassword();
/**
* Create the password text widget.
*/
createUITextPassword();
/**
* Create the OK button.
*/
createUIButtonOK();
/**
* Create the cancel button.
*/
createUIButtonCancel();
}
/**
* Creates the SWT component for the cancel button.
*/
private void createUIButtonCancel() {
/**
* Create the button.
*/
cancelButton = new Button(loginComposite, SWT.PUSH);
okButtonFormData.right = new FormAttachment(cancelButton, -6);
FormData cancelButtonFormData = new FormData();
cancelButtonFormData.left = new FormAttachment(0, 392);
cancelButtonFormData.right = new FormAttachment(100, -10);
cancelButtonFormData.bottom = new FormAttachment(100, -10);
cancelButton.setLayoutData(cancelButtonFormData);
cancelButton.setText("Cancel");
}
/**
* Creates the SWT component for the OK button.
*/
private void createUIButtonOK() {
/**
* Create the button.
*/
okButton = new Button(loginComposite, SWT.PUSH);
passwordTextBoxFormData.bottom = new FormAttachment(okButton, -6);
okButtonFormData = new FormData();
okButtonFormData.left = new FormAttachment(0, 279);
okButtonFormData.bottom = new FormAttachment(100, -10);
okButton.setLayoutData(okButtonFormData);
okButton.setText("OK");
}
/**
* Creates the SWT component for the password text box.
*/
private void createUITextPassword() {
/**
* Create the text widget.
*/
int style = SWT.PASSWORD | SWT.BORDER;
passwordTextBox = new Text(loginComposite, style);
passwordLabelFormData.right = new FormAttachment(passwordTextBox, -6);
passwordTextBoxFormData = new FormData();
passwordTextBoxFormData.right = new FormAttachment(100, -10);
passwordTextBoxFormData.left = new FormAttachment(0, 279);
passwordTextBox.setLayoutData(passwordTextBoxFormData);
}
/**
* Creates the SWT component for the password label.
*/
private void createUILabelPassword() {
/**
* Create the label.
*/
passwordLabel = new Label(loginComposite, SWT.NONE);
passwordLabelFormData = new FormData();
passwordLabelFormData.top = new FormAttachment(usernameLabel, 11);
passwordLabel.setLayoutData(passwordLabelFormData);
passwordLabel.setText("&Password:");
}
/**
* Creates SWT component for the username text box.
*/
private void createUITextUserName() {
/**
* Create the text widget.
*/
usernameTextBox = new Text(loginComposite, SWT.BORDER);
usernameLabelFormData.top = new FormAttachment(usernameTextBox, 3, SWT.TOP);
usernameLabelFormData.right = new FormAttachment(usernameTextBox, -6);
usernameTextBoxFormData = new FormData();
usernameTextBoxFormData.top = new FormAttachment(0, 233);
usernameTextBoxFormData.right = new FormAttachment(100, -10);
usernameTextBoxFormData.left = new FormAttachment(0, 279);
usernameTextBox.setLayoutData(usernameTextBoxFormData);
}
/**
* Creates SWT component for the username label.
*/
private void createUILabelUserName() {
/**
* Create the label
*/
usernameLabel = new Label(loginComposite, SWT.NONE);
usernameLabelFormData = new FormData();
usernameLabel.setLayoutData(usernameLabelFormData);
usernameLabel.setText("&User Name:");
}
/**
* Creates SWT component for the login composite.
*/
private void createUICompositeLogin() {
/**
* Create the composite and set the layout.
*/
loginComposite = new Composite(getSplash(), SWT.BORDER);
loginComposite.setLayout(new FormLayout());
}
/**
* Configures the splash screen SWT/UI components.
*/
private void configureUISplash() {
/**
* Configure layout
*/
FillLayout layout = new FillLayout();
getSplash().setLayout(layout);
/**
* Force shell to inherit the splash background
*/
getSplash().setBackgroundMode(SWT.INHERIT_DEFAULT);
}
}
Oddly enough, the bitmap (created in Photoshop/Mac) image was seen as corrupt in Eclipse, but opened fine in all graphics applications (including Photoshop/Win). I opened the file in MS Paint and saved without changes. The splash started working fine.
Check your bitmap if you get this error!

Resources