diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/FE_SRC_COMMON/com/ForgeEssentials/util/TeleportCenter.java b/src/FE_SRC_COMMON/com/ForgeEssentials/util/TeleportCenter.java
index 95a307e69..21c3740c5 100644
--- a/src/FE_SRC_COMMON/com/ForgeEssentials/util/TeleportCenter.java
+++ b/src/FE_SRC_COMMON/com/ForgeEssentials/util/TeleportCenter.java
@@ -1,112 +1,112 @@
package com.ForgeEssentials.util;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import net.minecraft.entity.player.EntityPlayer;
import com.ForgeEssentials.core.PlayerInfo;
import com.ForgeEssentials.data.SaveableObject;
import com.ForgeEssentials.permission.PermissionsAPI;
import com.ForgeEssentials.permission.query.PermQueryPlayer;
import com.ForgeEssentials.util.AreaSelector.WarpPoint;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.IScheduledTickHandler;
import cpw.mods.fml.common.TickType;
/**
* Use this for all TPs. This system does it all for you: warmup, cooldown, bypass for both, going between dimensions.
*
* @author Dries007
*
*/
public class TeleportCenter implements IScheduledTickHandler
{
public static HashMap<String, Warp> warps = new HashMap<String, Warp>();
private static ArrayList<TPdata> que = new ArrayList();
private static ArrayList<TPdata> removeQue = new ArrayList();
public static int tpWarmup;
public static int tpCooldown;
public static final String BYPASS_WARMUP = "ForgeEssentials.TeleportCenter.BypassWarmup";
public static final String BYPASS_COOLDOWN = "ForgeEssentials.TeleportCenter.BypassCooldown";
public static void addToTpQue(WarpPoint point, EntityPlayer player)
{
- if(PlayerInfo.getPlayerInfo(player).TPcooldown != 0 || !PermissionsAPI.checkPermAllowed(new PermQueryPlayer(player, BYPASS_COOLDOWN)))
+ if(PlayerInfo.getPlayerInfo(player).TPcooldown == 0 || PermissionsAPI.checkPermAllowed(new PermQueryPlayer(player, BYPASS_COOLDOWN)))
{
player.sendChatToPlayer(Localization.get(Localization.TC_COOLDOWN).replaceAll("%c", ""+PlayerInfo.getPlayerInfo(player).TPcooldown));
}
else
{
PlayerInfo.getPlayerInfo(player).TPcooldown = tpCooldown;
TPdata data = new TPdata(point, player);
if(tpWarmup == 0 || PermissionsAPI.checkPermAllowed(new PermQueryPlayer(player, BYPASS_WARMUP)))
{
data.doTP();
}
else
{
player.sendChatToPlayer(Localization.get(Localization.TC_WARMUP).replaceAll("%w", ""+tpWarmup));
que.add(data);
}
}
}
public static void abort(TPdata tpData)
{
removeQue.add(tpData);
tpData.getPlayer().sendChatToPlayer(Localization.get(Localization.TC_ABORTED));
}
public static void TPdone(TPdata tpData)
{
removeQue.add(tpData);
tpData.getPlayer().sendChatToPlayer(Localization.get(Localization.TC_DONE));
}
@Override
public void tickStart(EnumSet<TickType> type, Object... tickData)
{
for(TPdata data : que)
{
data.count();
}
que.removeAll(removeQue);
removeQue.clear();
for(Object player : FMLCommonHandler.instance().getMinecraftServerInstance().getConfigurationManager().playerEntityList)
{
PlayerInfo.getPlayerInfo((EntityPlayer) player).TPcooldownTick();
}
}
@Override
public void tickEnd(EnumSet<TickType> type, Object... tickData)
{
//Not needed here
}
@Override
public EnumSet<TickType> ticks()
{
return EnumSet.of(TickType.SERVER);
}
@Override
public String getLabel()
{
return "TeleportCenter";
}
@Override
public int nextTickSpacing()
{
return 20;
}
}
| true | true | public static void addToTpQue(WarpPoint point, EntityPlayer player)
{
if(PlayerInfo.getPlayerInfo(player).TPcooldown != 0 || !PermissionsAPI.checkPermAllowed(new PermQueryPlayer(player, BYPASS_COOLDOWN)))
{
player.sendChatToPlayer(Localization.get(Localization.TC_COOLDOWN).replaceAll("%c", ""+PlayerInfo.getPlayerInfo(player).TPcooldown));
}
else
{
PlayerInfo.getPlayerInfo(player).TPcooldown = tpCooldown;
TPdata data = new TPdata(point, player);
if(tpWarmup == 0 || PermissionsAPI.checkPermAllowed(new PermQueryPlayer(player, BYPASS_WARMUP)))
{
data.doTP();
}
else
{
player.sendChatToPlayer(Localization.get(Localization.TC_WARMUP).replaceAll("%w", ""+tpWarmup));
que.add(data);
}
}
}
| public static void addToTpQue(WarpPoint point, EntityPlayer player)
{
if(PlayerInfo.getPlayerInfo(player).TPcooldown == 0 || PermissionsAPI.checkPermAllowed(new PermQueryPlayer(player, BYPASS_COOLDOWN)))
{
player.sendChatToPlayer(Localization.get(Localization.TC_COOLDOWN).replaceAll("%c", ""+PlayerInfo.getPlayerInfo(player).TPcooldown));
}
else
{
PlayerInfo.getPlayerInfo(player).TPcooldown = tpCooldown;
TPdata data = new TPdata(point, player);
if(tpWarmup == 0 || PermissionsAPI.checkPermAllowed(new PermQueryPlayer(player, BYPASS_WARMUP)))
{
data.doTP();
}
else
{
player.sendChatToPlayer(Localization.get(Localization.TC_WARMUP).replaceAll("%w", ""+tpWarmup));
que.add(data);
}
}
}
|
diff --git a/src/test/java/org/mule/module/magento/automation/testcases/CancelOrderTestCases.java b/src/test/java/org/mule/module/magento/automation/testcases/CancelOrderTestCases.java
index 95531cb8..4157979d 100644
--- a/src/test/java/org/mule/module/magento/automation/testcases/CancelOrderTestCases.java
+++ b/src/test/java/org/mule/module/magento/automation/testcases/CancelOrderTestCases.java
@@ -1,102 +1,102 @@
package org.mule.module.magento.automation.testcases;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.mule.api.MuleEvent;
import org.mule.api.processor.MessageProcessor;
import com.magento.api.CatalogProductCreateEntity;
import com.magento.api.ShoppingCartCustomerAddressEntity;
import com.magento.api.ShoppingCartCustomerEntity;
import com.magento.api.ShoppingCartPaymentMethodEntity;
import com.magento.api.ShoppingCartProductEntity;
public class CancelOrderTestCases extends MagentoTestParent {
@Before
public void setUp() {
try {
testObjects = (HashMap<String, Object>) context.getBean("cancelOrder");
ShoppingCartCustomerEntity customer = (ShoppingCartCustomerEntity) testObjects.get("customer");
List<ShoppingCartCustomerAddressEntity> addresses = (List<ShoppingCartCustomerAddressEntity>) testObjects.get("customerAddresses");
String shippingMethod = testObjects.get("shippingMethod").toString();
ShoppingCartPaymentMethodEntity paymentMethod = (ShoppingCartPaymentMethodEntity) testObjects.get("paymentMethod");
List<HashMap<String, Object>> products = (List<HashMap<String, Object>>) testObjects.get("products");
List<ShoppingCartProductEntity> shoppingCartProducts = new ArrayList<ShoppingCartProductEntity>();
List<Integer> productIds = new ArrayList<Integer>();
for (HashMap<String, Object> product : products) {
// Get the product data
String productType = (String) product.get("type");
int productSet = (Integer) product.get("set");
String productSKU = (String) product.get("sku");
CatalogProductCreateEntity attributes = (CatalogProductCreateEntity) product.get("attributesRef");
// Create the product and get the product ID
int productId = createProduct(productType, productSet, productSKU, attributes);
// Get the quantity to place in the shopping cart
double qtyToPurchase = (Double) product.get("qtyToPurchase");
// Create the shopping cart product entity
ShoppingCartProductEntity shoppingCartProduct = new ShoppingCartProductEntity();
shoppingCartProduct.setProduct_id(productId + "");
shoppingCartProduct.setQty(qtyToPurchase);
shoppingCartProducts.add(shoppingCartProduct);
productIds.add(productId);
}
+ testObjects.put("productIds", productIds);
String orderId = createShoppingCartOrder(customer, addresses, paymentMethod, shippingMethod, shoppingCartProducts);
- testObjects.put("productIds", productIds);
testObjects.put("orderId", orderId);
}
catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Category({SmokeTests.class, RegressionTests.class})
@Test
public void testCancelOrder() {
try {
MessageProcessor flow = lookupFlowConstruct("cancel-order");
MuleEvent response = flow.process(getTestEvent(testObjects));
Boolean result = (Boolean) response.getMessage().getPayload();
assertTrue(result);
}
catch (Exception e) {
e.printStackTrace();
fail();
}
}
@After
public void tearDown() {
List<Integer> productIds = (List<Integer>) testObjects.get("productIds");
for (Integer productId : productIds) {
try {
deleteProductById(productId);
}
catch (Exception e) {
e.printStackTrace();
fail();
}
}
}
}
| false | true | public void setUp() {
try {
testObjects = (HashMap<String, Object>) context.getBean("cancelOrder");
ShoppingCartCustomerEntity customer = (ShoppingCartCustomerEntity) testObjects.get("customer");
List<ShoppingCartCustomerAddressEntity> addresses = (List<ShoppingCartCustomerAddressEntity>) testObjects.get("customerAddresses");
String shippingMethod = testObjects.get("shippingMethod").toString();
ShoppingCartPaymentMethodEntity paymentMethod = (ShoppingCartPaymentMethodEntity) testObjects.get("paymentMethod");
List<HashMap<String, Object>> products = (List<HashMap<String, Object>>) testObjects.get("products");
List<ShoppingCartProductEntity> shoppingCartProducts = new ArrayList<ShoppingCartProductEntity>();
List<Integer> productIds = new ArrayList<Integer>();
for (HashMap<String, Object> product : products) {
// Get the product data
String productType = (String) product.get("type");
int productSet = (Integer) product.get("set");
String productSKU = (String) product.get("sku");
CatalogProductCreateEntity attributes = (CatalogProductCreateEntity) product.get("attributesRef");
// Create the product and get the product ID
int productId = createProduct(productType, productSet, productSKU, attributes);
// Get the quantity to place in the shopping cart
double qtyToPurchase = (Double) product.get("qtyToPurchase");
// Create the shopping cart product entity
ShoppingCartProductEntity shoppingCartProduct = new ShoppingCartProductEntity();
shoppingCartProduct.setProduct_id(productId + "");
shoppingCartProduct.setQty(qtyToPurchase);
shoppingCartProducts.add(shoppingCartProduct);
productIds.add(productId);
}
String orderId = createShoppingCartOrder(customer, addresses, paymentMethod, shippingMethod, shoppingCartProducts);
testObjects.put("productIds", productIds);
testObjects.put("orderId", orderId);
}
catch (Exception e) {
e.printStackTrace();
fail();
}
}
| public void setUp() {
try {
testObjects = (HashMap<String, Object>) context.getBean("cancelOrder");
ShoppingCartCustomerEntity customer = (ShoppingCartCustomerEntity) testObjects.get("customer");
List<ShoppingCartCustomerAddressEntity> addresses = (List<ShoppingCartCustomerAddressEntity>) testObjects.get("customerAddresses");
String shippingMethod = testObjects.get("shippingMethod").toString();
ShoppingCartPaymentMethodEntity paymentMethod = (ShoppingCartPaymentMethodEntity) testObjects.get("paymentMethod");
List<HashMap<String, Object>> products = (List<HashMap<String, Object>>) testObjects.get("products");
List<ShoppingCartProductEntity> shoppingCartProducts = new ArrayList<ShoppingCartProductEntity>();
List<Integer> productIds = new ArrayList<Integer>();
for (HashMap<String, Object> product : products) {
// Get the product data
String productType = (String) product.get("type");
int productSet = (Integer) product.get("set");
String productSKU = (String) product.get("sku");
CatalogProductCreateEntity attributes = (CatalogProductCreateEntity) product.get("attributesRef");
// Create the product and get the product ID
int productId = createProduct(productType, productSet, productSKU, attributes);
// Get the quantity to place in the shopping cart
double qtyToPurchase = (Double) product.get("qtyToPurchase");
// Create the shopping cart product entity
ShoppingCartProductEntity shoppingCartProduct = new ShoppingCartProductEntity();
shoppingCartProduct.setProduct_id(productId + "");
shoppingCartProduct.setQty(qtyToPurchase);
shoppingCartProducts.add(shoppingCartProduct);
productIds.add(productId);
}
testObjects.put("productIds", productIds);
String orderId = createShoppingCartOrder(customer, addresses, paymentMethod, shippingMethod, shoppingCartProducts);
testObjects.put("orderId", orderId);
}
catch (Exception e) {
e.printStackTrace();
fail();
}
}
|
diff --git a/src/com/jidesoft/swing/LabeledTextField.java b/src/com/jidesoft/swing/LabeledTextField.java
index a37d0dca..ee9cbc1d 100644
--- a/src/com/jidesoft/swing/LabeledTextField.java
+++ b/src/com/jidesoft/swing/LabeledTextField.java
@@ -1,526 +1,530 @@
/*
* @(#)ShortcutField.java 7/9/2002
*
* Copyright 2002 - 2002 JIDE Software Inc. All rights reserved.
*/
package com.jidesoft.swing;
import com.jidesoft.plaf.UIDefaultsLookup;
import com.jidesoft.utils.SystemInfo;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* <code>LabeledTextField</code> is a combo component which includes text field and an optional JLabel in the front and
* another optional AbstractButton at the end.
*/
public class LabeledTextField extends JPanel {
protected JTextField _textField;
protected JLabel _label;
protected AbstractButton _button;
protected String _labelText;
protected Icon _icon;
protected String _hintText;
protected JLabel _hintLabel;
protected PopupMenuCustomizer _customizer;
protected KeyStroke _contextMenuKeyStroke;
/**
* The PopupMenuCustomizer for the context menu when clicking on the label/icon before the text field.
*/
public static interface PopupMenuCustomizer {
void customize(LabeledTextField field, JPopupMenu menu);
}
public LabeledTextField() {
this(null, null);
}
public LabeledTextField(Icon icon) {
this(icon, null);
}
public LabeledTextField(Icon icon, String labelText) {
super();
_icon = icon;
_labelText = labelText;
initComponent();
}
protected void initComponent() {
_label = createLabel();
if (_label != null) {
_label.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
showContextMenu();
}
@Override
public void mouseReleased(MouseEvent e) {
}
});
}
_button = createButton();
_textField = createTextField();
initLayout(_label, _textField, _button);
setContextMenuKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, KeyEvent.ALT_DOWN_MASK));
registerContextMenuKeyStroke(getContextMenuKeyStroke());
updateUI();
}
private void registerContextMenuKeyStroke(KeyStroke keyStroke) {
if (keyStroke != null) {
registerKeyboardAction(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showContextMenu();
}
}, keyStroke, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
}
}
private void unregisterContextMenuKeyStroke(KeyStroke keyStroke) {
if (keyStroke != null)
unregisterKeyboardAction(keyStroke);
}
/**
* Shows the context menu.
*/
protected void showContextMenu() {
if (isEnabled()) {
JPopupMenu menu = createContextMenu();
PopupMenuCustomizer customizer = getPopupMenuCustomizer();
if (customizer != null && menu != null) {
customizer.customize(LabeledTextField.this, menu);
}
if (menu != null && menu.getComponentCount() > 0) {
Point location = _label.getLocation();
menu.show(LabeledTextField.this, location.x + (_label.getIcon() == null ? 1 : _label.getIcon().getIconWidth() / 2), location.y + _label.getHeight() + 1);
}
}
}
/**
* Setup the layout of the components. By default, we used a border layout with label first, field in the center and
* button last.
*
* @param label the label
* @param field the text field.
* @param button the button
*/
protected void initLayout(final JLabel label, final JTextField field, final AbstractButton button) {
setLayout(new BorderLayout(3, 3));
if (label != null) {
add(label, BorderLayout.BEFORE_LINE_BEGINS);
}
_hintLabel = new JLabel(getHintText());
_hintLabel.setOpaque(false);
Color foreground = UIDefaultsLookup.getColor("Label.disabledForeground");
if (foreground == null) {
foreground = Color.GRAY;
}
_hintLabel.setForeground(foreground);
final DefaultOverlayable overlayable = new DefaultOverlayable(field, _hintLabel, DefaultOverlayable.WEST);
overlayable.setOpaque(false);
field.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
adjustOverlay(field, overlayable);
}
public void focusGained(FocusEvent e) {
adjustOverlay(field, overlayable);
}
});
field.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
adjustOverlay(field, overlayable);
}
public void removeUpdate(DocumentEvent e) {
adjustOverlay(field, overlayable);
}
public void changedUpdate(DocumentEvent e) {
adjustOverlay(field, overlayable);
}
});
add(overlayable);
if (button != null) {
add(button, BorderLayout.AFTER_LINE_ENDS);
}
}
private void adjustOverlay(JTextField field, DefaultOverlayable overlayable) {
if (field.hasFocus()) {
overlayable.setOverlayVisible(false);
}
else {
String text = field.getText();
if (text != null && text.length() != 0) {
overlayable.setOverlayVisible(false);
}
else {
overlayable.setOverlayVisible(true);
}
}
}
/**
* Creates a text field. By default it will return a JTextField with opaque set to false. Subclass can override this
* method to create their own text field such as JFormattedTextField.
*
* @return a text field.
*/
protected JTextField createTextField() {
JTextField textField = new OverlayTextField();
SelectAllUtils.install(textField);
JideSwingUtilities.setComponentTransparent(textField);
textField.setColumns(20);
return textField;
}
/**
* Creates a context menu. The context menu will be shown when user clicks on the label.
*
* @return a context menu.
*/
protected JidePopupMenu createContextMenu() {
return new JidePopupMenu();
}
@Override
public void updateUI() {
super.updateUI();
Border textFieldBorder = UIDefaultsLookup.getBorder("TextField.border");
if (textFieldBorder != null) {
boolean big = textFieldBorder.getBorderInsets(this).top >= 2;
if (big)
setBorder(textFieldBorder);
else
setBorder(BorderFactory.createCompoundBorder(textFieldBorder, BorderFactory.createEmptyBorder(2, 2, 2, 2)));
}
else {
setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), BorderFactory.createEmptyBorder(2, 2, 2, 2)));
}
if (isEnabled()) {
LookAndFeel.installColors(this, "TextField.background", "TextField.foreground");
}
else {
LookAndFeel.installColors(this, "TextField.disableBackground", "TextField.inactiveForeground");
}
if (textFieldBorder != null && _textField != null) {
_textField.setBorder(BorderFactory.createEmptyBorder());
}
setEnabled(isEnabled());
}
/**
* Creates the button that appears after the text field. By default it returns null so there is no button. Subclass
* can override it to create their own button. A typical usage of this is to create a browse button to browse a file
* or directory.
*
* @return the button.
*/
protected AbstractButton createButton() {
return null;
}
/**
* Creates the label that appears before the text field. By default, it only has a search icon.
*
* @return the label.
*/
protected JLabel createLabel() {
JLabel label = new JLabel(_icon);
label.setText(_labelText);
return label;
}
/**
* Sets the text that appears before the text field.
*
* @param text the text that appears before the text field.
*/
public void setLabelText(String text) {
_labelText = text;
if (_label != null) {
_label.setText(text);
}
}
/**
* Gets the text that appears before the text field.
*
* @return the text that appears before the text field. By default it's null, meaning no text.
*/
public String getLabelText() {
if (_label != null) {
return _label.getText();
}
else {
return _labelText;
}
}
/**
* Sets the icon that appears before the text field.
*
* @param icon the icon that appears before the text field.
*/
public void setIcon(Icon icon) {
_icon = icon;
if (_label != null) {
_label.setIcon(icon);
}
}
/**
* Gets the icon that appears before the text field.
*
* @return the icon that appears before the text field.
*/
public Icon getIcon() {
if (_label != null) {
return _label.getIcon();
}
else {
return _icon;
}
}
/**
* Gets the JLabel that appears before text field.
*
* @return the JLabel that appears before text field.
*/
public JLabel getLabel() {
return _label;
}
/**
* Gets the AbstractButton that appears after text field.
*
* @return the AbstractButton that appears after text field.
*/
public AbstractButton getButton() {
return _button;
}
/**
* Sets the number of columns in this TextField, and then invalidate the layout.
*
* @param columns the number of columns for this text field.
*/
public void setColumns(int columns) {
if (getTextField() != null) {
getTextField().setColumns(columns);
}
}
/**
* Sets the text in this TextField.
*
* @param text the new text in this TextField.
*/
public void setText(String text) {
if (getTextField() != null) {
getTextField().setText(text);
}
}
/**
* Gets the text in this TextField.
*
* @return the text in this TextField.
*/
public String getText() {
if (getTextField() != null) {
return getTextField().getText();
}
else {
return null;
}
}
/**
* Gets the actual text field.
*
* @return the actual text field.
*/
public JTextField getTextField() {
return _textField;
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
if (enabled) {
if (getTextField() != null) {
getTextField().setEnabled(true);
}
if (getLabel() != null) {
getLabel().setEnabled(true);
}
if (getButton() != null) {
getButton().setEnabled(true);
}
}
else {
if (getTextField() != null) {
getTextField().setEnabled(false);
}
if (getLabel() != null) {
getLabel().setEnabled(false);
}
if (getButton() != null) {
getButton().setEnabled(false);
}
setBackground(UIDefaultsLookup.getColor("control"));
}
if (_hintLabel != null) {
- _hintLabel.setVisible(isEnabled());
+ boolean textEmpty = true;
+ if (getTextField() != null) {
+ textEmpty = getTextField().getText() == null || getTextField().getText().isEmpty();
+ }
+ _hintLabel.setVisible(isEnabled() && textEmpty);
}
JTextField textField = getTextField();
if(textField != null) {
// this probably won't work with L&F which ignore the background property like GTK L&F
setBackground(textField.getBackground());
setForeground(textField.getForeground());
}
else {
if(enabled) {
setBackground(UIDefaultsLookup.getColor("TextField.background"));
setForeground(UIDefaultsLookup.getColor("TextField.foreground"));
}
else {
Color background = UIDefaultsLookup.getColor("TextField.disabledBackground");
if(background == null) {
// TextField.disabledBackground not defined by metal
background = UIDefaultsLookup.getColor("TextField.inactiveBackground");
// Nimbus uses TextField[Disabled].backgroundPainter (not a Color)
// but don't know how to set that for a single panel instance, maybe with a ClientProperty?
}
setBackground(background);
setForeground(UIDefaultsLookup.getColor("TextField.inactiveForeground"));
}
}
}
public int getBaseline(int width, int height) {
if (SystemInfo.isJdk6Above()) {
try {
Method method = Component.class.getMethod("getBaseline", new Class[]{int.class, int.class});
Object value = method.invoke(_textField, width, height);
if (value instanceof Integer) {
return (Integer) value;
}
}
catch (NoSuchMethodException e) {
// ignore
}
catch (IllegalAccessException e) {
// ignore
}
catch (InvocationTargetException e) {
// ignore
}
}
return -1;
}
/**
* Gets the hint text when the field is empty and not focused.
*
* @return the hint text.
*/
public String getHintText() {
return _hintText;
}
/**
* Sets the hint text.
*
* @param hintText the new hint text.
*/
public void setHintText(String hintText) {
_hintText = hintText;
if (_hintLabel != null) {
_hintLabel.setText(_hintText);
}
}
/**
* Gets the PopupMenuCustomizer.
*
* @return the PopupMenuCustomizer.
*/
public PopupMenuCustomizer getPopupMenuCustomizer() {
return _customizer;
}
/**
* Sets the PopupMenuCustomizer. PopupMenuCustomizer can be used to do customize the popup menu for the
* <code>LabeledTextField</code>.
* <p/>
* PopupMenuCustomizer has a customize method. The popup menu of this menu will be passed in. You can
* add/remove/change the menu items in customize method. For example,
* <code><pre>
* field.setPopupMenuCustomzier(new LabeledTextField.PopupMenuCustomizer() {
* void customize(LabledTextField field, JPopupMenu menu) {
* menu.removeAll();
* menu.add(new JMenuItem("..."));
* menu.add(new JMenuItem("..."));
* }
* }
* </pre></code>
* If the menu is never used, the two add methods will never be called thus improve the performance.
*
* @param customizer the PopupMenuCustomizer
*/
public void setPopupMenuCustomizer(PopupMenuCustomizer customizer) {
_customizer = customizer;
}
/**
* Gets the keystroke that will bring up the context menu. If you never set it before, it will return SHIFT-F10 for
* operating systems other than Mac OS X.
*
* @return the keystroke that will bring up the context menu.
*/
public KeyStroke getContextMenuKeyStroke() {
if (_contextMenuKeyStroke == null) {
_contextMenuKeyStroke = !SystemInfo.isMacOSX() ? KeyStroke.getKeyStroke(KeyEvent.VK_F10, KeyEvent.SHIFT_MASK) : null;
}
return _contextMenuKeyStroke;
}
/**
* Changes the keystroke that brings up the context menu which is normally shown when user clicks on the label icon
* before the text field.
*
* @param contextMenuKeyStroke the new keystroke to bring up the context menu.
*/
public void setContextMenuKeyStroke(KeyStroke contextMenuKeyStroke) {
if (_contextMenuKeyStroke != null) {
unregisterContextMenuKeyStroke(_contextMenuKeyStroke);
}
_contextMenuKeyStroke = contextMenuKeyStroke;
if (_contextMenuKeyStroke != null) {
registerContextMenuKeyStroke(_contextMenuKeyStroke);
}
}
}
| true | true | public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
if (enabled) {
if (getTextField() != null) {
getTextField().setEnabled(true);
}
if (getLabel() != null) {
getLabel().setEnabled(true);
}
if (getButton() != null) {
getButton().setEnabled(true);
}
}
else {
if (getTextField() != null) {
getTextField().setEnabled(false);
}
if (getLabel() != null) {
getLabel().setEnabled(false);
}
if (getButton() != null) {
getButton().setEnabled(false);
}
setBackground(UIDefaultsLookup.getColor("control"));
}
if (_hintLabel != null) {
_hintLabel.setVisible(isEnabled());
}
JTextField textField = getTextField();
if(textField != null) {
// this probably won't work with L&F which ignore the background property like GTK L&F
setBackground(textField.getBackground());
setForeground(textField.getForeground());
}
else {
if(enabled) {
setBackground(UIDefaultsLookup.getColor("TextField.background"));
setForeground(UIDefaultsLookup.getColor("TextField.foreground"));
}
else {
Color background = UIDefaultsLookup.getColor("TextField.disabledBackground");
if(background == null) {
// TextField.disabledBackground not defined by metal
background = UIDefaultsLookup.getColor("TextField.inactiveBackground");
// Nimbus uses TextField[Disabled].backgroundPainter (not a Color)
// but don't know how to set that for a single panel instance, maybe with a ClientProperty?
}
setBackground(background);
setForeground(UIDefaultsLookup.getColor("TextField.inactiveForeground"));
}
}
}
| public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
if (enabled) {
if (getTextField() != null) {
getTextField().setEnabled(true);
}
if (getLabel() != null) {
getLabel().setEnabled(true);
}
if (getButton() != null) {
getButton().setEnabled(true);
}
}
else {
if (getTextField() != null) {
getTextField().setEnabled(false);
}
if (getLabel() != null) {
getLabel().setEnabled(false);
}
if (getButton() != null) {
getButton().setEnabled(false);
}
setBackground(UIDefaultsLookup.getColor("control"));
}
if (_hintLabel != null) {
boolean textEmpty = true;
if (getTextField() != null) {
textEmpty = getTextField().getText() == null || getTextField().getText().isEmpty();
}
_hintLabel.setVisible(isEnabled() && textEmpty);
}
JTextField textField = getTextField();
if(textField != null) {
// this probably won't work with L&F which ignore the background property like GTK L&F
setBackground(textField.getBackground());
setForeground(textField.getForeground());
}
else {
if(enabled) {
setBackground(UIDefaultsLookup.getColor("TextField.background"));
setForeground(UIDefaultsLookup.getColor("TextField.foreground"));
}
else {
Color background = UIDefaultsLookup.getColor("TextField.disabledBackground");
if(background == null) {
// TextField.disabledBackground not defined by metal
background = UIDefaultsLookup.getColor("TextField.inactiveBackground");
// Nimbus uses TextField[Disabled].backgroundPainter (not a Color)
// but don't know how to set that for a single panel instance, maybe with a ClientProperty?
}
setBackground(background);
setForeground(UIDefaultsLookup.getColor("TextField.inactiveForeground"));
}
}
}
|
diff --git a/xlthotel_core/src/main/java/com/xlthotel/core/filter/MediaItemFilter.java b/xlthotel_core/src/main/java/com/xlthotel/core/filter/MediaItemFilter.java
index 7635f5c..aae3055 100644
--- a/xlthotel_core/src/main/java/com/xlthotel/core/filter/MediaItemFilter.java
+++ b/xlthotel_core/src/main/java/com/xlthotel/core/filter/MediaItemFilter.java
@@ -1,99 +1,99 @@
package com.xlthotel.core.filter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.google.common.collect.Maps;
import com.xlthotel.core.service.PhotoService;
import com.xlthotel.core.service.imp.PhotoServiceImpl;
import com.xlthotel.foundation.common.SimpleServletRequestUtils;
import com.xlthotel.foundation.constants.PhotoScalerType;
public class MediaItemFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(MediaItemFilter.class);
private ServletContext servletContext;
private static final Map<String, String> mimeTable = new HashMap<String, String>();
{
mimeTable.put("JPG", "jpeg");
mimeTable.put("JPEG", "jpeg");
mimeTable.put("PNG", "png");
mimeTable.put("GIF", "gif");
mimeTable.put("BMP", "jpeg");
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
servletContext = filterConfig.getServletContext();
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
String uri = req.getRequestURI();
- if (!uri.contains("/servlet/admin/media/")) {
+ if (!uri.contains("/servlet/media/")) {
chain.doFilter(request, response);
return;
}
try {
PhotoService photoService = getSpringContext().getBean("photoServiceImpl", PhotoServiceImpl.class);
- String path = uri.substring(uri.indexOf("/servlet/admin/media/") + "/servlet/admin/media/".length(), uri.length());
+ String path = uri.substring(uri.indexOf("/servlet/media/") + "/servlet/media/".length(), uri.length());
String scalerType = SimpleServletRequestUtils.getStringParameter(req, "scalerType", null);
int width = SimpleServletRequestUtils.getIntParameter(req, "width", 0);
int hight = SimpleServletRequestUtils.getIntParameter(req, "hight", 0);
byte[] photoStream = null;
if (StringUtils.isBlank(scalerType)) {
photoStream = photoService.getPhoto(path, width, hight);
} else {
try {
PhotoScalerType photoScalerType = PhotoScalerType.valueOf(scalerType);
photoStream = photoService.getPhoto(path, photoScalerType);
} catch (Exception e) {
photoStream = photoService.getPhoto(path, -1, -1);
}
}
String suffix = path.substring(path.lastIndexOf(".") + 1, path.length());
resp.setHeader("Cache-Control", "max-age=3600, must-revalidate");
resp.setContentType("image/" + mimeTable.get(suffix.toUpperCase()));
resp.setCharacterEncoding("UTF-8");
ServletOutputStream out = resp.getOutputStream();
out.write(photoStream);
out.close();
return;
} catch (Exception ex) {
logger.error("Can not find the media item[" + uri + "]", ex);
chain.doFilter(request, response);
}
}
@Override
public void destroy() {
servletContext = null;
}
private WebApplicationContext getSpringContext() {
return WebApplicationContextUtils.getWebApplicationContext(servletContext);
}
}
| false | true | public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
String uri = req.getRequestURI();
if (!uri.contains("/servlet/admin/media/")) {
chain.doFilter(request, response);
return;
}
try {
PhotoService photoService = getSpringContext().getBean("photoServiceImpl", PhotoServiceImpl.class);
String path = uri.substring(uri.indexOf("/servlet/admin/media/") + "/servlet/admin/media/".length(), uri.length());
String scalerType = SimpleServletRequestUtils.getStringParameter(req, "scalerType", null);
int width = SimpleServletRequestUtils.getIntParameter(req, "width", 0);
int hight = SimpleServletRequestUtils.getIntParameter(req, "hight", 0);
byte[] photoStream = null;
if (StringUtils.isBlank(scalerType)) {
photoStream = photoService.getPhoto(path, width, hight);
} else {
try {
PhotoScalerType photoScalerType = PhotoScalerType.valueOf(scalerType);
photoStream = photoService.getPhoto(path, photoScalerType);
} catch (Exception e) {
photoStream = photoService.getPhoto(path, -1, -1);
}
}
String suffix = path.substring(path.lastIndexOf(".") + 1, path.length());
resp.setHeader("Cache-Control", "max-age=3600, must-revalidate");
resp.setContentType("image/" + mimeTable.get(suffix.toUpperCase()));
resp.setCharacterEncoding("UTF-8");
ServletOutputStream out = resp.getOutputStream();
out.write(photoStream);
out.close();
return;
} catch (Exception ex) {
logger.error("Can not find the media item[" + uri + "]", ex);
chain.doFilter(request, response);
}
}
| public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
String uri = req.getRequestURI();
if (!uri.contains("/servlet/media/")) {
chain.doFilter(request, response);
return;
}
try {
PhotoService photoService = getSpringContext().getBean("photoServiceImpl", PhotoServiceImpl.class);
String path = uri.substring(uri.indexOf("/servlet/media/") + "/servlet/media/".length(), uri.length());
String scalerType = SimpleServletRequestUtils.getStringParameter(req, "scalerType", null);
int width = SimpleServletRequestUtils.getIntParameter(req, "width", 0);
int hight = SimpleServletRequestUtils.getIntParameter(req, "hight", 0);
byte[] photoStream = null;
if (StringUtils.isBlank(scalerType)) {
photoStream = photoService.getPhoto(path, width, hight);
} else {
try {
PhotoScalerType photoScalerType = PhotoScalerType.valueOf(scalerType);
photoStream = photoService.getPhoto(path, photoScalerType);
} catch (Exception e) {
photoStream = photoService.getPhoto(path, -1, -1);
}
}
String suffix = path.substring(path.lastIndexOf(".") + 1, path.length());
resp.setHeader("Cache-Control", "max-age=3600, must-revalidate");
resp.setContentType("image/" + mimeTable.get(suffix.toUpperCase()));
resp.setCharacterEncoding("UTF-8");
ServletOutputStream out = resp.getOutputStream();
out.write(photoStream);
out.close();
return;
} catch (Exception ex) {
logger.error("Can not find the media item[" + uri + "]", ex);
chain.doFilter(request, response);
}
}
|
diff --git a/javasvn/src/org/tmatesoft/svn/core/internal/SVNCommitUtil.java b/javasvn/src/org/tmatesoft/svn/core/internal/SVNCommitUtil.java
index 21c9ecfc3..c888900f8 100644
--- a/javasvn/src/org/tmatesoft/svn/core/internal/SVNCommitUtil.java
+++ b/javasvn/src/org/tmatesoft/svn/core/internal/SVNCommitUtil.java
@@ -1,535 +1,537 @@
/*
* ====================================================================
* Copyright (c) 2004 TMate Software Ltd. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://tmate.org/svn/license.html.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
* ====================================================================
*/
package org.tmatesoft.svn.core.internal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import org.tmatesoft.svn.core.ISVNDirectoryEntry;
import org.tmatesoft.svn.core.ISVNEntry;
import org.tmatesoft.svn.core.ISVNRootEntry;
import org.tmatesoft.svn.core.SVNProperty;
import org.tmatesoft.svn.core.SVNStatus;
import org.tmatesoft.svn.core.io.ISVNEditor;
import org.tmatesoft.svn.core.io.SVNCommitInfo;
import org.tmatesoft.svn.core.io.SVNException;
import org.tmatesoft.svn.core.io.SVNRepositoryLocation;
import org.tmatesoft.svn.core.progress.ISVNProgressViewer;
import org.tmatesoft.svn.core.progress.SVNProgressDummyViewer;
import org.tmatesoft.svn.util.DebugLog;
import org.tmatesoft.svn.util.PathUtil;
import org.tmatesoft.svn.util.TimeUtil;
/**
* @author TMate Software Ltd.
*/
public class SVNCommitUtil {
private static final String SVN_ENTRY_REPLACED = "svn:entry:replaced";
public static String buildCommitTree(Collection modifiedEntries, Map map, Map locks) throws SVNException {
map = map == null ? new HashMap() : map;
locks = locks == null ? new HashMap() : locks;
ISVNEntry root = null;
for(Iterator entries = modifiedEntries.iterator(); entries.hasNext();) {
ISVNEntry entry = (ISVNEntry) entries.next();
String url = PathUtil.decode(entry.getPropertyValue(SVNProperty.URL));
if (entry instanceof ISVNRootEntry) {
root = entry;
}
map.put(url, entry);
if (entry.getPropertyValue(SVNProperty.LOCK_TOKEN) != null) {
url = SVNRepositoryLocation.parseURL(url).toCanonicalForm();
locks.put(url, entry.getPropertyValue(SVNProperty.LOCK_TOKEN));
}
if (entry.isScheduledForDeletion() && entry.isDirectory()) {
// collect locks for all children.
collectChildrenLocks(entry.asDirectory(), locks);
}
}
DebugLog.log("modified paths: " + modifiedEntries);
DebugLog.log("modified map : " + map);
DebugLog.log("modified locks: " + locks);
// now add common root entry ?
String commonRoot = null;
String[] urls = (String[]) map.keySet().toArray(new String[map.size()]);
if (root == null) {
String[] paths = new String[urls.length];
String host = null;
// convert urls to path, removing host part of the url (always a common root).
for(int i = 0; i < paths.length; i++) {
// put path part of the URL only, without leading slash.
int index = urls[i].indexOf("://");
index = urls[i].indexOf('/', index + "://".length());
if (index < 0) {
index = urls[i].length();
}
host = urls[i].substring(0, index);
paths[i] = PathUtil.removeLeadingSlash(urls[i].substring(index));
}
// we may have "repo/trunk" (root entry)
// and files like "repo/trunk/"
if (map.size() == 1) {
ISVNEntry rootEntry = (ISVNEntry) map.get(urls[0]);
// if entry is already a folder, let it be root.
if (!rootEntry.isDirectory() || rootEntry.isScheduledForAddition() || rootEntry.isScheduledForDeletion()
|| rootEntry.isPropertiesModified()) {
commonRoot = PathUtil.getCommonRoot(paths);
DebugLog.log("using parent as root : " + commonRoot);
} else {
commonRoot = paths[0];
DebugLog.log("using root as is : " + commonRoot);
}
} else {
commonRoot = PathUtil.getCommonRoot(paths);
}
commonRoot = "".equals(commonRoot) ? host : PathUtil.append(host, commonRoot);
} else {
commonRoot = root.getPropertyValue(SVNProperty.URL);
commonRoot = PathUtil.decode(commonRoot);
}
// this root may or may not exist in the map.
if (!map.containsKey(commonRoot)) {
map.put(commonRoot, null);
}
// replace map urls with paths
for(int i = 0; i < urls.length; i++) {
String key = urls[i];
Object value = map.get(key);
String newKey = key.substring(commonRoot.length());
newKey = PathUtil.removeLeadingSlash(newKey);
map.put(newKey, value);
map.remove(key);
}
if (map.containsKey(commonRoot)) {
map.put("", map.get(commonRoot));
map.remove(commonRoot);
}
return commonRoot;
}
private static void collectChildrenLocks(ISVNDirectoryEntry parent, Map locks) throws SVNException {
for(Iterator children = parent.childEntries(); children.hasNext();) {
ISVNEntry entry = (ISVNEntry) children.next();
String lock = entry.getPropertyValue(SVNProperty.LOCK_TOKEN);
if (lock != null) {
String url = PathUtil.decode(entry.getPropertyValue(SVNProperty.URL));
url = SVNRepositoryLocation.parseURL(url).toCanonicalForm();
locks.put(url, lock);
}
if (entry.isDirectory()) {
collectChildrenLocks(entry.asDirectory(), locks);
}
}
}
public static void harvestCommitables(ISVNEntry root, String[] paths, boolean recursive, Collection modified) throws SVNException {
String entryPath = root.getPath();
DebugLog.log("HV: processing " + entryPath);
boolean harvest = false;
for(int i = 0; i < paths.length; i++) {
harvest = (!recursive && entryPath.startsWith(paths[i])) ||
(recursive && (entryPath.startsWith(paths[i]) || paths[i].startsWith(entryPath)));
if (harvest) {
break;
}
}
if (!harvest) {
DebugLog.log("HV: processing " + entryPath + " => not below commit roots" );
return;
}
if (root.isMissing()) {
DebugLog.log("HV: processing " + entryPath + " => missing, skipped" );
return;
}
boolean copy = root.getPropertyValue(SVNProperty.COPIED) != null;
long revision = SVNProperty.longValue(root.getPropertyValue(SVNProperty.REVISION));
if (root.isDirectory()) {
if (root.isScheduledForAddition() || root.isScheduledForDeletion() || root.isPropertiesModified()) {
// add to modified only if it is below one of the paths.
for(int i = 0; i < paths.length; i++) {
if (entryPath.startsWith(paths[i])) {
DebugLog.log("HV: processing " + entryPath + " => added to modified as directory" );
modified.add(root);
break;
}
}
}
if (root.isScheduledForDeletion() && !root.isScheduledForAddition()) {
DebugLog.log("HV: processing " + entryPath + " => children are not collected for deleted directory " );
return;
}
if (recursive) {
for(Iterator children = root.asDirectory().childEntries(); children.hasNext();) {
ISVNEntry child = (ISVNEntry) children.next();
DebugLog.log("HV: processing " + entryPath + " => collecting child: " + child.getPath() );
long childRevision = SVNProperty.longValue(child.getPropertyValue(SVNProperty.REVISION));
if (copy) {
DebugLog.log("HV: processing unmodified copied child " + child.getPath() );
if (child.getPropertyValue(SVNProperty.COPYFROM_URL) == null) {
String parentCopyFromURL = root.getPropertyValue(SVNProperty.COPYFROM_URL);
child.setPropertyValue(SVNProperty.COPYFROM_URL, PathUtil.append(parentCopyFromURL, PathUtil.encode(child.getName())));
child.setPropertyValue(SVNProperty.COPYFROM_REVISION, SVNProperty.toString(childRevision));
}
}
harvestCommitables(child, paths, recursive, modified);
if (copy) {
if (!modified.contains(child) && revision != childRevision) {
DebugLog.log("HV: copied child collected, revision differs from parent " + child.getPath() );
modified.add(child);
}
}
}
}
} else {
if (root.isScheduledForAddition() ||
root.isScheduledForDeletion() ||
root.isPropertiesModified() ||
root.asFile().isContentsModified()) {
DebugLog.log("HV: processing " + entryPath + " => added to modified as file" );
modified.add(root);
}
}
}
public static void doCommit(String path, String url, Map entries, ISVNEditor editor, SVNWorkspace ws, ISVNProgressViewer progressViewer) throws SVNException {
doCommit(path, url, entries, editor, ws, progressViewer, new HashSet());
}
public static void doCommit(String path, String url, Map entries, ISVNEditor editor, SVNWorkspace ws, ISVNProgressViewer progressViewer, Set committedPaths) throws SVNException {
- progressViewer = progressViewer == null ? new SVNProgressDummyViewer() : progressViewer;
+ progressViewer = progressViewer == null ? new SVNProgressDummyViewer() : progressViewer;
ISVNEntry root = (ISVNEntry) entries.get(path);
String realPath = path;
if (root != null && root.getAlias() != null) {
path = PathUtil.append(PathUtil.removeTail(path), root.getAlias());
path = PathUtil.removeLeadingSlash(path);
}
long revision = root == null ? -1 : SVNProperty.longValue(root.getPropertyValue(SVNProperty.REVISION));
boolean copied = false;
if (root != null) {
root.setPropertyValue(SVNProperty.COMMITTED_REVISION, null);
copied = Boolean.TRUE.toString().equals(root.getPropertyValue(SVNProperty.COPIED));
}
if ("".equals(realPath) && !copied) {
DebugLog.log("ROOT OPEN: " + path);
editor.openRoot(-1);
if (root != null) {
if (root.sendChangedProperties(editor)) {
ws.fireEntryCommitted(root, SVNStatus.MODIFIED);
}
}
} else if (root != null && (root.isScheduledForAddition() || copied)) {
if ("".equals(realPath)) {
DebugLog.log("ROOT OPEN: " + path);
editor.openRoot(-1);
}
DebugLog.log("DIR ADD: " + path);
String copyFromURL = root.getPropertyValue(SVNProperty.COPYFROM_URL);
long copyFromRevision = -1;
if (copyFromURL != null) {
copyFromURL = SVNRepositoryLocation.parseURL(copyFromURL).toCanonicalForm();
copyFromRevision = Long.parseLong(root.getPropertyValue(SVNProperty.COPYFROM_REVISION));
DebugLog.log("copyfrom path:" + copyFromURL);
DebugLog.log("parent's url: " + url);
copyFromURL = copyFromURL.substring(url.length());
if (!copyFromURL.startsWith("/")) {
copyFromURL = "/" + copyFromURL;
}
DebugLog.log("copyfrom path:" + copyFromURL);
}
// here we could have alias.
editor.addDir(path, copyFromURL, copyFromRevision);
root.sendChangedProperties(editor);
ws.fireEntryCommitted(root, SVNStatus.ADDED);
} else if (root != null && root.isPropertiesModified()) {
DebugLog.log("DIR OPEN: " + path + ", " + revision);
editor.openDir(path, revision);
if (root.sendChangedProperties(editor)) {
ws.fireEntryCommitted(root, SVNStatus.MODIFIED);
}
} else if (root == null) {
DebugLog.log("DIR OPEN (virtual): " + path + ", " + revision);
editor.openDir(path, revision);
}
String[] virtualChildren = getVirtualChildren(entries, realPath);
DebugLog.log("virtual children count: " + virtualChildren.length);
for(int i = 0; i < virtualChildren.length; i++) {
String childPath = virtualChildren[i];
doCommit(childPath, url, entries, editor, ws, progressViewer, committedPaths);
}
ISVNEntry[] children = getDirectChildren(entries, realPath);
DebugLog.log("direct children count: " + children.length);
ISVNEntry parent = null;
for(int i = 0; i < children.length; i++) {
ISVNEntry child = children[i];
if (parent == null) {
parent = ws.locateParentEntry(child.getPath());
}
- String childPath = child.getAlias() != null ? PathUtil.append(path, child.getAlias()) :
- PathUtil.append(path, child.getName());
+ DebugLog.log("parent path: " + path);
+ String shortChildName = PathUtil.tail(child.getPropertyValue(SVNProperty.URL));
+ String childPath = child.getAlias() != null ? PathUtil.append(path, child.getAlias()) :
+ PathUtil.append(path, shortChildName);
- String realChildPath = PathUtil.removeLeadingSlash(PathUtil.append(path, child.getName()));
+ String realChildPath = PathUtil.removeLeadingSlash(PathUtil.append(path, shortChildName));
childPath = PathUtil.removeLeadingSlash(childPath);
childPath = PathUtil.removeTrailingSlash(childPath);
revision = SVNProperty.longValue(child.getPropertyValue(SVNProperty.REVISION));
committedPaths.add(childPath);
progressViewer.setProgress((double)committedPaths.size() / (double)entries.keySet().size());
if (child.isScheduledForAddition() && child.isScheduledForDeletion()) {
DebugLog.log("FILE REPLACE: " + childPath);
child.setPropertyValue(SVNProperty.COMMITTED_REVISION, null);
editor.deleteEntry(childPath, revision);
updateReplacementSchedule(child);
if (child.isDirectory()) {
doCommit(childPath, url, entries, editor, ws, progressViewer, committedPaths);
} else {
editor.addFile(childPath, null, -1);
child.sendChangedProperties(editor);
child.asFile().generateDelta(editor);
editor.closeFile(null);
}
ws.fireEntryCommitted(child, SVNStatus.REPLACED);
DebugLog.log("FILE REPLACE: DONE");
} else if (child.isScheduledForDeletion()) {
DebugLog.log("FILE DELETE: " + childPath);
child.setPropertyValue(SVNProperty.COMMITTED_REVISION, null);
if (child.getPropertyValue(SVN_ENTRY_REPLACED) != null) {
DebugLog.log("FILE NOT DELETED, PARENT WAS REPLACED");
} else {
editor.deleteEntry(childPath, revision);
ws.fireEntryCommitted(child, SVNStatus.DELETED);
DebugLog.log("FILE DELETE: DONE");
}
} else if (child.isDirectory()) {
doCommit(realChildPath, url, entries, editor, ws, progressViewer, committedPaths);
} else {
boolean childIsCopied = Boolean.TRUE.toString().equals(child.getPropertyValue(SVNProperty.COPIED));
long copyFromRev = SVNProperty.longValue(child.getPropertyValue(SVNProperty.COPYFROM_REVISION));
String digest = null;
if (childIsCopied && !child.isScheduledForAddition() && copyFromRev >= 0) {
DebugLog.log("FILE COPY: " + childPath);
// first copy it to have in place for modifications if required.
// get copyfrom url and copyfrom rev
String copyFromURL = child.getPropertyValue(SVNProperty.COPYFROM_URL);
if (copyFromURL != null) {
copyFromURL = SVNRepositoryLocation.parseURL(copyFromURL).toCanonicalForm();
DebugLog.log("copyfrom path:" + copyFromURL);
DebugLog.log("parent's url: " + url);
// should be relative to repos root.
copyFromURL = copyFromURL.substring(url.length());
if (!copyFromURL.startsWith("/")) {
copyFromURL = "/" + copyFromURL;
}
DebugLog.log("copyfrom path:" + copyFromURL);
}
editor.addFile(childPath, copyFromURL, copyFromRev);
editor.closeFile(null);
ws.fireEntryCommitted(child, SVNStatus.ADDED);
DebugLog.log("FILE COPY: DONE");
}
if (child.isScheduledForAddition()) {
DebugLog.log("FILE ADD: " + childPath);
child.setPropertyValue(SVNProperty.COMMITTED_REVISION, null);
String copyFromURL = child.getPropertyValue(SVNProperty.COPYFROM_URL);
long copyFromRevision = -1;
if (copyFromURL != null) {
copyFromURL = SVNRepositoryLocation.parseURL(copyFromURL).toCanonicalForm();
copyFromRevision = Long.parseLong(child.getPropertyValue(SVNProperty.COPYFROM_REVISION));
DebugLog.log("copyfrom path:" + copyFromURL);
DebugLog.log("parent's url: " + url);
// should be relative to repos root.
copyFromURL = copyFromURL.substring(url.length());
if (!copyFromURL.startsWith("/")) {
copyFromURL = "/" + copyFromURL;
}
DebugLog.log("copyfrom path:" + copyFromURL);
}
editor.addFile(childPath, copyFromURL, copyFromRevision);
child.sendChangedProperties(editor);
digest = child.asFile().generateDelta(editor);
editor.closeFile(digest);
ws.fireEntryCommitted(child, SVNStatus.ADDED);
DebugLog.log("FILE ADD: DONE");
} else if (child.asFile().isContentsModified() || child.isPropertiesModified()) {
DebugLog.log("FILE COMMIT: " + childPath + " : " + revision);
child.setPropertyValue(SVNProperty.COMMITTED_REVISION, null);
editor.openFile(childPath, revision);
child.sendChangedProperties(editor);
if (child.asFile().isContentsModified()) {
digest = child.asFile().generateDelta(editor);
}
editor.closeFile(digest);
ws.fireEntryCommitted(child, SVNStatus.MODIFIED);
DebugLog.log("FILE COMMIT: DONE: " + digest);
}
}
}
DebugLog.log("DIR CLOSE: " + path);
editor.closeDir();
if ("".equals(realPath) && copied) {
DebugLog.log("DIR CLOSE (ROOT) ");
editor.closeDir();
}
}
public static void updateWorkingCopy(SVNCommitInfo info, String uuid, Map commitTree, SVNWorkspace ws, boolean keepLocks) throws SVNException {
Set parents = new HashSet();
LinkedList sorted = new LinkedList();
for(Iterator entries = commitTree.values().iterator(); entries.hasNext();) {
ISVNEntry entry = (ISVNEntry) entries.next();
if (entry == null) {
continue;
}
int index = 0;
for(Iterator els = sorted.iterator(); els.hasNext();) {
ISVNEntry current = (ISVNEntry) els.next();
if (entry.getPath().compareTo(current.getPath()) >= 0) {
sorted.add(index, entry);
entry = null;
break;
}
index++;
}
if (entry != null) {
sorted.add(entry);
}
}
for(Iterator entries = sorted.iterator(); entries.hasNext();) {
ISVNEntry entry = (ISVNEntry) entries.next();
if (entry == null) {
continue;
}
updateWCEntry(entry, info, uuid, parents, ws, keepLocks);
}
for(Iterator entries = parents.iterator(); entries.hasNext();) {
ISVNEntry parent = (ISVNEntry) entries.next();
if (!commitTree.containsValue(parent)) {
DebugLog.log("UPDATE (save): " + parent.getPath());
parent.save(false);
}
}
}
private static void updateWCEntry(ISVNEntry entry, SVNCommitInfo info, String uuid, Collection parents, SVNWorkspace ws, boolean keepLocks) throws SVNException {
String revStr = Long.toString(info.getNewRevision());
entry.setPropertyValue(SVNProperty.REVISION, revStr);
if (entry.getPropertyValue(SVNProperty.COPIED) != null && entry.isDirectory()) {
DebugLog.log("PROCESSING COPIED DIR: " + entry.getPath());
for(Iterator copied = entry.asDirectory().childEntries(); copied.hasNext();) {
ISVNEntry child = (ISVNEntry) copied.next();
parents.add(child);
DebugLog.log("PROCESSING COPIED CHILD: " + child.getPath());
updateWCEntry(child, info, uuid, parents, ws, keepLocks);
}
}
ISVNEntry parent = ws.locateParentEntry(entry.getPath());
if (parent != null) {
// have to be deleted.
parents.add(parent);
if (entry.isScheduledForDeletion() && !entry.isScheduledForAddition()) {
DebugLog.log("UPDATE (delete): " + entry.getPath());
boolean storeInfo = entry.getPropertyValue(SVN_ENTRY_REPLACED) == null;
parent.asDirectory().deleteChild(entry.getName(), storeInfo);
return;
}
}
if (entry.getPropertyValue(SVNProperty.COMMITTED_REVISION) == null || entry.getPropertyValue(SVNProperty.COPIED) != null) {
entry.setPropertyValue(SVNProperty.COPIED, null);
entry.setPropertyValue(SVNProperty.COPYFROM_URL, null);
entry.setPropertyValue(SVNProperty.COPYFROM_REVISION, null);
entry.setPropertyValue(SVNProperty.SCHEDULE, null);
entry.setPropertyValue(SVNProperty.DELETED, null);
entry.setPropertyValue(SVNProperty.COMMITTED_REVISION, revStr);
entry.setPropertyValue(SVNProperty.LAST_AUTHOR, info.getAuthor());
entry.setPropertyValue(SVNProperty.COMMITTED_DATE, TimeUtil.formatDate(info.getDate()));
entry.setPropertyValue(SVNProperty.UUID, uuid);
if (!keepLocks) {
entry.setPropertyValue(SVNProperty.LOCK_TOKEN, null);
entry.setPropertyValue(SVNProperty.LOCK_OWNER, null);
entry.setPropertyValue(SVNProperty.LOCK_COMMENT, null);
entry.setPropertyValue(SVNProperty.LOCK_CREATION_DATE, null);
}
}
if (parent != null) {
parent.asDirectory().unschedule(entry.getName());
}
DebugLog.log("UPDATE (commit): " + entry.getPath());
entry.commit();
}
private static void updateReplacementSchedule(ISVNEntry entry) throws SVNException {
if (SVNProperty.SCHEDULE_REPLACE.equals(entry.getPropertyValue(SVNProperty.SCHEDULE))) {
entry.setPropertyValue(SVNProperty.SCHEDULE, SVNProperty.SCHEDULE_ADD);
if (entry.isDirectory()) {
for(Iterator children = entry.asDirectory().childEntries(); children.hasNext();) {
updateReplacementSchedule((ISVNEntry) children.next());
}
}
} else if (SVNProperty.SCHEDULE_DELETE.equals(entry.getPropertyValue(SVNProperty.SCHEDULE))) {
entry.setPropertyValue(SVN_ENTRY_REPLACED, "true");
}
}
private static ISVNEntry[] getDirectChildren(Map map, String url) {
Collection children = new ArrayList();
for(Iterator keys = map.keySet().iterator(); keys.hasNext();) {
String childURL = (String) keys.next();
String parentURL = PathUtil.removeTail(childURL);
parentURL = PathUtil.removeLeadingSlash(parentURL);
if (parentURL != null && parentURL.equals(url) && map.get(childURL) != null && !childURL.equals(url)) {
if (!children.contains(map.get(childURL))) {
children.add(map.get(childURL));
}
}
}
return (ISVNEntry[]) children.toArray(new ISVNEntry[children.size()]);
}
private static String[] getVirtualChildren(Map map, String url) {
// if url is root then only return entries with '/'
Collection children = new ArrayList();
for(Iterator keys = map.keySet().iterator(); keys.hasNext();) {
String childURL = (String) keys.next();
if (childURL.startsWith(url) && !childURL.equals(url)) {
childURL = childURL.substring(url.length());
if (!childURL.startsWith("/") && !"".equals(url)) {
// otherwise it may be just a and abc
continue;
}
childURL = PathUtil.removeLeadingSlash(childURL);
String vChild = PathUtil.append(url, PathUtil.head(childURL));
vChild = PathUtil.removeLeadingSlash(vChild);
if (!vChild.equals(url) && map.get(vChild) == null && !children.contains(vChild)) {
children.add(vChild);
}
}
}
return (String[]) children.toArray(new String[children.size()]);
}
}
| false | true | public static void doCommit(String path, String url, Map entries, ISVNEditor editor, SVNWorkspace ws, ISVNProgressViewer progressViewer, Set committedPaths) throws SVNException {
progressViewer = progressViewer == null ? new SVNProgressDummyViewer() : progressViewer;
ISVNEntry root = (ISVNEntry) entries.get(path);
String realPath = path;
if (root != null && root.getAlias() != null) {
path = PathUtil.append(PathUtil.removeTail(path), root.getAlias());
path = PathUtil.removeLeadingSlash(path);
}
long revision = root == null ? -1 : SVNProperty.longValue(root.getPropertyValue(SVNProperty.REVISION));
boolean copied = false;
if (root != null) {
root.setPropertyValue(SVNProperty.COMMITTED_REVISION, null);
copied = Boolean.TRUE.toString().equals(root.getPropertyValue(SVNProperty.COPIED));
}
if ("".equals(realPath) && !copied) {
DebugLog.log("ROOT OPEN: " + path);
editor.openRoot(-1);
if (root != null) {
if (root.sendChangedProperties(editor)) {
ws.fireEntryCommitted(root, SVNStatus.MODIFIED);
}
}
} else if (root != null && (root.isScheduledForAddition() || copied)) {
if ("".equals(realPath)) {
DebugLog.log("ROOT OPEN: " + path);
editor.openRoot(-1);
}
DebugLog.log("DIR ADD: " + path);
String copyFromURL = root.getPropertyValue(SVNProperty.COPYFROM_URL);
long copyFromRevision = -1;
if (copyFromURL != null) {
copyFromURL = SVNRepositoryLocation.parseURL(copyFromURL).toCanonicalForm();
copyFromRevision = Long.parseLong(root.getPropertyValue(SVNProperty.COPYFROM_REVISION));
DebugLog.log("copyfrom path:" + copyFromURL);
DebugLog.log("parent's url: " + url);
copyFromURL = copyFromURL.substring(url.length());
if (!copyFromURL.startsWith("/")) {
copyFromURL = "/" + copyFromURL;
}
DebugLog.log("copyfrom path:" + copyFromURL);
}
// here we could have alias.
editor.addDir(path, copyFromURL, copyFromRevision);
root.sendChangedProperties(editor);
ws.fireEntryCommitted(root, SVNStatus.ADDED);
} else if (root != null && root.isPropertiesModified()) {
DebugLog.log("DIR OPEN: " + path + ", " + revision);
editor.openDir(path, revision);
if (root.sendChangedProperties(editor)) {
ws.fireEntryCommitted(root, SVNStatus.MODIFIED);
}
} else if (root == null) {
DebugLog.log("DIR OPEN (virtual): " + path + ", " + revision);
editor.openDir(path, revision);
}
String[] virtualChildren = getVirtualChildren(entries, realPath);
DebugLog.log("virtual children count: " + virtualChildren.length);
for(int i = 0; i < virtualChildren.length; i++) {
String childPath = virtualChildren[i];
doCommit(childPath, url, entries, editor, ws, progressViewer, committedPaths);
}
ISVNEntry[] children = getDirectChildren(entries, realPath);
DebugLog.log("direct children count: " + children.length);
ISVNEntry parent = null;
for(int i = 0; i < children.length; i++) {
ISVNEntry child = children[i];
if (parent == null) {
parent = ws.locateParentEntry(child.getPath());
}
String childPath = child.getAlias() != null ? PathUtil.append(path, child.getAlias()) :
PathUtil.append(path, child.getName());
String realChildPath = PathUtil.removeLeadingSlash(PathUtil.append(path, child.getName()));
childPath = PathUtil.removeLeadingSlash(childPath);
childPath = PathUtil.removeTrailingSlash(childPath);
revision = SVNProperty.longValue(child.getPropertyValue(SVNProperty.REVISION));
committedPaths.add(childPath);
progressViewer.setProgress((double)committedPaths.size() / (double)entries.keySet().size());
if (child.isScheduledForAddition() && child.isScheduledForDeletion()) {
DebugLog.log("FILE REPLACE: " + childPath);
child.setPropertyValue(SVNProperty.COMMITTED_REVISION, null);
editor.deleteEntry(childPath, revision);
updateReplacementSchedule(child);
if (child.isDirectory()) {
doCommit(childPath, url, entries, editor, ws, progressViewer, committedPaths);
} else {
editor.addFile(childPath, null, -1);
child.sendChangedProperties(editor);
child.asFile().generateDelta(editor);
editor.closeFile(null);
}
ws.fireEntryCommitted(child, SVNStatus.REPLACED);
DebugLog.log("FILE REPLACE: DONE");
} else if (child.isScheduledForDeletion()) {
DebugLog.log("FILE DELETE: " + childPath);
child.setPropertyValue(SVNProperty.COMMITTED_REVISION, null);
if (child.getPropertyValue(SVN_ENTRY_REPLACED) != null) {
DebugLog.log("FILE NOT DELETED, PARENT WAS REPLACED");
} else {
editor.deleteEntry(childPath, revision);
ws.fireEntryCommitted(child, SVNStatus.DELETED);
DebugLog.log("FILE DELETE: DONE");
}
} else if (child.isDirectory()) {
doCommit(realChildPath, url, entries, editor, ws, progressViewer, committedPaths);
} else {
boolean childIsCopied = Boolean.TRUE.toString().equals(child.getPropertyValue(SVNProperty.COPIED));
long copyFromRev = SVNProperty.longValue(child.getPropertyValue(SVNProperty.COPYFROM_REVISION));
String digest = null;
if (childIsCopied && !child.isScheduledForAddition() && copyFromRev >= 0) {
DebugLog.log("FILE COPY: " + childPath);
// first copy it to have in place for modifications if required.
// get copyfrom url and copyfrom rev
String copyFromURL = child.getPropertyValue(SVNProperty.COPYFROM_URL);
if (copyFromURL != null) {
copyFromURL = SVNRepositoryLocation.parseURL(copyFromURL).toCanonicalForm();
DebugLog.log("copyfrom path:" + copyFromURL);
DebugLog.log("parent's url: " + url);
// should be relative to repos root.
copyFromURL = copyFromURL.substring(url.length());
if (!copyFromURL.startsWith("/")) {
copyFromURL = "/" + copyFromURL;
}
DebugLog.log("copyfrom path:" + copyFromURL);
}
editor.addFile(childPath, copyFromURL, copyFromRev);
editor.closeFile(null);
ws.fireEntryCommitted(child, SVNStatus.ADDED);
DebugLog.log("FILE COPY: DONE");
}
if (child.isScheduledForAddition()) {
DebugLog.log("FILE ADD: " + childPath);
child.setPropertyValue(SVNProperty.COMMITTED_REVISION, null);
String copyFromURL = child.getPropertyValue(SVNProperty.COPYFROM_URL);
long copyFromRevision = -1;
if (copyFromURL != null) {
copyFromURL = SVNRepositoryLocation.parseURL(copyFromURL).toCanonicalForm();
copyFromRevision = Long.parseLong(child.getPropertyValue(SVNProperty.COPYFROM_REVISION));
DebugLog.log("copyfrom path:" + copyFromURL);
DebugLog.log("parent's url: " + url);
// should be relative to repos root.
copyFromURL = copyFromURL.substring(url.length());
if (!copyFromURL.startsWith("/")) {
copyFromURL = "/" + copyFromURL;
}
DebugLog.log("copyfrom path:" + copyFromURL);
}
editor.addFile(childPath, copyFromURL, copyFromRevision);
child.sendChangedProperties(editor);
digest = child.asFile().generateDelta(editor);
editor.closeFile(digest);
ws.fireEntryCommitted(child, SVNStatus.ADDED);
DebugLog.log("FILE ADD: DONE");
} else if (child.asFile().isContentsModified() || child.isPropertiesModified()) {
DebugLog.log("FILE COMMIT: " + childPath + " : " + revision);
child.setPropertyValue(SVNProperty.COMMITTED_REVISION, null);
editor.openFile(childPath, revision);
child.sendChangedProperties(editor);
if (child.asFile().isContentsModified()) {
digest = child.asFile().generateDelta(editor);
}
editor.closeFile(digest);
ws.fireEntryCommitted(child, SVNStatus.MODIFIED);
DebugLog.log("FILE COMMIT: DONE: " + digest);
}
}
}
DebugLog.log("DIR CLOSE: " + path);
editor.closeDir();
if ("".equals(realPath) && copied) {
DebugLog.log("DIR CLOSE (ROOT) ");
editor.closeDir();
}
}
| public static void doCommit(String path, String url, Map entries, ISVNEditor editor, SVNWorkspace ws, ISVNProgressViewer progressViewer, Set committedPaths) throws SVNException {
progressViewer = progressViewer == null ? new SVNProgressDummyViewer() : progressViewer;
ISVNEntry root = (ISVNEntry) entries.get(path);
String realPath = path;
if (root != null && root.getAlias() != null) {
path = PathUtil.append(PathUtil.removeTail(path), root.getAlias());
path = PathUtil.removeLeadingSlash(path);
}
long revision = root == null ? -1 : SVNProperty.longValue(root.getPropertyValue(SVNProperty.REVISION));
boolean copied = false;
if (root != null) {
root.setPropertyValue(SVNProperty.COMMITTED_REVISION, null);
copied = Boolean.TRUE.toString().equals(root.getPropertyValue(SVNProperty.COPIED));
}
if ("".equals(realPath) && !copied) {
DebugLog.log("ROOT OPEN: " + path);
editor.openRoot(-1);
if (root != null) {
if (root.sendChangedProperties(editor)) {
ws.fireEntryCommitted(root, SVNStatus.MODIFIED);
}
}
} else if (root != null && (root.isScheduledForAddition() || copied)) {
if ("".equals(realPath)) {
DebugLog.log("ROOT OPEN: " + path);
editor.openRoot(-1);
}
DebugLog.log("DIR ADD: " + path);
String copyFromURL = root.getPropertyValue(SVNProperty.COPYFROM_URL);
long copyFromRevision = -1;
if (copyFromURL != null) {
copyFromURL = SVNRepositoryLocation.parseURL(copyFromURL).toCanonicalForm();
copyFromRevision = Long.parseLong(root.getPropertyValue(SVNProperty.COPYFROM_REVISION));
DebugLog.log("copyfrom path:" + copyFromURL);
DebugLog.log("parent's url: " + url);
copyFromURL = copyFromURL.substring(url.length());
if (!copyFromURL.startsWith("/")) {
copyFromURL = "/" + copyFromURL;
}
DebugLog.log("copyfrom path:" + copyFromURL);
}
// here we could have alias.
editor.addDir(path, copyFromURL, copyFromRevision);
root.sendChangedProperties(editor);
ws.fireEntryCommitted(root, SVNStatus.ADDED);
} else if (root != null && root.isPropertiesModified()) {
DebugLog.log("DIR OPEN: " + path + ", " + revision);
editor.openDir(path, revision);
if (root.sendChangedProperties(editor)) {
ws.fireEntryCommitted(root, SVNStatus.MODIFIED);
}
} else if (root == null) {
DebugLog.log("DIR OPEN (virtual): " + path + ", " + revision);
editor.openDir(path, revision);
}
String[] virtualChildren = getVirtualChildren(entries, realPath);
DebugLog.log("virtual children count: " + virtualChildren.length);
for(int i = 0; i < virtualChildren.length; i++) {
String childPath = virtualChildren[i];
doCommit(childPath, url, entries, editor, ws, progressViewer, committedPaths);
}
ISVNEntry[] children = getDirectChildren(entries, realPath);
DebugLog.log("direct children count: " + children.length);
ISVNEntry parent = null;
for(int i = 0; i < children.length; i++) {
ISVNEntry child = children[i];
if (parent == null) {
parent = ws.locateParentEntry(child.getPath());
}
DebugLog.log("parent path: " + path);
String shortChildName = PathUtil.tail(child.getPropertyValue(SVNProperty.URL));
String childPath = child.getAlias() != null ? PathUtil.append(path, child.getAlias()) :
PathUtil.append(path, shortChildName);
String realChildPath = PathUtil.removeLeadingSlash(PathUtil.append(path, shortChildName));
childPath = PathUtil.removeLeadingSlash(childPath);
childPath = PathUtil.removeTrailingSlash(childPath);
revision = SVNProperty.longValue(child.getPropertyValue(SVNProperty.REVISION));
committedPaths.add(childPath);
progressViewer.setProgress((double)committedPaths.size() / (double)entries.keySet().size());
if (child.isScheduledForAddition() && child.isScheduledForDeletion()) {
DebugLog.log("FILE REPLACE: " + childPath);
child.setPropertyValue(SVNProperty.COMMITTED_REVISION, null);
editor.deleteEntry(childPath, revision);
updateReplacementSchedule(child);
if (child.isDirectory()) {
doCommit(childPath, url, entries, editor, ws, progressViewer, committedPaths);
} else {
editor.addFile(childPath, null, -1);
child.sendChangedProperties(editor);
child.asFile().generateDelta(editor);
editor.closeFile(null);
}
ws.fireEntryCommitted(child, SVNStatus.REPLACED);
DebugLog.log("FILE REPLACE: DONE");
} else if (child.isScheduledForDeletion()) {
DebugLog.log("FILE DELETE: " + childPath);
child.setPropertyValue(SVNProperty.COMMITTED_REVISION, null);
if (child.getPropertyValue(SVN_ENTRY_REPLACED) != null) {
DebugLog.log("FILE NOT DELETED, PARENT WAS REPLACED");
} else {
editor.deleteEntry(childPath, revision);
ws.fireEntryCommitted(child, SVNStatus.DELETED);
DebugLog.log("FILE DELETE: DONE");
}
} else if (child.isDirectory()) {
doCommit(realChildPath, url, entries, editor, ws, progressViewer, committedPaths);
} else {
boolean childIsCopied = Boolean.TRUE.toString().equals(child.getPropertyValue(SVNProperty.COPIED));
long copyFromRev = SVNProperty.longValue(child.getPropertyValue(SVNProperty.COPYFROM_REVISION));
String digest = null;
if (childIsCopied && !child.isScheduledForAddition() && copyFromRev >= 0) {
DebugLog.log("FILE COPY: " + childPath);
// first copy it to have in place for modifications if required.
// get copyfrom url and copyfrom rev
String copyFromURL = child.getPropertyValue(SVNProperty.COPYFROM_URL);
if (copyFromURL != null) {
copyFromURL = SVNRepositoryLocation.parseURL(copyFromURL).toCanonicalForm();
DebugLog.log("copyfrom path:" + copyFromURL);
DebugLog.log("parent's url: " + url);
// should be relative to repos root.
copyFromURL = copyFromURL.substring(url.length());
if (!copyFromURL.startsWith("/")) {
copyFromURL = "/" + copyFromURL;
}
DebugLog.log("copyfrom path:" + copyFromURL);
}
editor.addFile(childPath, copyFromURL, copyFromRev);
editor.closeFile(null);
ws.fireEntryCommitted(child, SVNStatus.ADDED);
DebugLog.log("FILE COPY: DONE");
}
if (child.isScheduledForAddition()) {
DebugLog.log("FILE ADD: " + childPath);
child.setPropertyValue(SVNProperty.COMMITTED_REVISION, null);
String copyFromURL = child.getPropertyValue(SVNProperty.COPYFROM_URL);
long copyFromRevision = -1;
if (copyFromURL != null) {
copyFromURL = SVNRepositoryLocation.parseURL(copyFromURL).toCanonicalForm();
copyFromRevision = Long.parseLong(child.getPropertyValue(SVNProperty.COPYFROM_REVISION));
DebugLog.log("copyfrom path:" + copyFromURL);
DebugLog.log("parent's url: " + url);
// should be relative to repos root.
copyFromURL = copyFromURL.substring(url.length());
if (!copyFromURL.startsWith("/")) {
copyFromURL = "/" + copyFromURL;
}
DebugLog.log("copyfrom path:" + copyFromURL);
}
editor.addFile(childPath, copyFromURL, copyFromRevision);
child.sendChangedProperties(editor);
digest = child.asFile().generateDelta(editor);
editor.closeFile(digest);
ws.fireEntryCommitted(child, SVNStatus.ADDED);
DebugLog.log("FILE ADD: DONE");
} else if (child.asFile().isContentsModified() || child.isPropertiesModified()) {
DebugLog.log("FILE COMMIT: " + childPath + " : " + revision);
child.setPropertyValue(SVNProperty.COMMITTED_REVISION, null);
editor.openFile(childPath, revision);
child.sendChangedProperties(editor);
if (child.asFile().isContentsModified()) {
digest = child.asFile().generateDelta(editor);
}
editor.closeFile(digest);
ws.fireEntryCommitted(child, SVNStatus.MODIFIED);
DebugLog.log("FILE COMMIT: DONE: " + digest);
}
}
}
DebugLog.log("DIR CLOSE: " + path);
editor.closeDir();
if ("".equals(realPath) && copied) {
DebugLog.log("DIR CLOSE (ROOT) ");
editor.closeDir();
}
}
|
diff --git a/src/main/java/org/bukkit/ChatColor.java b/src/main/java/org/bukkit/ChatColor.java
index 834bcc68..06540b2c 100644
--- a/src/main/java/org/bukkit/ChatColor.java
+++ b/src/main/java/org/bukkit/ChatColor.java
@@ -1,126 +1,126 @@
package org.bukkit;
import java.util.HashMap;
import java.util.Map;
/**
* All supported color values for chat
*/
public enum ChatColor {
/**
* Represents black
*/
BLACK(0x0),
/**
* Represents dark blue
*/
DARK_BLUE(0x1),
/**
* Represents dark green
*/
DARK_GREEN(0x2),
/**
* Represents dark blue (aqua)
*/
DARK_AQUA(0x3),
/**
* Represents dark red
*/
DARK_RED(0x4),
/**
* Represents dark purple
*/
DARK_PURPLE(0x5),
/**
* Represents gold
*/
GOLD(0x6),
/**
* Represents gray
*/
GRAY(0x7),
/**
* Represents dark gray
*/
DARK_GRAY(0x8),
/**
* Represents blue
*/
BLUE(0x9),
/**
* Represents green
*/
GREEN(0xA),
/**
* Represents aqua
*/
AQUA(0xB),
/**
* Represents red
*/
RED(0xC),
/**
* Represents light purple
*/
LIGHT_PURPLE(0xD),
/**
* Represents yellow
*/
YELLOW(0xE),
/**
* Represents white
*/
WHITE(0xF);
private final int code;
private final static Map<Integer, ChatColor> colors = new HashMap<Integer, ChatColor>();
private ChatColor(final int code) {
this.code = code;
}
/**
* Gets the data value associated with this color
*
* @return An integer value of this color code
*/
public int getCode() {
return code;
}
@Override
public String toString() {
return String.format("\u00A7%x", code);
}
/**
* Gets the color represented by the specified color code
*
* @param code Code to check
* @return Associative {@link org.bukkit.ChatColor} with the given code, or null if it doesn't exist
*/
public static ChatColor getByCode(final int code) {
return colors.get(code);
}
/**
* Strips the given message of all color codes
*
* @param input String to strip of color
* @return A copy of the input string, without any coloring
*/
public static String stripColor(final String input) {
if (input == null) {
return null;
}
- return input.replaceAll("(?i)\u00A7[0-F]", "");
+ return input.replaceAll("(?i)\u00A7[0-9A-F]", "");
}
static {
for (ChatColor color : ChatColor.values()) {
colors.put(color.getCode(), color);
}
}
}
| true | true | public static String stripColor(final String input) {
if (input == null) {
return null;
}
return input.replaceAll("(?i)\u00A7[0-F]", "");
}
| public static String stripColor(final String input) {
if (input == null) {
return null;
}
return input.replaceAll("(?i)\u00A7[0-9A-F]", "");
}
|
diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/util/CVSDateFormatter.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/util/CVSDateFormatter.java
index 26354b589..c75025842 100644
--- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/util/CVSDateFormatter.java
+++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/util/CVSDateFormatter.java
@@ -1,104 +1,106 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.team.internal.ccvs.core.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
/**
* Utility class for converting timestamps used in Entry file lines. The format
* required in the Entry file is ISO C asctime() function (Sun Apr 7 01:29:26 1996).
* <p>
* To be compatible with asctime(), the day field in the entryline format is
* padded with a space and not a zero. Most other CVS clients use string comparison
* for timestamps based on the result of the C function asctime().
* </p>
*/
public class CVSDateFormatter {
private static final String ENTRYLINE_FORMAT = "E MMM dd HH:mm:ss yyyy"; //$NON-NLS-1$
private static final String SERVER_FORMAT = "dd MMM yyyy HH:mm:ss";//$NON-NLS-1$
private static final int ENTRYLINE_TENS_DAY_OFFSET = 8;
private static final SimpleDateFormat serverFormat = new SimpleDateFormat(SERVER_FORMAT, Locale.US);
private static SimpleDateFormat entryLineFormat = new SimpleDateFormat(ENTRYLINE_FORMAT, Locale.US);
static {
entryLineFormat.setTimeZone(TimeZone.getTimeZone("GMT")); //$NON-NLS-1$
}
static synchronized public Date serverStampToDate(String text) throws ParseException {
serverFormat.setTimeZone(getTimeZone(text));
Date date = serverFormat.parse(text);
return date;
}
static synchronized public String dateToServerStamp(Date date) {
serverFormat.setTimeZone(TimeZone.getTimeZone("GMT"));//$NON-NLS-1$
return serverFormat.format(date) + " -0000"; //$NON-NLS-1$
}
static synchronized public Date entryLineToDate(String text) throws ParseException {
try {
if (text.charAt(ENTRYLINE_TENS_DAY_OFFSET) == ' ') {
StringBuffer buf = new StringBuffer(text);
buf.setCharAt(ENTRYLINE_TENS_DAY_OFFSET, '0');
text = buf.toString();
}
} catch (StringIndexOutOfBoundsException e) {
throw new ParseException(e.getMessage(), ENTRYLINE_TENS_DAY_OFFSET);
}
return entryLineFormat.parse(text);
}
static synchronized public String dateToEntryLine(Date date) {
if (date == null) return ""; //$NON-NLS-1$
String passOne = entryLineFormat.format(date);
if (passOne.charAt(ENTRYLINE_TENS_DAY_OFFSET) != '0') return passOne;
StringBuffer passTwo = new StringBuffer(passOne);
passTwo.setCharAt(ENTRYLINE_TENS_DAY_OFFSET, ' ');
return passTwo.toString();
}
static synchronized public String dateToNotifyServer(Date date) {
serverFormat.setTimeZone(TimeZone.getTimeZone("GMT"));//$NON-NLS-1$
return serverFormat.format(date) + " GMT"; //$NON-NLS-1$
}
/*
* Converts timezone text from date string from CVS server and
* returns a timezone representing the received timezone.
* Timezone string is of the following format: [-|+]MMSS
*/
static private TimeZone getTimeZone(String dateFromServer) {
+ if (dateFromServer.lastIndexOf("0000") != -1) //$NON-NLS-1$
+ return TimeZone.getTimeZone("GMT");//$NON-NLS-1$
String tz = null;
StringBuffer resultTz = new StringBuffer("GMT");//$NON-NLS-1$
if (dateFromServer.indexOf("-") != -1) {//$NON-NLS-1$
resultTz.append("-");//$NON-NLS-1$
tz = dateFromServer.substring(dateFromServer.indexOf("-"));//$NON-NLS-1$
} else if (dateFromServer.indexOf("+") != -1) {//$NON-NLS-1$
resultTz.append('+');
tz = dateFromServer.substring(dateFromServer.indexOf("+"));//$NON-NLS-1$
}
try {
if(tz!=null) {
resultTz.append(tz.substring(1, 3) /*hours*/ + ":" + tz.substring(3, 5) /*minutes*/);//$NON-NLS-1$
return TimeZone.getTimeZone(resultTz.toString());
}
} catch(IndexOutOfBoundsException e) {
return TimeZone.getTimeZone("GMT");//$NON-NLS-1$
}
return TimeZone.getTimeZone("GMT");//$NON-NLS-1$
}
}
| true | true | static private TimeZone getTimeZone(String dateFromServer) {
String tz = null;
StringBuffer resultTz = new StringBuffer("GMT");//$NON-NLS-1$
if (dateFromServer.indexOf("-") != -1) {//$NON-NLS-1$
resultTz.append("-");//$NON-NLS-1$
tz = dateFromServer.substring(dateFromServer.indexOf("-"));//$NON-NLS-1$
} else if (dateFromServer.indexOf("+") != -1) {//$NON-NLS-1$
resultTz.append('+');
tz = dateFromServer.substring(dateFromServer.indexOf("+"));//$NON-NLS-1$
}
try {
if(tz!=null) {
resultTz.append(tz.substring(1, 3) /*hours*/ + ":" + tz.substring(3, 5) /*minutes*/);//$NON-NLS-1$
return TimeZone.getTimeZone(resultTz.toString());
}
} catch(IndexOutOfBoundsException e) {
return TimeZone.getTimeZone("GMT");//$NON-NLS-1$
}
return TimeZone.getTimeZone("GMT");//$NON-NLS-1$
}
| static private TimeZone getTimeZone(String dateFromServer) {
if (dateFromServer.lastIndexOf("0000") != -1) //$NON-NLS-1$
return TimeZone.getTimeZone("GMT");//$NON-NLS-1$
String tz = null;
StringBuffer resultTz = new StringBuffer("GMT");//$NON-NLS-1$
if (dateFromServer.indexOf("-") != -1) {//$NON-NLS-1$
resultTz.append("-");//$NON-NLS-1$
tz = dateFromServer.substring(dateFromServer.indexOf("-"));//$NON-NLS-1$
} else if (dateFromServer.indexOf("+") != -1) {//$NON-NLS-1$
resultTz.append('+');
tz = dateFromServer.substring(dateFromServer.indexOf("+"));//$NON-NLS-1$
}
try {
if(tz!=null) {
resultTz.append(tz.substring(1, 3) /*hours*/ + ":" + tz.substring(3, 5) /*minutes*/);//$NON-NLS-1$
return TimeZone.getTimeZone(resultTz.toString());
}
} catch(IndexOutOfBoundsException e) {
return TimeZone.getTimeZone("GMT");//$NON-NLS-1$
}
return TimeZone.getTimeZone("GMT");//$NON-NLS-1$
}
|
diff --git a/src/com/android/phone/InCallControlState.java b/src/com/android/phone/InCallControlState.java
index 00f14622..5469cfbd 100644
--- a/src/com/android/phone/InCallControlState.java
+++ b/src/com/android/phone/InCallControlState.java
@@ -1,187 +1,187 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.phone;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import com.android.internal.telephony.Call;
import com.android.internal.telephony.Connection;
import com.android.internal.telephony.Phone;
/**
* Helper class to keep track of enabledness, visibility, and "on/off"
* or "checked" state of the various controls available in the in-call
* UI, based on the current telephony state.
*
* This class is independent of the exact UI controls used on any given
* device. (Some devices use onscreen touchable buttons, for example, and
* other devices use menu items.) To avoid cluttering up the InCallMenu
* and InCallTouchUi code with logic about which functions are available
* right now, we instead have that logic here, and provide simple boolean
* flags to indicate the state and/or enabledness of all possible in-call
* user operations.
*
* (In other words, this is the "model" that corresponds to the "view"
* implemented by InCallMenu and InCallTouchUi.)
*/
public class InCallControlState {
private static final String LOG_TAG = "InCallControlState";
private static final boolean DBG = (PhoneApp.DBG_LEVEL >= 2);
private InCallScreen mInCallScreen;
private Phone mPhone;
//
// Our "public API": Boolean flags to indicate the state and/or
// enabledness of all possible in-call user operations:
//
public boolean manageConferenceVisible;
public boolean manageConferenceEnabled;
//
public boolean canAddCall;
//
public boolean canSwap;
public boolean canMerge;
//
public boolean bluetoothEnabled;
public boolean bluetoothIndicatorOn;
//
public boolean speakerEnabled;
public boolean speakerOn;
//
public boolean canMute;
public boolean muteIndicatorOn;
//
public boolean dialpadEnabled;
//
public boolean onHold;
public boolean canHold;
public InCallControlState(InCallScreen inCallScreen, Phone phone) {
if (DBG) log("InCallControlState constructor...");
mInCallScreen = inCallScreen;
mPhone = phone;
}
/**
* Updates all our public boolean flags based on the current state of
* the Phone.
*/
public void update() {
final boolean hasRingingCall = !mPhone.getRingingCall().isIdle();
final Call fgCall = mPhone.getForegroundCall();
final Call.State fgCallState = fgCall.getState();
final boolean hasActiveCall = !fgCall.isIdle();
final boolean hasHoldingCall = !mPhone.getBackgroundCall().isIdle();
// Manage conference: visible only if the foreground call is a
// conference call. Enabled unless the "Manage conference" UI is
// already up.
manageConferenceVisible = PhoneUtils.isConferenceCall(fgCall);
manageConferenceEnabled = !mInCallScreen.isManageConferenceMode();
// "Add call":
canAddCall = PhoneUtils.okToAddCall(mPhone);
// Swap / merge calls
canSwap = PhoneUtils.okToSwapCalls(mPhone);
canMerge = PhoneUtils.okToMergeCalls(mPhone);
// "Bluetooth":
if (mInCallScreen.isBluetoothAvailable()) {
bluetoothEnabled = true;
bluetoothIndicatorOn = mInCallScreen.isBluetoothAudioConnectedOrPending();
} else {
bluetoothEnabled = false;
bluetoothIndicatorOn = false;
}
// "Speaker": Disabled if a wired headset is plugged in,
// otherwise enabled. The current speaker state comes from
// the AudioManager.
if (PhoneApp.getInstance().isHeadsetPlugged()) {
// Wired headset is present; Speaker button is meaningless.
speakerEnabled = false;
speakerOn = false;
} else {
// No wired headset; Speaker button is enabled and behaves normally.
speakerEnabled = true;
speakerOn = PhoneUtils.isSpeakerOn(mInCallScreen);
}
// "Mute": only enabled when the foreground call is ACTIVE.
// (It's meaningless while on hold, or while DIALING/ALERTING.)
// Also disabled (on CDMA devices) during emergency calls.
if (mPhone.getPhoneName().equals("CDMA")) {
Connection c = fgCall.getLatestConnection();
- boolean isEmergencyCall =
- PhoneNumberUtils.isEmergencyNumber(c.getAddress());
+ boolean isEmergencyCall = false;
+ if (c != null) isEmergencyCall = PhoneNumberUtils.isEmergencyNumber(c.getAddress());
if (isEmergencyCall) { // disable "Mute" item
canMute = false;
muteIndicatorOn = false;
} else {
canMute = (fgCallState == Call.State.ACTIVE);
muteIndicatorOn = PhoneUtils.getMute(mPhone);
}
} else {
canMute = (fgCallState == Call.State.ACTIVE);
muteIndicatorOn = PhoneUtils.getMute(mPhone);
}
// "Dialpad": Enabled only when it's OK to use the dialpad in the
// first place.
dialpadEnabled = mInCallScreen.okToShowDialpad();
// "Hold": "On hold" means that there's a holding call and
// *no* foreground call. (If there *is* a foreground call,
// that's "two lines in use".) "Hold" is disabled if both
// lines are in use, or if the foreground call is non-idle and
// in any state other than ACTIVE.
onHold = hasHoldingCall && !hasActiveCall;
canHold = !((hasActiveCall && hasHoldingCall)
|| (hasActiveCall && (fgCallState != Call.State.ACTIVE)));
if (DBG) dumpState();
}
public void dumpState() {
log("InCallControlState:");
log(" manageConferenceVisible: " + manageConferenceVisible);
log(" manageConferenceEnabled: " + manageConferenceEnabled);
log(" canAddCall: " + canAddCall);
log(" canSwap: " + canSwap);
log(" canMerge: " + canMerge);
log(" bluetoothEnabled: " + bluetoothEnabled);
log(" bluetoothIndicatorOn: " + bluetoothIndicatorOn);
log(" speakerEnabled: " + speakerEnabled);
log(" speakerOn: " + speakerOn);
log(" canMute: " + canMute);
log(" muteIndicatorOn: " + muteIndicatorOn);
log(" dialpadEnabled: " + dialpadEnabled);
log(" onHold: " + onHold);
log(" canHold: " + canHold);
}
private void log(String msg) {
Log.d(LOG_TAG, msg);
}
}
| true | true | public void update() {
final boolean hasRingingCall = !mPhone.getRingingCall().isIdle();
final Call fgCall = mPhone.getForegroundCall();
final Call.State fgCallState = fgCall.getState();
final boolean hasActiveCall = !fgCall.isIdle();
final boolean hasHoldingCall = !mPhone.getBackgroundCall().isIdle();
// Manage conference: visible only if the foreground call is a
// conference call. Enabled unless the "Manage conference" UI is
// already up.
manageConferenceVisible = PhoneUtils.isConferenceCall(fgCall);
manageConferenceEnabled = !mInCallScreen.isManageConferenceMode();
// "Add call":
canAddCall = PhoneUtils.okToAddCall(mPhone);
// Swap / merge calls
canSwap = PhoneUtils.okToSwapCalls(mPhone);
canMerge = PhoneUtils.okToMergeCalls(mPhone);
// "Bluetooth":
if (mInCallScreen.isBluetoothAvailable()) {
bluetoothEnabled = true;
bluetoothIndicatorOn = mInCallScreen.isBluetoothAudioConnectedOrPending();
} else {
bluetoothEnabled = false;
bluetoothIndicatorOn = false;
}
// "Speaker": Disabled if a wired headset is plugged in,
// otherwise enabled. The current speaker state comes from
// the AudioManager.
if (PhoneApp.getInstance().isHeadsetPlugged()) {
// Wired headset is present; Speaker button is meaningless.
speakerEnabled = false;
speakerOn = false;
} else {
// No wired headset; Speaker button is enabled and behaves normally.
speakerEnabled = true;
speakerOn = PhoneUtils.isSpeakerOn(mInCallScreen);
}
// "Mute": only enabled when the foreground call is ACTIVE.
// (It's meaningless while on hold, or while DIALING/ALERTING.)
// Also disabled (on CDMA devices) during emergency calls.
if (mPhone.getPhoneName().equals("CDMA")) {
Connection c = fgCall.getLatestConnection();
boolean isEmergencyCall =
PhoneNumberUtils.isEmergencyNumber(c.getAddress());
if (isEmergencyCall) { // disable "Mute" item
canMute = false;
muteIndicatorOn = false;
} else {
canMute = (fgCallState == Call.State.ACTIVE);
muteIndicatorOn = PhoneUtils.getMute(mPhone);
}
} else {
canMute = (fgCallState == Call.State.ACTIVE);
muteIndicatorOn = PhoneUtils.getMute(mPhone);
}
// "Dialpad": Enabled only when it's OK to use the dialpad in the
// first place.
dialpadEnabled = mInCallScreen.okToShowDialpad();
// "Hold": "On hold" means that there's a holding call and
// *no* foreground call. (If there *is* a foreground call,
// that's "two lines in use".) "Hold" is disabled if both
// lines are in use, or if the foreground call is non-idle and
// in any state other than ACTIVE.
onHold = hasHoldingCall && !hasActiveCall;
canHold = !((hasActiveCall && hasHoldingCall)
|| (hasActiveCall && (fgCallState != Call.State.ACTIVE)));
if (DBG) dumpState();
}
| public void update() {
final boolean hasRingingCall = !mPhone.getRingingCall().isIdle();
final Call fgCall = mPhone.getForegroundCall();
final Call.State fgCallState = fgCall.getState();
final boolean hasActiveCall = !fgCall.isIdle();
final boolean hasHoldingCall = !mPhone.getBackgroundCall().isIdle();
// Manage conference: visible only if the foreground call is a
// conference call. Enabled unless the "Manage conference" UI is
// already up.
manageConferenceVisible = PhoneUtils.isConferenceCall(fgCall);
manageConferenceEnabled = !mInCallScreen.isManageConferenceMode();
// "Add call":
canAddCall = PhoneUtils.okToAddCall(mPhone);
// Swap / merge calls
canSwap = PhoneUtils.okToSwapCalls(mPhone);
canMerge = PhoneUtils.okToMergeCalls(mPhone);
// "Bluetooth":
if (mInCallScreen.isBluetoothAvailable()) {
bluetoothEnabled = true;
bluetoothIndicatorOn = mInCallScreen.isBluetoothAudioConnectedOrPending();
} else {
bluetoothEnabled = false;
bluetoothIndicatorOn = false;
}
// "Speaker": Disabled if a wired headset is plugged in,
// otherwise enabled. The current speaker state comes from
// the AudioManager.
if (PhoneApp.getInstance().isHeadsetPlugged()) {
// Wired headset is present; Speaker button is meaningless.
speakerEnabled = false;
speakerOn = false;
} else {
// No wired headset; Speaker button is enabled and behaves normally.
speakerEnabled = true;
speakerOn = PhoneUtils.isSpeakerOn(mInCallScreen);
}
// "Mute": only enabled when the foreground call is ACTIVE.
// (It's meaningless while on hold, or while DIALING/ALERTING.)
// Also disabled (on CDMA devices) during emergency calls.
if (mPhone.getPhoneName().equals("CDMA")) {
Connection c = fgCall.getLatestConnection();
boolean isEmergencyCall = false;
if (c != null) isEmergencyCall = PhoneNumberUtils.isEmergencyNumber(c.getAddress());
if (isEmergencyCall) { // disable "Mute" item
canMute = false;
muteIndicatorOn = false;
} else {
canMute = (fgCallState == Call.State.ACTIVE);
muteIndicatorOn = PhoneUtils.getMute(mPhone);
}
} else {
canMute = (fgCallState == Call.State.ACTIVE);
muteIndicatorOn = PhoneUtils.getMute(mPhone);
}
// "Dialpad": Enabled only when it's OK to use the dialpad in the
// first place.
dialpadEnabled = mInCallScreen.okToShowDialpad();
// "Hold": "On hold" means that there's a holding call and
// *no* foreground call. (If there *is* a foreground call,
// that's "two lines in use".) "Hold" is disabled if both
// lines are in use, or if the foreground call is non-idle and
// in any state other than ACTIVE.
onHold = hasHoldingCall && !hasActiveCall;
canHold = !((hasActiveCall && hasHoldingCall)
|| (hasActiveCall && (fgCallState != Call.State.ACTIVE)));
if (DBG) dumpState();
}
|
diff --git a/netbeans-virgo-server-support/src/th/co/geniustree/virgo/server/api/Deployer.java b/netbeans-virgo-server-support/src/th/co/geniustree/virgo/server/api/Deployer.java
index 48b323f..ba33873 100644
--- a/netbeans-virgo-server-support/src/th/co/geniustree/virgo/server/api/Deployer.java
+++ b/netbeans-virgo-server-support/src/th/co/geniustree/virgo/server/api/Deployer.java
@@ -1,127 +1,127 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package th.co.geniustree.virgo.server.api;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.management.remote.JMXConnector;
import javax.swing.SwingUtilities;
import th.co.geniustree.virgo.server.JmxConnectorHelper;
import th.co.geniustree.virgo.server.VirgoServerInstanceImplementation;
/**
*
* @author pramoth
*/
public class Deployer {
private final VirgoServerInstanceImplementation instance;
public Deployer(VirgoServerInstanceImplementation instance) {
this.instance = instance;
}
public void deploy(File file, boolean recoverable) throws Exception {
if (SwingUtilities.isEventDispatchThread()) {
throw new IllegalStateException("Can't call in EDT.");
}
JMXConnector connector = null;
try {
connector = JmxConnectorHelper.createConnector(instance.getAttr());
} catch (IOException iOException) {
StartCommand startCommand = instance.getLookup().lookup(StartCommand.class);
if (startCommand != null) {
- connector = startCommand.startAndWait(true);
+ connector = startCommand.startAndWait(false);
}
}
if (connector != null) {
try {
MBeanServerConnection mBeanServerConnection = connector.getMBeanServerConnection();
ObjectName name = new ObjectName(Constants.MBEAN_DEPLOYER);
Object[] params = {file.toURI().toString(), recoverable};
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Deploy {0} ", new String[]{file.toURI().toString()});
String[] signature = {"java.lang.String", "boolean"};
// invoke the execute method of the Deployer MBean
mBeanServerConnection.invoke(name, "deploy", params, signature);
} catch (IOException iOException) {
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Can't connect Virgo JMX.", iOException);
instance.stoped();
} catch (MalformedObjectNameException malformedObjectNameException) {
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Can't connect Virgo JMX.", malformedObjectNameException);
instance.stoped();
} catch (InstanceNotFoundException instanceNotFoundException) {
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Can't connect Virgo JMX.", instanceNotFoundException);
instance.stoped();
} catch (MBeanException mBeanException) {
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Operation fail..", mBeanException);
} catch (ReflectionException reflectionException) {
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Operation fail..", reflectionException);
} finally {
JmxConnectorHelper.silentClose(connector);
}
} else {
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Can't connect Virgo JMX.");
}
}
public void undeploy(String simbolicname, String bundleVersion) {
if (SwingUtilities.isEventDispatchThread()) {
throw new IllegalStateException("Ca'nt call in EDT.");
}
JMXConnector connector = null;
try {
connector = JmxConnectorHelper.createConnector(instance.getAttr());
MBeanServerConnection mBeanServerConnection = connector.getMBeanServerConnection();
ObjectName name = new ObjectName(Constants.MBEAN_DEPLOYER);
Object[] params = {simbolicname, bundleVersion};
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Undeploy {0} ;version={1}", new String[]{simbolicname, bundleVersion});
String[] signature = {"java.lang.String", "java.lang.String"};
try {
// invoke the execute method of the Deployer MBean
mBeanServerConnection.invoke(name, "undeploy", params, signature);
} catch (Exception ex) {
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Can't undeploy bundle {0} ;version={1}", new String[]{simbolicname, bundleVersion});
}
} catch (Exception ex) {
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Can't connect Virgo JMX.", ex);
} finally {
JmxConnectorHelper.silentClose(connector);
}
}
public void refresh(File file, String bundleVersion) {
if (SwingUtilities.isEventDispatchThread()) {
throw new IllegalStateException("Ca'nt call in EDT.");
}
JMXConnector connector = null;
try {
connector = JmxConnectorHelper.createConnector(instance.getAttr());
MBeanServerConnection mBeanServerConnection = connector.getMBeanServerConnection();
ObjectName name = new ObjectName(Constants.MBEAN_DEPLOYER);
Object[] params = {file.toURI().toString(), bundleVersion};
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Refresh {0} ;version={1}", new String[]{file.toURI().toString(), bundleVersion});
String[] signature = {"java.lang.String", "java.lang.String"};
try {
// invoke the execute method of the Deployer MBean
mBeanServerConnection.invoke(name, "refresh", params, signature);
} catch (Exception ex) {
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Can't refresh bundle {0} ;version={1}", new String[]{file.toURI().toString(), bundleVersion});
}
} catch (Exception ex) {
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Can't connect Virgo JMX.", ex);
} finally {
JmxConnectorHelper.silentClose(connector);
}
}
}
| true | true | public void deploy(File file, boolean recoverable) throws Exception {
if (SwingUtilities.isEventDispatchThread()) {
throw new IllegalStateException("Can't call in EDT.");
}
JMXConnector connector = null;
try {
connector = JmxConnectorHelper.createConnector(instance.getAttr());
} catch (IOException iOException) {
StartCommand startCommand = instance.getLookup().lookup(StartCommand.class);
if (startCommand != null) {
connector = startCommand.startAndWait(true);
}
}
if (connector != null) {
try {
MBeanServerConnection mBeanServerConnection = connector.getMBeanServerConnection();
ObjectName name = new ObjectName(Constants.MBEAN_DEPLOYER);
Object[] params = {file.toURI().toString(), recoverable};
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Deploy {0} ", new String[]{file.toURI().toString()});
String[] signature = {"java.lang.String", "boolean"};
// invoke the execute method of the Deployer MBean
mBeanServerConnection.invoke(name, "deploy", params, signature);
} catch (IOException iOException) {
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Can't connect Virgo JMX.", iOException);
instance.stoped();
} catch (MalformedObjectNameException malformedObjectNameException) {
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Can't connect Virgo JMX.", malformedObjectNameException);
instance.stoped();
} catch (InstanceNotFoundException instanceNotFoundException) {
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Can't connect Virgo JMX.", instanceNotFoundException);
instance.stoped();
} catch (MBeanException mBeanException) {
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Operation fail..", mBeanException);
} catch (ReflectionException reflectionException) {
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Operation fail..", reflectionException);
} finally {
JmxConnectorHelper.silentClose(connector);
}
} else {
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Can't connect Virgo JMX.");
}
}
| public void deploy(File file, boolean recoverable) throws Exception {
if (SwingUtilities.isEventDispatchThread()) {
throw new IllegalStateException("Can't call in EDT.");
}
JMXConnector connector = null;
try {
connector = JmxConnectorHelper.createConnector(instance.getAttr());
} catch (IOException iOException) {
StartCommand startCommand = instance.getLookup().lookup(StartCommand.class);
if (startCommand != null) {
connector = startCommand.startAndWait(false);
}
}
if (connector != null) {
try {
MBeanServerConnection mBeanServerConnection = connector.getMBeanServerConnection();
ObjectName name = new ObjectName(Constants.MBEAN_DEPLOYER);
Object[] params = {file.toURI().toString(), recoverable};
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Deploy {0} ", new String[]{file.toURI().toString()});
String[] signature = {"java.lang.String", "boolean"};
// invoke the execute method of the Deployer MBean
mBeanServerConnection.invoke(name, "deploy", params, signature);
} catch (IOException iOException) {
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Can't connect Virgo JMX.", iOException);
instance.stoped();
} catch (MalformedObjectNameException malformedObjectNameException) {
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Can't connect Virgo JMX.", malformedObjectNameException);
instance.stoped();
} catch (InstanceNotFoundException instanceNotFoundException) {
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Can't connect Virgo JMX.", instanceNotFoundException);
instance.stoped();
} catch (MBeanException mBeanException) {
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Operation fail..", mBeanException);
} catch (ReflectionException reflectionException) {
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Operation fail..", reflectionException);
} finally {
JmxConnectorHelper.silentClose(connector);
}
} else {
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Can't connect Virgo JMX.");
}
}
|
diff --git a/src/test/java/com/salesforce/phoenix/schema/PDataTypeTest.java b/src/test/java/com/salesforce/phoenix/schema/PDataTypeTest.java
index da86ad0c..23822aab 100644
--- a/src/test/java/com/salesforce/phoenix/schema/PDataTypeTest.java
+++ b/src/test/java/com/salesforce/phoenix/schema/PDataTypeTest.java
@@ -1,299 +1,299 @@
/*******************************************************************************
* Copyright (c) 2013, Salesforce.com, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of Salesforce.com nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package com.salesforce.phoenix.schema;
import static org.junit.Assert.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Test;
import com.salesforce.phoenix.util.TestUtil;
public class PDataTypeTest {
@Test
public void testLong() {
Long la = 4L;
byte[] b = PDataType.LONG.toBytes(la);
Long lb = (Long)PDataType.LONG.toObject(b);
assertEquals(la,lb);
Long na = 1L;
Long nb = -1L;
byte[] ba = PDataType.LONG.toBytes(na);
byte[] bb = PDataType.LONG.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
}
@Test
public void testInt() {
Integer na = 4;
byte[] b = PDataType.INTEGER.toBytes(na);
Integer nb = (Integer)PDataType.INTEGER.toObject(b);
assertEquals(na,nb);
na = 1;
nb = -1;
byte[] ba = PDataType.INTEGER.toBytes(na);
byte[] bb = PDataType.INTEGER.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
na = -1;
nb = -3;
ba = PDataType.INTEGER.toBytes(na);
bb = PDataType.INTEGER.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
na = -3;
nb = -100000000;
ba = PDataType.INTEGER.toBytes(na);
bb = PDataType.INTEGER.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
}
@Test
public void testBigDecimal() {
byte[] b;
BigDecimal na, nb;
b = new byte[] {
(byte)0xc2,0x02,0x10,0x36,0x22,0x22,0x22,0x22,0x22,0x22,0x0f,0x27,0x38,0x1c,0x05,0x40,0x62,0x21,0x54,0x4d,0x4e,0x01,0x14,0x36,0x0d,0x33
};
BigDecimal decodedBytes = (BigDecimal)PDataType.DECIMAL.toObject(b);
assertTrue(decodedBytes.compareTo(BigDecimal.ZERO) > 0);
na = new BigDecimal(new BigInteger("12345678901239998123456789"), 2);
//[-52, 13, 35, 57, 79, 91, 13, 40, 100, 82, 24, 46, 68, 90]
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
TestUtil.assertRoundEquals(na,nb);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
na = new BigDecimal("115.533333333333331438552704639732837677001953125");
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
TestUtil.assertRoundEquals(na,nb);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
na = new BigDecimal(2.5);
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
assertTrue(na.compareTo(nb) == 0);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
// If we don't remove trailing zeros, this fails
na = new BigDecimal(Double.parseDouble("96.45238095238095"));
String naStr = na.toString();
assertTrue(naStr != null);
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
TestUtil.assertRoundEquals(na,nb);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
// If we don't remove trailing zeros, this fails
na = new BigDecimal(-1000);
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
assertTrue(na.compareTo(nb) == 0);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
na = TestUtil.computeAverage(11000, 3);
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
assertTrue(na.compareTo(nb) == 0);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
na = new BigDecimal(new BigInteger("12345678901239999"), 2);
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
assertTrue(na.compareTo(nb) == 0);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
na = new BigDecimal(1);
nb = new BigDecimal(-1);
byte[] ba = PDataType.DECIMAL.toBytes(na);
byte[] bb = PDataType.DECIMAL.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
assertTrue(ba.length <= PDataType.DECIMAL.estimateByteSize(na));
assertTrue(bb.length <= PDataType.DECIMAL.estimateByteSize(nb));
na = new BigDecimal(-1);
nb = new BigDecimal(-2);
ba = PDataType.DECIMAL.toBytes(na);
bb = PDataType.DECIMAL.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
assertTrue(ba.length <= PDataType.DECIMAL.estimateByteSize(na));
assertTrue(bb.length <= PDataType.DECIMAL.estimateByteSize(nb));
na = new BigDecimal(-3);
nb = new BigDecimal(-1000);
assertTrue(na.compareTo(nb) > 0);
ba = PDataType.DECIMAL.toBytes(na);
bb = PDataType.DECIMAL.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
assertTrue(ba.length <= PDataType.DECIMAL.estimateByteSize(na));
assertTrue(bb.length <= PDataType.DECIMAL.estimateByteSize(nb));
na = new BigDecimal(BigInteger.valueOf(12345678901239998L), 2);
nb = new BigDecimal(97);
assertTrue(na.compareTo(nb) > 0);
ba = PDataType.DECIMAL.toBytes(na);
bb = PDataType.DECIMAL.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
assertTrue(ba.length <= PDataType.DECIMAL.estimateByteSize(na));
assertTrue(bb.length <= PDataType.DECIMAL.estimateByteSize(nb));
List<BigDecimal> values = Arrays.asList(new BigDecimal[] {
new BigDecimal(-1000),
new BigDecimal(-100000000),
new BigDecimal(1000),
new BigDecimal("-0.001"),
new BigDecimal("0.001"),
new BigDecimal(new BigInteger("12345678901239999"), 2),
new BigDecimal(new BigInteger("12345678901239998"), 2),
new BigDecimal(new BigInteger("12345678901239998123456789"), 2), // bigger than long
new BigDecimal(new BigInteger("-1000"),3),
new BigDecimal(new BigInteger("-1000"),10),
new BigDecimal(99),
new BigDecimal(97),
new BigDecimal(-3)
});
List<byte[]> byteValues = new ArrayList<byte[]>();
for (int i = 0; i < values.size(); i++) {
byteValues.add(PDataType.DECIMAL.toBytes(values.get(i)));
}
for (int i = 0; i < values.size(); i++) {
BigDecimal expected = values.get(i);
BigDecimal actual = (BigDecimal)PDataType.DECIMAL.toObject(byteValues.get(i));
assertTrue("For " + i + " expected " + expected + " but got " + actual,expected.round(PDataType.DEFAULT_MATH_CONTEXT).compareTo(actual.round(PDataType.DEFAULT_MATH_CONTEXT)) == 0);
assertTrue(byteValues.get(i).length <= PDataType.DECIMAL.estimateByteSize(expected));
}
Collections.sort(values);
Collections.sort(byteValues, Bytes.BYTES_COMPARATOR);
for (int i = 0; i < values.size(); i++) {
BigDecimal expected = values.get(i);
byte[] bytes = PDataType.DECIMAL.toBytes(values.get(i));
- if (bytes == null);
+ assertNotNull("bytes converted from valuess should not be null!", bytes);
BigDecimal actual = (BigDecimal)PDataType.DECIMAL.toObject(byteValues.get(i));
assertTrue("For " + i + " expected " + expected + " but got " + actual,expected.round(PDataType.DEFAULT_MATH_CONTEXT).compareTo(actual.round(PDataType.DEFAULT_MATH_CONTEXT))==0);
}
}
@Test
public void testEmptyString() throws Throwable {
byte[] b1 = PDataType.VARCHAR.toBytes("");
byte[] b2 = PDataType.VARCHAR.toBytes(null);
assert (b1.length == 0 && Bytes.compareTo(b1, b2) == 0);
}
@Test
public void testNull() throws Throwable {
byte[] b = new byte[8];
for (PDataType type : PDataType.values()) {
try {
type.toBytes(null);
type.toBytes(null, b, 0);
type.toObject(new byte[0],0,0);
type.toObject(new byte[0],0,0, type);
} catch (ConstraintViolationException e) {
// Fixed width types do not support the concept of a "null" value.
if (! (type.isFixedWidth() && e.getMessage().contains("may not be null"))) {
fail(type + ":" + e);
}
}
}
}
@Test
public void testValueCoersion() throws Exception {
// Testing coercing integer to other values.
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.LONG));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.LONG, 10));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.LONG, 0));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.LONG, -10));
assertFalse(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_INT));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_INT, 10));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_INT, 0));
assertFalse(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_INT, -10));
assertFalse(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_LONG));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_LONG, 10));
assertTrue(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_LONG, 0));
assertFalse(PDataType.INTEGER.isCoercibleTo(PDataType.UNSIGNED_LONG, -10));
// Testing coercing long to other values.
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.INTEGER));
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.INTEGER, Long.MAX_VALUE));
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.INTEGER, Integer.MAX_VALUE + 10L));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.INTEGER, (long)Integer.MAX_VALUE));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.INTEGER, Integer.MAX_VALUE - 10L));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.INTEGER, 10L));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.INTEGER, 0L));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.INTEGER, -10L));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.INTEGER, Integer.MIN_VALUE + 10L));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.INTEGER, (long)Integer.MIN_VALUE));
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.INTEGER, Integer.MIN_VALUE - 10L));
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.INTEGER, Long.MIN_VALUE));
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_INT));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_INT, 10L));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_INT, 0L));
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_INT, -10L));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_LONG));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_LONG, Long.MAX_VALUE));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_LONG, 10L));
assertTrue(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_LONG, 0L));
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_LONG, -10L));
assertFalse(PDataType.LONG.isCoercibleTo(PDataType.UNSIGNED_LONG, Long.MIN_VALUE));
// Testing coercing unsigned_int to other values.
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.INTEGER));
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.INTEGER, 10));
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.INTEGER, 0));
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.LONG));
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.LONG, 10));
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.LONG, 0));
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.UNSIGNED_LONG));
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.UNSIGNED_LONG, 10));
assertTrue(PDataType.UNSIGNED_INT.isCoercibleTo(PDataType.UNSIGNED_LONG, 0));
// Testing coercing unsigned_long to other values.
assertFalse(PDataType.UNSIGNED_LONG.isCoercibleTo(PDataType.INTEGER));
assertTrue(PDataType.UNSIGNED_LONG.isCoercibleTo(PDataType.INTEGER, 10L));
assertTrue(PDataType.UNSIGNED_LONG.isCoercibleTo(PDataType.INTEGER, 0L));
assertTrue(PDataType.UNSIGNED_LONG.isCoercibleTo(PDataType.LONG));
assertFalse(PDataType.UNSIGNED_LONG.isCoercibleTo(PDataType.UNSIGNED_INT));
}
}
| true | true | public void testBigDecimal() {
byte[] b;
BigDecimal na, nb;
b = new byte[] {
(byte)0xc2,0x02,0x10,0x36,0x22,0x22,0x22,0x22,0x22,0x22,0x0f,0x27,0x38,0x1c,0x05,0x40,0x62,0x21,0x54,0x4d,0x4e,0x01,0x14,0x36,0x0d,0x33
};
BigDecimal decodedBytes = (BigDecimal)PDataType.DECIMAL.toObject(b);
assertTrue(decodedBytes.compareTo(BigDecimal.ZERO) > 0);
na = new BigDecimal(new BigInteger("12345678901239998123456789"), 2);
//[-52, 13, 35, 57, 79, 91, 13, 40, 100, 82, 24, 46, 68, 90]
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
TestUtil.assertRoundEquals(na,nb);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
na = new BigDecimal("115.533333333333331438552704639732837677001953125");
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
TestUtil.assertRoundEquals(na,nb);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
na = new BigDecimal(2.5);
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
assertTrue(na.compareTo(nb) == 0);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
// If we don't remove trailing zeros, this fails
na = new BigDecimal(Double.parseDouble("96.45238095238095"));
String naStr = na.toString();
assertTrue(naStr != null);
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
TestUtil.assertRoundEquals(na,nb);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
// If we don't remove trailing zeros, this fails
na = new BigDecimal(-1000);
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
assertTrue(na.compareTo(nb) == 0);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
na = TestUtil.computeAverage(11000, 3);
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
assertTrue(na.compareTo(nb) == 0);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
na = new BigDecimal(new BigInteger("12345678901239999"), 2);
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
assertTrue(na.compareTo(nb) == 0);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
na = new BigDecimal(1);
nb = new BigDecimal(-1);
byte[] ba = PDataType.DECIMAL.toBytes(na);
byte[] bb = PDataType.DECIMAL.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
assertTrue(ba.length <= PDataType.DECIMAL.estimateByteSize(na));
assertTrue(bb.length <= PDataType.DECIMAL.estimateByteSize(nb));
na = new BigDecimal(-1);
nb = new BigDecimal(-2);
ba = PDataType.DECIMAL.toBytes(na);
bb = PDataType.DECIMAL.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
assertTrue(ba.length <= PDataType.DECIMAL.estimateByteSize(na));
assertTrue(bb.length <= PDataType.DECIMAL.estimateByteSize(nb));
na = new BigDecimal(-3);
nb = new BigDecimal(-1000);
assertTrue(na.compareTo(nb) > 0);
ba = PDataType.DECIMAL.toBytes(na);
bb = PDataType.DECIMAL.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
assertTrue(ba.length <= PDataType.DECIMAL.estimateByteSize(na));
assertTrue(bb.length <= PDataType.DECIMAL.estimateByteSize(nb));
na = new BigDecimal(BigInteger.valueOf(12345678901239998L), 2);
nb = new BigDecimal(97);
assertTrue(na.compareTo(nb) > 0);
ba = PDataType.DECIMAL.toBytes(na);
bb = PDataType.DECIMAL.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
assertTrue(ba.length <= PDataType.DECIMAL.estimateByteSize(na));
assertTrue(bb.length <= PDataType.DECIMAL.estimateByteSize(nb));
List<BigDecimal> values = Arrays.asList(new BigDecimal[] {
new BigDecimal(-1000),
new BigDecimal(-100000000),
new BigDecimal(1000),
new BigDecimal("-0.001"),
new BigDecimal("0.001"),
new BigDecimal(new BigInteger("12345678901239999"), 2),
new BigDecimal(new BigInteger("12345678901239998"), 2),
new BigDecimal(new BigInteger("12345678901239998123456789"), 2), // bigger than long
new BigDecimal(new BigInteger("-1000"),3),
new BigDecimal(new BigInteger("-1000"),10),
new BigDecimal(99),
new BigDecimal(97),
new BigDecimal(-3)
});
List<byte[]> byteValues = new ArrayList<byte[]>();
for (int i = 0; i < values.size(); i++) {
byteValues.add(PDataType.DECIMAL.toBytes(values.get(i)));
}
for (int i = 0; i < values.size(); i++) {
BigDecimal expected = values.get(i);
BigDecimal actual = (BigDecimal)PDataType.DECIMAL.toObject(byteValues.get(i));
assertTrue("For " + i + " expected " + expected + " but got " + actual,expected.round(PDataType.DEFAULT_MATH_CONTEXT).compareTo(actual.round(PDataType.DEFAULT_MATH_CONTEXT)) == 0);
assertTrue(byteValues.get(i).length <= PDataType.DECIMAL.estimateByteSize(expected));
}
Collections.sort(values);
Collections.sort(byteValues, Bytes.BYTES_COMPARATOR);
for (int i = 0; i < values.size(); i++) {
BigDecimal expected = values.get(i);
byte[] bytes = PDataType.DECIMAL.toBytes(values.get(i));
if (bytes == null);
BigDecimal actual = (BigDecimal)PDataType.DECIMAL.toObject(byteValues.get(i));
assertTrue("For " + i + " expected " + expected + " but got " + actual,expected.round(PDataType.DEFAULT_MATH_CONTEXT).compareTo(actual.round(PDataType.DEFAULT_MATH_CONTEXT))==0);
}
}
| public void testBigDecimal() {
byte[] b;
BigDecimal na, nb;
b = new byte[] {
(byte)0xc2,0x02,0x10,0x36,0x22,0x22,0x22,0x22,0x22,0x22,0x0f,0x27,0x38,0x1c,0x05,0x40,0x62,0x21,0x54,0x4d,0x4e,0x01,0x14,0x36,0x0d,0x33
};
BigDecimal decodedBytes = (BigDecimal)PDataType.DECIMAL.toObject(b);
assertTrue(decodedBytes.compareTo(BigDecimal.ZERO) > 0);
na = new BigDecimal(new BigInteger("12345678901239998123456789"), 2);
//[-52, 13, 35, 57, 79, 91, 13, 40, 100, 82, 24, 46, 68, 90]
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
TestUtil.assertRoundEquals(na,nb);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
na = new BigDecimal("115.533333333333331438552704639732837677001953125");
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
TestUtil.assertRoundEquals(na,nb);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
na = new BigDecimal(2.5);
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
assertTrue(na.compareTo(nb) == 0);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
// If we don't remove trailing zeros, this fails
na = new BigDecimal(Double.parseDouble("96.45238095238095"));
String naStr = na.toString();
assertTrue(naStr != null);
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
TestUtil.assertRoundEquals(na,nb);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
// If we don't remove trailing zeros, this fails
na = new BigDecimal(-1000);
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
assertTrue(na.compareTo(nb) == 0);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
na = TestUtil.computeAverage(11000, 3);
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
assertTrue(na.compareTo(nb) == 0);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
na = new BigDecimal(new BigInteger("12345678901239999"), 2);
b = PDataType.DECIMAL.toBytes(na);
nb = (BigDecimal)PDataType.DECIMAL.toObject(b);
assertTrue(na.compareTo(nb) == 0);
assertTrue(b.length <= PDataType.DECIMAL.estimateByteSize(na));
na = new BigDecimal(1);
nb = new BigDecimal(-1);
byte[] ba = PDataType.DECIMAL.toBytes(na);
byte[] bb = PDataType.DECIMAL.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
assertTrue(ba.length <= PDataType.DECIMAL.estimateByteSize(na));
assertTrue(bb.length <= PDataType.DECIMAL.estimateByteSize(nb));
na = new BigDecimal(-1);
nb = new BigDecimal(-2);
ba = PDataType.DECIMAL.toBytes(na);
bb = PDataType.DECIMAL.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
assertTrue(ba.length <= PDataType.DECIMAL.estimateByteSize(na));
assertTrue(bb.length <= PDataType.DECIMAL.estimateByteSize(nb));
na = new BigDecimal(-3);
nb = new BigDecimal(-1000);
assertTrue(na.compareTo(nb) > 0);
ba = PDataType.DECIMAL.toBytes(na);
bb = PDataType.DECIMAL.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
assertTrue(ba.length <= PDataType.DECIMAL.estimateByteSize(na));
assertTrue(bb.length <= PDataType.DECIMAL.estimateByteSize(nb));
na = new BigDecimal(BigInteger.valueOf(12345678901239998L), 2);
nb = new BigDecimal(97);
assertTrue(na.compareTo(nb) > 0);
ba = PDataType.DECIMAL.toBytes(na);
bb = PDataType.DECIMAL.toBytes(nb);
assertTrue(Bytes.compareTo(ba, bb) > 0);
assertTrue(ba.length <= PDataType.DECIMAL.estimateByteSize(na));
assertTrue(bb.length <= PDataType.DECIMAL.estimateByteSize(nb));
List<BigDecimal> values = Arrays.asList(new BigDecimal[] {
new BigDecimal(-1000),
new BigDecimal(-100000000),
new BigDecimal(1000),
new BigDecimal("-0.001"),
new BigDecimal("0.001"),
new BigDecimal(new BigInteger("12345678901239999"), 2),
new BigDecimal(new BigInteger("12345678901239998"), 2),
new BigDecimal(new BigInteger("12345678901239998123456789"), 2), // bigger than long
new BigDecimal(new BigInteger("-1000"),3),
new BigDecimal(new BigInteger("-1000"),10),
new BigDecimal(99),
new BigDecimal(97),
new BigDecimal(-3)
});
List<byte[]> byteValues = new ArrayList<byte[]>();
for (int i = 0; i < values.size(); i++) {
byteValues.add(PDataType.DECIMAL.toBytes(values.get(i)));
}
for (int i = 0; i < values.size(); i++) {
BigDecimal expected = values.get(i);
BigDecimal actual = (BigDecimal)PDataType.DECIMAL.toObject(byteValues.get(i));
assertTrue("For " + i + " expected " + expected + " but got " + actual,expected.round(PDataType.DEFAULT_MATH_CONTEXT).compareTo(actual.round(PDataType.DEFAULT_MATH_CONTEXT)) == 0);
assertTrue(byteValues.get(i).length <= PDataType.DECIMAL.estimateByteSize(expected));
}
Collections.sort(values);
Collections.sort(byteValues, Bytes.BYTES_COMPARATOR);
for (int i = 0; i < values.size(); i++) {
BigDecimal expected = values.get(i);
byte[] bytes = PDataType.DECIMAL.toBytes(values.get(i));
assertNotNull("bytes converted from valuess should not be null!", bytes);
BigDecimal actual = (BigDecimal)PDataType.DECIMAL.toObject(byteValues.get(i));
assertTrue("For " + i + " expected " + expected + " but got " + actual,expected.round(PDataType.DEFAULT_MATH_CONTEXT).compareTo(actual.round(PDataType.DEFAULT_MATH_CONTEXT))==0);
}
}
|
diff --git a/src/main/java/com/novoda/notils/logger/AndroidHelper.java b/src/main/java/com/novoda/notils/logger/AndroidHelper.java
index 63949d9..321c833 100644
--- a/src/main/java/com/novoda/notils/logger/AndroidHelper.java
+++ b/src/main/java/com/novoda/notils/logger/AndroidHelper.java
@@ -1,32 +1,31 @@
package com.novoda.notils.logger;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
public final class AndroidHelper {
public static final class AppName {
public static String fromContext(Context context) {
final PackageManager pm = context.getApplicationContext().getPackageManager();
- ApplicationInfo ai;
try {
- ai = pm.getApplicationInfo(context.getPackageName(), 0);
- } catch (final PackageManager.NameNotFoundException e) {
- ai = null;
+ ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0);
+ return (String) pm.getApplicationLabel(ai);
+ } catch (PackageManager.NameNotFoundException ignored) {
+ return null;
}
- return ai != null ? (String) pm.getApplicationLabel(ai) : null;
}
}
public static boolean isAndroid() {
try {
Class.forName("android.os.Build");
return Build.VERSION.SDK_INT != 0;
} catch (ClassNotFoundException ignored) {
return false;
}
}
}
| false | true | public static String fromContext(Context context) {
final PackageManager pm = context.getApplicationContext().getPackageManager();
ApplicationInfo ai;
try {
ai = pm.getApplicationInfo(context.getPackageName(), 0);
} catch (final PackageManager.NameNotFoundException e) {
ai = null;
}
return ai != null ? (String) pm.getApplicationLabel(ai) : null;
}
| public static String fromContext(Context context) {
final PackageManager pm = context.getApplicationContext().getPackageManager();
try {
ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0);
return (String) pm.getApplicationLabel(ai);
} catch (PackageManager.NameNotFoundException ignored) {
return null;
}
}
|
diff --git a/src/main/java/org/dynmap/web/handlers/SendMessageHandler.java b/src/main/java/org/dynmap/web/handlers/SendMessageHandler.java
index 5578e3b3..eefca517 100644
--- a/src/main/java/org/dynmap/web/handlers/SendMessageHandler.java
+++ b/src/main/java/org/dynmap/web/handlers/SendMessageHandler.java
@@ -1,138 +1,141 @@
package org.dynmap.web.handlers;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;
import org.dynmap.DynmapPlugin;
import org.dynmap.Event;
import org.dynmap.Log;
import org.dynmap.web.HttpField;
import org.dynmap.web.HttpHandler;
import org.dynmap.web.HttpMethod;
import org.dynmap.web.HttpRequest;
import org.dynmap.web.HttpResponse;
import org.dynmap.web.HttpStatus;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class SendMessageHandler implements HttpHandler {
protected static final Logger log = Logger.getLogger("Minecraft");
private static final JSONParser parser = new JSONParser();
public Event<Message> onMessageReceived = new Event<SendMessageHandler.Message>();
private Charset cs_utf8 = Charset.forName("UTF-8");
public int maximumMessageInterval = 1000;
public boolean hideip = false;
public boolean trustclientname = false;
public boolean use_player_login_ip = false;
public boolean require_player_login_ip = false;
public DynmapPlugin plug_in;
public String spamMessage = "\"You may only chat once every %interval% seconds.\"";
private HashMap<String, WebUser> disallowedUsers = new HashMap<String, WebUser>();
private LinkedList<WebUser> disallowedUserQueue = new LinkedList<WebUser>();
private Object disallowedUsersLock = new Object();
private HashMap<String,String> useralias = new HashMap<String,String>();
private int aliasindex = 1;
@Override
public void handle(String path, HttpRequest request, HttpResponse response) throws Exception {
if (!request.method.equals(HttpMethod.Post)) {
response.status = HttpStatus.MethodNotAllowed;
response.fields.put(HttpField.Accept, HttpMethod.Post);
return;
}
InputStreamReader reader = new InputStreamReader(request.body, cs_utf8);
JSONObject o = (JSONObject)parser.parse(reader);
final Message message = new Message();
message.name = "";
if(trustclientname) {
message.name = String.valueOf(o.get("name"));
}
boolean isip = true;
if((message.name == null) || message.name.equals("")) {
/* If proxied client address, get original */
if(request.fields.containsKey("X-Forwarded-For"))
message.name = request.fields.get("X-Forwarded-For");
/* If from loopback, we're probably getting from proxy - need to trust client */
else if(request.rmtaddr.getAddress().isLoopbackAddress())
message.name = String.valueOf(o.get("name"));
else
message.name = request.rmtaddr.getAddress().getHostAddress();
}
if(use_player_login_ip) {
List<String> ids = plug_in.getIDsForIP(message.name);
if(ids != null) {
message.name = ids.get(0);
isip = false;
}
else if(require_player_login_ip) {
Log.info("Ignore message from '" + message.name + "' - no matching player login recorded");
+ response.fields.put("Content-Length", "0");
+ response.status = HttpStatus.Forbidden;
+ response.getBody();
return;
}
}
if(hideip && isip) { /* If hiding IP, find or assign alias */
synchronized(disallowedUsersLock) {
String n = useralias.get(message.name);
if(n == null) { /* Make ID */
n = String.format("web-%03d", aliasindex);
aliasindex++;
useralias.put(message.name, n);
}
message.name = n;
}
}
message.message = String.valueOf(o.get("message"));
final long now = System.currentTimeMillis();
synchronized(disallowedUsersLock) {
// Allow users that user that are now allowed to send messages.
while (!disallowedUserQueue.isEmpty()) {
WebUser wu = disallowedUserQueue.getFirst();
if (now >= wu.nextMessageTime) {
disallowedUserQueue.remove();
disallowedUsers.remove(wu.name);
} else {
break;
}
}
WebUser user = disallowedUsers.get(message.name);
if (user == null) {
user = new WebUser() {{
name = message.name;
nextMessageTime = now+maximumMessageInterval;
}};
disallowedUsers.put(user.name, user);
disallowedUserQueue.add(user);
} else {
response.fields.put("Content-Length", "0");
response.status = HttpStatus.Forbidden;
response.getBody();
return;
}
}
onMessageReceived.trigger(message);
response.fields.put(HttpField.ContentLength, "0");
response.status = HttpStatus.OK;
response.getBody();
}
public static class Message {
public String name;
public String message;
}
public static class WebUser {
public long nextMessageTime;
public String name;
}
}
| true | true | public void handle(String path, HttpRequest request, HttpResponse response) throws Exception {
if (!request.method.equals(HttpMethod.Post)) {
response.status = HttpStatus.MethodNotAllowed;
response.fields.put(HttpField.Accept, HttpMethod.Post);
return;
}
InputStreamReader reader = new InputStreamReader(request.body, cs_utf8);
JSONObject o = (JSONObject)parser.parse(reader);
final Message message = new Message();
message.name = "";
if(trustclientname) {
message.name = String.valueOf(o.get("name"));
}
boolean isip = true;
if((message.name == null) || message.name.equals("")) {
/* If proxied client address, get original */
if(request.fields.containsKey("X-Forwarded-For"))
message.name = request.fields.get("X-Forwarded-For");
/* If from loopback, we're probably getting from proxy - need to trust client */
else if(request.rmtaddr.getAddress().isLoopbackAddress())
message.name = String.valueOf(o.get("name"));
else
message.name = request.rmtaddr.getAddress().getHostAddress();
}
if(use_player_login_ip) {
List<String> ids = plug_in.getIDsForIP(message.name);
if(ids != null) {
message.name = ids.get(0);
isip = false;
}
else if(require_player_login_ip) {
Log.info("Ignore message from '" + message.name + "' - no matching player login recorded");
return;
}
}
if(hideip && isip) { /* If hiding IP, find or assign alias */
synchronized(disallowedUsersLock) {
String n = useralias.get(message.name);
if(n == null) { /* Make ID */
n = String.format("web-%03d", aliasindex);
aliasindex++;
useralias.put(message.name, n);
}
message.name = n;
}
}
message.message = String.valueOf(o.get("message"));
final long now = System.currentTimeMillis();
synchronized(disallowedUsersLock) {
// Allow users that user that are now allowed to send messages.
while (!disallowedUserQueue.isEmpty()) {
WebUser wu = disallowedUserQueue.getFirst();
if (now >= wu.nextMessageTime) {
disallowedUserQueue.remove();
disallowedUsers.remove(wu.name);
} else {
break;
}
}
WebUser user = disallowedUsers.get(message.name);
if (user == null) {
user = new WebUser() {{
name = message.name;
nextMessageTime = now+maximumMessageInterval;
}};
disallowedUsers.put(user.name, user);
disallowedUserQueue.add(user);
} else {
response.fields.put("Content-Length", "0");
response.status = HttpStatus.Forbidden;
response.getBody();
return;
}
}
onMessageReceived.trigger(message);
response.fields.put(HttpField.ContentLength, "0");
response.status = HttpStatus.OK;
response.getBody();
}
| public void handle(String path, HttpRequest request, HttpResponse response) throws Exception {
if (!request.method.equals(HttpMethod.Post)) {
response.status = HttpStatus.MethodNotAllowed;
response.fields.put(HttpField.Accept, HttpMethod.Post);
return;
}
InputStreamReader reader = new InputStreamReader(request.body, cs_utf8);
JSONObject o = (JSONObject)parser.parse(reader);
final Message message = new Message();
message.name = "";
if(trustclientname) {
message.name = String.valueOf(o.get("name"));
}
boolean isip = true;
if((message.name == null) || message.name.equals("")) {
/* If proxied client address, get original */
if(request.fields.containsKey("X-Forwarded-For"))
message.name = request.fields.get("X-Forwarded-For");
/* If from loopback, we're probably getting from proxy - need to trust client */
else if(request.rmtaddr.getAddress().isLoopbackAddress())
message.name = String.valueOf(o.get("name"));
else
message.name = request.rmtaddr.getAddress().getHostAddress();
}
if(use_player_login_ip) {
List<String> ids = plug_in.getIDsForIP(message.name);
if(ids != null) {
message.name = ids.get(0);
isip = false;
}
else if(require_player_login_ip) {
Log.info("Ignore message from '" + message.name + "' - no matching player login recorded");
response.fields.put("Content-Length", "0");
response.status = HttpStatus.Forbidden;
response.getBody();
return;
}
}
if(hideip && isip) { /* If hiding IP, find or assign alias */
synchronized(disallowedUsersLock) {
String n = useralias.get(message.name);
if(n == null) { /* Make ID */
n = String.format("web-%03d", aliasindex);
aliasindex++;
useralias.put(message.name, n);
}
message.name = n;
}
}
message.message = String.valueOf(o.get("message"));
final long now = System.currentTimeMillis();
synchronized(disallowedUsersLock) {
// Allow users that user that are now allowed to send messages.
while (!disallowedUserQueue.isEmpty()) {
WebUser wu = disallowedUserQueue.getFirst();
if (now >= wu.nextMessageTime) {
disallowedUserQueue.remove();
disallowedUsers.remove(wu.name);
} else {
break;
}
}
WebUser user = disallowedUsers.get(message.name);
if (user == null) {
user = new WebUser() {{
name = message.name;
nextMessageTime = now+maximumMessageInterval;
}};
disallowedUsers.put(user.name, user);
disallowedUserQueue.add(user);
} else {
response.fields.put("Content-Length", "0");
response.status = HttpStatus.Forbidden;
response.getBody();
return;
}
}
onMessageReceived.trigger(message);
response.fields.put(HttpField.ContentLength, "0");
response.status = HttpStatus.OK;
response.getBody();
}
|
diff --git a/src/water/parser/ParseDataset.java b/src/water/parser/ParseDataset.java
index f9f1d1b96..e180208ae 100644
--- a/src/water/parser/ParseDataset.java
+++ b/src/water/parser/ParseDataset.java
@@ -1,146 +1,146 @@
package water.parser;
import java.io.IOException;
import java.util.zip.*;
import jsr166y.RecursiveAction;
import water.*;
import com.google.common.base.Throwables;
import com.google.common.io.Closeables;
/**
* Helper class to parse an entire ValueArray data, and produce a structured
* ValueArray result.
*
* @author <a href="mailto:[email protected]"></a>
*/
@SuppressWarnings("fallthrough")
public final class ParseDataset {
public static enum Compression { NONE, ZIP, GZIP }
// Guess
public static Compression guessCompressionMethod(Value dataset) {
byte[] b = dataset.getFirstBytes(); // First chunk
AutoBuffer ab = new AutoBuffer(b);
// Look for ZIP magic
if (b.length > ZipFile.LOCHDR && ab.get4(0) == ZipFile.LOCSIG)
return Compression.ZIP;
if (b.length > 2 && ab.get2(0) == GZIPInputStream.GZIP_MAGIC)
return Compression.GZIP;
return Compression.NONE;
}
// Parse the dataset (uncompressed, zippped) as a CSV-style thingy and
// produce a structured dataset as a result.
private static void parseImpl( Key result, Value dataset ) {
if( dataset.isHex() )
throw new IllegalArgumentException("This is a binary structured dataset; "
+ "parse() only works on text files.");
try {
// try if it is XLS file first
try {
parseUncompressed(result,dataset,CustomParser.Type.XLS);
return;
} catch (Exception e) {
// pass
}
Compression compression = guessCompressionMethod(dataset);
if (compression == Compression.ZIP) {
try {
parseUncompressed(result,dataset,CustomParser.Type.XLSX);
return;
} catch (Exception e) {
// pass
}
}
switch (compression) {
case NONE: parseUncompressed(result, dataset,CustomParser.Type.CSV); break;
case ZIP : parseZipped (result, dataset); break;
case GZIP: parseGZipped (result, dataset); break;
- default : throw new Error("Uknown compression of dataset!");
+ default : throw new Error("Unknown compression of dataset!");
}
} catch( Exception e ) {
ParseStatus.error(result, e.getMessage());
throw Throwables.propagate(e);
}
}
public static void parse( Key result, Value dataset ) {
ParseStatus.initialize(result, dataset.length());
parseImpl(result, dataset);
}
public static void forkParseDataset( final Key result, final Value dataset ) {
ParseStatus.initialize(result, dataset.length());
H2O.FJP_NORM.submit(new RecursiveAction() {
@Override
protected void compute() {
parseImpl(result, dataset);
}
});
}
// Parse the uncompressed dataset as a CSV-style structure and produce a structured dataset
// result. This does a distributed parallel parse.
public static void parseUncompressed( Key result, Value dataset, CustomParser.Type parserType ) throws Exception {
DParseTask phaseOne = DParseTask.createPassOne(dataset, result, parserType);
phaseOne.passOne();
if ((phaseOne._error != null) && !phaseOne._error.isEmpty()) {
System.err.println(phaseOne._error);
throw new Exception("The dataset format is not recognized/supported");
}
DParseTask phaseTwo = DParseTask.createPassTwo(phaseOne);
phaseTwo.passTwo();
if ((phaseTwo._error != null) && !phaseTwo._error.isEmpty()) {
System.err.println(phaseTwo._error);
UKV.remove(result); // delete bad stuff if any
throw new Exception("The dataset format is not recognized/supported");
}
}
// Unpack zipped CSV-style structure and call method parseUncompressed(...)
// The method exepct a dataset which contains a ZIP file encapsulating one file.
public static void parseZipped( Key result, Value dataset ) throws IOException {
// Dataset contains zipped CSV
ZipInputStream zis = null;
Key key = null;
try {
// Create Zip input stream and uncompress the data into a new key <ORIGINAL-KEY-NAME>_UNZIPPED
zis = new ZipInputStream(dataset.openStream());
// Get the *FIRST* entry
ZipEntry ze = zis.getNextEntry();
// There is at least one entry in zip file and it is not a directory.
if (ze != null && !ze.isDirectory()) {
key = ValueArray.readPut(new String(dataset._key._kb) + "_UNZIPPED", zis);
}
// else it is possible to dive into a directory but in this case I would
// prefer to return error since the ZIP file has not expected format
} finally { Closeables.closeQuietly(zis); }
if( key == null ) throw new Error("Cannot uncompressed ZIP-compressed dataset!");
Value uncompressedDataset = DKV.get(key);
parse(result, uncompressedDataset);
UKV.remove(key);
}
public static void parseGZipped( Key result, Value dataset ) throws IOException {
GZIPInputStream gzis = null;
Key key = null;
try {
gzis = new GZIPInputStream(dataset.openStream());
key = ValueArray.readPut(new String(dataset._key._kb) + "_UNZIPPED", gzis);
} finally { Closeables.closeQuietly(gzis); }
if( key == null ) throw new Error("Cannot uncompressed GZIP-compressed dataset!");
Value uncompressedDataset = DKV.get(key);
parse(result, uncompressedDataset);
UKV.remove(key);
}
// True if the array is all NaNs
static boolean allNaNs( double ds[] ) {
for( double d : ds )
if( !Double.isNaN(d) )
return false;
return true;
}
}
| true | true | private static void parseImpl( Key result, Value dataset ) {
if( dataset.isHex() )
throw new IllegalArgumentException("This is a binary structured dataset; "
+ "parse() only works on text files.");
try {
// try if it is XLS file first
try {
parseUncompressed(result,dataset,CustomParser.Type.XLS);
return;
} catch (Exception e) {
// pass
}
Compression compression = guessCompressionMethod(dataset);
if (compression == Compression.ZIP) {
try {
parseUncompressed(result,dataset,CustomParser.Type.XLSX);
return;
} catch (Exception e) {
// pass
}
}
switch (compression) {
case NONE: parseUncompressed(result, dataset,CustomParser.Type.CSV); break;
case ZIP : parseZipped (result, dataset); break;
case GZIP: parseGZipped (result, dataset); break;
default : throw new Error("Uknown compression of dataset!");
}
} catch( Exception e ) {
ParseStatus.error(result, e.getMessage());
throw Throwables.propagate(e);
}
}
| private static void parseImpl( Key result, Value dataset ) {
if( dataset.isHex() )
throw new IllegalArgumentException("This is a binary structured dataset; "
+ "parse() only works on text files.");
try {
// try if it is XLS file first
try {
parseUncompressed(result,dataset,CustomParser.Type.XLS);
return;
} catch (Exception e) {
// pass
}
Compression compression = guessCompressionMethod(dataset);
if (compression == Compression.ZIP) {
try {
parseUncompressed(result,dataset,CustomParser.Type.XLSX);
return;
} catch (Exception e) {
// pass
}
}
switch (compression) {
case NONE: parseUncompressed(result, dataset,CustomParser.Type.CSV); break;
case ZIP : parseZipped (result, dataset); break;
case GZIP: parseGZipped (result, dataset); break;
default : throw new Error("Unknown compression of dataset!");
}
} catch( Exception e ) {
ParseStatus.error(result, e.getMessage());
throw Throwables.propagate(e);
}
}
|
diff --git a/src/com/android/email/activity/MailboxList.java b/src/com/android/email/activity/MailboxList.java
index 9e7a6fba..50711c0b 100644
--- a/src/com/android/email/activity/MailboxList.java
+++ b/src/com/android/email/activity/MailboxList.java
@@ -1,361 +1,358 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.email.activity;
import com.android.email.Controller;
import com.android.email.ControllerResultUiThreadWrapper;
import com.android.email.Email;
import com.android.email.R;
import com.android.email.Utility;
import com.android.email.activity.setup.AccountSettings;
import com.android.email.mail.AuthenticationFailedException;
import com.android.email.mail.CertificateValidationException;
import com.android.email.mail.MessagingException;
import com.android.email.provider.EmailContent.Account;
import com.android.email.provider.EmailContent.AccountColumns;
import android.app.ActionBar;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
public class MailboxList extends Activity implements MailboxListFragment.Callback {
// Intent extras (internal to this activity)
private static final String EXTRA_ACCOUNT_ID = "com.android.email.activity._ACCOUNT_ID";
// UI support
private ActionBar mActionBar;
private boolean mProgressRunning;
private TextView mErrorBanner;
private MailboxListFragment mListFragment;
private Controller.Result mControllerCallback;
// DB access
private long mAccountId;
private AsyncTask<Void, Void, String[]> mLoadAccountNameTask;
/**
* Open a specific account.
*
* @param context
* @param accountId the account to view
*/
public static void actionHandleAccount(Context context, long accountId) {
Intent intent = new Intent(context, MailboxList.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(EXTRA_ACCOUNT_ID, accountId);
context.startActivity(intent);
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mAccountId = getIntent().getLongExtra(EXTRA_ACCOUNT_ID, -1);
if (mAccountId == -1) {
finish();
return;
}
setContentView(R.layout.mailbox_list);
mControllerCallback = new ControllerResultUiThreadWrapper<ControllerResults>(
new Handler(), new ControllerResults());
mActionBar = getActionBar();
mErrorBanner = (TextView) findViewById(R.id.connection_error_text);
mListFragment = (MailboxListFragment) findFragmentById(R.id.mailbox_list_fragment);
mActionBar.setStandardNavigationMode(this.getText(R.string.mailbox_list_title));
mListFragment.setCallback(this);
mListFragment.openMailboxes(mAccountId);
// Go to the database for the account name
mLoadAccountNameTask = new AsyncTask<Void, Void, String[]>() {
@Override
protected String[] doInBackground(Void... params) {
String accountName = null;
Uri uri = ContentUris.withAppendedId(Account.CONTENT_URI, mAccountId);
Cursor c = MailboxList.this.getContentResolver().query(
uri, new String[] { AccountColumns.DISPLAY_NAME }, null, null, null);
try {
if (c.moveToFirst()) {
accountName = c.getString(0);
}
} finally {
c.close();
}
return new String[] { accountName };
}
@Override
protected void onPostExecute(String[] result) {
if (result == null) {
return;
}
final String accountName = (String) result[0];
// accountName is null if account name can't be retrieved or query exception
if (accountName == null) {
// something is wrong with this account
finish();
}
- // STOPSHIP this doesn't work - the subtitle doesn't work - bug 2805131
-// mActionBar.setStandardNavigationMode(
-// MailboxList.this.getText(R.string.mailbox_list_title),
-// accountName);
- // STOPSHIP - so, for temp fix, show the account name (since it's the dynamic value)
- mActionBar.setStandardNavigationMode(accountName);
+ mActionBar.setStandardNavigationMode(
+ MailboxList.this.getText(R.string.mailbox_list_title),
+ accountName);
}
}.execute();
}
@Override
public void onPause() {
super.onPause();
Controller.getInstance(getApplication()).removeResultCallback(mControllerCallback);
}
@Override
public void onResume() {
super.onResume();
Controller.getInstance(getApplication()).addResultCallback(mControllerCallback);
// Exit immediately if the accounts list has changed (e.g. externally deleted)
if (Email.getNotifyUiAccountsChanged()) {
Welcome.actionStart(this);
finish();
return;
}
// TODO: may need to clear notifications here
}
@Override
protected void onDestroy() {
super.onDestroy();
Utility.cancelTaskInterrupt(mLoadAccountNameTask);
mLoadAccountNameTask = null;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.mailbox_list_option, menu);
return true;
}
// STOPSHIP - this is a placeholder if/until there's support for progress in actionbar
// Remove it, or replace with a better icon
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem item = menu.findItem(R.id.refresh);
if (mProgressRunning) {
item.setIcon(android.R.drawable.progress_indeterminate_horizontal);
} else {
item.setIcon(R.drawable.ic_menu_refresh);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onAccounts();
return true;
case R.id.refresh:
onRefresh(-1);
return true;
case R.id.compose:
onCompose();
return true;
case R.id.account_settings:
onEditAccount();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Implements MailboxFragment.Callback
*/
public void onMailboxSelected(long accountId, long mailboxId) {
onOpenMailbox(mailboxId);
}
/**
* Implements MailboxFragment.Callback
*/
public void onRefresh(long accountId, long mailboxId) {
onRefresh(mailboxId);
}
/**
* Refresh the mailbox list, or a single mailbox
* @param mailboxId -1 for all
*/
private void onRefresh(long mailboxId) {
Controller controller = Controller.getInstance(getApplication());
showProgressIcon(true);
if (mailboxId >= 0) {
controller.updateMailbox(mAccountId, mailboxId);
} else {
controller.updateMailboxList(mAccountId);
}
}
private void onAccounts() {
AccountFolderList.actionShowAccounts(this);
finish();
}
private void onEditAccount() {
AccountSettings.actionSettings(this, mAccountId);
}
private void onOpenMailbox(long mailboxId) {
MessageList.actionHandleMailbox(this, mailboxId);
}
private void onCompose() {
MessageCompose.actionCompose(this, mAccountId);
}
private void showProgressIcon(boolean show) {
// STOPSHIP: This doesn't work, pending fix is bug b/2802962
//setProgressBarIndeterminateVisibility(show);
// STOPSHIP: This is a hack used to replace the refresh icon with a spinner
mProgressRunning = show;
invalidateOptionsMenu();
}
private void showErrorBanner(String message) {
boolean isVisible = mErrorBanner.getVisibility() == View.VISIBLE;
if (message != null) {
mErrorBanner.setText(message);
if (!isVisible) {
mErrorBanner.setVisibility(View.VISIBLE);
mErrorBanner.startAnimation(
AnimationUtils.loadAnimation(
MailboxList.this, R.anim.header_appear));
}
} else {
if (isVisible) {
mErrorBanner.setVisibility(View.GONE);
mErrorBanner.startAnimation(
AnimationUtils.loadAnimation(
MailboxList.this, R.anim.header_disappear));
}
}
}
/**
* Controller results listener. We wrap it with {@link ControllerResultUiThreadWrapper},
* so all methods are called on the UI thread.
*/
private class ControllerResults extends Controller.Result {
// TODO report errors into UI
@Override
public void updateMailboxListCallback(MessagingException result, long accountKey,
int progress) {
if (accountKey == mAccountId) {
updateBanner(result, progress);
updateProgress(result, progress);
}
}
// TODO report errors into UI
@Override
public void updateMailboxCallback(MessagingException result, long accountKey,
long mailboxKey, int progress, int numNewMessages) {
if (result != null || progress == 100) {
Email.updateMailboxRefreshTime(mailboxKey);
}
if (accountKey == mAccountId) {
updateBanner(result, progress);
updateProgress(result, progress);
}
}
@Override
public void sendMailCallback(MessagingException result, long accountId, long messageId,
int progress) {
if (accountId == mAccountId) {
updateBanner(result, progress);
updateProgress(result, progress);
}
}
private void updateProgress(MessagingException result, int progress) {
showProgressIcon(result == null && progress < 100);
}
/**
* Show or hide the connection error banner, and convert the various MessagingException
* variants into localizable text. There is hysteresis in the show/hide logic: Once shown,
* the banner will remain visible until some progress is made on the connection. The
* goal is to keep it from flickering during retries in a bad connection state.
*
* @param result
* @param progress
*/
private void updateBanner(MessagingException result, int progress) {
if (result != null) {
int id = R.string.status_network_error;
if (result instanceof AuthenticationFailedException) {
id = R.string.account_setup_failed_dlg_auth_message;
} else if (result instanceof CertificateValidationException) {
id = R.string.account_setup_failed_dlg_certificate_message;
} else {
switch (result.getExceptionType()) {
case MessagingException.IOERROR:
id = R.string.account_setup_failed_ioerror;
break;
case MessagingException.TLS_REQUIRED:
id = R.string.account_setup_failed_tls_required;
break;
case MessagingException.AUTH_REQUIRED:
id = R.string.account_setup_failed_auth_required;
break;
case MessagingException.GENERAL_SECURITY:
id = R.string.account_setup_failed_security;
break;
}
}
showErrorBanner(getString(id));
} else if (progress > 0) {
showErrorBanner(null);
}
}
}
}
| true | true | public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mAccountId = getIntent().getLongExtra(EXTRA_ACCOUNT_ID, -1);
if (mAccountId == -1) {
finish();
return;
}
setContentView(R.layout.mailbox_list);
mControllerCallback = new ControllerResultUiThreadWrapper<ControllerResults>(
new Handler(), new ControllerResults());
mActionBar = getActionBar();
mErrorBanner = (TextView) findViewById(R.id.connection_error_text);
mListFragment = (MailboxListFragment) findFragmentById(R.id.mailbox_list_fragment);
mActionBar.setStandardNavigationMode(this.getText(R.string.mailbox_list_title));
mListFragment.setCallback(this);
mListFragment.openMailboxes(mAccountId);
// Go to the database for the account name
mLoadAccountNameTask = new AsyncTask<Void, Void, String[]>() {
@Override
protected String[] doInBackground(Void... params) {
String accountName = null;
Uri uri = ContentUris.withAppendedId(Account.CONTENT_URI, mAccountId);
Cursor c = MailboxList.this.getContentResolver().query(
uri, new String[] { AccountColumns.DISPLAY_NAME }, null, null, null);
try {
if (c.moveToFirst()) {
accountName = c.getString(0);
}
} finally {
c.close();
}
return new String[] { accountName };
}
@Override
protected void onPostExecute(String[] result) {
if (result == null) {
return;
}
final String accountName = (String) result[0];
// accountName is null if account name can't be retrieved or query exception
if (accountName == null) {
// something is wrong with this account
finish();
}
// STOPSHIP this doesn't work - the subtitle doesn't work - bug 2805131
// mActionBar.setStandardNavigationMode(
// MailboxList.this.getText(R.string.mailbox_list_title),
// accountName);
// STOPSHIP - so, for temp fix, show the account name (since it's the dynamic value)
mActionBar.setStandardNavigationMode(accountName);
}
}.execute();
}
| public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mAccountId = getIntent().getLongExtra(EXTRA_ACCOUNT_ID, -1);
if (mAccountId == -1) {
finish();
return;
}
setContentView(R.layout.mailbox_list);
mControllerCallback = new ControllerResultUiThreadWrapper<ControllerResults>(
new Handler(), new ControllerResults());
mActionBar = getActionBar();
mErrorBanner = (TextView) findViewById(R.id.connection_error_text);
mListFragment = (MailboxListFragment) findFragmentById(R.id.mailbox_list_fragment);
mActionBar.setStandardNavigationMode(this.getText(R.string.mailbox_list_title));
mListFragment.setCallback(this);
mListFragment.openMailboxes(mAccountId);
// Go to the database for the account name
mLoadAccountNameTask = new AsyncTask<Void, Void, String[]>() {
@Override
protected String[] doInBackground(Void... params) {
String accountName = null;
Uri uri = ContentUris.withAppendedId(Account.CONTENT_URI, mAccountId);
Cursor c = MailboxList.this.getContentResolver().query(
uri, new String[] { AccountColumns.DISPLAY_NAME }, null, null, null);
try {
if (c.moveToFirst()) {
accountName = c.getString(0);
}
} finally {
c.close();
}
return new String[] { accountName };
}
@Override
protected void onPostExecute(String[] result) {
if (result == null) {
return;
}
final String accountName = (String) result[0];
// accountName is null if account name can't be retrieved or query exception
if (accountName == null) {
// something is wrong with this account
finish();
}
mActionBar.setStandardNavigationMode(
MailboxList.this.getText(R.string.mailbox_list_title),
accountName);
}
}.execute();
}
|
diff --git a/plugins/com.python.pydev.analysis/src/com/python/pydev/analysis/ctrl_1/UndefinedVariableFixParticipant.java b/plugins/com.python.pydev.analysis/src/com/python/pydev/analysis/ctrl_1/UndefinedVariableFixParticipant.java
index e44971993..ecfd731f7 100644
--- a/plugins/com.python.pydev.analysis/src/com/python/pydev/analysis/ctrl_1/UndefinedVariableFixParticipant.java
+++ b/plugins/com.python.pydev.analysis/src/com/python/pydev/analysis/ctrl_1/UndefinedVariableFixParticipant.java
@@ -1,219 +1,222 @@
/*
* Created on 24/09/2005
*/
package com.python.pydev.analysis.ctrl_1;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.swt.graphics.Image;
import org.python.pydev.core.FullRepIterable;
import org.python.pydev.core.IModulesManager;
import org.python.pydev.core.IPythonNature;
import org.python.pydev.core.Tuple;
import org.python.pydev.core.bundle.ImageCache;
import org.python.pydev.core.docutils.PySelection;
import org.python.pydev.core.structure.FastStringBuffer;
import org.python.pydev.editor.PyEdit;
import org.python.pydev.editor.codecompletion.IPyCompletionProposal;
import org.python.pydev.editor.codefolding.PySourceViewer;
import org.python.pydev.plugin.PydevPlugin;
import org.python.pydev.ui.UIConstants;
import com.python.pydev.analysis.AnalysisPlugin;
import com.python.pydev.analysis.CtxInsensitiveImportComplProposal;
import com.python.pydev.analysis.IAnalysisPreferences;
import com.python.pydev.analysis.additionalinfo.AbstractAdditionalInterpreterInfo;
import com.python.pydev.analysis.additionalinfo.AdditionalProjectInterpreterInfo;
import com.python.pydev.analysis.additionalinfo.IInfo;
import com.python.pydev.analysis.builder.AnalysisParserObserver;
import com.python.pydev.analysis.builder.AnalysisRunner;
import com.python.pydev.analysis.ui.AutoImportsPreferencesPage;
/**
* Class that'll create proposals for fixing an undefined variable found.
*
* @author Fabio
*/
public class UndefinedVariableFixParticipant implements IAnalysisMarkersParticipant{
/**
* Defines whether a reparse should be forced after applying the completion.
*/
private boolean forceReparseOnApply;
public UndefinedVariableFixParticipant(){
this(true);
}
public UndefinedVariableFixParticipant(boolean forceReparseOnApply){
this.forceReparseOnApply = forceReparseOnApply;
}
/**
* @see IAnalysisMarkersParticipant#addProps(IMarker, IAnalysisPreferences, String, PySelection, int, IPythonNature,
* PyEdit, List)
*
*/
public void addProps(IMarker marker,
IAnalysisPreferences analysisPreferences,
String line,
PySelection ps,
int offset,
IPythonNature nature,
PyEdit edit,
List<ICompletionProposal> props) throws BadLocationException, CoreException {
Integer id = (Integer) marker.getAttribute(AnalysisRunner.PYDEV_ANALYSIS_TYPE);
if(id != IAnalysisPreferences.TYPE_UNDEFINED_VARIABLE){
return;
}
+ if(nature == null){
+ return;
+ }
Integer start = (Integer) marker.getAttribute(IMarker.CHAR_START);
Integer end = (Integer) marker.getAttribute(IMarker.CHAR_END);
ps.setSelection(start, end);
String markerContents = ps.getSelectedText();
String fullRep = ps.getFullRepAfterSelection();
ImageCache imageCache = PydevPlugin.getImageCache();
Image packageImage = null;
if(imageCache != null){ //making tests
packageImage = imageCache.get(UIConstants.COMPLETION_PACKAGE_ICON);
}
IModulesManager projectModulesManager = nature.getAstManager().getModulesManager();
Set<String> allModules = projectModulesManager.getAllModuleNames(true, markerContents.toLowerCase());
//when an undefined variable is found, we can:
// - add an auto import (if it is a class or a method or some global attribute)
// - declare it as a local or global variable
// - change its name to some other global or local (mistyped)
// - create a method or class for it (if it is a call)
Set<Tuple<String,String>> mods = new HashSet<Tuple<String,String>>();
//1. check if it is some module
//use a single buffer to create all the strings
FastStringBuffer buffer = new FastStringBuffer();
for (String completeName : allModules) {
FullRepIterable iterable = new FullRepIterable(completeName);
for (String mod : iterable) {
if(fullRep.startsWith(mod)){
if(fullRep.length() == mod.length() //it does not only start with, but it is equal to it.
|| (fullRep.length() > mod.length() && fullRep.charAt(mod.length()) == '.')
){
buffer.clear();
String realImportRep = buffer.append("import ").append(mod).toString();
buffer.clear();
String displayString = buffer.append("Import ").append(mod).toString();
addProp(props, realImportRep, displayString, packageImage, offset, mods);
}
}
String[] strings = FullRepIterable.headAndTail(mod);
String packageName = strings[0];
String importRep = strings[1];
if(importRep.equals(markerContents)){
if(packageName.length() > 0){
buffer.clear();
String realImportRep = buffer.append("from ").append(packageName).append(" ").append("import ").append(strings[1]).toString();
buffer.clear();
String displayString = buffer.append("Import ").append(importRep).append(" (").append(packageName).append(")").toString();
addProp(props, realImportRep, displayString, packageImage, offset, mods);
}else{
buffer.clear();
String realImportRep = buffer.append("import ").append(strings[1]).toString();
buffer.clear();
String displayString = buffer.append("Import ").append(importRep).toString();
addProp(props, realImportRep, displayString, packageImage, offset, mods);
}
}
}
}
//2. check if it is some global class or method
List<AbstractAdditionalInterpreterInfo> additionalInfo = AdditionalProjectInterpreterInfo.getAdditionalInfo(nature);
FastStringBuffer tempBuf = new FastStringBuffer();
for (AbstractAdditionalInterpreterInfo info : additionalInfo) {
List<IInfo> tokensEqualTo = info.getTokensEqualTo(markerContents, AbstractAdditionalInterpreterInfo.TOP_LEVEL);
for (IInfo found : tokensEqualTo) {
//there always is a declaring module
String name = found.getName();
String declPackage = found.getDeclaringModuleName();
String declPackageWithoutInit = declPackage;
if(declPackageWithoutInit.endsWith(".__init__")){
declPackageWithoutInit = declPackageWithoutInit.substring(0, declPackageWithoutInit.length()-9);
}
declPackageWithoutInit = AutoImportsPreferencesPage
.removeImportsStartingWithUnderIfNeeded(declPackageWithoutInit, tempBuf);
buffer.clear();
String importDeclaration = buffer.append("from ").append(declPackageWithoutInit).append(" import ")
.append(name).toString();
buffer.clear();
String displayImport = buffer.append("Import ").append(name).append(" (").append(declPackage)
.append(")").toString();
addProp(props, importDeclaration, displayImport, AnalysisPlugin.getImageForAutoImportTypeInfo(found), offset, mods);
}
}
}
private void addProp(List<ICompletionProposal> props, String importDeclaration, String displayImport,
Image importImage, int offset, Set<Tuple<String, String>> mods) {
Tuple<String, String> tuple = new Tuple<String, String>(importDeclaration, displayImport);
if(mods.contains(tuple)){
return;
}
mods.add(tuple);
props.add(new CtxInsensitiveImportComplProposal(
"",
offset,
0,
0,
importImage,
displayImport,
null,
"",
IPyCompletionProposal.PRIORITY_LOCALS,
importDeclaration
){
@Override
public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) {
super.apply(viewer, trigger, stateMask, offset);
if(forceReparseOnApply){
//and after applying it, let's request a reanalysis
if(viewer instanceof PySourceViewer){
PySourceViewer sourceViewer = (PySourceViewer) viewer;
PyEdit edit = sourceViewer.getEdit();
if(edit != null){
edit.getParser().forceReparse(new Tuple<String, Boolean>(
AnalysisParserObserver.ANALYSIS_PARSER_OBSERVER_FORCE, true));
}
}
}
}
});
}
}
| true | true | public void addProps(IMarker marker,
IAnalysisPreferences analysisPreferences,
String line,
PySelection ps,
int offset,
IPythonNature nature,
PyEdit edit,
List<ICompletionProposal> props) throws BadLocationException, CoreException {
Integer id = (Integer) marker.getAttribute(AnalysisRunner.PYDEV_ANALYSIS_TYPE);
if(id != IAnalysisPreferences.TYPE_UNDEFINED_VARIABLE){
return;
}
Integer start = (Integer) marker.getAttribute(IMarker.CHAR_START);
Integer end = (Integer) marker.getAttribute(IMarker.CHAR_END);
ps.setSelection(start, end);
String markerContents = ps.getSelectedText();
String fullRep = ps.getFullRepAfterSelection();
ImageCache imageCache = PydevPlugin.getImageCache();
Image packageImage = null;
if(imageCache != null){ //making tests
packageImage = imageCache.get(UIConstants.COMPLETION_PACKAGE_ICON);
}
IModulesManager projectModulesManager = nature.getAstManager().getModulesManager();
Set<String> allModules = projectModulesManager.getAllModuleNames(true, markerContents.toLowerCase());
//when an undefined variable is found, we can:
// - add an auto import (if it is a class or a method or some global attribute)
// - declare it as a local or global variable
// - change its name to some other global or local (mistyped)
// - create a method or class for it (if it is a call)
Set<Tuple<String,String>> mods = new HashSet<Tuple<String,String>>();
//1. check if it is some module
//use a single buffer to create all the strings
FastStringBuffer buffer = new FastStringBuffer();
for (String completeName : allModules) {
FullRepIterable iterable = new FullRepIterable(completeName);
for (String mod : iterable) {
if(fullRep.startsWith(mod)){
if(fullRep.length() == mod.length() //it does not only start with, but it is equal to it.
|| (fullRep.length() > mod.length() && fullRep.charAt(mod.length()) == '.')
){
buffer.clear();
String realImportRep = buffer.append("import ").append(mod).toString();
buffer.clear();
String displayString = buffer.append("Import ").append(mod).toString();
addProp(props, realImportRep, displayString, packageImage, offset, mods);
}
}
String[] strings = FullRepIterable.headAndTail(mod);
String packageName = strings[0];
String importRep = strings[1];
if(importRep.equals(markerContents)){
if(packageName.length() > 0){
buffer.clear();
String realImportRep = buffer.append("from ").append(packageName).append(" ").append("import ").append(strings[1]).toString();
buffer.clear();
String displayString = buffer.append("Import ").append(importRep).append(" (").append(packageName).append(")").toString();
addProp(props, realImportRep, displayString, packageImage, offset, mods);
}else{
buffer.clear();
String realImportRep = buffer.append("import ").append(strings[1]).toString();
buffer.clear();
String displayString = buffer.append("Import ").append(importRep).toString();
addProp(props, realImportRep, displayString, packageImage, offset, mods);
}
}
}
}
//2. check if it is some global class or method
List<AbstractAdditionalInterpreterInfo> additionalInfo = AdditionalProjectInterpreterInfo.getAdditionalInfo(nature);
FastStringBuffer tempBuf = new FastStringBuffer();
for (AbstractAdditionalInterpreterInfo info : additionalInfo) {
List<IInfo> tokensEqualTo = info.getTokensEqualTo(markerContents, AbstractAdditionalInterpreterInfo.TOP_LEVEL);
for (IInfo found : tokensEqualTo) {
//there always is a declaring module
String name = found.getName();
String declPackage = found.getDeclaringModuleName();
String declPackageWithoutInit = declPackage;
if(declPackageWithoutInit.endsWith(".__init__")){
declPackageWithoutInit = declPackageWithoutInit.substring(0, declPackageWithoutInit.length()-9);
}
declPackageWithoutInit = AutoImportsPreferencesPage
.removeImportsStartingWithUnderIfNeeded(declPackageWithoutInit, tempBuf);
buffer.clear();
String importDeclaration = buffer.append("from ").append(declPackageWithoutInit).append(" import ")
.append(name).toString();
buffer.clear();
String displayImport = buffer.append("Import ").append(name).append(" (").append(declPackage)
.append(")").toString();
addProp(props, importDeclaration, displayImport, AnalysisPlugin.getImageForAutoImportTypeInfo(found), offset, mods);
}
}
}
| public void addProps(IMarker marker,
IAnalysisPreferences analysisPreferences,
String line,
PySelection ps,
int offset,
IPythonNature nature,
PyEdit edit,
List<ICompletionProposal> props) throws BadLocationException, CoreException {
Integer id = (Integer) marker.getAttribute(AnalysisRunner.PYDEV_ANALYSIS_TYPE);
if(id != IAnalysisPreferences.TYPE_UNDEFINED_VARIABLE){
return;
}
if(nature == null){
return;
}
Integer start = (Integer) marker.getAttribute(IMarker.CHAR_START);
Integer end = (Integer) marker.getAttribute(IMarker.CHAR_END);
ps.setSelection(start, end);
String markerContents = ps.getSelectedText();
String fullRep = ps.getFullRepAfterSelection();
ImageCache imageCache = PydevPlugin.getImageCache();
Image packageImage = null;
if(imageCache != null){ //making tests
packageImage = imageCache.get(UIConstants.COMPLETION_PACKAGE_ICON);
}
IModulesManager projectModulesManager = nature.getAstManager().getModulesManager();
Set<String> allModules = projectModulesManager.getAllModuleNames(true, markerContents.toLowerCase());
//when an undefined variable is found, we can:
// - add an auto import (if it is a class or a method or some global attribute)
// - declare it as a local or global variable
// - change its name to some other global or local (mistyped)
// - create a method or class for it (if it is a call)
Set<Tuple<String,String>> mods = new HashSet<Tuple<String,String>>();
//1. check if it is some module
//use a single buffer to create all the strings
FastStringBuffer buffer = new FastStringBuffer();
for (String completeName : allModules) {
FullRepIterable iterable = new FullRepIterable(completeName);
for (String mod : iterable) {
if(fullRep.startsWith(mod)){
if(fullRep.length() == mod.length() //it does not only start with, but it is equal to it.
|| (fullRep.length() > mod.length() && fullRep.charAt(mod.length()) == '.')
){
buffer.clear();
String realImportRep = buffer.append("import ").append(mod).toString();
buffer.clear();
String displayString = buffer.append("Import ").append(mod).toString();
addProp(props, realImportRep, displayString, packageImage, offset, mods);
}
}
String[] strings = FullRepIterable.headAndTail(mod);
String packageName = strings[0];
String importRep = strings[1];
if(importRep.equals(markerContents)){
if(packageName.length() > 0){
buffer.clear();
String realImportRep = buffer.append("from ").append(packageName).append(" ").append("import ").append(strings[1]).toString();
buffer.clear();
String displayString = buffer.append("Import ").append(importRep).append(" (").append(packageName).append(")").toString();
addProp(props, realImportRep, displayString, packageImage, offset, mods);
}else{
buffer.clear();
String realImportRep = buffer.append("import ").append(strings[1]).toString();
buffer.clear();
String displayString = buffer.append("Import ").append(importRep).toString();
addProp(props, realImportRep, displayString, packageImage, offset, mods);
}
}
}
}
//2. check if it is some global class or method
List<AbstractAdditionalInterpreterInfo> additionalInfo = AdditionalProjectInterpreterInfo.getAdditionalInfo(nature);
FastStringBuffer tempBuf = new FastStringBuffer();
for (AbstractAdditionalInterpreterInfo info : additionalInfo) {
List<IInfo> tokensEqualTo = info.getTokensEqualTo(markerContents, AbstractAdditionalInterpreterInfo.TOP_LEVEL);
for (IInfo found : tokensEqualTo) {
//there always is a declaring module
String name = found.getName();
String declPackage = found.getDeclaringModuleName();
String declPackageWithoutInit = declPackage;
if(declPackageWithoutInit.endsWith(".__init__")){
declPackageWithoutInit = declPackageWithoutInit.substring(0, declPackageWithoutInit.length()-9);
}
declPackageWithoutInit = AutoImportsPreferencesPage
.removeImportsStartingWithUnderIfNeeded(declPackageWithoutInit, tempBuf);
buffer.clear();
String importDeclaration = buffer.append("from ").append(declPackageWithoutInit).append(" import ")
.append(name).toString();
buffer.clear();
String displayImport = buffer.append("Import ").append(name).append(" (").append(declPackage)
.append(")").toString();
addProp(props, importDeclaration, displayImport, AnalysisPlugin.getImageForAutoImportTypeInfo(found), offset, mods);
}
}
}
|
diff --git a/core/src/main/java/hudson/util/DescribableList.java b/core/src/main/java/hudson/util/DescribableList.java
index ec7912ea5..af7644701 100644
--- a/core/src/main/java/hudson/util/DescribableList.java
+++ b/core/src/main/java/hudson/util/DescribableList.java
@@ -1,149 +1,149 @@
package hudson.util;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.converters.collections.AbstractCollectionConverter;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.mapper.Mapper;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.model.Descriptor.FormException;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.StaplerRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Persisted list of {@link Describable}s with some operations specific
* to {@link Descriptor}s.
*
* @author Kohsuke Kawaguchi
*/
public class DescribableList<T extends Describable<T>, D extends Descriptor<T>> implements Iterable<T> {
private final CopyOnWriteList<T> data = new CopyOnWriteList<T>();
private Owner owner;
private DescribableList() {
}
public DescribableList(Owner owner) {
setOwner(owner);
}
public void setOwner(Owner owner) {
this.owner = owner;
}
public void add(T item) throws IOException {
data.add(item);
owner.save();
}
public T get(D descriptor) {
for (T t : data)
if(t.getDescriptor()==descriptor)
return t;
return null;
}
public boolean contains(D d) {
return get(d)!=null;
}
public void remove(D descriptor) throws IOException {
for (T t : data) {
if(t.getDescriptor()==descriptor) {
data.remove(t);
owner.save();
return;
}
}
}
public Iterator<T> iterator() {
return data.iterator();
}
@SuppressWarnings("unchecked")
public Map<D,T> toMap() {
return (Map)Descriptor.toMap(data);
}
/**
* Gets all the {@link Describable}s in an array.
*/
public T[] toArray(T[] array) {
return data.toArray(array);
}
public void addAllTo(Collection<? super T> dst) {
data.addAllTo(dst);
}
/**
* Rebuilds the list by creating a fresh instances from the submitted form.
*
* <p>
* This method is almost always used by the owner.
* This method does not invoke the save method.
*
* @param json
* Structured form data that includes the data for nested descriptor list.
*/
public void rebuild(StaplerRequest req, JSONObject json, List<? extends Descriptor<T>> descriptors, String prefix) throws FormException {
List<T> newList = new ArrayList<T>();
for( int i=0; i< descriptors.size(); i++ ) {
String name = prefix + i;
- if(req.getParameter(name)!=null) {
+ if(json.has(name)) {
T instance = descriptors.get(i).newInstance(req,json.getJSONObject(name));
newList.add(instance);
}
}
data.replaceBy(newList);
}
public interface Owner {
/**
* Called whenever the list is changed, so that it can be saved.
*/
void save() throws IOException;
}
/**
* {@link Converter} implementation for XStream.
*/
public static final class ConverterImpl extends AbstractCollectionConverter {
CopyOnWriteList.ConverterImpl copyOnWriteListConverter;
public ConverterImpl(Mapper mapper) {
super(mapper);
copyOnWriteListConverter = new CopyOnWriteList.ConverterImpl(mapper());
}
public boolean canConvert(Class type) {
return type==DescribableList.class;
}
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
for (Object o : (DescribableList) source)
writeItem(o, context, writer);
}
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
CopyOnWriteList core = copyOnWriteListConverter.unmarshal(reader, context);
DescribableList r = new DescribableList();
r.data.replaceBy(core);
return r;
}
}
}
| true | true | public void rebuild(StaplerRequest req, JSONObject json, List<? extends Descriptor<T>> descriptors, String prefix) throws FormException {
List<T> newList = new ArrayList<T>();
for( int i=0; i< descriptors.size(); i++ ) {
String name = prefix + i;
if(req.getParameter(name)!=null) {
T instance = descriptors.get(i).newInstance(req,json.getJSONObject(name));
newList.add(instance);
}
}
data.replaceBy(newList);
}
| public void rebuild(StaplerRequest req, JSONObject json, List<? extends Descriptor<T>> descriptors, String prefix) throws FormException {
List<T> newList = new ArrayList<T>();
for( int i=0; i< descriptors.size(); i++ ) {
String name = prefix + i;
if(json.has(name)) {
T instance = descriptors.get(i).newInstance(req,json.getJSONObject(name));
newList.add(instance);
}
}
data.replaceBy(newList);
}
|
diff --git a/astrid/plugin-src/com/todoroo/astrid/producteev/ProducteevDetailExposer.java b/astrid/plugin-src/com/todoroo/astrid/producteev/ProducteevDetailExposer.java
index aecd45464..545a3f822 100644
--- a/astrid/plugin-src/com/todoroo/astrid/producteev/ProducteevDetailExposer.java
+++ b/astrid/plugin-src/com/todoroo/astrid/producteev/ProducteevDetailExposer.java
@@ -1,141 +1,141 @@
/**
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.astrid.producteev;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.timsu.astrid.R;
import com.todoroo.andlib.data.TodorooCursor;
import com.todoroo.astrid.adapter.TaskAdapter;
import com.todoroo.astrid.api.AstridApiConstants;
import com.todoroo.astrid.api.DetailExposer;
import com.todoroo.astrid.model.Metadata;
import com.todoroo.astrid.model.StoreObject;
import com.todoroo.astrid.producteev.sync.ProducteevDashboard;
import com.todoroo.astrid.producteev.sync.ProducteevDataService;
import com.todoroo.astrid.producteev.sync.ProducteevNote;
import com.todoroo.astrid.producteev.sync.ProducteevTask;
import com.todoroo.astrid.utility.Preferences;
/**
* Exposes Task Details for Producteev:
* - notes
*
* @author Tim Su <[email protected]>
*
*/
public class ProducteevDetailExposer extends BroadcastReceiver implements DetailExposer{
@Override
public void onReceive(Context context, Intent intent) {
// if we aren't logged in, don't expose features
if(!ProducteevUtilities.INSTANCE.isLoggedIn())
return;
long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1);
if(taskId == -1)
return;
boolean extended = intent.getBooleanExtra(AstridApiConstants.EXTRAS_EXTENDED, false);
String taskDetail = getTaskDetails(context, taskId, extended);
if(taskDetail == null)
return;
Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_SEND_DETAILS);
broadcastIntent.putExtra(AstridApiConstants.EXTRAS_ADDON, ProducteevUtilities.IDENTIFIER);
broadcastIntent.putExtra(AstridApiConstants.EXTRAS_TASK_ID, taskId);
broadcastIntent.putExtra(AstridApiConstants.EXTRAS_EXTENDED, extended);
broadcastIntent.putExtra(AstridApiConstants.EXTRAS_RESPONSE, taskDetail);
context.sendBroadcast(broadcastIntent, AstridApiConstants.PERMISSION_READ);
}
@Override
public String getTaskDetails(Context context, long id, boolean extended) {
Metadata metadata = ProducteevDataService.getInstance().getTaskMetadata(id);
if(metadata == null)
return null;
StringBuilder builder = new StringBuilder();
if(!extended) {
long dashboardId = metadata.getValue(ProducteevTask.DASHBOARD_ID);
long responsibleId = -1;
if(metadata.containsNonNullValue(ProducteevTask.RESPONSIBLE_ID))
responsibleId = metadata.getValue(ProducteevTask.RESPONSIBLE_ID);
long creatorId = -1;
if(metadata.containsNonNullValue(ProducteevTask.CREATOR_ID))
- responsibleId = metadata.getValue(ProducteevTask.CREATOR_ID);
+ creatorId = metadata.getValue(ProducteevTask.CREATOR_ID);
// display dashboard if not "no sync" or "default"
StoreObject ownerDashboard = null;
for(StoreObject dashboard : ProducteevDataService.getInstance().getDashboards()) {
if(dashboard == null || !dashboard.containsNonNullValue(ProducteevDashboard.REMOTE_ID))
continue;
if(dashboard.getValue(ProducteevDashboard.REMOTE_ID) == dashboardId) {
ownerDashboard = dashboard;
break;
}
}
if(dashboardId != ProducteevUtilities.DASHBOARD_NO_SYNC && dashboardId
!= Preferences.getLong(ProducteevUtilities.PREF_DEFAULT_DASHBOARD, 0L) &&
ownerDashboard != null) {
String dashboardName = ownerDashboard.getValue(ProducteevDashboard.NAME);
builder.append("<img src='silk_folder'/> ").append(dashboardName).append(TaskAdapter.DETAIL_SEPARATOR); //$NON-NLS-1$
}
// display responsible user if not current one
if(responsibleId > 0 && ownerDashboard != null && responsibleId !=
Preferences.getLong(ProducteevUtilities.PREF_USER_ID, 0L)) {
String user = getUserFromDashboard(ownerDashboard, responsibleId);
if(user != null)
builder.append("<img src='silk_user_gray'/> ").append(user).append(TaskAdapter.DETAIL_SEPARATOR); //$NON-NLS-1$
}
// display creator user if not the current one
if(creatorId > 0 && ownerDashboard != null && creatorId !=
Preferences.getLong(ProducteevUtilities.PREF_USER_ID, 0L)) {
- String user = getUserFromDashboard(ownerDashboard, responsibleId);
+ String user = getUserFromDashboard(ownerDashboard, creatorId);
if(user != null)
- builder.append("<img src='silk_user_gray'/> ").append( //$NON-NLS-1$
+ builder.append("<img src='silk_user_orange'/> ").append( //$NON-NLS-1$
context.getString(R.string.producteev_PDE_task_from, user)).
append(TaskAdapter.DETAIL_SEPARATOR);
}
} else {
TodorooCursor<Metadata> notesCursor = ProducteevDataService.getInstance().getTaskNotesCursor(id);
try {
for(notesCursor.moveToFirst(); !notesCursor.isAfterLast(); notesCursor.moveToNext()) {
metadata.readFromCursor(notesCursor);
builder.append(metadata.getValue(ProducteevNote.MESSAGE)).append(TaskAdapter.DETAIL_SEPARATOR);
}
} finally {
notesCursor.close();
}
}
if(builder.length() == 0)
return null;
String result = builder.toString();
return result.substring(0, result.length() - TaskAdapter.DETAIL_SEPARATOR.length());
}
/** Try and find user in the dashboard. return null if un-findable */
private String getUserFromDashboard(StoreObject dashboard, long userId) {
String users = ";" + dashboard.getValue(ProducteevDashboard.USERS); //$NON-NLS-1$
int index = users.indexOf(";" + userId + ","); //$NON-NLS-1$ //$NON-NLS-2$
if(index > -1)
return users.substring(users.indexOf(',', index) + 1,
users.indexOf(';', index + 1));
return null;
}
@Override
public String getPluginIdentifier() {
return ProducteevUtilities.IDENTIFIER;
}
}
| false | true | public String getTaskDetails(Context context, long id, boolean extended) {
Metadata metadata = ProducteevDataService.getInstance().getTaskMetadata(id);
if(metadata == null)
return null;
StringBuilder builder = new StringBuilder();
if(!extended) {
long dashboardId = metadata.getValue(ProducteevTask.DASHBOARD_ID);
long responsibleId = -1;
if(metadata.containsNonNullValue(ProducteevTask.RESPONSIBLE_ID))
responsibleId = metadata.getValue(ProducteevTask.RESPONSIBLE_ID);
long creatorId = -1;
if(metadata.containsNonNullValue(ProducteevTask.CREATOR_ID))
responsibleId = metadata.getValue(ProducteevTask.CREATOR_ID);
// display dashboard if not "no sync" or "default"
StoreObject ownerDashboard = null;
for(StoreObject dashboard : ProducteevDataService.getInstance().getDashboards()) {
if(dashboard == null || !dashboard.containsNonNullValue(ProducteevDashboard.REMOTE_ID))
continue;
if(dashboard.getValue(ProducteevDashboard.REMOTE_ID) == dashboardId) {
ownerDashboard = dashboard;
break;
}
}
if(dashboardId != ProducteevUtilities.DASHBOARD_NO_SYNC && dashboardId
!= Preferences.getLong(ProducteevUtilities.PREF_DEFAULT_DASHBOARD, 0L) &&
ownerDashboard != null) {
String dashboardName = ownerDashboard.getValue(ProducteevDashboard.NAME);
builder.append("<img src='silk_folder'/> ").append(dashboardName).append(TaskAdapter.DETAIL_SEPARATOR); //$NON-NLS-1$
}
// display responsible user if not current one
if(responsibleId > 0 && ownerDashboard != null && responsibleId !=
Preferences.getLong(ProducteevUtilities.PREF_USER_ID, 0L)) {
String user = getUserFromDashboard(ownerDashboard, responsibleId);
if(user != null)
builder.append("<img src='silk_user_gray'/> ").append(user).append(TaskAdapter.DETAIL_SEPARATOR); //$NON-NLS-1$
}
// display creator user if not the current one
if(creatorId > 0 && ownerDashboard != null && creatorId !=
Preferences.getLong(ProducteevUtilities.PREF_USER_ID, 0L)) {
String user = getUserFromDashboard(ownerDashboard, responsibleId);
if(user != null)
builder.append("<img src='silk_user_gray'/> ").append( //$NON-NLS-1$
context.getString(R.string.producteev_PDE_task_from, user)).
append(TaskAdapter.DETAIL_SEPARATOR);
}
} else {
TodorooCursor<Metadata> notesCursor = ProducteevDataService.getInstance().getTaskNotesCursor(id);
try {
for(notesCursor.moveToFirst(); !notesCursor.isAfterLast(); notesCursor.moveToNext()) {
metadata.readFromCursor(notesCursor);
builder.append(metadata.getValue(ProducteevNote.MESSAGE)).append(TaskAdapter.DETAIL_SEPARATOR);
}
} finally {
notesCursor.close();
}
}
if(builder.length() == 0)
return null;
String result = builder.toString();
return result.substring(0, result.length() - TaskAdapter.DETAIL_SEPARATOR.length());
}
| public String getTaskDetails(Context context, long id, boolean extended) {
Metadata metadata = ProducteevDataService.getInstance().getTaskMetadata(id);
if(metadata == null)
return null;
StringBuilder builder = new StringBuilder();
if(!extended) {
long dashboardId = metadata.getValue(ProducteevTask.DASHBOARD_ID);
long responsibleId = -1;
if(metadata.containsNonNullValue(ProducteevTask.RESPONSIBLE_ID))
responsibleId = metadata.getValue(ProducteevTask.RESPONSIBLE_ID);
long creatorId = -1;
if(metadata.containsNonNullValue(ProducteevTask.CREATOR_ID))
creatorId = metadata.getValue(ProducteevTask.CREATOR_ID);
// display dashboard if not "no sync" or "default"
StoreObject ownerDashboard = null;
for(StoreObject dashboard : ProducteevDataService.getInstance().getDashboards()) {
if(dashboard == null || !dashboard.containsNonNullValue(ProducteevDashboard.REMOTE_ID))
continue;
if(dashboard.getValue(ProducteevDashboard.REMOTE_ID) == dashboardId) {
ownerDashboard = dashboard;
break;
}
}
if(dashboardId != ProducteevUtilities.DASHBOARD_NO_SYNC && dashboardId
!= Preferences.getLong(ProducteevUtilities.PREF_DEFAULT_DASHBOARD, 0L) &&
ownerDashboard != null) {
String dashboardName = ownerDashboard.getValue(ProducteevDashboard.NAME);
builder.append("<img src='silk_folder'/> ").append(dashboardName).append(TaskAdapter.DETAIL_SEPARATOR); //$NON-NLS-1$
}
// display responsible user if not current one
if(responsibleId > 0 && ownerDashboard != null && responsibleId !=
Preferences.getLong(ProducteevUtilities.PREF_USER_ID, 0L)) {
String user = getUserFromDashboard(ownerDashboard, responsibleId);
if(user != null)
builder.append("<img src='silk_user_gray'/> ").append(user).append(TaskAdapter.DETAIL_SEPARATOR); //$NON-NLS-1$
}
// display creator user if not the current one
if(creatorId > 0 && ownerDashboard != null && creatorId !=
Preferences.getLong(ProducteevUtilities.PREF_USER_ID, 0L)) {
String user = getUserFromDashboard(ownerDashboard, creatorId);
if(user != null)
builder.append("<img src='silk_user_orange'/> ").append( //$NON-NLS-1$
context.getString(R.string.producteev_PDE_task_from, user)).
append(TaskAdapter.DETAIL_SEPARATOR);
}
} else {
TodorooCursor<Metadata> notesCursor = ProducteevDataService.getInstance().getTaskNotesCursor(id);
try {
for(notesCursor.moveToFirst(); !notesCursor.isAfterLast(); notesCursor.moveToNext()) {
metadata.readFromCursor(notesCursor);
builder.append(metadata.getValue(ProducteevNote.MESSAGE)).append(TaskAdapter.DETAIL_SEPARATOR);
}
} finally {
notesCursor.close();
}
}
if(builder.length() == 0)
return null;
String result = builder.toString();
return result.substring(0, result.length() - TaskAdapter.DETAIL_SEPARATOR.length());
}
|
diff --git a/connectors/solr/connector/src/main/java/org/apache/manifoldcf/agents/output/solr/HttpPoster.java b/connectors/solr/connector/src/main/java/org/apache/manifoldcf/agents/output/solr/HttpPoster.java
index 645a6711f..09c969138 100644
--- a/connectors/solr/connector/src/main/java/org/apache/manifoldcf/agents/output/solr/HttpPoster.java
+++ b/connectors/solr/connector/src/main/java/org/apache/manifoldcf/agents/output/solr/HttpPoster.java
@@ -1,2089 +1,2090 @@
/* $Id: HttpPoster.java 991295 2010-08-31 19:12:14Z kwright $ */
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.manifoldcf.agents.output.solr;
import org.apache.manifoldcf.core.interfaces.*;
import org.apache.manifoldcf.core.common.Base64;
import org.apache.manifoldcf.core.common.XMLDoc;
import org.apache.manifoldcf.agents.interfaces.*;
import org.apache.manifoldcf.agents.system.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.net.*;
import javax.net.ssl.*;
import org.apache.log4j.*;
/**
* Posts an input stream to SOLR
*
* @author James Sablatura, modified by Karl Wright
*/
public class HttpPoster
{
public static final String _rcsid = "@(#)$Id: HttpPoster.java 991295 2010-08-31 19:12:14Z kwright $";
/** Ingestion buffer size property. */
public static String ingestBufferSizeProperty = "org.apache.manifoldcf.ingest.buffersize";
public static String ingestCredentialsRealm = "org.apache.manifoldcf.ingest.credentialrealm";
public static String ingestResponseRetryCount = "org.apache.manifoldcf.ingest.responseretrycount";
public static String ingestResponseRetryInterval = "org.apache.manifoldcf.ingest.retryinterval";
public static String ingestRescheduleInterval = "org.apache.manifoldcf.ingest.rescheduleinterval";
public static String ingestURIProperty = "org.apache.manifoldcf.ingest.uri";
public static String ingestUserProperty = "org.apache.manifoldcf.ingest.user";
public static String ingestPasswordProperty = "org.apache.manifoldcf.ingest.password";
public static String ingestMaxConnectionsProperty = "org.apache.manifoldcf.ingest.maxconnections";
// Chunk size for base64-encoded headers
protected final static int HEADER_CHUNK = 4096;
private String protocol;
private String host;
private javax.net.ssl.SSLSocketFactory socketFactory;
private int port;
private String encodedCredentials;
private String realm;
private String postUpdateAction;
private String postRemoveAction;
private String postStatusAction;
private String allowAttributeName;
private String denyAttributeName;
private String idAttributeName;
private static final String LITERAL = "literal.";
private static final String NOTHING = "__NOTHING__";
private static final String ID_METADATA = "lcf_metadata_id";
private int buffersize = 32768; // default buffer size
double sizeCoefficient = 0.0005; // 20 ms additional timeout per 2000 bytes, pulled out of my butt
/** the number of times we should poll for the response */
int responseRetries = 9000; // Long basic wait: 3 minutes. This will also be added to by a term based on the size of the request.
/** how long we should wait before checking for a new stream */
long responseRetryWait = 20L;
/** How long to wait before retrying a failed ingestion */
long interruptionRetryTime = 60000L;
/** The multipart separator we're going to use. I was thinking of including a random number, but that would wreck repeatability */
protected static byte[] separatorBytes = null;
protected static byte[] endBytes = null;
protected static byte[] postambleBytes = null;
protected static byte[] preambleBytes = null;
static
{
try
{
String separatorString = "------------------T-H-I-S--I-S--A--S-E-P-A-R-A-T-O-R--399123410141511";
separatorBytes = (separatorString+"\r\n").getBytes("ASCII");
endBytes = ("--"+separatorString+"--\r\n").getBytes("ASCII");
postambleBytes = "\r\n".getBytes("ASCII");
preambleBytes = "--".getBytes("ASCII");
}
catch (java.io.UnsupportedEncodingException e)
{
e.printStackTrace();
System.exit(1);
}
}
/** This is the secure socket factory we will use. I'm presuming it's thread-safe, but
* if not, synchronization blocks are in order when it's used. */
protected static javax.net.ssl.SSLSocketFactory openSecureSocketFactory = null;
static
{
try
{
openSecureSocketFactory = getOpenSecureSocketFactory();
}
catch (ManifoldCFException e)
{
// If we can't create, print and fail
e.printStackTrace();
System.exit(100);
}
}
/**
* Initialized the http poster.
* @param userID is the unencoded user name, or null.
* @param password is the unencoded password, or null.
*/
public HttpPoster(String protocol, String server, int port, String webappName,
String updatePath, String removePath, String statusPath,
String realm, String userID, String password,
String allowAttributeName, String denyAttributeName, String idAttributeName,
IKeystoreManager keystoreManager)
throws ManifoldCFException
{
this.allowAttributeName = allowAttributeName;
this.denyAttributeName = denyAttributeName;
this.idAttributeName = idAttributeName;
this.host = server;
this.port = port;
this.protocol = protocol;
if (keystoreManager != null)
this.socketFactory = keystoreManager.getSecureSocketFactory();
else
// Use the "trust everything" one.
this.socketFactory = openSecureSocketFactory;
if (userID != null && userID.length() > 0 && password != null)
{
try
{
encodedCredentials = new org.apache.manifoldcf.core.common.Base64().encodeByteArray((userID+":"+password).getBytes("UTF-8"));
}
catch (java.io.UnsupportedEncodingException e)
{
throw new ManifoldCFException("Couldn't convert to utf-8 bytes: "+e.getMessage(),e);
}
this.realm = realm;
}
else
encodedCredentials = null;
String postURI = protocol + "://" + server + ":" + Integer.toString(port);
if (webappName.length() > 0)
webappName = "/" + webappName;
postUpdateAction = webappName + updatePath;
postRemoveAction = webappName + removePath;
postStatusAction = webappName + statusPath;
String x = ManifoldCF.getProperty(ingestBufferSizeProperty);
if (x != null && x.length() > 0)
buffersize = new Integer(x).intValue();
x = ManifoldCF.getProperty(ingestResponseRetryCount);
if (x != null && x.length() > 0)
responseRetries = new Integer(x).intValue();
x = ManifoldCF.getProperty(ingestResponseRetryInterval);
if (x != null && x.length() > 0)
responseRetryWait = new Long(x).longValue();
x = ManifoldCF.getProperty(ingestRescheduleInterval);
if (x != null && x.length() > 0)
interruptionRetryTime = new Long(x).longValue();
}
/** Cause a commit to happen.
*/
public void commitPost()
throws ManifoldCFException, ServiceInterruption
{
if (Logging.ingest.isDebugEnabled())
Logging.ingest.debug("commitPost()");
int ioErrorRetry = 5;
while (true)
{
// Open a socket to ingest, and to the response stream to get the post result
try
{
CommitThread t = new CommitThread();
try
{
t.start();
t.join();
Throwable thr = t.getException();
if (thr != null)
{
if (thr instanceof ServiceInterruption)
throw (ServiceInterruption)thr;
if (thr instanceof ManifoldCFException)
throw (ManifoldCFException)thr;
if (thr instanceof IOException)
throw (IOException)thr;
if (thr instanceof RuntimeException)
throw (RuntimeException)thr;
else
throw (Error)thr;
}
return;
}
catch (InterruptedException e)
{
t.interrupt();
throw new ManifoldCFException("Interrupted: "+e.getMessage(),ManifoldCFException.INTERRUPTED);
}
}
catch (IOException ioe)
{
if (ioErrorRetry == 0)
{
long currentTime = System.currentTimeMillis();
throw new ServiceInterruption("IO exception committing: "+ioe.getMessage(),
ioe,
currentTime + interruptionRetryTime,
currentTime + 2L * 60L * 60000L,
-1,
true);
}
}
// Go back around again!
// Sleep for a time, and retry
try
{
ManifoldCF.sleep(10000L);
}
catch (InterruptedException e)
{
throw new ManifoldCFException("Interrupted",ManifoldCFException.INTERRUPTED);
}
ioErrorRetry--;
}
}
/**
* Post the input stream to ingest
* @param documentURI is the document's uri.
* @param document is the document structure to ingest.
* @param arguments are the configuration arguments to pass in the post. Key is argument name, value is a list of the argument values.
* @param authorityNameString is the name of the governing authority for this document's acls, or null if none.
* @param activities is the activities object, so we can report what's happening.
* @return true if the ingestion was successful, or false if the ingestion is illegal.
* @throws ManifoldCFException, ServiceInterruption
*/
public boolean indexPost(String documentURI,
RepositoryDocument document, Map arguments, Map sourceTargets,
String authorityNameString, IOutputAddActivity activities)
throws ManifoldCFException, ServiceInterruption
{
if (Logging.ingest.isDebugEnabled())
Logging.ingest.debug("indexPost(): '" + documentURI + "'");
// The SOLR connector cannot deal with folder-level security at this time. If they are seen, reject the document.
if (document.countDirectoryACLs() != 0)
return false;
// Convert the incoming acls to qualified forms
String[] shareAcls = convertACL(document.getShareACL(),authorityNameString,activities);
String[] shareDenyAcls = convertACL(document.getShareDenyACL(),authorityNameString,activities);
String[] acls = convertACL(document.getACL(),authorityNameString,activities);
String[] denyAcls = convertACL(document.getDenyACL(),authorityNameString,activities);
// This flag keeps track of whether we read anything from the input stream yet.
// If not, we can retry here. If so, we have to reschedule.
boolean readFromDocumentStreamYet = false;
int ioErrorRetry = 3;
while (true)
{
try
{
IngestThread t = new IngestThread(documentURI,document,arguments,sourceTargets,shareAcls,shareDenyAcls,acls,denyAcls);
try
{
t.start();
t.join();
// Log the activity, if any, regardless of any exception
if (t.getActivityCode() != null)
activities.recordActivity(t.getActivityStart(),SolrConnector.INGEST_ACTIVITY,t.getActivityBytes(),documentURI,t.getActivityCode(),t.getActivityDetails());
readFromDocumentStreamYet = (readFromDocumentStreamYet || t.getReadFromDocumentStreamYet());
Throwable thr = t.getException();
if (thr != null)
{
if (thr instanceof ServiceInterruption)
throw (ServiceInterruption)thr;
if (thr instanceof ManifoldCFException)
throw (ManifoldCFException)thr;
if (thr instanceof IOException)
throw (IOException)thr;
if (thr instanceof RuntimeException)
throw (RuntimeException)thr;
else
throw (Error)thr;
}
return t.getRval();
}
catch (InterruptedException e)
{
t.interrupt();
throw new ManifoldCFException("Interrupted: "+e.getMessage(),ManifoldCFException.INTERRUPTED);
}
}
catch (java.net.SocketTimeoutException ioe)
{
if (readFromDocumentStreamYet || ioErrorRetry == 0)
{
// If this continues, we should indeed abort the job. Retries should not go on indefinitely either; 2 hours is plenty
long currentTime = System.currentTimeMillis();
throw new ServiceInterruption("IO error connecting to ingestion API: "+ioe.getMessage()+"; ingestion will be retried again later",
ioe,
currentTime + interruptionRetryTime,
currentTime + 2L * 60L * 60000L,
-1,
true);
}
}
catch (IOException ioe)
{
if (readFromDocumentStreamYet || ioErrorRetry == 0)
{
// If this continues, we should indeed abort the job. Retries should not go on indefinitely either; 2 hours is plenty
long currentTime = System.currentTimeMillis();
throw new ServiceInterruption("IO error ingesting document: "+ioe.getMessage()+"; ingestion will be retried again later",
ioe,
currentTime + interruptionRetryTime,
currentTime + 2L * 60L * 60000L,
-1,
true);
}
}
// Sleep for a time, and retry
try
{
ManifoldCF.sleep(10000L);
}
catch (InterruptedException e)
{
throw new ManifoldCFException("Interrupted: "+e.getMessage(),ManifoldCFException.INTERRUPTED);
}
ioErrorRetry--;
// Go back around again!
}
}
/** Post a check request.
*/
public void checkPost()
throws ManifoldCFException, ServiceInterruption
{
if (Logging.ingest.isDebugEnabled())
Logging.ingest.debug("checkPost()");
int ioErrorRetry = 5;
while (true)
{
// Open a socket to ingest, and to the response stream to get the post result
try
{
StatusThread t = new StatusThread();
try
{
t.start();
t.join();
Throwable thr = t.getException();
if (thr != null)
{
if (thr instanceof ServiceInterruption)
throw (ServiceInterruption)thr;
if (thr instanceof ManifoldCFException)
throw (ManifoldCFException)thr;
if (thr instanceof IOException)
throw (IOException)thr;
if (thr instanceof RuntimeException)
throw (RuntimeException)thr;
else
throw (Error)thr;
}
return;
}
catch (InterruptedException e)
{
t.interrupt();
throw new ManifoldCFException("Interrupted: "+e.getMessage(),ManifoldCFException.INTERRUPTED);
}
}
catch (IOException ioe)
{
if (ioErrorRetry == 0)
{
long currentTime = System.currentTimeMillis();
throw new ServiceInterruption("IO exception checking: "+ioe.getMessage(),
ioe,
currentTime + interruptionRetryTime,
currentTime + 2L * 60L * 60000L,
-1,
true);
}
}
// Go back around again!
// Sleep for a time, and retry
try
{
ManifoldCF.sleep(10000L);
}
catch (InterruptedException e)
{
throw new ManifoldCFException("Interrupted",ManifoldCFException.INTERRUPTED);
}
ioErrorRetry--;
}
}
/** Post a delete request.
*@param documentURI is the document's URI.
*/
public void deletePost(String documentURI, IOutputRemoveActivity activities)
throws ManifoldCFException, ServiceInterruption
{
if (Logging.ingest.isDebugEnabled())
Logging.ingest.debug("deletePost(): '" + documentURI + "'");
int ioErrorRetry = 5;
while (true)
{
try
{
DeleteThread t = new DeleteThread(documentURI);
try
{
t.start();
t.join();
// Log the activity, if any, regardless of any exception
if (t.getActivityCode() != null)
activities.recordActivity(t.getActivityStart(),SolrConnector.REMOVE_ACTIVITY,null,documentURI,t.getActivityCode(),t.getActivityDetails());
Throwable thr = t.getException();
if (thr != null)
{
if (thr instanceof ServiceInterruption)
throw (ServiceInterruption)thr;
if (thr instanceof ManifoldCFException)
throw (ManifoldCFException)thr;
if (thr instanceof IOException)
throw (IOException)thr;
if (thr instanceof RuntimeException)
throw (RuntimeException)thr;
else
throw (Error)thr;
}
return;
}
catch (InterruptedException e)
{
t.interrupt();
throw new ManifoldCFException("Interrupted: "+e.getMessage(),ManifoldCFException.INTERRUPTED);
}
}
catch (IOException ioe)
{
if (ioErrorRetry == 0)
{
long currentTime = System.currentTimeMillis();
throw new ServiceInterruption("IO exception deleting: "+ioe.getMessage()+"; deletion will be retried again later",
ioe,
currentTime + interruptionRetryTime,
currentTime + 2L * 60L * 60000L,
-1,
true);
}
// Fall through and recycle
}
// Go back around again!
// Sleep for a time, and retry
try
{
ManifoldCF.sleep(10000L);
}
catch (InterruptedException e)
{
throw new ManifoldCFException("Interrupted",ManifoldCFException.INTERRUPTED);
}
ioErrorRetry--;
}
}
/** Convert an unqualified ACL to qualified form.
* @param acl is the initial, unqualified ACL.
* @param authorityNameString is the name of the governing authority for this document's acls, or null if none.
* @param activities is the activities object, so we can report what's happening.
* @return the modified ACL.
*/
protected static String[] convertACL(String[] acl, String authorityNameString, IOutputAddActivity activities)
throws ManifoldCFException
{
if (acl != null)
{
String[] rval = new String[acl.length];
int i = 0;
while (i < rval.length)
{
rval[i] = activities.qualifyAccessToken(authorityNameString,acl[i]);
i++;
}
return rval;
}
return new String[0];
}
/**
* Read an ascii line from an input stream
*/
protected static String readLine(InputStream in)
throws IOException
{
ByteBuffer bb = new ByteBuffer();
while (true)
{
int x = in.read();
if (x == -1)
throw new IOException("Unexpected EOF");
if (x == 13)
continue;
if (x == 10)
break;
bb.append((byte)x);
}
return bb.toString("ASCII");
}
/**
* Get the response code of the post
* @param in the stream the response is going to come from
* @return the response details.
* @throws ManifoldCFException
*/
protected CodeDetails getResponse(InputStream in) throws ManifoldCFException, ServiceInterruption
{
Logging.ingest.debug("Waiting for response stream");
try
{
// Stream.ready() always returns false for secure sockets :-(. So
// we have to rely on socket timeouts to interrupt us if the server goes down.
String responseCode = readLine(in);
if (Logging.ingest.isDebugEnabled())
Logging.ingest.debug("Response code from ingest: '" + responseCode + "'");
// Read the response headers
String contentType = "text/plain; charset=iso-8859-1";
while (true)
{
String headerLine = readLine(in);
if (headerLine.length() == 0)
break;
// Look for the headers we care about, ignore the rest...
int spaceIndex = headerLine.indexOf(" ");
if (spaceIndex != -1)
{
String headerName = headerLine.substring(0,spaceIndex);
String headerValue = headerLine.substring(spaceIndex).trim().toLowerCase();
if (headerName.toLowerCase().equals("content-type:"))
{
contentType = headerValue;
}
}
}
// Now read the response data. It's safe to assemble the data in memory.
int charsetIndex = contentType.indexOf("charset=");
String charsetName = "iso-8859-1";
if (charsetIndex != -1)
charsetName = contentType.substring(charsetIndex+8);
// NOTE: We may get back an unparseable pile of goo here, especially if the error is a 500 error.
// But we can't hand the binary to the XML parser and still be able to get at the raw data. So we
// read the data into memory first (as binary), and then make a decision based on parseability as to whether
// we attempt to decode it.
byte[] responseContent = readInputStream(in);
XMLDoc doc = null;
String rawString = null;
try
{
doc = new XMLDoc(new ByteArrayInputStream(responseContent));
}
catch (ManifoldCFException e)
{
// Syntax errors should be eaten; we'll just return a null doc in that case.
// But we do try to convert the raw data to string form.
try
{
rawString = new String(responseContent,charsetName);
}
catch (UnsupportedEncodingException e2)
{
// Uh oh, can't even convert it to a string. Now we are desperate.
rawString = "Response had an illegal encoding: "+e2.getMessage();
e.printStackTrace();
}
}
Logging.ingest.debug("Read of response stream complete");
return new CodeDetails(responseCode,doc,rawString);
}
catch (java.net.SocketTimeoutException e)
{
// If this continues, we should indeed abort the job. Retries should not go on indefinitely either; 2 hours is plenty
long currentTime = System.currentTimeMillis();
throw new ServiceInterruption("Ingestion API socket timeout exception waiting for response code: "+e.getMessage()+"; ingestion will be retried again later",
e,
currentTime + interruptionRetryTime,
currentTime + 2L * 60L * 60000L,
-1,
true);
}
catch (InterruptedIOException e)
{
throw new ManifoldCFException("Interrupted",ManifoldCFException.INTERRUPTED);
}
catch (java.net.ConnectException e)
{
// If this continues, we should indeed abort the job. Retries should not go on indefinitely either; 2 hours is plenty
long currentTime = System.currentTimeMillis();
throw new ServiceInterruption("Timed out connecting to ingestion API: "+e.getMessage()+"; ingestion will be retried again later",
e,
currentTime + interruptionRetryTime,
currentTime + 2L * 60L * 60000L,
-1,
true);
}
catch (java.net.SocketException e)
{
// Return 400 error; likely a connection reset which lost us the response data, so
// just treat it as something OK.
return new CodeDetails("HTTP/1.0 400 Connection Reset",null,null);
}
catch (IOException ioe)
{
Logging.ingest.warn("IO exception trying to get response from ingestion API: "+ioe.getMessage(),ioe);
// If this continues, we should indeed abort the job. Retries should not go on indefinitely either; 2 hours is plenty
long currentTime = System.currentTimeMillis();
throw new ServiceInterruption("IO exception waiting for response code: "+ioe.getMessage()+"; ingestion will be retried again later",
ioe,
currentTime + interruptionRetryTime,
currentTime + 2L * 60L * 60000L,
-1,
true);
}
}
/** Read input stream into an in-memory array */
protected static byte[] readInputStream(InputStream is)
throws IOException
{
// Create an array of byte arrays, and assemble the result into a final piece at the end.
List array = new ArrayList();
int count = 0;
while (true)
{
byte[] buffer = new byte[65536];
int amt = is.read(buffer);
if (amt == -1)
break;
count += amt;
array.add(buffer);
}
byte[] rval = new byte[count];
int pointer = 0;
int index = 0;
while (pointer < count)
{
byte[] buffer = (byte[])array.get(index++);
if (buffer.length > count-pointer)
{
System.arraycopy(buffer,0,rval,pointer,count-pointer);
pointer = count;
}
else
{
System.arraycopy(buffer,0,rval,pointer,buffer.length);
pointer += buffer.length;
}
}
return rval;
}
/** Write credentials to output */
protected void writeCredentials(OutputStream out)
throws IOException
{
// Apply credentials if present
if (encodedCredentials != null)
{
Logging.ingest.debug("Applying credentials");
byte[] tmp = ("Authorization: Basic " + encodedCredentials + "\r\n").getBytes("UTF-8");
out.write(tmp, 0, tmp.length);
tmp = ("WWW-Authenticate: Basic realm=\"" + ((realm != null) ? realm : "") + "\"\r\n").getBytes("UTF-8");
out.write(tmp, 0, tmp.length);
}
}
/** Build a secure socket factory based on no keystore and a lax trust manager.
* This allows use of SSL for privacy but not identification. */
protected static javax.net.ssl.SSLSocketFactory getOpenSecureSocketFactory()
throws ManifoldCFException
{
try
{
java.security.SecureRandom secureRandom = java.security.SecureRandom.getInstance("SHA1PRNG");
// Create an SSL context
javax.net.ssl.SSLContext sslContext = javax.net.ssl.SSLContext.getInstance("SSL");
sslContext.init(null,new LaxTrustManager[]{new LaxTrustManager()},secureRandom);
return sslContext.getSocketFactory();
}
catch (java.security.NoSuchAlgorithmException e)
{
throw new ManifoldCFException("No such algorithm: "+e.getMessage(),e);
}
catch (java.security.KeyManagementException e)
{
throw new ManifoldCFException("Key management exception: "+e.getMessage(),e);
}
}
/** Create a socket in a manner consistent with all of our specified parameters.
*/
protected Socket createSocket(long responseRetryCount)
throws IOException, ManifoldCFException
{
Socket socket;
if (protocol.equals("https") && socketFactory != null)
{
try
{
//SocketFactory factory = SSLSocketFactory.getDefault();
socket = socketFactory.createSocket(host,port);
}
catch (InterruptedIOException e)
{
throw e;
}
catch (IOException e)
{
throw new ManifoldCFException("Couldn't set up SSL connection to ingestion API: "+e.getMessage(),e);
}
}
else
socket = new Socket(host, port);
// Calculate the timeout we want
long timeoutMilliseconds = responseRetryWait * responseRetryCount;
socket.setSoTimeout((int)timeoutMilliseconds);
return socket;
}
/** Byte buffer class */
protected static class ByteBuffer
{
byte[] theBuffer;
int bufferAmt;
public ByteBuffer()
{
createBuffer(64);
}
protected void createBuffer(int size)
{
theBuffer = new byte[size];
}
public void append(byte b)
{
if (bufferAmt == theBuffer.length)
{
byte[] oldBuffer = theBuffer;
createBuffer(bufferAmt * 2);
int i = 0;
while (i < bufferAmt)
{
theBuffer[i] = oldBuffer[i];
i++;
}
}
theBuffer[bufferAmt++] = b;
}
public String toString(String encoding)
throws java.io.UnsupportedEncodingException
{
return new String(theBuffer,0,bufferAmt,encoding);
}
}
/** Our own trust manager, which ignores certificate issues */
protected static class LaxTrustManager implements X509TrustManager
{
/** Does nothing */
public LaxTrustManager()
{
}
/** Return a list of accepted issuers. There are none. */
public java.security.cert.X509Certificate[] getAcceptedIssuers()
{
return new java.security.cert.X509Certificate[0];
}
/** We have no problem with any clients */
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException
{
}
/** We have no problem with any servers */
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException
{
}
}
/** Calculate the length of the preamble */
protected static int lengthPreamble()
throws IOException
{
return preambleBytes.length;
}
/** Calculate the length of a boundary */
protected static int lengthBoundary(String contentType, String name, String fileName)
throws IOException
{
int rval = 0;
rval += separatorBytes.length;
String value = "Content-Disposition: form-data";
if (name != null)
value += "; name=\""+name+"\"";
if (fileName != null)
value += "; filename=\""+fileName+"\"";
value += "\r\n";
byte[] tmp = value.getBytes("ASCII");
rval += tmp.length;
tmp = ("Content-Type: "+contentType+"\r\n\r\n").getBytes("ASCII");
rval += tmp.length;
return rval;
}
/** Calculate the length of the postamble */
protected static int lengthPostamble()
throws IOException
{
return postambleBytes.length;
}
/** Calculate the length of a field */
protected static int lengthField(String fieldName, String fieldValue)
throws IOException
{
int rval = lengthPreamble() + lengthBoundary("text/plain; charset=UTF-8",fieldName,null);
byte[] tmp = fieldValue.getBytes("UTF-8");
rval += tmp.length;
rval += lengthPostamble();
return rval;
}
/** Count the size of an acl level */
protected int lengthACLs(String aclType, String[] acl, String[] denyAcl)
throws IOException
{
int totalLength = 0;
String metadataACLName = LITERAL + allowAttributeName + aclType;
int i = 0;
while (i < acl.length)
{
totalLength += lengthField(metadataACLName,acl[i++]);
}
String metadataDenyACLName = LITERAL + denyAttributeName + aclType;
i = 0;
while (i < denyAcl.length)
{
totalLength += lengthField(metadataDenyACLName,denyAcl[i++]);
}
return totalLength;
}
/** Write the preamble */
protected static void writePreamble(OutputStream out)
throws IOException
{
out.write(preambleBytes, 0, preambleBytes.length);
}
/** Write a boundary */
protected static void writeBoundary(OutputStream out, String contentType, String name, String fileName)
throws IOException
{
out.write(separatorBytes, 0, separatorBytes.length);
String value = "Content-Disposition: form-data";
if (name != null)
value += "; name=\""+name+"\"";
if (fileName != null)
value += "; filename=\""+fileName+"\"";
value += "\r\n";
byte[] tmp = value.getBytes("ASCII");
out.write(tmp, 0, tmp.length);
tmp = ("Content-Type: "+contentType+"\r\n\r\n").getBytes("ASCII");
out.write(tmp, 0, tmp.length);
}
/** Write the postamble */
protected static void writePostamble(OutputStream out)
throws IOException
{
out.write(postambleBytes, 0, postambleBytes.length);
}
/** Write a field */
protected static void writeField(OutputStream out, String fieldName, String fieldValue)
throws IOException
{
writePreamble(out);
writeBoundary(out,"text/plain; charset=UTF-8",fieldName,null);
byte[] tmp = fieldValue.getBytes("UTF-8");
out.write(tmp, 0, tmp.length);
writePostamble(out);
}
/** Output an acl level */
protected void writeACLs(OutputStream out, String aclType, String[] acl, String[] denyAcl)
throws IOException
{
String metadataACLName = LITERAL + allowAttributeName + aclType;
int i = 0;
while (i < acl.length)
{
writeField(out,metadataACLName,acl[i++]);
}
String metadataDenyACLName = LITERAL + denyAttributeName + aclType;
i = 0;
while (i < denyAcl.length)
{
writeField(out,metadataDenyACLName,denyAcl[i++]);
}
}
/** XML encoding */
protected static String xmlEncode(String input)
{
StringBuffer sb = new StringBuffer("<![CDATA[");
sb.append(input);
sb.append("]]>");
return sb.toString();
}
/** Killable thread that does ingestions.
* Java 1.5 stopped permitting thread interruptions to abort socket waits. As a result, it is impossible to get threads to shutdown cleanly that are doing
* such waits. So, the places where this happens are segregated in their own threads so that they can be just abandoned.
*
* This thread does a single document ingestion.
*/
protected class IngestThread extends java.lang.Thread
{
protected String documentURI;
protected RepositoryDocument document;
protected Map arguments;
protected Map sourceTargets;
protected String[] shareAcls;
protected String[] shareDenyAcls;
protected String[] acls;
protected String[] denyAcls;
protected Long activityStart = null;
protected Long activityBytes = null;
protected String activityCode = null;
protected String activityDetails = null;
protected Throwable exception = null;
protected boolean readFromDocumentStreamYet = false;
protected boolean rval = false;
public IngestThread(String documentURI, RepositoryDocument document, Map arguments, Map sourceTargets,
String[] shareAcls, String[] shareDenyAcls, String[] acls, String[] denyAcls)
{
super();
setDaemon(true);
this.documentURI = documentURI;
this.document = document;
this.arguments = arguments;
this.shareAcls = shareAcls;
this.shareDenyAcls = shareDenyAcls;
this.acls = acls;
this.denyAcls = denyAcls;
this.sourceTargets = sourceTargets;
}
public void run()
{
long length = document.getBinaryLength();
InputStream is = document.getBinaryStream();
try
{
// Do the operation!
long fullStartTime = System.currentTimeMillis();
// Open a socket to ingest, and to the response stream to get the post result
try
{
// Set up the socket, and the (optional) secure socket.
long responseRetryCount = responseRetries + (long)((float)length * sizeCoefficient);
Socket socket = createSocket(responseRetryCount);
try
{
InputStream in = socket.getInputStream();
try
{
OutputStream out = socket.getOutputStream();
try
{
// Create the output stream to SOLR
byte[] tmp = ("POST " + postUpdateAction + " HTTP/1.0\r\n").getBytes("ASCII");
out.write(tmp, 0, tmp.length);
// Set all the headers
writeCredentials(out);
// Headers must include the following:
// Content-Type
// Content-Length
// The content-length is calculated using the entire body length, which therefore includes the length of all the metadata fields as well.
// Come up with a boundary. Ideally, the boundary should be something that doesn't exist in any of the data. In practice, that would mean
// scanning all such data at least twice: once to make sure we avoided all boundary collisions, and a second time to actually output the data.
// This is such a huge chunk of overhead, I've decided for now to just punt and pick something that's pretty unlikely.
// Calculate the content length. To do this, we have to walk through the entire multipart assembly process, but calculate the length rather than output
// anything.
int totalLength = 0;
// Count the id.
totalLength += lengthField(LITERAL+idAttributeName,documentURI);
// Count the acls
totalLength += lengthACLs("share",shareAcls,shareDenyAcls);
totalLength += lengthACLs("document",acls,denyAcls);
// Count the arguments
Iterator iter = arguments.keySet().iterator();
while (iter.hasNext())
{
String name = (String)iter.next();
List values = (List)arguments.get(name);
int j = 0;
while (j < values.size())
{
String value = (String)values.get(j++);
totalLength += lengthField(name,value);
}
}
// Count the metadata.
iter = document.getFields();
while (iter.hasNext())
{
String fieldName = (String)iter.next();
String newFieldName = (String)sourceTargets.get(fieldName);
if (newFieldName == null)
newFieldName = fieldName;
// Make SURE we can't double up on the id field inadvertantly!
if (newFieldName.length() > 0)
{
if (newFieldName.toLowerCase().equals(idAttributeName.toLowerCase()))
newFieldName = ID_METADATA;
Object[] values = document.getField(fieldName);
// We only handle strings right now!!!
int k = 0;
while (k < values.length)
{
String value = (String)values[k++];
totalLength += lengthField(LITERAL+newFieldName,value);
}
}
}
// Count the binary data
totalLength += lengthPreamble();
totalLength += lengthBoundary("application/octet-stream","myfile","docname");
totalLength += length;
// Count the postamble
totalLength += lengthPostamble();
// Count the end marker.
totalLength += endBytes.length;
// Now, output the content-length header, and another newline, to start the data.
tmp = ("Content-Length: "+Integer.toString(totalLength)+"\r\n").getBytes("ASCII");
out.write(tmp, 0, tmp.length);
tmp = ("Content-Type: multipart/form-data; boundary=").getBytes("ASCII");
out.write(tmp, 0, tmp.length);
out.write(separatorBytes, 0, separatorBytes.length);
// End of headers.
tmp = "\r\n".getBytes("ASCII");
out.write(tmp, 0, tmp.length);
// Write the id field
writeField(out,LITERAL+idAttributeName,documentURI);
// Write the access token information
writeACLs(out,"share",shareAcls,shareDenyAcls);
writeACLs(out,"document",acls,denyAcls);
// Write the arguments
iter = arguments.keySet().iterator();
while (iter.hasNext())
{
String name = (String)iter.next();
List values = (List)arguments.get(name);
int j = 0;
while (j < values.size())
{
String value = (String)values.get(j++);
writeField(out,name,value);
}
}
// Write the metadata, each in a field by itself
iter = document.getFields();
while (iter.hasNext())
{
String fieldName = (String)iter.next();
String newFieldName = (String)sourceTargets.get(fieldName);
if (newFieldName == null)
newFieldName = fieldName;
if (newFieldName.length() > 0)
{
if (newFieldName.toLowerCase().equals(idAttributeName.toLowerCase()))
newFieldName = ID_METADATA;
Object[] values = document.getField(fieldName);
// We only handle strings right now!!!
int k = 0;
while (k < values.length)
{
String value = (String)values[k++];
writeField(out,LITERAL+newFieldName,value);
}
}
}
// Write the content
writePreamble(out);
writeBoundary(out,"application/octet-stream","myfile","docname");
// Stream the data
long total = 0;
long now, later;
now = System.currentTimeMillis();
byte[] bytes = new byte[buffersize];
// Write out the contents of the inputstream to the socket
while (true)
{
int count;
// Specially catch all errors that come from reading the input stream itself.
// This will help us segregate errors that come from the stream vs. those that come from the ingestion system.
try
{
count = is.read(bytes);
}
catch (java.net.SocketTimeoutException ioe)
{
// We have to catch socket timeout exceptions specially, because they are derived from InterruptedIOException
// They are otherwise just like IOExceptions
// Log the error
Logging.ingest.warn("Error reading data for transmission to Ingestion API: "+ioe.getMessage(),ioe);
activityStart = new Long(fullStartTime);
activityCode = "-1";
activityDetails = "Couldn't read document: "+ioe.getMessage();
// If this continues, we should indeed abort the job. Retries should not go on indefinitely either; 2 hours is plenty
long currentTime = System.currentTimeMillis();
throw new ServiceInterruption("IO error reading document for ingestion: "+ioe.getMessage()+"; read will be retried again later",
ioe,
currentTime + interruptionRetryTime,
currentTime + 2L * 60L * 60000L,
-1,
true);
}
catch (InterruptedIOException ioe)
{
// If the transfer was interrupted, it may be because we are shutting down the thread.
// Third-party library exceptions derived from InterruptedIOException are possible; if the stream comes from httpclient especially.
// If we see one of these, we treat it as "not an interruption".
if (!ioe.getClass().getName().equals("java.io.InterruptedIOException"))
{
// Log the error
Logging.ingest.warn("Error reading data for transmission to Ingestion API: "+ioe.getMessage(),ioe);
activityStart = new Long(fullStartTime);
activityCode = "-1";
activityDetails = "Couldn't read document: "+ioe.getMessage();
// If this continues, we should indeed abort the job. Retries should not go on indefinitely either; 2 hours is plenty
long currentTime = System.currentTimeMillis();
throw new ServiceInterruption("IO error reading document for ingestion: "+ioe.getMessage()+"; read will be retried again later",
ioe,
currentTime + interruptionRetryTime,
currentTime + 2L * 60L * 60000L,
-1,
true);
}
else
throw ioe;
}
catch (IOException ioe)
{
// We need to decide whether to throw a service interruption or lcf exception, based on what went wrong.
// We never retry here; the cause is the repository, so there's not any point.
// Log the error
Logging.ingest.warn("Error reading data for transmission to Ingestion API: "+ioe.getMessage(),ioe);
activityStart = new Long(fullStartTime);
activityCode = "-1";
activityDetails = "Couldn't read document: "+ioe.getMessage();
// If this continues, we should indeed abort the job. Retries should not go on indefinitely either; 2 hours is plenty
long currentTime = System.currentTimeMillis();
throw new ServiceInterruption("IO error reading document for ingestion: "+ioe.getMessage()+"; read will be retried again later",
ioe,
currentTime + interruptionRetryTime,
currentTime + 2L * 60L * 60000L,
-1,
true);
}
if (count == -1)
break;
readFromDocumentStreamYet = true;
out.write(bytes,0,count);
total += (long)count;
}
// Write the postamble
writePostamble(out);
// Write the end marker
out.write(endBytes, 0, endBytes.length);
out.flush();
later = System.currentTimeMillis();
if (Logging.ingest.isDebugEnabled())
Logging.ingest.debug("Total bytes posted: " + new Long(total).toString() + ", total time: " + (later - now));
// Now, process response
CodeDetails cd;
try
{
cd = getResponse(in);
}
catch (ServiceInterruption si)
{
activityStart = new Long(now);
activityCode = "-2";
activityDetails = si.getMessage();
throw si;
}
activityStart = new Long(now);
activityBytes = new Long(length);
activityCode = cd.getCode();
activityDetails = cd.getDetails();
int codeValue = cd.getCodeValue();
// A negative number means http error of some kind.
if (codeValue < 0)
throw new ManifoldCFException("Http protocol error");
// 200 means we got a status document back
if (codeValue == 200)
{
// Look at response XML
cd.parseIngestionResponse();
rval = true;
return;
}
// Anything else means the document didn't ingest.
// There are three possibilities here:
// 1) The document will NEVER ingest (it's illegal), in which case a 400 or 403 will be returned, and
// 2) There is a transient error, in which case we will want to try again, after a wait.
// If the situation is (2), then we CAN'T retry if we already read any of the stream; therefore
// we are forced to throw a "service interrupted" exception, and let the caller reschedule
// the ingestion.
// 3) Something is wrong with the setup, e.g. bad credentials. In this case we chuck a ManifoldCFException,
// since this will abort the current activity entirely.
if (codeValue == 401)
throw new ManifoldCFException("Bad credentials for ingestion",ManifoldCFException.SETUP_ERROR);
- if (codeValue >= 400 && codeValue < 500)
+ if ((codeValue >= 400 && codeValue < 500) ||
+ (codeValue == 500 && cd.getDetails() != null && cd.getDetails().indexOf("org.apache.tika.exception.TikaException") != -1))
{
rval = false;
return;
}
// If this continues, we should indeed abort the job. Retries should not go on indefinitely either; 2 hours is plenty
long currentTime = System.currentTimeMillis();
throw new ServiceInterruption("Error "+Integer.toString(codeValue)+" from ingestion request; ingestion will be retried again later",
new ManifoldCFException("Ingestion HTTP error code "+Integer.toString(codeValue)),
currentTime + interruptionRetryTime,
currentTime + 2L * 60L * 60000L,
-1,
true);
}
finally
{
out.close();
}
}
finally
{
in.close();
}
}
finally
{
try
{
socket.close();
}
catch (InterruptedIOException e)
{
throw e;
}
catch (IOException e)
{
Logging.ingest.debug("Error closing socket: "+e.getMessage(),e);
// Do NOT rethrow
}
}
}
catch (UnsupportedEncodingException ioe)
{
throw new ManifoldCFException("Fatal ingestion error: "+ioe.getMessage(),ioe);
}
catch (java.net.SocketTimeoutException ioe)
{
// These are just like IO errors, but since they are derived from InterruptedIOException, they have to be caught first.
// Log the error
Logging.ingest.warn("Error connecting to ingestion API: "+ioe.getMessage(),ioe);
activityStart = new Long(fullStartTime);
activityCode = "-1";
activityDetails = ioe.getMessage();
throw ioe;
}
catch (InterruptedIOException e)
{
return;
}
catch (IOException ioe)
{
activityStart = new Long(fullStartTime);
// Intercept "broken pipe" exception, since that seems to be what we get if the ingestion API kills the socket right after a 400 goes out.
// Basically, we have no choice but to interpret that in the same manner as a 400, since no matter how we do it, it's a race and the 'broken pipe'
// result is always possible. So we might as well expect it and treat it properly.
if (ioe.getClass().getName().equals("java.net.SocketException") && ioe.getMessage().toLowerCase().indexOf("broken pipe") != -1)
{
// We've seen what looks like the ingestion interface forcibly closing the socket.
// We *choose* to interpret this just like a 400 response. However, we log in the history using a different code,
// since we really don't know what happened for sure.
// Record the attempt
activityCode = "-103";
activityDetails = "Presuming an ingestion rejection: "+ioe.getMessage();
rval = false;
return;
}
// Record the attempt
activityCode = "-1";
activityDetails = ioe.getMessage();
// Log the error
Logging.ingest.warn("Error communicating with Ingestion API: "+ioe.getMessage(),ioe);
throw ioe;
}
}
catch (Throwable e)
{
this.exception = e;
}
}
public Throwable getException()
{
return exception;
}
public Long getActivityStart()
{
return activityStart;
}
public Long getActivityBytes()
{
return activityBytes;
}
public String getActivityCode()
{
return activityCode;
}
public String getActivityDetails()
{
return activityDetails;
}
public boolean getReadFromDocumentStreamYet()
{
return readFromDocumentStreamYet;
}
public boolean getRval()
{
return rval;
}
}
/** Killable thread that does deletions.
* Java 1.5 stopped permitting thread interruptions to abort socket waits. As a result, it is impossible to get threads to shutdown cleanly that are doing
* such waits. So, the places where this happens are segregated in their own threads so that they can be just abandoned.
*
* This thread does a single document deletion.
*/
protected class DeleteThread extends java.lang.Thread
{
protected String documentURI;
protected Long activityStart = null;
protected String activityCode = null;
protected String activityDetails = null;
protected Throwable exception = null;
public DeleteThread(String documentURI)
{
super();
setDaemon(true);
this.documentURI = documentURI;
}
public void run()
{
try
{
// Do the operation!
long fullStartTime = System.currentTimeMillis();
// Open a socket to ingest, and to the response stream to get the post result
try
{
// Set up the socket, and the (optional) secure socket.
Socket socket = createSocket(responseRetries);
try
{
InputStream in = socket.getInputStream();
try
{
OutputStream out = socket.getOutputStream();
try
{
byte[] requestBytes = ("<delete><id>"+xmlEncode(documentURI)+"</id></delete>").getBytes("UTF-8");
long startTime = System.currentTimeMillis();
byte[] tmp = ("POST " + postRemoveAction + " HTTP/1.0\r\n").getBytes("ASCII");
out.write(tmp, 0, tmp.length);
// Set all the headers
writeCredentials(out);
tmp = ("Content-Length: "+Integer.toString(requestBytes.length)+"\r\n").getBytes("ASCII");
out.write(tmp, 0, tmp.length);
tmp = ("Content-Type: text/xml; charset=UTF-8\r\n\r\n").getBytes("ASCII");
out.write(tmp, 0, tmp.length);
out.write(requestBytes);
out.flush();
if (Logging.ingest.isDebugEnabled())
Logging.ingest.debug("Delete posted");
CodeDetails cd;
try
{
cd = getResponse(in);
}
catch (ServiceInterruption si)
{
activityStart = new Long(startTime);
activityCode = "-2";
activityDetails = si.getMessage();
throw si;
}
activityStart = new Long(startTime);
activityCode = cd.getCode();
activityDetails = cd.getDetails();
int codeValue = cd.getCodeValue();
if (codeValue < 0)
throw new ManifoldCFException("Http protocol error");
// 200 means we got an xml document back
if (codeValue == 200)
{
// Look at response XML
cd.parseRemovalResponse();
return;
}
// We ignore everything in the range from 400-500 now
if (codeValue == 401)
throw new ManifoldCFException("Bad credentials for ingestion",ManifoldCFException.SETUP_ERROR);
if (codeValue >= 400 && codeValue < 500)
return;
// Anything else means the document didn't delete. Throw the error.
throw new ManifoldCFException("Error deleting document: '"+cd.getDescription()+"'");
}
finally
{
out.close();
}
}
finally
{
in.close();
}
}
finally
{
try
{
socket.close();
}
catch (InterruptedIOException e)
{
throw e;
}
catch (IOException e)
{
Logging.ingest.debug("Error closing socket: "+e.getMessage(),e);
// Do NOT rethrow
}
}
}
catch (UnsupportedEncodingException ioe)
{
throw new ManifoldCFException("Fatal ingestion error: "+ioe.getMessage(),ioe);
}
catch (InterruptedIOException ioe)
{
return;
}
catch (IOException ioe)
{
// Log the error
Logging.ingest.warn("Error communicating with Ingestion API: "+ioe.getMessage(),ioe);
activityStart = new Long(fullStartTime);
activityCode = "-1";
activityDetails = ioe.getMessage();
throw ioe;
}
}
catch (Throwable e)
{
this.exception = e;
}
}
public Throwable getException()
{
return exception;
}
public Long getActivityStart()
{
return activityStart;
}
public String getActivityCode()
{
return activityCode;
}
public String getActivityDetails()
{
return activityDetails;
}
}
/** Killable thread that does a commit.
* Java 1.5 stopped permitting thread interruptions to abort socket waits. As a result, it is impossible to get threads to shutdown cleanly that are doing
* such waits. So, the places where this happens are segregated in their own threads so that they can be just abandoned.
*
* This thread does a commit.
*/
protected class CommitThread extends java.lang.Thread
{
protected Throwable exception = null;
public CommitThread()
{
super();
setDaemon(true);
}
public void run()
{
try
{
// Do the operation!
// Open a socket to update request handler, and to the response stream to get the post result
try
{
// Set up the socket, and the (optional) secure socket.
Socket socket = createSocket(responseRetries);
try
{
InputStream in = socket.getInputStream();
try
{
OutputStream out = socket.getOutputStream();
try
{
// Create the output stream to GTS
byte[] tmp = ("GET " + postUpdateAction + "?commit=true HTTP/1.0\r\n").getBytes("ASCII");
out.write(tmp, 0, tmp.length);
writeCredentials(out);
tmp = ("Content-Length: 0\r\n\r\n").getBytes("ASCII");
out.write(tmp, 0, tmp.length);
if (Logging.ingest.isDebugEnabled())
Logging.ingest.debug("Commit request posted");
out.flush();
CodeDetails cd = getResponse(in);
int codeValue = cd.getCodeValue();
if (codeValue < 0)
throw new ManifoldCFException("Http protocol error");
// 200 means everything went OK
if (codeValue == 200)
{
cd.parseCommitResponse();
return;
}
// We ignore everything in the range from 400-500 now
if (codeValue == 401)
throw new ManifoldCFException("Bad credentials for commit request",ManifoldCFException.SETUP_ERROR);
// Anything else means the info request failed.
throw new ManifoldCFException("Error connecting to update request API: '"+cd.getDescription()+"'");
}
finally
{
out.close();
}
}
finally
{
in.close();
}
}
finally
{
try
{
socket.close();
}
catch (InterruptedIOException e)
{
throw e;
}
catch (IOException e)
{
Logging.ingest.debug("Error closing socket: "+e.getMessage(),e);
// Do NOT rethrow
}
}
}
catch (UnsupportedEncodingException ioe)
{
throw new ManifoldCFException("Fatal commit error: "+ioe.getMessage(),ioe);
}
catch (InterruptedIOException ioe)
{
// Exit the thread.
return;
}
catch (IOException ioe)
{
// Log the error
Logging.ingest.warn("Error communicating with update request handler: "+ioe.getMessage(),ioe);
throw ioe;
}
}
catch (Throwable e)
{
this.exception = e;
}
}
public Throwable getException()
{
return exception;
}
}
/** Killable thread that does a status check.
* Java 1.5 stopped permitting thread interruptions to abort socket waits. As a result, it is impossible to get threads to shutdown cleanly that are doing
* such waits. So, the places where this happens are segregated in their own threads so that they can be just abandoned.
*
* This thread does a status check.
*/
protected class StatusThread extends java.lang.Thread
{
protected Throwable exception = null;
public StatusThread()
{
super();
setDaemon(true);
}
public void run()
{
try
{
// Do the operation!
// Open a socket to ingest, and to the response stream to get the post result
try
{
// Set up the socket, and the (optional) secure socket.
Socket socket = createSocket(responseRetries);
try
{
InputStream in = socket.getInputStream();
try
{
OutputStream out = socket.getOutputStream();
try
{
// Create the output stream to GTS
byte[] tmp = ("GET " + postStatusAction + " HTTP/1.0\r\n").getBytes("ASCII");
out.write(tmp, 0, tmp.length);
writeCredentials(out);
tmp = ("Content-Length: 0\r\n\r\n").getBytes("ASCII");
out.write(tmp, 0, tmp.length);
if (Logging.ingest.isDebugEnabled())
Logging.ingest.debug("Status request posted");
out.flush();
CodeDetails cd = getResponse(in);
int codeValue = cd.getCodeValue();
if (codeValue < 0)
throw new ManifoldCFException("Http protocol error");
// 200 means everything went OK
if (codeValue == 200)
{
cd.parseStatusResponse();
return;
}
// We ignore everything in the range from 400-500 now
if (codeValue == 401)
throw new ManifoldCFException("Bad credentials for ingestion",ManifoldCFException.SETUP_ERROR);
// Anything else means the info request failed.
throw new ManifoldCFException("Error connecting to ingestion API: '"+cd.getDescription()+"'");
}
finally
{
out.close();
}
}
finally
{
in.close();
}
}
finally
{
try
{
socket.close();
}
catch (InterruptedIOException e)
{
throw e;
}
catch (IOException e)
{
Logging.ingest.debug("Error closing socket: "+e.getMessage(),e);
// Do NOT rethrow
}
}
}
catch (UnsupportedEncodingException ioe)
{
throw new ManifoldCFException("Fatal ingestion error: "+ioe.getMessage(),ioe);
}
catch (InterruptedIOException ioe)
{
// Exit the thread.
return;
}
catch (IOException ioe)
{
// Log the error
Logging.ingest.warn("Error communicating with Ingestion API: "+ioe.getMessage(),ioe);
throw ioe;
}
}
catch (Throwable e)
{
this.exception = e;
}
}
public Throwable getException()
{
return exception;
}
}
/** Code+details paper object */
protected static class CodeDetails
{
protected String code;
protected int codeValue;
protected String details;
protected String res;
protected XMLDoc returnDoc;
protected String rawString;
public CodeDetails(String res, XMLDoc returnDoc, String rawString)
{
this.res = res;
this.returnDoc = returnDoc;
this.rawString = rawString;
codeValue = -100;
code = "-100";
details = "Http response was improperly formed";
int firstSpace = res.indexOf(" ");
if (firstSpace != -1)
{
int secondSpace = res.indexOf(" ", firstSpace + 1);
if (secondSpace != -1)
{
code = res.substring(firstSpace + 1, secondSpace);
details = res.substring(secondSpace+1).trim();
try
{
codeValue = (int)(new Double(code).doubleValue());
if (codeValue == 200)
details = null;
}
catch (NumberFormatException e)
{
// Fall through and leave codeValue unaltered
}
}
}
}
public String getCode()
{
return code;
}
public int getCodeValue()
{
return codeValue;
}
public String getDetails()
{
return details;
}
public XMLDoc getReturnDoc()
{
return returnDoc;
}
public String getDescription()
throws ManifoldCFException
{
return res + "\r\n" + ((returnDoc!=null)?returnDoc.getXML():((rawString!=null)?rawString:""));
}
public void parseIngestionResponse()
throws ManifoldCFException
{
// Look at response XML
String statusValue = "unknown";
XMLDoc doc = getReturnDoc();
if (doc != null)
{
if (Logging.ingest.isDebugEnabled())
Logging.ingest.debug("SOLR: Saw ingestion response document '"+doc.getXML()+"'");
//Object root = doc.getRoot();
ArrayList list = doc.processPath("*",null);
int k = 0;
while (k < list.size())
{
Object listNode = list.get(k++);
if (doc.getNodeName(listNode).equals("response"))
{
ArrayList list2 = doc.processPath("*",listNode);
int q = 0;
while (q < list2.size())
{
Object respNode = list2.get(q++);
if (doc.getNodeName(respNode).equals("lst"))
{
String lstName = doc.getValue(respNode,"name");
if (lstName.equals("responseHeader"))
{
ArrayList list3 = doc.processPath("*",respNode);
int z = 0;
while (z < list3.size())
{
Object headerNode = list3.get(z++);
if (doc.getNodeName(headerNode).equals("int"))
{
String value = doc.getValue(headerNode,"name");
if (value.equals("status"))
{
statusValue = doc.getData(headerNode).trim();
}
}
}
}
}
}
}
}
if (statusValue.equals("0"))
return;
throw new ManifoldCFException("Ingestion returned error: "+statusValue);
}
else
throw new ManifoldCFException("XML parsing error on response");
}
public void parseRemovalResponse()
throws ManifoldCFException
{
parseIngestionResponse();
}
public void parseCommitResponse()
throws ManifoldCFException
{
parseIngestionResponse();
}
public void parseStatusResponse()
throws ManifoldCFException
{
// Look at response XML
String statusValue = "unknown";
XMLDoc doc = getReturnDoc();
if (doc != null)
{
if (Logging.ingest.isDebugEnabled())
Logging.ingest.debug("SOLR: Saw status response document '"+doc.getXML()+"'");
//Object root = doc.getRoot();
ArrayList list = doc.processPath("*",null);
int k = 0;
while (k < list.size())
{
Object listNode = list.get(k++);
if (doc.getNodeName(listNode).equals("response"))
{
ArrayList list2 = doc.processPath("*",listNode);
int q = 0;
while (q < list2.size())
{
Object respNode = list2.get(q++);
if (doc.getNodeName(respNode).equals("str"))
{
String value = doc.getValue(respNode,"name");
if (value.equals("status"))
{
statusValue = doc.getData(respNode).trim();
}
}
}
}
}
if (statusValue.equals("OK"))
return;
throw new ManifoldCFException("Status error: "+statusValue);
}
else
throw new ManifoldCFException("XML parsing error on response");
}
}
}
| true | true | public void run()
{
long length = document.getBinaryLength();
InputStream is = document.getBinaryStream();
try
{
// Do the operation!
long fullStartTime = System.currentTimeMillis();
// Open a socket to ingest, and to the response stream to get the post result
try
{
// Set up the socket, and the (optional) secure socket.
long responseRetryCount = responseRetries + (long)((float)length * sizeCoefficient);
Socket socket = createSocket(responseRetryCount);
try
{
InputStream in = socket.getInputStream();
try
{
OutputStream out = socket.getOutputStream();
try
{
// Create the output stream to SOLR
byte[] tmp = ("POST " + postUpdateAction + " HTTP/1.0\r\n").getBytes("ASCII");
out.write(tmp, 0, tmp.length);
// Set all the headers
writeCredentials(out);
// Headers must include the following:
// Content-Type
// Content-Length
// The content-length is calculated using the entire body length, which therefore includes the length of all the metadata fields as well.
// Come up with a boundary. Ideally, the boundary should be something that doesn't exist in any of the data. In practice, that would mean
// scanning all such data at least twice: once to make sure we avoided all boundary collisions, and a second time to actually output the data.
// This is such a huge chunk of overhead, I've decided for now to just punt and pick something that's pretty unlikely.
// Calculate the content length. To do this, we have to walk through the entire multipart assembly process, but calculate the length rather than output
// anything.
int totalLength = 0;
// Count the id.
totalLength += lengthField(LITERAL+idAttributeName,documentURI);
// Count the acls
totalLength += lengthACLs("share",shareAcls,shareDenyAcls);
totalLength += lengthACLs("document",acls,denyAcls);
// Count the arguments
Iterator iter = arguments.keySet().iterator();
while (iter.hasNext())
{
String name = (String)iter.next();
List values = (List)arguments.get(name);
int j = 0;
while (j < values.size())
{
String value = (String)values.get(j++);
totalLength += lengthField(name,value);
}
}
// Count the metadata.
iter = document.getFields();
while (iter.hasNext())
{
String fieldName = (String)iter.next();
String newFieldName = (String)sourceTargets.get(fieldName);
if (newFieldName == null)
newFieldName = fieldName;
// Make SURE we can't double up on the id field inadvertantly!
if (newFieldName.length() > 0)
{
if (newFieldName.toLowerCase().equals(idAttributeName.toLowerCase()))
newFieldName = ID_METADATA;
Object[] values = document.getField(fieldName);
// We only handle strings right now!!!
int k = 0;
while (k < values.length)
{
String value = (String)values[k++];
totalLength += lengthField(LITERAL+newFieldName,value);
}
}
}
// Count the binary data
totalLength += lengthPreamble();
totalLength += lengthBoundary("application/octet-stream","myfile","docname");
totalLength += length;
// Count the postamble
totalLength += lengthPostamble();
// Count the end marker.
totalLength += endBytes.length;
// Now, output the content-length header, and another newline, to start the data.
tmp = ("Content-Length: "+Integer.toString(totalLength)+"\r\n").getBytes("ASCII");
out.write(tmp, 0, tmp.length);
tmp = ("Content-Type: multipart/form-data; boundary=").getBytes("ASCII");
out.write(tmp, 0, tmp.length);
out.write(separatorBytes, 0, separatorBytes.length);
// End of headers.
tmp = "\r\n".getBytes("ASCII");
out.write(tmp, 0, tmp.length);
// Write the id field
writeField(out,LITERAL+idAttributeName,documentURI);
// Write the access token information
writeACLs(out,"share",shareAcls,shareDenyAcls);
writeACLs(out,"document",acls,denyAcls);
// Write the arguments
iter = arguments.keySet().iterator();
while (iter.hasNext())
{
String name = (String)iter.next();
List values = (List)arguments.get(name);
int j = 0;
while (j < values.size())
{
String value = (String)values.get(j++);
writeField(out,name,value);
}
}
// Write the metadata, each in a field by itself
iter = document.getFields();
while (iter.hasNext())
{
String fieldName = (String)iter.next();
String newFieldName = (String)sourceTargets.get(fieldName);
if (newFieldName == null)
newFieldName = fieldName;
if (newFieldName.length() > 0)
{
if (newFieldName.toLowerCase().equals(idAttributeName.toLowerCase()))
newFieldName = ID_METADATA;
Object[] values = document.getField(fieldName);
// We only handle strings right now!!!
int k = 0;
while (k < values.length)
{
String value = (String)values[k++];
writeField(out,LITERAL+newFieldName,value);
}
}
}
// Write the content
writePreamble(out);
writeBoundary(out,"application/octet-stream","myfile","docname");
// Stream the data
long total = 0;
long now, later;
now = System.currentTimeMillis();
byte[] bytes = new byte[buffersize];
// Write out the contents of the inputstream to the socket
while (true)
{
int count;
// Specially catch all errors that come from reading the input stream itself.
// This will help us segregate errors that come from the stream vs. those that come from the ingestion system.
try
{
count = is.read(bytes);
}
catch (java.net.SocketTimeoutException ioe)
{
// We have to catch socket timeout exceptions specially, because they are derived from InterruptedIOException
// They are otherwise just like IOExceptions
// Log the error
Logging.ingest.warn("Error reading data for transmission to Ingestion API: "+ioe.getMessage(),ioe);
activityStart = new Long(fullStartTime);
activityCode = "-1";
activityDetails = "Couldn't read document: "+ioe.getMessage();
// If this continues, we should indeed abort the job. Retries should not go on indefinitely either; 2 hours is plenty
long currentTime = System.currentTimeMillis();
throw new ServiceInterruption("IO error reading document for ingestion: "+ioe.getMessage()+"; read will be retried again later",
ioe,
currentTime + interruptionRetryTime,
currentTime + 2L * 60L * 60000L,
-1,
true);
}
catch (InterruptedIOException ioe)
{
// If the transfer was interrupted, it may be because we are shutting down the thread.
// Third-party library exceptions derived from InterruptedIOException are possible; if the stream comes from httpclient especially.
// If we see one of these, we treat it as "not an interruption".
if (!ioe.getClass().getName().equals("java.io.InterruptedIOException"))
{
// Log the error
Logging.ingest.warn("Error reading data for transmission to Ingestion API: "+ioe.getMessage(),ioe);
activityStart = new Long(fullStartTime);
activityCode = "-1";
activityDetails = "Couldn't read document: "+ioe.getMessage();
// If this continues, we should indeed abort the job. Retries should not go on indefinitely either; 2 hours is plenty
long currentTime = System.currentTimeMillis();
throw new ServiceInterruption("IO error reading document for ingestion: "+ioe.getMessage()+"; read will be retried again later",
ioe,
currentTime + interruptionRetryTime,
currentTime + 2L * 60L * 60000L,
-1,
true);
}
else
throw ioe;
}
catch (IOException ioe)
{
// We need to decide whether to throw a service interruption or lcf exception, based on what went wrong.
// We never retry here; the cause is the repository, so there's not any point.
// Log the error
Logging.ingest.warn("Error reading data for transmission to Ingestion API: "+ioe.getMessage(),ioe);
activityStart = new Long(fullStartTime);
activityCode = "-1";
activityDetails = "Couldn't read document: "+ioe.getMessage();
// If this continues, we should indeed abort the job. Retries should not go on indefinitely either; 2 hours is plenty
long currentTime = System.currentTimeMillis();
throw new ServiceInterruption("IO error reading document for ingestion: "+ioe.getMessage()+"; read will be retried again later",
ioe,
currentTime + interruptionRetryTime,
currentTime + 2L * 60L * 60000L,
-1,
true);
}
if (count == -1)
break;
readFromDocumentStreamYet = true;
out.write(bytes,0,count);
total += (long)count;
}
// Write the postamble
writePostamble(out);
// Write the end marker
out.write(endBytes, 0, endBytes.length);
out.flush();
later = System.currentTimeMillis();
if (Logging.ingest.isDebugEnabled())
Logging.ingest.debug("Total bytes posted: " + new Long(total).toString() + ", total time: " + (later - now));
// Now, process response
CodeDetails cd;
try
{
cd = getResponse(in);
}
catch (ServiceInterruption si)
{
activityStart = new Long(now);
activityCode = "-2";
activityDetails = si.getMessage();
throw si;
}
activityStart = new Long(now);
activityBytes = new Long(length);
activityCode = cd.getCode();
activityDetails = cd.getDetails();
int codeValue = cd.getCodeValue();
// A negative number means http error of some kind.
if (codeValue < 0)
throw new ManifoldCFException("Http protocol error");
// 200 means we got a status document back
if (codeValue == 200)
{
// Look at response XML
cd.parseIngestionResponse();
rval = true;
return;
}
// Anything else means the document didn't ingest.
// There are three possibilities here:
// 1) The document will NEVER ingest (it's illegal), in which case a 400 or 403 will be returned, and
// 2) There is a transient error, in which case we will want to try again, after a wait.
// If the situation is (2), then we CAN'T retry if we already read any of the stream; therefore
// we are forced to throw a "service interrupted" exception, and let the caller reschedule
// the ingestion.
// 3) Something is wrong with the setup, e.g. bad credentials. In this case we chuck a ManifoldCFException,
// since this will abort the current activity entirely.
if (codeValue == 401)
throw new ManifoldCFException("Bad credentials for ingestion",ManifoldCFException.SETUP_ERROR);
if (codeValue >= 400 && codeValue < 500)
{
rval = false;
return;
}
// If this continues, we should indeed abort the job. Retries should not go on indefinitely either; 2 hours is plenty
long currentTime = System.currentTimeMillis();
throw new ServiceInterruption("Error "+Integer.toString(codeValue)+" from ingestion request; ingestion will be retried again later",
new ManifoldCFException("Ingestion HTTP error code "+Integer.toString(codeValue)),
currentTime + interruptionRetryTime,
currentTime + 2L * 60L * 60000L,
-1,
true);
}
finally
{
out.close();
}
}
finally
{
in.close();
}
}
finally
{
try
{
socket.close();
}
catch (InterruptedIOException e)
{
throw e;
}
catch (IOException e)
{
Logging.ingest.debug("Error closing socket: "+e.getMessage(),e);
// Do NOT rethrow
}
}
}
catch (UnsupportedEncodingException ioe)
{
throw new ManifoldCFException("Fatal ingestion error: "+ioe.getMessage(),ioe);
}
catch (java.net.SocketTimeoutException ioe)
{
// These are just like IO errors, but since they are derived from InterruptedIOException, they have to be caught first.
// Log the error
Logging.ingest.warn("Error connecting to ingestion API: "+ioe.getMessage(),ioe);
activityStart = new Long(fullStartTime);
activityCode = "-1";
activityDetails = ioe.getMessage();
throw ioe;
}
catch (InterruptedIOException e)
{
return;
}
catch (IOException ioe)
{
activityStart = new Long(fullStartTime);
// Intercept "broken pipe" exception, since that seems to be what we get if the ingestion API kills the socket right after a 400 goes out.
// Basically, we have no choice but to interpret that in the same manner as a 400, since no matter how we do it, it's a race and the 'broken pipe'
// result is always possible. So we might as well expect it and treat it properly.
if (ioe.getClass().getName().equals("java.net.SocketException") && ioe.getMessage().toLowerCase().indexOf("broken pipe") != -1)
{
// We've seen what looks like the ingestion interface forcibly closing the socket.
// We *choose* to interpret this just like a 400 response. However, we log in the history using a different code,
// since we really don't know what happened for sure.
// Record the attempt
activityCode = "-103";
activityDetails = "Presuming an ingestion rejection: "+ioe.getMessage();
rval = false;
return;
}
// Record the attempt
activityCode = "-1";
activityDetails = ioe.getMessage();
// Log the error
Logging.ingest.warn("Error communicating with Ingestion API: "+ioe.getMessage(),ioe);
throw ioe;
}
}
catch (Throwable e)
{
this.exception = e;
}
}
| public void run()
{
long length = document.getBinaryLength();
InputStream is = document.getBinaryStream();
try
{
// Do the operation!
long fullStartTime = System.currentTimeMillis();
// Open a socket to ingest, and to the response stream to get the post result
try
{
// Set up the socket, and the (optional) secure socket.
long responseRetryCount = responseRetries + (long)((float)length * sizeCoefficient);
Socket socket = createSocket(responseRetryCount);
try
{
InputStream in = socket.getInputStream();
try
{
OutputStream out = socket.getOutputStream();
try
{
// Create the output stream to SOLR
byte[] tmp = ("POST " + postUpdateAction + " HTTP/1.0\r\n").getBytes("ASCII");
out.write(tmp, 0, tmp.length);
// Set all the headers
writeCredentials(out);
// Headers must include the following:
// Content-Type
// Content-Length
// The content-length is calculated using the entire body length, which therefore includes the length of all the metadata fields as well.
// Come up with a boundary. Ideally, the boundary should be something that doesn't exist in any of the data. In practice, that would mean
// scanning all such data at least twice: once to make sure we avoided all boundary collisions, and a second time to actually output the data.
// This is such a huge chunk of overhead, I've decided for now to just punt and pick something that's pretty unlikely.
// Calculate the content length. To do this, we have to walk through the entire multipart assembly process, but calculate the length rather than output
// anything.
int totalLength = 0;
// Count the id.
totalLength += lengthField(LITERAL+idAttributeName,documentURI);
// Count the acls
totalLength += lengthACLs("share",shareAcls,shareDenyAcls);
totalLength += lengthACLs("document",acls,denyAcls);
// Count the arguments
Iterator iter = arguments.keySet().iterator();
while (iter.hasNext())
{
String name = (String)iter.next();
List values = (List)arguments.get(name);
int j = 0;
while (j < values.size())
{
String value = (String)values.get(j++);
totalLength += lengthField(name,value);
}
}
// Count the metadata.
iter = document.getFields();
while (iter.hasNext())
{
String fieldName = (String)iter.next();
String newFieldName = (String)sourceTargets.get(fieldName);
if (newFieldName == null)
newFieldName = fieldName;
// Make SURE we can't double up on the id field inadvertantly!
if (newFieldName.length() > 0)
{
if (newFieldName.toLowerCase().equals(idAttributeName.toLowerCase()))
newFieldName = ID_METADATA;
Object[] values = document.getField(fieldName);
// We only handle strings right now!!!
int k = 0;
while (k < values.length)
{
String value = (String)values[k++];
totalLength += lengthField(LITERAL+newFieldName,value);
}
}
}
// Count the binary data
totalLength += lengthPreamble();
totalLength += lengthBoundary("application/octet-stream","myfile","docname");
totalLength += length;
// Count the postamble
totalLength += lengthPostamble();
// Count the end marker.
totalLength += endBytes.length;
// Now, output the content-length header, and another newline, to start the data.
tmp = ("Content-Length: "+Integer.toString(totalLength)+"\r\n").getBytes("ASCII");
out.write(tmp, 0, tmp.length);
tmp = ("Content-Type: multipart/form-data; boundary=").getBytes("ASCII");
out.write(tmp, 0, tmp.length);
out.write(separatorBytes, 0, separatorBytes.length);
// End of headers.
tmp = "\r\n".getBytes("ASCII");
out.write(tmp, 0, tmp.length);
// Write the id field
writeField(out,LITERAL+idAttributeName,documentURI);
// Write the access token information
writeACLs(out,"share",shareAcls,shareDenyAcls);
writeACLs(out,"document",acls,denyAcls);
// Write the arguments
iter = arguments.keySet().iterator();
while (iter.hasNext())
{
String name = (String)iter.next();
List values = (List)arguments.get(name);
int j = 0;
while (j < values.size())
{
String value = (String)values.get(j++);
writeField(out,name,value);
}
}
// Write the metadata, each in a field by itself
iter = document.getFields();
while (iter.hasNext())
{
String fieldName = (String)iter.next();
String newFieldName = (String)sourceTargets.get(fieldName);
if (newFieldName == null)
newFieldName = fieldName;
if (newFieldName.length() > 0)
{
if (newFieldName.toLowerCase().equals(idAttributeName.toLowerCase()))
newFieldName = ID_METADATA;
Object[] values = document.getField(fieldName);
// We only handle strings right now!!!
int k = 0;
while (k < values.length)
{
String value = (String)values[k++];
writeField(out,LITERAL+newFieldName,value);
}
}
}
// Write the content
writePreamble(out);
writeBoundary(out,"application/octet-stream","myfile","docname");
// Stream the data
long total = 0;
long now, later;
now = System.currentTimeMillis();
byte[] bytes = new byte[buffersize];
// Write out the contents of the inputstream to the socket
while (true)
{
int count;
// Specially catch all errors that come from reading the input stream itself.
// This will help us segregate errors that come from the stream vs. those that come from the ingestion system.
try
{
count = is.read(bytes);
}
catch (java.net.SocketTimeoutException ioe)
{
// We have to catch socket timeout exceptions specially, because they are derived from InterruptedIOException
// They are otherwise just like IOExceptions
// Log the error
Logging.ingest.warn("Error reading data for transmission to Ingestion API: "+ioe.getMessage(),ioe);
activityStart = new Long(fullStartTime);
activityCode = "-1";
activityDetails = "Couldn't read document: "+ioe.getMessage();
// If this continues, we should indeed abort the job. Retries should not go on indefinitely either; 2 hours is plenty
long currentTime = System.currentTimeMillis();
throw new ServiceInterruption("IO error reading document for ingestion: "+ioe.getMessage()+"; read will be retried again later",
ioe,
currentTime + interruptionRetryTime,
currentTime + 2L * 60L * 60000L,
-1,
true);
}
catch (InterruptedIOException ioe)
{
// If the transfer was interrupted, it may be because we are shutting down the thread.
// Third-party library exceptions derived from InterruptedIOException are possible; if the stream comes from httpclient especially.
// If we see one of these, we treat it as "not an interruption".
if (!ioe.getClass().getName().equals("java.io.InterruptedIOException"))
{
// Log the error
Logging.ingest.warn("Error reading data for transmission to Ingestion API: "+ioe.getMessage(),ioe);
activityStart = new Long(fullStartTime);
activityCode = "-1";
activityDetails = "Couldn't read document: "+ioe.getMessage();
// If this continues, we should indeed abort the job. Retries should not go on indefinitely either; 2 hours is plenty
long currentTime = System.currentTimeMillis();
throw new ServiceInterruption("IO error reading document for ingestion: "+ioe.getMessage()+"; read will be retried again later",
ioe,
currentTime + interruptionRetryTime,
currentTime + 2L * 60L * 60000L,
-1,
true);
}
else
throw ioe;
}
catch (IOException ioe)
{
// We need to decide whether to throw a service interruption or lcf exception, based on what went wrong.
// We never retry here; the cause is the repository, so there's not any point.
// Log the error
Logging.ingest.warn("Error reading data for transmission to Ingestion API: "+ioe.getMessage(),ioe);
activityStart = new Long(fullStartTime);
activityCode = "-1";
activityDetails = "Couldn't read document: "+ioe.getMessage();
// If this continues, we should indeed abort the job. Retries should not go on indefinitely either; 2 hours is plenty
long currentTime = System.currentTimeMillis();
throw new ServiceInterruption("IO error reading document for ingestion: "+ioe.getMessage()+"; read will be retried again later",
ioe,
currentTime + interruptionRetryTime,
currentTime + 2L * 60L * 60000L,
-1,
true);
}
if (count == -1)
break;
readFromDocumentStreamYet = true;
out.write(bytes,0,count);
total += (long)count;
}
// Write the postamble
writePostamble(out);
// Write the end marker
out.write(endBytes, 0, endBytes.length);
out.flush();
later = System.currentTimeMillis();
if (Logging.ingest.isDebugEnabled())
Logging.ingest.debug("Total bytes posted: " + new Long(total).toString() + ", total time: " + (later - now));
// Now, process response
CodeDetails cd;
try
{
cd = getResponse(in);
}
catch (ServiceInterruption si)
{
activityStart = new Long(now);
activityCode = "-2";
activityDetails = si.getMessage();
throw si;
}
activityStart = new Long(now);
activityBytes = new Long(length);
activityCode = cd.getCode();
activityDetails = cd.getDetails();
int codeValue = cd.getCodeValue();
// A negative number means http error of some kind.
if (codeValue < 0)
throw new ManifoldCFException("Http protocol error");
// 200 means we got a status document back
if (codeValue == 200)
{
// Look at response XML
cd.parseIngestionResponse();
rval = true;
return;
}
// Anything else means the document didn't ingest.
// There are three possibilities here:
// 1) The document will NEVER ingest (it's illegal), in which case a 400 or 403 will be returned, and
// 2) There is a transient error, in which case we will want to try again, after a wait.
// If the situation is (2), then we CAN'T retry if we already read any of the stream; therefore
// we are forced to throw a "service interrupted" exception, and let the caller reschedule
// the ingestion.
// 3) Something is wrong with the setup, e.g. bad credentials. In this case we chuck a ManifoldCFException,
// since this will abort the current activity entirely.
if (codeValue == 401)
throw new ManifoldCFException("Bad credentials for ingestion",ManifoldCFException.SETUP_ERROR);
if ((codeValue >= 400 && codeValue < 500) ||
(codeValue == 500 && cd.getDetails() != null && cd.getDetails().indexOf("org.apache.tika.exception.TikaException") != -1))
{
rval = false;
return;
}
// If this continues, we should indeed abort the job. Retries should not go on indefinitely either; 2 hours is plenty
long currentTime = System.currentTimeMillis();
throw new ServiceInterruption("Error "+Integer.toString(codeValue)+" from ingestion request; ingestion will be retried again later",
new ManifoldCFException("Ingestion HTTP error code "+Integer.toString(codeValue)),
currentTime + interruptionRetryTime,
currentTime + 2L * 60L * 60000L,
-1,
true);
}
finally
{
out.close();
}
}
finally
{
in.close();
}
}
finally
{
try
{
socket.close();
}
catch (InterruptedIOException e)
{
throw e;
}
catch (IOException e)
{
Logging.ingest.debug("Error closing socket: "+e.getMessage(),e);
// Do NOT rethrow
}
}
}
catch (UnsupportedEncodingException ioe)
{
throw new ManifoldCFException("Fatal ingestion error: "+ioe.getMessage(),ioe);
}
catch (java.net.SocketTimeoutException ioe)
{
// These are just like IO errors, but since they are derived from InterruptedIOException, they have to be caught first.
// Log the error
Logging.ingest.warn("Error connecting to ingestion API: "+ioe.getMessage(),ioe);
activityStart = new Long(fullStartTime);
activityCode = "-1";
activityDetails = ioe.getMessage();
throw ioe;
}
catch (InterruptedIOException e)
{
return;
}
catch (IOException ioe)
{
activityStart = new Long(fullStartTime);
// Intercept "broken pipe" exception, since that seems to be what we get if the ingestion API kills the socket right after a 400 goes out.
// Basically, we have no choice but to interpret that in the same manner as a 400, since no matter how we do it, it's a race and the 'broken pipe'
// result is always possible. So we might as well expect it and treat it properly.
if (ioe.getClass().getName().equals("java.net.SocketException") && ioe.getMessage().toLowerCase().indexOf("broken pipe") != -1)
{
// We've seen what looks like the ingestion interface forcibly closing the socket.
// We *choose* to interpret this just like a 400 response. However, we log in the history using a different code,
// since we really don't know what happened for sure.
// Record the attempt
activityCode = "-103";
activityDetails = "Presuming an ingestion rejection: "+ioe.getMessage();
rval = false;
return;
}
// Record the attempt
activityCode = "-1";
activityDetails = ioe.getMessage();
// Log the error
Logging.ingest.warn("Error communicating with Ingestion API: "+ioe.getMessage(),ioe);
throw ioe;
}
}
catch (Throwable e)
{
this.exception = e;
}
}
|
diff --git a/skeletons/winservice/sample/src/AlertServer.java b/skeletons/winservice/sample/src/AlertServer.java
index 0712ad6..babe2f4 100644
--- a/skeletons/winservice/sample/src/AlertServer.java
+++ b/skeletons/winservice/sample/src/AlertServer.java
@@ -1,117 +1,120 @@
import java.net.*;
import java.util.*;
import java.io.*;
import javax.swing.JOptionPane;
public class AlertServer
{
private ServerSocket m_socket;
public class SListener implements Runnable
{
public Socket m_sock;
public SListener(Socket s)
{
m_sock = s;
}
public void run()
{
try {
InputStream is = m_sock.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
+ OutputStream outs = m_sock.getOutputStream();
+ Writer out = new OutputStreamWriter(outs);
String line;
while ((line=br.readLine()) != null)
{
FileWriter fw = new FileWriter("c:/alertserver.log", true);
+ out.write("PRINTING <" + line + ">");
System.out.println("Received: " + line);
fw.write(line + "\n");
if (line.startsWith("EXIT"))
{
System.out.println("calling System.exit(0);");
System.exit(0);
return;
}
fw.close();
JOptionPane.showMessageDialog(null, line, "alert", JOptionPane.ERROR_MESSAGE);
}
is.close();
} catch (IOException iox)
{
iox.printStackTrace();
}
}
}
public AlertServer()
{
}
public void setup()
{
try {
m_socket = new ServerSocket(2073);
} catch (Exception ex)
{
ex.printStackTrace();
}
}
public void listen()
{
try {
while (true)
{
Socket sock = m_socket.accept();
SListener sl = new SListener(sock);
new Thread(sl).start();
}
} catch (Exception exc)
{
exc.printStackTrace();
}
}
public void shutdown()
{
try {
FileWriter fw = new FileWriter("c:/shutdown.log", true);
fw.write("END NOW " + System.currentTimeMillis() + "\n");
fw.close();
} catch (IOException iox)
{
iox.printStackTrace();
}
}
static public void main(String[] args)
{
final AlertServer a = new AlertServer();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run()
{
// JOptionPane.showMessageDialog(null, "TERMINATING!", "alert", JOptionPane.ERROR_MESSAGE);
try {
FileWriter fw = new FileWriter("shutdown1.log", true);
fw.write("END NOW " + System.currentTimeMillis() + "\n");
fw.close();
} catch (Exception exc)
{
exc.printStackTrace();
}
System.out.println("SHUTDOWN...");
a.shutdown();
}
});
a.setup();
a.listen();
}
}
| false | true | public void run()
{
try {
InputStream is = m_sock.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line=br.readLine()) != null)
{
FileWriter fw = new FileWriter("c:/alertserver.log", true);
System.out.println("Received: " + line);
fw.write(line + "\n");
if (line.startsWith("EXIT"))
{
System.out.println("calling System.exit(0);");
System.exit(0);
return;
}
fw.close();
JOptionPane.showMessageDialog(null, line, "alert", JOptionPane.ERROR_MESSAGE);
}
is.close();
} catch (IOException iox)
{
iox.printStackTrace();
}
}
| public void run()
{
try {
InputStream is = m_sock.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
OutputStream outs = m_sock.getOutputStream();
Writer out = new OutputStreamWriter(outs);
String line;
while ((line=br.readLine()) != null)
{
FileWriter fw = new FileWriter("c:/alertserver.log", true);
out.write("PRINTING <" + line + ">");
System.out.println("Received: " + line);
fw.write(line + "\n");
if (line.startsWith("EXIT"))
{
System.out.println("calling System.exit(0);");
System.exit(0);
return;
}
fw.close();
JOptionPane.showMessageDialog(null, line, "alert", JOptionPane.ERROR_MESSAGE);
}
is.close();
} catch (IOException iox)
{
iox.printStackTrace();
}
}
|
diff --git a/app/src/com/halcyonwaves/apps/meinemediathek/fragments/SearchResultsFragment.java b/app/src/com/halcyonwaves/apps/meinemediathek/fragments/SearchResultsFragment.java
index e57cfa1..b2e18f3 100644
--- a/app/src/com/halcyonwaves/apps/meinemediathek/fragments/SearchResultsFragment.java
+++ b/app/src/com/halcyonwaves/apps/meinemediathek/fragments/SearchResultsFragment.java
@@ -1,108 +1,108 @@
package com.halcyonwaves.apps.meinemediathek.fragments;
import java.util.List;
import android.app.AlertDialog;
import android.app.ListFragment;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.Loader;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import com.halcyonwaves.apps.meinemediathek.R;
import com.halcyonwaves.apps.meinemediathek.SearchResultEntry;
import com.halcyonwaves.apps.meinemediathek.activities.MovieOverviewActivity;
import com.halcyonwaves.apps.meinemediathek.adapter.SearchResultsAdapter;
import com.halcyonwaves.apps.meinemediathek.loaders.ZDFSearchResultsLoader;
public class SearchResultsFragment extends ListFragment implements LoaderCallbacks< List< SearchResultEntry > >, OnClickListener {
private final static String TAG = "SearchResultsFragment";
private SearchResultsAdapter searchResultsAdapter = null;
@Override
public void onActivityCreated( final Bundle savedInstanceState ) {
super.onActivityCreated( savedInstanceState );
// initialize the adapter for fetching the data
this.searchResultsAdapter = new SearchResultsAdapter( this.getActivity() );
this.setListAdapter( this.searchResultsAdapter );
// start out with a progress indicator.
this.setListShown( false );
// prepare the loader. Either re-connect with an existing one, or start a new one.
this.getLoaderManager().initLoader( 0, this.getActivity().getIntent().getExtras(), this );
}
@Override
public void onClick( final DialogInterface dialog, final int which ) {
this.getActivity().finish();
}
@Override
public Loader< List< SearchResultEntry > > onCreateLoader( final int id, final Bundle args ) {
// get the supplied information from the intent which started this fragment
final String searchFor = this.getActivity().getIntent().getExtras().getString( "searchFor" );
Log.v( SearchResultsFragment.TAG, "The user is searching for: " + searchFor );
// return the requested loader
return new ZDFSearchResultsLoader( this.getActivity(), searchFor );
}
@Override
public void onListItemClick( final ListView l, final View v, final int position, final long id ) {
super.onListItemClick( l, v, position, id );
// get the item the user has selected
final SearchResultEntry selectedResults = (SearchResultEntry) this.getListAdapter().getItem( position );
// open the activity which shows the details about the selected entry
final Intent intent = new Intent( SearchResultsFragment.this.getActivity(), MovieOverviewActivity.class );
intent.putExtra( "title", selectedResults.title );
intent.putExtra( "description", selectedResults.description );
intent.putExtra( "downloadLink", selectedResults.downloadLink );
intent.putExtra( "previewImage", selectedResults.previewImage.getAbsolutePath() );
SearchResultsFragment.this.startActivity( intent );
}
@Override
public void onLoaderReset( final Loader< List< SearchResultEntry > > loader ) {
this.searchResultsAdapter.setData( null ); // clear the data in the adapter.
}
@Override
public void onLoadFinished( final Loader< List< SearchResultEntry > > loader, final List< SearchResultEntry > data ) {
// if an socket exception occurred, show a message
if( ((ZDFSearchResultsLoader) loader).socketTimeoutOccurred() ) {
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( this.getActivity() );
alertDialogBuilder.setTitle( this.getString( R.string.dlg_title_timeout ) );
alertDialogBuilder.setMessage( this.getString( R.string.dlg_msg_timeout ) );
alertDialogBuilder.setPositiveButton( android.R.string.ok, this );
alertDialogBuilder.create().show();
}
- //
- if( data.size() <= 0 ) {
+ // if there were no results tell it to the user
+ if( !((ZDFSearchResultsLoader) loader).socketTimeoutOccurred() && data.size() <= 0 ) {
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( this.getActivity() );
alertDialogBuilder.setTitle( this.getString( R.string.dlg_title_noresults ) );
alertDialogBuilder.setMessage( this.getString( R.string.dlg_msg_noresults ) );
alertDialogBuilder.setPositiveButton( android.R.string.ok, this );
alertDialogBuilder.create().show();
}
// set the new data in the adapter and show the list
this.searchResultsAdapter.setData( data );
if( this.isResumed() ) {
this.setListShown( true );
} else {
this.setListShownNoAnimation( true );
}
}
}
| true | true | public void onLoadFinished( final Loader< List< SearchResultEntry > > loader, final List< SearchResultEntry > data ) {
// if an socket exception occurred, show a message
if( ((ZDFSearchResultsLoader) loader).socketTimeoutOccurred() ) {
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( this.getActivity() );
alertDialogBuilder.setTitle( this.getString( R.string.dlg_title_timeout ) );
alertDialogBuilder.setMessage( this.getString( R.string.dlg_msg_timeout ) );
alertDialogBuilder.setPositiveButton( android.R.string.ok, this );
alertDialogBuilder.create().show();
}
//
if( data.size() <= 0 ) {
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( this.getActivity() );
alertDialogBuilder.setTitle( this.getString( R.string.dlg_title_noresults ) );
alertDialogBuilder.setMessage( this.getString( R.string.dlg_msg_noresults ) );
alertDialogBuilder.setPositiveButton( android.R.string.ok, this );
alertDialogBuilder.create().show();
}
// set the new data in the adapter and show the list
this.searchResultsAdapter.setData( data );
if( this.isResumed() ) {
this.setListShown( true );
} else {
this.setListShownNoAnimation( true );
}
}
| public void onLoadFinished( final Loader< List< SearchResultEntry > > loader, final List< SearchResultEntry > data ) {
// if an socket exception occurred, show a message
if( ((ZDFSearchResultsLoader) loader).socketTimeoutOccurred() ) {
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( this.getActivity() );
alertDialogBuilder.setTitle( this.getString( R.string.dlg_title_timeout ) );
alertDialogBuilder.setMessage( this.getString( R.string.dlg_msg_timeout ) );
alertDialogBuilder.setPositiveButton( android.R.string.ok, this );
alertDialogBuilder.create().show();
}
// if there were no results tell it to the user
if( !((ZDFSearchResultsLoader) loader).socketTimeoutOccurred() && data.size() <= 0 ) {
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( this.getActivity() );
alertDialogBuilder.setTitle( this.getString( R.string.dlg_title_noresults ) );
alertDialogBuilder.setMessage( this.getString( R.string.dlg_msg_noresults ) );
alertDialogBuilder.setPositiveButton( android.R.string.ok, this );
alertDialogBuilder.create().show();
}
// set the new data in the adapter and show the list
this.searchResultsAdapter.setData( data );
if( this.isResumed() ) {
this.setListShown( true );
} else {
this.setListShownNoAnimation( true );
}
}
|
diff --git a/src/com/joilnen/DrawGameHelper2.java b/src/com/joilnen/DrawGameHelper2.java
index c49c9f4..af7f3f6 100644
--- a/src/com/joilnen/DrawGameHelper2.java
+++ b/src/com/joilnen/DrawGameHelper2.java
@@ -1,137 +1,137 @@
package com.joilnen;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Message;
import android.os.Handler;
import android.util.Log;
import com.joilnen.Bzzz.RenderView;
import com.joilnen.Bzzz.RenderView2;
import com.joilnen.Mosca;
import com.joilnen.BigMosca;
import com.joilnen.Bolo;
import com.joilnen.InfoBar2;
import java.util.Random;
class DrawGameHelper2 {
private RenderView2 renderView;
private InfoBar2 infoBar;
private static long start_elapsed_time = System.currentTimeMillis();
private static int ELAPSED_TIME = 55;
private Handler handler = new Handler();
public DrawGameHelper2(RenderView2 renderView) {
this.renderView = renderView;
this.infoBar = new InfoBar2(renderView);
}
public void draw(Canvas canvas) {
- canvas.drawRGB(255, 255, 255);
try {
+ canvas.drawRGB(255, 255, 255);
canvas.drawBitmap(renderView.bolo.getBitmap(), 10, 310, null);
for(Mosca it:renderView.moscas) {
if(it.getY() < 450)
it.move();
else {
System.out.format("valor %d\n", it.getStatus());
if(it.getStatus() == SkinType.VOANDO_D)
it.setStatus(SkinType.POUSADA_D);
else
it.setStatus(SkinType.POUSADA_E);
}
canvas.drawBitmap(it.getBitmap(), it.getX(), it.getY(), null);
}
/****
for(BigMosca it:renderView.big_moscas) {
if(it.getY() < 430)
it.move();
else {
System.out.format("valor %d\n", it.getStatus());
if(it.getStatus() == SkinType.VOANDO_D)
it.setStatus(SkinType.POUSADA_D);
else
it.setStatus(SkinType.POUSADA_E);
}
canvas.drawBitmap(it.getBitmap(), it.getX(), it.getY(), null);
// if(it.getStatus() == SkinType.MORRENDO) renderView.moscas.remove(it);
}
for(MoscaAgulha it:renderView.moscas_agulha) {
if(it.getY() < 430)
it.move();
else {
System.out.format("valor %d\n", it.getStatus());
if(it.getStatus() == SkinType.VOANDO_D)
it.setStatus(SkinType.POUSADA_D);
else
it.setStatus(SkinType.POUSADA_E);
}
canvas.drawBitmap(it.getBitmap(), it.getX(), it.getY(), null);
// if(it.getStatus() == SkinType.MORRENDO) renderView.moscas.remove(it);
}
for(MoscaOndular it:renderView.moscas_ondular) {
if(it.getY() < 430)
it.move();
else {
System.out.format("valor %d\n", it.getStatus());
if(it.getStatus() == SkinType.VOANDO_D)
it.setStatus(SkinType.POUSADA_D);
else
it.setStatus(SkinType.POUSADA_E);
}
canvas.drawBitmap(it.getBitmap(), it.getX(), it.getY(), null);
// if(it.getStatus() == SkinType.MORRENDO) renderView.moscas.remove(it);
}
***/
for(final Mosca it:renderView.moscas) {
if(it.getStatus() == SkinType.MORRENDO) {
handler.post( new Runnable() {
public void run() {
renderView.moscas.remove(it);
infoBar.increment(10);
}
});
break;
}
}
if(renderView.moscas.size() < 6) {
// for(int i = 0; i < 6; i++) {
int i = new Random().nextInt(10);;
final Mosca m = new Mosca(this.renderView.getContext());
if((i % 3) == 0) m.setStatus(SkinType.VOANDO_D);
else m.setStatus(SkinType.VOANDO_E);
handler.post( new Runnable() {
public void run() {
renderView.moscas.add(m);
}
});
// }
}
infoBar.draw(canvas);
}
catch(Exception e) {
Log.d("Bzzz", "Nao consegui mover a mosca");
}
// Log.d("Bzzz", new String("Elapsed time " + Long.toString(System.currentTimeMillis() - start_elapsed_time)));
long res = Math.abs(System.currentTimeMillis() - start_elapsed_time);
// Log.d("Bzzz", new String("Elapsed time " + Long.toString(res)));
if(res < 30000)
try { Thread.sleep(ELAPSED_TIME + (30000 - res)/1000); } catch(Exception e) { }
else
try { Thread.sleep(ELAPSED_TIME); } catch (Exception e) { }
}
}
| false | true | public void draw(Canvas canvas) {
canvas.drawRGB(255, 255, 255);
try {
canvas.drawBitmap(renderView.bolo.getBitmap(), 10, 310, null);
for(Mosca it:renderView.moscas) {
if(it.getY() < 450)
it.move();
else {
System.out.format("valor %d\n", it.getStatus());
if(it.getStatus() == SkinType.VOANDO_D)
it.setStatus(SkinType.POUSADA_D);
else
it.setStatus(SkinType.POUSADA_E);
}
canvas.drawBitmap(it.getBitmap(), it.getX(), it.getY(), null);
}
/****
for(BigMosca it:renderView.big_moscas) {
if(it.getY() < 430)
it.move();
else {
System.out.format("valor %d\n", it.getStatus());
if(it.getStatus() == SkinType.VOANDO_D)
it.setStatus(SkinType.POUSADA_D);
else
it.setStatus(SkinType.POUSADA_E);
}
canvas.drawBitmap(it.getBitmap(), it.getX(), it.getY(), null);
// if(it.getStatus() == SkinType.MORRENDO) renderView.moscas.remove(it);
}
for(MoscaAgulha it:renderView.moscas_agulha) {
if(it.getY() < 430)
it.move();
else {
System.out.format("valor %d\n", it.getStatus());
if(it.getStatus() == SkinType.VOANDO_D)
it.setStatus(SkinType.POUSADA_D);
else
it.setStatus(SkinType.POUSADA_E);
}
canvas.drawBitmap(it.getBitmap(), it.getX(), it.getY(), null);
// if(it.getStatus() == SkinType.MORRENDO) renderView.moscas.remove(it);
}
for(MoscaOndular it:renderView.moscas_ondular) {
if(it.getY() < 430)
it.move();
else {
System.out.format("valor %d\n", it.getStatus());
if(it.getStatus() == SkinType.VOANDO_D)
it.setStatus(SkinType.POUSADA_D);
else
it.setStatus(SkinType.POUSADA_E);
}
canvas.drawBitmap(it.getBitmap(), it.getX(), it.getY(), null);
// if(it.getStatus() == SkinType.MORRENDO) renderView.moscas.remove(it);
}
***/
for(final Mosca it:renderView.moscas) {
if(it.getStatus() == SkinType.MORRENDO) {
handler.post( new Runnable() {
public void run() {
renderView.moscas.remove(it);
infoBar.increment(10);
}
});
break;
}
}
if(renderView.moscas.size() < 6) {
// for(int i = 0; i < 6; i++) {
int i = new Random().nextInt(10);;
final Mosca m = new Mosca(this.renderView.getContext());
if((i % 3) == 0) m.setStatus(SkinType.VOANDO_D);
else m.setStatus(SkinType.VOANDO_E);
handler.post( new Runnable() {
public void run() {
renderView.moscas.add(m);
}
});
// }
}
infoBar.draw(canvas);
}
catch(Exception e) {
Log.d("Bzzz", "Nao consegui mover a mosca");
}
// Log.d("Bzzz", new String("Elapsed time " + Long.toString(System.currentTimeMillis() - start_elapsed_time)));
long res = Math.abs(System.currentTimeMillis() - start_elapsed_time);
// Log.d("Bzzz", new String("Elapsed time " + Long.toString(res)));
if(res < 30000)
try { Thread.sleep(ELAPSED_TIME + (30000 - res)/1000); } catch(Exception e) { }
else
try { Thread.sleep(ELAPSED_TIME); } catch (Exception e) { }
}
| public void draw(Canvas canvas) {
try {
canvas.drawRGB(255, 255, 255);
canvas.drawBitmap(renderView.bolo.getBitmap(), 10, 310, null);
for(Mosca it:renderView.moscas) {
if(it.getY() < 450)
it.move();
else {
System.out.format("valor %d\n", it.getStatus());
if(it.getStatus() == SkinType.VOANDO_D)
it.setStatus(SkinType.POUSADA_D);
else
it.setStatus(SkinType.POUSADA_E);
}
canvas.drawBitmap(it.getBitmap(), it.getX(), it.getY(), null);
}
/****
for(BigMosca it:renderView.big_moscas) {
if(it.getY() < 430)
it.move();
else {
System.out.format("valor %d\n", it.getStatus());
if(it.getStatus() == SkinType.VOANDO_D)
it.setStatus(SkinType.POUSADA_D);
else
it.setStatus(SkinType.POUSADA_E);
}
canvas.drawBitmap(it.getBitmap(), it.getX(), it.getY(), null);
// if(it.getStatus() == SkinType.MORRENDO) renderView.moscas.remove(it);
}
for(MoscaAgulha it:renderView.moscas_agulha) {
if(it.getY() < 430)
it.move();
else {
System.out.format("valor %d\n", it.getStatus());
if(it.getStatus() == SkinType.VOANDO_D)
it.setStatus(SkinType.POUSADA_D);
else
it.setStatus(SkinType.POUSADA_E);
}
canvas.drawBitmap(it.getBitmap(), it.getX(), it.getY(), null);
// if(it.getStatus() == SkinType.MORRENDO) renderView.moscas.remove(it);
}
for(MoscaOndular it:renderView.moscas_ondular) {
if(it.getY() < 430)
it.move();
else {
System.out.format("valor %d\n", it.getStatus());
if(it.getStatus() == SkinType.VOANDO_D)
it.setStatus(SkinType.POUSADA_D);
else
it.setStatus(SkinType.POUSADA_E);
}
canvas.drawBitmap(it.getBitmap(), it.getX(), it.getY(), null);
// if(it.getStatus() == SkinType.MORRENDO) renderView.moscas.remove(it);
}
***/
for(final Mosca it:renderView.moscas) {
if(it.getStatus() == SkinType.MORRENDO) {
handler.post( new Runnable() {
public void run() {
renderView.moscas.remove(it);
infoBar.increment(10);
}
});
break;
}
}
if(renderView.moscas.size() < 6) {
// for(int i = 0; i < 6; i++) {
int i = new Random().nextInt(10);;
final Mosca m = new Mosca(this.renderView.getContext());
if((i % 3) == 0) m.setStatus(SkinType.VOANDO_D);
else m.setStatus(SkinType.VOANDO_E);
handler.post( new Runnable() {
public void run() {
renderView.moscas.add(m);
}
});
// }
}
infoBar.draw(canvas);
}
catch(Exception e) {
Log.d("Bzzz", "Nao consegui mover a mosca");
}
// Log.d("Bzzz", new String("Elapsed time " + Long.toString(System.currentTimeMillis() - start_elapsed_time)));
long res = Math.abs(System.currentTimeMillis() - start_elapsed_time);
// Log.d("Bzzz", new String("Elapsed time " + Long.toString(res)));
if(res < 30000)
try { Thread.sleep(ELAPSED_TIME + (30000 - res)/1000); } catch(Exception e) { }
else
try { Thread.sleep(ELAPSED_TIME); } catch (Exception e) { }
}
|
diff --git a/src/com/redhat/ceylon/launcher/CeylonClassLoader.java b/src/com/redhat/ceylon/launcher/CeylonClassLoader.java
index 76d947688..05bda6039 100644
--- a/src/com/redhat/ceylon/launcher/CeylonClassLoader.java
+++ b/src/com/redhat/ceylon/launcher/CeylonClassLoader.java
@@ -1,199 +1,199 @@
package com.redhat.ceylon.launcher;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* Ceylon-specific class loader that knows how to find and add
* all needed dependencies for compiler and runtime.
* Implements child-first class loading to prevent mix-ups with
* Java's own tool-chain.
*
* @author Tako Schotanus
*
*/
public class CeylonClassLoader extends URLClassLoader {
public CeylonClassLoader() throws URISyntaxException, MalformedURLException, FileNotFoundException {
super(getClassPathUrls());
}
public CeylonClassLoader(ClassLoader parentLoader) throws URISyntaxException, MalformedURLException, FileNotFoundException {
super(getClassPathUrls(), parentLoader);
}
private static URL[] getClassPathUrls() throws URISyntaxException, MalformedURLException, FileNotFoundException {
List<File> cp = getClassPath();
URL[] urls = new URL[cp.size()];
int i = 0;
for (File f : cp) {
urls[i++] = f.toURI().toURL();
}
return urls;
}
public static List<File> getClassPath() throws URISyntaxException, FileNotFoundException {
// Determine the necessary folders
File ceylonHome = LauncherUtil.determineHome();
File ceylonRepo = LauncherUtil.determineRepo();
File ceylonLib = LauncherUtil.determineLibs();
// Perform some sanity checks
if (!ceylonHome.isDirectory()) {
throw new FileNotFoundException("Could not determine the Ceylon home directory (" + ceylonHome + ")");
}
if (!ceylonRepo.isDirectory()) {
throw new FileNotFoundException("The Ceylon system repository could not be found (" + ceylonRepo + ")");
}
if (!ceylonLib.isDirectory()) {
throw new FileNotFoundException("The Ceylon system libraries could not be found (" + ceylonLib + ")");
}
List<File> archives = new LinkedList<File>();
// List all the JARs we find in the LIB directory
findLibraries(archives, ceylonLib);
// List all the necessary Ceylon JARs and CARs
String version = LauncherUtil.determineSystemVersion();
archives.add(getRepoJar(ceylonRepo, "com.redhat.ceylon.compiler.java", version));
archives.add(getRepoCar(ceylonRepo, "ceylon.language", version));
archives.add(getRepoJar(ceylonRepo, "ceylon.runtime", version));
archives.add(getRepoJar(ceylonRepo, "com.redhat.ceylon.compiler.js", version));
archives.add(getRepoJar(ceylonRepo, "com.redhat.ceylon.typechecker", version));
archives.add(getRepoJar(ceylonRepo, "com.redhat.ceylon.common", version));
archives.add(getRepoJar(ceylonRepo, "com.redhat.ceylon.module-resolver", version));
archives.add(getRepoJar(ceylonRepo, "org.jboss.jandex", "1.0.3.Final"));
archives.add(getRepoJar(ceylonRepo, "org.jboss.modules", "1.1.3.GA"));
archives.add(getRepoJar(ceylonRepo, "org.jboss.logmanager", "1.4.0.Final"));
// Maven support for CMR
archives.add(getRepoJar(ceylonRepo, "com.redhat.ceylon.maven-support", "1.0")); // optional
// For the typechecker
- archives.add(getRepoJar(ceylonRepo, "org.antlr-runtime", "3.4"));
+ archives.add(getRepoJar(ceylonRepo, "org.antlr.runtime", "3.4"));
// For the JS backend
archives.add(getRepoJar(ceylonRepo, "net.minidev.json-smart", "1.1.1"));
// For the "doc" tool
archives.add(getRepoJar(ceylonRepo, "org.tautua.markdownpapers.core", "1.2.7"));
archives.add(getRepoJar(ceylonRepo, "com.github.rjeschke.txtmark", "0.8-c0dcd373ce"));
// For the --out http:// functionality of the compiler
archives.add(getRepoJar(ceylonRepo, "com.googlecode.sardine", "314"));
archives.add(getRepoJar(ceylonRepo, "org.apache.httpcomponents.httpclient", "4.1.1"));
archives.add(getRepoJar(ceylonRepo, "org.apache.httpcomponents.httpcore", "4.1.1"));
archives.add(getRepoJar(ceylonRepo, "org.apache.commons.logging", "1.1.1"));
archives.add(getRepoJar(ceylonRepo, "org.apache.commons.codec", "1.4"));
archives.add(getRepoJar(ceylonRepo, "org.slf4j.api", "1.6.1"));
archives.add(getRepoJar(ceylonRepo, "org.slf4j.simple", "1.6.1")); // optional
return archives;
}
private static File getRepoJar(File repo, String moduleName, String version) {
return getRepoUrl(repo, moduleName, version, "jar");
}
private static File getRepoCar(File repo, String moduleName, String version) {
return getRepoUrl(repo, moduleName, version, "car");
}
private static File getRepoUrl(File repo, String moduleName, String version, String extension) {
return new File(repo, moduleName.replace('.', '/') + "/" + version + "/" + moduleName + "-" + version + "." + extension);
}
private static void findLibraries(List<File> libs, File folder) {
File[] items = folder.listFiles();
for (File f : items) {
if (f.isDirectory()) {
findLibraries(libs, f);
} else if (f.getName().toLowerCase().endsWith(".jar")) {
libs.add(f);
}
}
}
@Override
protected synchronized Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException {
// First, check if the class has already been loaded
Class<?> c = findLoadedClass(name);
if (c == null) {
try {
// checking local
c = findClass(name);
} catch (ClassNotFoundException e) {
// checking parent
// This call to loadClass may eventually call findClass again, in case the parent doesn't find anything.
c = super.loadClass(name, resolve);
}
}
if (resolve) {
resolveClass(c);
}
return c;
}
@Override
public URL getResource(String name) {
URL url = findResource(name);
if (url == null) {
// This call to getResource may eventually call findResource again, in case the parent doesn't find anything.
url = super.getResource(name);
}
return url;
}
@Override
public Enumeration<URL> getResources(String name) throws IOException {
/**
* Similar to super, but local resources are enumerated before parent resources
*/
Enumeration<URL> localUrls = findResources(name);
Enumeration<URL> parentUrls = null;
if (getParent() != null) {
parentUrls = getParent().getResources(name);
}
final List<URL> urls = new ArrayList<URL>();
if (localUrls != null) {
while (localUrls.hasMoreElements()) {
urls.add(localUrls.nextElement());
}
}
if (parentUrls != null) {
while (parentUrls.hasMoreElements()) {
urls.add(parentUrls.nextElement());
}
}
return new Enumeration<URL>() {
Iterator<URL> iter = urls.iterator();
public boolean hasMoreElements() {
return iter.hasNext();
}
public URL nextElement() {
return iter.next();
}
};
}
@Override
public InputStream getResourceAsStream(String name) {
URL url = getResource(name);
try {
return url != null ? url.openStream() : null;
} catch (IOException e) {
}
return null;
}
}
| true | true | public static List<File> getClassPath() throws URISyntaxException, FileNotFoundException {
// Determine the necessary folders
File ceylonHome = LauncherUtil.determineHome();
File ceylonRepo = LauncherUtil.determineRepo();
File ceylonLib = LauncherUtil.determineLibs();
// Perform some sanity checks
if (!ceylonHome.isDirectory()) {
throw new FileNotFoundException("Could not determine the Ceylon home directory (" + ceylonHome + ")");
}
if (!ceylonRepo.isDirectory()) {
throw new FileNotFoundException("The Ceylon system repository could not be found (" + ceylonRepo + ")");
}
if (!ceylonLib.isDirectory()) {
throw new FileNotFoundException("The Ceylon system libraries could not be found (" + ceylonLib + ")");
}
List<File> archives = new LinkedList<File>();
// List all the JARs we find in the LIB directory
findLibraries(archives, ceylonLib);
// List all the necessary Ceylon JARs and CARs
String version = LauncherUtil.determineSystemVersion();
archives.add(getRepoJar(ceylonRepo, "com.redhat.ceylon.compiler.java", version));
archives.add(getRepoCar(ceylonRepo, "ceylon.language", version));
archives.add(getRepoJar(ceylonRepo, "ceylon.runtime", version));
archives.add(getRepoJar(ceylonRepo, "com.redhat.ceylon.compiler.js", version));
archives.add(getRepoJar(ceylonRepo, "com.redhat.ceylon.typechecker", version));
archives.add(getRepoJar(ceylonRepo, "com.redhat.ceylon.common", version));
archives.add(getRepoJar(ceylonRepo, "com.redhat.ceylon.module-resolver", version));
archives.add(getRepoJar(ceylonRepo, "org.jboss.jandex", "1.0.3.Final"));
archives.add(getRepoJar(ceylonRepo, "org.jboss.modules", "1.1.3.GA"));
archives.add(getRepoJar(ceylonRepo, "org.jboss.logmanager", "1.4.0.Final"));
// Maven support for CMR
archives.add(getRepoJar(ceylonRepo, "com.redhat.ceylon.maven-support", "1.0")); // optional
// For the typechecker
archives.add(getRepoJar(ceylonRepo, "org.antlr-runtime", "3.4"));
// For the JS backend
archives.add(getRepoJar(ceylonRepo, "net.minidev.json-smart", "1.1.1"));
// For the "doc" tool
archives.add(getRepoJar(ceylonRepo, "org.tautua.markdownpapers.core", "1.2.7"));
archives.add(getRepoJar(ceylonRepo, "com.github.rjeschke.txtmark", "0.8-c0dcd373ce"));
// For the --out http:// functionality of the compiler
archives.add(getRepoJar(ceylonRepo, "com.googlecode.sardine", "314"));
archives.add(getRepoJar(ceylonRepo, "org.apache.httpcomponents.httpclient", "4.1.1"));
archives.add(getRepoJar(ceylonRepo, "org.apache.httpcomponents.httpcore", "4.1.1"));
archives.add(getRepoJar(ceylonRepo, "org.apache.commons.logging", "1.1.1"));
archives.add(getRepoJar(ceylonRepo, "org.apache.commons.codec", "1.4"));
archives.add(getRepoJar(ceylonRepo, "org.slf4j.api", "1.6.1"));
archives.add(getRepoJar(ceylonRepo, "org.slf4j.simple", "1.6.1")); // optional
return archives;
}
| public static List<File> getClassPath() throws URISyntaxException, FileNotFoundException {
// Determine the necessary folders
File ceylonHome = LauncherUtil.determineHome();
File ceylonRepo = LauncherUtil.determineRepo();
File ceylonLib = LauncherUtil.determineLibs();
// Perform some sanity checks
if (!ceylonHome.isDirectory()) {
throw new FileNotFoundException("Could not determine the Ceylon home directory (" + ceylonHome + ")");
}
if (!ceylonRepo.isDirectory()) {
throw new FileNotFoundException("The Ceylon system repository could not be found (" + ceylonRepo + ")");
}
if (!ceylonLib.isDirectory()) {
throw new FileNotFoundException("The Ceylon system libraries could not be found (" + ceylonLib + ")");
}
List<File> archives = new LinkedList<File>();
// List all the JARs we find in the LIB directory
findLibraries(archives, ceylonLib);
// List all the necessary Ceylon JARs and CARs
String version = LauncherUtil.determineSystemVersion();
archives.add(getRepoJar(ceylonRepo, "com.redhat.ceylon.compiler.java", version));
archives.add(getRepoCar(ceylonRepo, "ceylon.language", version));
archives.add(getRepoJar(ceylonRepo, "ceylon.runtime", version));
archives.add(getRepoJar(ceylonRepo, "com.redhat.ceylon.compiler.js", version));
archives.add(getRepoJar(ceylonRepo, "com.redhat.ceylon.typechecker", version));
archives.add(getRepoJar(ceylonRepo, "com.redhat.ceylon.common", version));
archives.add(getRepoJar(ceylonRepo, "com.redhat.ceylon.module-resolver", version));
archives.add(getRepoJar(ceylonRepo, "org.jboss.jandex", "1.0.3.Final"));
archives.add(getRepoJar(ceylonRepo, "org.jboss.modules", "1.1.3.GA"));
archives.add(getRepoJar(ceylonRepo, "org.jboss.logmanager", "1.4.0.Final"));
// Maven support for CMR
archives.add(getRepoJar(ceylonRepo, "com.redhat.ceylon.maven-support", "1.0")); // optional
// For the typechecker
archives.add(getRepoJar(ceylonRepo, "org.antlr.runtime", "3.4"));
// For the JS backend
archives.add(getRepoJar(ceylonRepo, "net.minidev.json-smart", "1.1.1"));
// For the "doc" tool
archives.add(getRepoJar(ceylonRepo, "org.tautua.markdownpapers.core", "1.2.7"));
archives.add(getRepoJar(ceylonRepo, "com.github.rjeschke.txtmark", "0.8-c0dcd373ce"));
// For the --out http:// functionality of the compiler
archives.add(getRepoJar(ceylonRepo, "com.googlecode.sardine", "314"));
archives.add(getRepoJar(ceylonRepo, "org.apache.httpcomponents.httpclient", "4.1.1"));
archives.add(getRepoJar(ceylonRepo, "org.apache.httpcomponents.httpcore", "4.1.1"));
archives.add(getRepoJar(ceylonRepo, "org.apache.commons.logging", "1.1.1"));
archives.add(getRepoJar(ceylonRepo, "org.apache.commons.codec", "1.4"));
archives.add(getRepoJar(ceylonRepo, "org.slf4j.api", "1.6.1"));
archives.add(getRepoJar(ceylonRepo, "org.slf4j.simple", "1.6.1")); // optional
return archives;
}
|
diff --git a/repository/gwt-client/src/main/java/org/mule/galaxy/repository/client/item/ChildItemsPanel.java b/repository/gwt-client/src/main/java/org/mule/galaxy/repository/client/item/ChildItemsPanel.java
index a11d79bb..5903cd1b 100755
--- a/repository/gwt-client/src/main/java/org/mule/galaxy/repository/client/item/ChildItemsPanel.java
+++ b/repository/gwt-client/src/main/java/org/mule/galaxy/repository/client/item/ChildItemsPanel.java
@@ -1,335 +1,336 @@
package org.mule.galaxy.repository.client.item;
import org.mule.galaxy.repository.client.RepositoryModule;
import org.mule.galaxy.repository.rpc.ItemInfo;
import org.mule.galaxy.repository.rpc.WPolicyException;
import org.mule.galaxy.web.client.Galaxy;
import org.mule.galaxy.web.client.PageInfo;
import org.mule.galaxy.web.client.ui.button.ToolbarButton;
import org.mule.galaxy.web.client.ui.button.ToolbarButtonEvent;
import org.mule.galaxy.web.client.ui.dialog.LightBox;
import org.mule.galaxy.web.client.ui.field.SearchStoreFilterField;
import org.mule.galaxy.web.client.ui.grid.BasicGrid;
import org.mule.galaxy.web.client.ui.panel.AbstractFlowComposite;
import org.mule.galaxy.web.client.ui.panel.FullContentPanel;
import org.mule.galaxy.web.client.ui.panel.InlineHelpPanel;
import org.mule.galaxy.web.client.ui.panel.PaddedContentPanel;
import org.mule.galaxy.web.client.ui.panel.ToolbarButtonBar;
import org.mule.galaxy.web.client.ui.panel.WidgetHelper;
import org.mule.galaxy.web.client.ui.util.Images;
import org.mule.galaxy.web.rpc.AbstractCallback;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelFactory;
import com.extjs.gxt.ui.client.data.BeanModelLookup;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.GridEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.store.Store;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.toolbar.FillToolItem;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.Image;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class ChildItemsPanel extends AbstractFlowComposite {
protected Collection items;
protected final RepositoryMenuPanel menuPanel;
private final Galaxy galaxy;
private final ItemInfo info;
private CheckBoxSelectionModel<BeanModel> selectionModel;
private RepositoryModule repository;
private ItemPanel itemPanel;
public ChildItemsPanel(Galaxy galaxy, RepositoryMenuPanel menuPanel,
ItemInfo item, ItemPanel itemPanel) {
super();
this.galaxy = galaxy;
this.repository = menuPanel.getRepositoryModule();
this.menuPanel = menuPanel;
this.info = item;
this.itemPanel = itemPanel;
}
@Override
public void doShowPage() {
super.doShowPage();
fetchAllItems();
}
private void fetchAllItems() {
AbstractCallback callback = new AbstractCallback(menuPanel) {
public void onCallSuccess(Object o) {
items = (Collection) o;
createItemGrid();
}
};
repository.getRegistryService().getItems(info != null ? info.getId() : null, false, callback);
}
/**
* generic grid for itemInfo
*
* @return
*/
private void createItemGrid() {
panel.clear();
ContentPanel contentPanel = new FullContentPanel();
contentPanel.setHeading("All Items");
if (info != null) {
contentPanel = new PaddedContentPanel();
contentPanel.setHeading(info.getName());
itemPanel.setHeading(info.getName());
}
contentPanel.setAutoHeight(true);
// add inline help string and widget
contentPanel.setTopComponent(new InlineHelpPanel(repository.getRepositoryConstants().repo_Tip(), 14));
BeanModelFactory factory = BeanModelLookup.get().getFactory(ItemInfo.class);
List<BeanModel> model = factory.createModel(items);
final ListStore<BeanModel> store = new ListStore<BeanModel>();
store.add(model);
ToolbarButtonBar toolbar = new ToolbarButtonBar();
// search filter
SearchStoreFilterField<BeanModel> filter = new SearchStoreFilterField<BeanModel>() {
@Override
protected boolean doSelect(Store<BeanModel> store, BeanModel parent,
BeanModel record, String property, String filter) {
String name = record.get("name");
name = name.toLowerCase();
String authorName = record.get("authorName");
authorName = authorName.toLowerCase();
String type = record.get("type");
type = type.toLowerCase();
if (name.indexOf(filter.toLowerCase()) != -1 ||
authorName.indexOf(filter.toLowerCase()) != -1 ||
type.indexOf(filter.toLowerCase()) != -1) {
return true;
}
return false;
}
};
filter.bind(store);
toolbar.add(filter);
toolbar.add(new FillToolItem());
selectionModel = new CheckBoxSelectionModel<BeanModel>();
List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
columns.add(selectionModel.getColumn());
ColumnConfig icon = new ColumnConfig("type", " ", 23);
icon.setRenderer(new GridCellRenderer() {
public Object render(ModelData modelData, String s, ColumnData columnData, int i, int i1, ListStore listStore, Grid grid) {
- if(modelData.get(s).equals("Workspace")) {
+ Object obj = modelData.get(s);
+ if(obj.equals("Workspace")) {
return new Image(Images.ICON_FOLDER);
}
return new Image(Images.ICON_TEXT);
}
});
columns.add(icon);
columns.add(new ColumnConfig("name", "Name", 250));
columns.add(new ColumnConfig("authorName", "Author", 200));
columns.add(new ColumnConfig("type", "Type", 200));
ColumnModel columnModel = new ColumnModel(columns);
BasicGrid<BeanModel> grid = new BasicGrid<BeanModel>(store, columnModel);
grid.setSelectionModel(selectionModel);
grid.addPlugin(selectionModel);
grid.setAutoExpandColumn("type");
grid.addListener(Events.CellClick, new Listener<BaseEvent>() {
public void handleEvent(BaseEvent be) {
GridEvent ge = (GridEvent) be;
// any non checkbox...
if (ge.getColIndex() > 0) {
ItemInfo ii = store.getAt(ge.getRowIndex()).getBean();
// drill down into the grid
menuPanel.showItem(ii);
History.newItem("item/" + ii.getId());
}
}
});
contentPanel.add(toolbar);
contentPanel.add(grid);
if (info == null || info.isModifiable()) {
if (info == null || info.getType().equals("Workspace")) {
final ToolbarButton newWkspaceBtn = new ToolbarButton("New Workspace");
newWkspaceBtn.setStyleName("toolbar-btn_center");
newWkspaceBtn.addSelectionListener(new SelectionListener<ToolbarButtonEvent>() {
@Override
public void componentSelected(ToolbarButtonEvent ce) {
showNewWorkspace();
}
});
newWkspaceBtn.setToolTip(repository.getRepositoryConstants().repo_NewWorkspace());
toolbar.add(newWkspaceBtn);
final ToolbarButton newArtifactBtn = new ToolbarButton("New Artifact");
newArtifactBtn.addSelectionListener(new SelectionListener<ToolbarButtonEvent>() {
@Override
public void componentSelected(ToolbarButtonEvent ce) {
showArtifactUploadForm(true);
}
});
newArtifactBtn.setToolTip(repository.getRepositoryConstants().repo_NewArtifact());
toolbar.add(newArtifactBtn);
} else if (info.getType().equals("Artifact")) {
final ToolbarButton newVersionBtn = new ToolbarButton("New Version");
newVersionBtn.addSelectionListener(new SelectionListener<ToolbarButtonEvent>() {
@Override
public void componentSelected(ToolbarButtonEvent ce) {
showArtifactUploadForm(false);
}
});
newVersionBtn.setToolTip(repository.getRepositoryConstants().repo_Items_New());
toolbar.add(newVersionBtn);
} else {
String token;
if (info.getId() != null) {
token = "add-item/" + info.getId();
} else {
token = "add-item/";
}
ToolbarButton newBtn = WidgetHelper.createToolbarHistoryButton("New", token, repository.getRepositoryConstants().repo_Items_New());
toolbar.add(newBtn);
}
}
final ToolbarButton delBtn = new ToolbarButton("Delete");
delBtn.setToolTip(repository.getRepositoryConstants().repo_Delete());
delBtn.setEnabled(false);
delBtn.addSelectionListener(new SelectionListener<ToolbarButtonEvent>() {
@Override
public void componentSelected(ToolbarButtonEvent ce) {
warnDelete(selectionModel.getSelectedItems());
}
});
if (info == null || info.isDeletable()) {
toolbar.add(delBtn);
}
selectionModel.addSelectionChangedListener(new SelectionChangedListener<BeanModel>() {
public void selectionChanged(SelectionChangedEvent<BeanModel> se) {
boolean isSelected = selectionModel.getSelectedItems().size() > 0;
delBtn.setEnabled(isSelected);
}
});
panel.add(contentPanel);
}
protected void showArtifactUploadForm(boolean parentIsWorkspace) {
LightBox popup = new LightBox(new AddArtifactForm(repository.getRegistryService(), info, parentIsWorkspace, this));
popup.show();
}
protected void showNewWorkspace() {
LightBox popup = new LightBox(new AddWorkspaceForm(repository.getRegistryService(), info));
popup.show();
}
protected void warnDelete(final List itemlist) {
final Listener<MessageBoxEvent> l = new Listener<MessageBoxEvent>() {
public void handleEvent(MessageBoxEvent ce) {
com.extjs.gxt.ui.client.widget.button.Button btn = ce.getButtonClicked();
if (Dialog.YES.equals(btn.getItemId())) {
delete(selectionModel.getSelectedItems());
}
}
};
MessageBox.confirm("Confirm", "Are you sure you want to delete these items?", l);
}
public void refresh() {
fetchAllItems();
menuPanel.refresh();
menuPanel.clearErrorMessage();
}
private void delete(List<BeanModel> seletedItems) {
final List<String> ids = new ArrayList<String>();
for (BeanModel data : seletedItems) {
ids.add((String) data.get("id"));
}
// FIXME: delete collection.
repository.getRegistryService().delete(ids, new AbstractCallback(menuPanel) {
@Override
public void onCallFailure(Throwable caught) {
if (caught instanceof WPolicyException) {
WPolicyException ex = (WPolicyException)caught;
handlePolicyFailures(caught, ex);
} else {
super.onFailure(caught);
}
}
public void onCallSuccess(Object arg0) {
fetchAllItems();
menuPanel.removeItems(info, ids);
menuPanel.setMessage("Items were deleted.");
}
});
}
protected void handlePolicyFailures(Throwable caught, WPolicyException ex) {
PageInfo page =
galaxy.getPageManager().createPageInfo("policy-failure-" + caught.hashCode(),
new PolicyResultsPanel(galaxy, ex.getPolicyFailures()),
0);
History.newItem(page.getName());
}
public CheckBoxSelectionModel<BeanModel> getSelectionModel() {
return selectionModel;
}
public void setSelectionModel(CheckBoxSelectionModel<BeanModel> selectionModel) {
this.selectionModel = selectionModel;
}
}
| true | true | private void createItemGrid() {
panel.clear();
ContentPanel contentPanel = new FullContentPanel();
contentPanel.setHeading("All Items");
if (info != null) {
contentPanel = new PaddedContentPanel();
contentPanel.setHeading(info.getName());
itemPanel.setHeading(info.getName());
}
contentPanel.setAutoHeight(true);
// add inline help string and widget
contentPanel.setTopComponent(new InlineHelpPanel(repository.getRepositoryConstants().repo_Tip(), 14));
BeanModelFactory factory = BeanModelLookup.get().getFactory(ItemInfo.class);
List<BeanModel> model = factory.createModel(items);
final ListStore<BeanModel> store = new ListStore<BeanModel>();
store.add(model);
ToolbarButtonBar toolbar = new ToolbarButtonBar();
// search filter
SearchStoreFilterField<BeanModel> filter = new SearchStoreFilterField<BeanModel>() {
@Override
protected boolean doSelect(Store<BeanModel> store, BeanModel parent,
BeanModel record, String property, String filter) {
String name = record.get("name");
name = name.toLowerCase();
String authorName = record.get("authorName");
authorName = authorName.toLowerCase();
String type = record.get("type");
type = type.toLowerCase();
if (name.indexOf(filter.toLowerCase()) != -1 ||
authorName.indexOf(filter.toLowerCase()) != -1 ||
type.indexOf(filter.toLowerCase()) != -1) {
return true;
}
return false;
}
};
filter.bind(store);
toolbar.add(filter);
toolbar.add(new FillToolItem());
selectionModel = new CheckBoxSelectionModel<BeanModel>();
List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
columns.add(selectionModel.getColumn());
ColumnConfig icon = new ColumnConfig("type", " ", 23);
icon.setRenderer(new GridCellRenderer() {
public Object render(ModelData modelData, String s, ColumnData columnData, int i, int i1, ListStore listStore, Grid grid) {
if(modelData.get(s).equals("Workspace")) {
return new Image(Images.ICON_FOLDER);
}
return new Image(Images.ICON_TEXT);
}
});
columns.add(icon);
columns.add(new ColumnConfig("name", "Name", 250));
columns.add(new ColumnConfig("authorName", "Author", 200));
columns.add(new ColumnConfig("type", "Type", 200));
ColumnModel columnModel = new ColumnModel(columns);
BasicGrid<BeanModel> grid = new BasicGrid<BeanModel>(store, columnModel);
grid.setSelectionModel(selectionModel);
grid.addPlugin(selectionModel);
grid.setAutoExpandColumn("type");
grid.addListener(Events.CellClick, new Listener<BaseEvent>() {
public void handleEvent(BaseEvent be) {
GridEvent ge = (GridEvent) be;
// any non checkbox...
if (ge.getColIndex() > 0) {
ItemInfo ii = store.getAt(ge.getRowIndex()).getBean();
// drill down into the grid
menuPanel.showItem(ii);
History.newItem("item/" + ii.getId());
}
}
});
contentPanel.add(toolbar);
contentPanel.add(grid);
if (info == null || info.isModifiable()) {
if (info == null || info.getType().equals("Workspace")) {
final ToolbarButton newWkspaceBtn = new ToolbarButton("New Workspace");
newWkspaceBtn.setStyleName("toolbar-btn_center");
newWkspaceBtn.addSelectionListener(new SelectionListener<ToolbarButtonEvent>() {
@Override
public void componentSelected(ToolbarButtonEvent ce) {
showNewWorkspace();
}
});
newWkspaceBtn.setToolTip(repository.getRepositoryConstants().repo_NewWorkspace());
toolbar.add(newWkspaceBtn);
final ToolbarButton newArtifactBtn = new ToolbarButton("New Artifact");
newArtifactBtn.addSelectionListener(new SelectionListener<ToolbarButtonEvent>() {
@Override
public void componentSelected(ToolbarButtonEvent ce) {
showArtifactUploadForm(true);
}
});
newArtifactBtn.setToolTip(repository.getRepositoryConstants().repo_NewArtifact());
toolbar.add(newArtifactBtn);
} else if (info.getType().equals("Artifact")) {
final ToolbarButton newVersionBtn = new ToolbarButton("New Version");
newVersionBtn.addSelectionListener(new SelectionListener<ToolbarButtonEvent>() {
@Override
public void componentSelected(ToolbarButtonEvent ce) {
showArtifactUploadForm(false);
}
});
newVersionBtn.setToolTip(repository.getRepositoryConstants().repo_Items_New());
toolbar.add(newVersionBtn);
} else {
String token;
if (info.getId() != null) {
token = "add-item/" + info.getId();
} else {
token = "add-item/";
}
ToolbarButton newBtn = WidgetHelper.createToolbarHistoryButton("New", token, repository.getRepositoryConstants().repo_Items_New());
toolbar.add(newBtn);
}
}
final ToolbarButton delBtn = new ToolbarButton("Delete");
delBtn.setToolTip(repository.getRepositoryConstants().repo_Delete());
delBtn.setEnabled(false);
delBtn.addSelectionListener(new SelectionListener<ToolbarButtonEvent>() {
@Override
public void componentSelected(ToolbarButtonEvent ce) {
warnDelete(selectionModel.getSelectedItems());
}
});
if (info == null || info.isDeletable()) {
toolbar.add(delBtn);
}
selectionModel.addSelectionChangedListener(new SelectionChangedListener<BeanModel>() {
public void selectionChanged(SelectionChangedEvent<BeanModel> se) {
boolean isSelected = selectionModel.getSelectedItems().size() > 0;
delBtn.setEnabled(isSelected);
}
});
panel.add(contentPanel);
}
| private void createItemGrid() {
panel.clear();
ContentPanel contentPanel = new FullContentPanel();
contentPanel.setHeading("All Items");
if (info != null) {
contentPanel = new PaddedContentPanel();
contentPanel.setHeading(info.getName());
itemPanel.setHeading(info.getName());
}
contentPanel.setAutoHeight(true);
// add inline help string and widget
contentPanel.setTopComponent(new InlineHelpPanel(repository.getRepositoryConstants().repo_Tip(), 14));
BeanModelFactory factory = BeanModelLookup.get().getFactory(ItemInfo.class);
List<BeanModel> model = factory.createModel(items);
final ListStore<BeanModel> store = new ListStore<BeanModel>();
store.add(model);
ToolbarButtonBar toolbar = new ToolbarButtonBar();
// search filter
SearchStoreFilterField<BeanModel> filter = new SearchStoreFilterField<BeanModel>() {
@Override
protected boolean doSelect(Store<BeanModel> store, BeanModel parent,
BeanModel record, String property, String filter) {
String name = record.get("name");
name = name.toLowerCase();
String authorName = record.get("authorName");
authorName = authorName.toLowerCase();
String type = record.get("type");
type = type.toLowerCase();
if (name.indexOf(filter.toLowerCase()) != -1 ||
authorName.indexOf(filter.toLowerCase()) != -1 ||
type.indexOf(filter.toLowerCase()) != -1) {
return true;
}
return false;
}
};
filter.bind(store);
toolbar.add(filter);
toolbar.add(new FillToolItem());
selectionModel = new CheckBoxSelectionModel<BeanModel>();
List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
columns.add(selectionModel.getColumn());
ColumnConfig icon = new ColumnConfig("type", " ", 23);
icon.setRenderer(new GridCellRenderer() {
public Object render(ModelData modelData, String s, ColumnData columnData, int i, int i1, ListStore listStore, Grid grid) {
Object obj = modelData.get(s);
if(obj.equals("Workspace")) {
return new Image(Images.ICON_FOLDER);
}
return new Image(Images.ICON_TEXT);
}
});
columns.add(icon);
columns.add(new ColumnConfig("name", "Name", 250));
columns.add(new ColumnConfig("authorName", "Author", 200));
columns.add(new ColumnConfig("type", "Type", 200));
ColumnModel columnModel = new ColumnModel(columns);
BasicGrid<BeanModel> grid = new BasicGrid<BeanModel>(store, columnModel);
grid.setSelectionModel(selectionModel);
grid.addPlugin(selectionModel);
grid.setAutoExpandColumn("type");
grid.addListener(Events.CellClick, new Listener<BaseEvent>() {
public void handleEvent(BaseEvent be) {
GridEvent ge = (GridEvent) be;
// any non checkbox...
if (ge.getColIndex() > 0) {
ItemInfo ii = store.getAt(ge.getRowIndex()).getBean();
// drill down into the grid
menuPanel.showItem(ii);
History.newItem("item/" + ii.getId());
}
}
});
contentPanel.add(toolbar);
contentPanel.add(grid);
if (info == null || info.isModifiable()) {
if (info == null || info.getType().equals("Workspace")) {
final ToolbarButton newWkspaceBtn = new ToolbarButton("New Workspace");
newWkspaceBtn.setStyleName("toolbar-btn_center");
newWkspaceBtn.addSelectionListener(new SelectionListener<ToolbarButtonEvent>() {
@Override
public void componentSelected(ToolbarButtonEvent ce) {
showNewWorkspace();
}
});
newWkspaceBtn.setToolTip(repository.getRepositoryConstants().repo_NewWorkspace());
toolbar.add(newWkspaceBtn);
final ToolbarButton newArtifactBtn = new ToolbarButton("New Artifact");
newArtifactBtn.addSelectionListener(new SelectionListener<ToolbarButtonEvent>() {
@Override
public void componentSelected(ToolbarButtonEvent ce) {
showArtifactUploadForm(true);
}
});
newArtifactBtn.setToolTip(repository.getRepositoryConstants().repo_NewArtifact());
toolbar.add(newArtifactBtn);
} else if (info.getType().equals("Artifact")) {
final ToolbarButton newVersionBtn = new ToolbarButton("New Version");
newVersionBtn.addSelectionListener(new SelectionListener<ToolbarButtonEvent>() {
@Override
public void componentSelected(ToolbarButtonEvent ce) {
showArtifactUploadForm(false);
}
});
newVersionBtn.setToolTip(repository.getRepositoryConstants().repo_Items_New());
toolbar.add(newVersionBtn);
} else {
String token;
if (info.getId() != null) {
token = "add-item/" + info.getId();
} else {
token = "add-item/";
}
ToolbarButton newBtn = WidgetHelper.createToolbarHistoryButton("New", token, repository.getRepositoryConstants().repo_Items_New());
toolbar.add(newBtn);
}
}
final ToolbarButton delBtn = new ToolbarButton("Delete");
delBtn.setToolTip(repository.getRepositoryConstants().repo_Delete());
delBtn.setEnabled(false);
delBtn.addSelectionListener(new SelectionListener<ToolbarButtonEvent>() {
@Override
public void componentSelected(ToolbarButtonEvent ce) {
warnDelete(selectionModel.getSelectedItems());
}
});
if (info == null || info.isDeletable()) {
toolbar.add(delBtn);
}
selectionModel.addSelectionChangedListener(new SelectionChangedListener<BeanModel>() {
public void selectionChanged(SelectionChangedEvent<BeanModel> se) {
boolean isSelected = selectionModel.getSelectedItems().size() > 0;
delBtn.setEnabled(isSelected);
}
});
panel.add(contentPanel);
}
|
diff --git a/src/schmoller/tubes/SpecialShapedRecipe.java b/src/schmoller/tubes/SpecialShapedRecipe.java
index 30381b6..29db2b7 100644
--- a/src/schmoller/tubes/SpecialShapedRecipe.java
+++ b/src/schmoller/tubes/SpecialShapedRecipe.java
@@ -1,206 +1,206 @@
package schmoller.tubes;
import java.util.HashMap;
import java.util.List;
import codechicken.microblock.Saw;
import schmoller.tubes.api.interfaces.ISpecialItemCompare;
import net.minecraft.block.Block;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.world.World;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.oredict.OreDictionary;
public class SpecialShapedRecipe implements IRecipe
{
public int width;
public int height;
public Object[] recipeItems;
public ItemStack output;
public boolean canMirror = true;
public SpecialShapedRecipe(ItemStack output, Object... definition)
{
this.output = output.copy();
String recipe = "";
int index = 0;
width = 0;
height = 0;
while (definition[index] instanceof String)
{
String line = (String)definition[index++];
++height;
width = line.length();
recipe += line;
}
HashMap<Character, Object> map = new HashMap<Character, Object>();
for (; index < definition.length; index += 2)
{
Character character = (Character)definition[index];
Object obj = definition[index+1];
if(obj instanceof Item)
obj = new ItemStack((Item)obj);
else if(obj instanceof Block)
obj = new ItemStack((Block)obj);
else if(obj instanceof Fluid)
obj = new FluidStack(((Fluid)obj), FluidContainerRegistry.BUCKET_VOLUME);
else if(!(obj instanceof String) && !(obj instanceof ItemStack) && !(obj instanceof FluidStack))
throw new IllegalArgumentException("Invalid definition: " + character + " = " + obj);
map.put(character, obj);
}
recipeItems = new Object[width * height];
for (int i = 0; i < width * height; ++i)
{
char c = recipe.charAt(i);
recipeItems[i] = map.get(c);
}
}
public SpecialShapedRecipe setCanMirror(boolean canMirror)
{
this.canMirror = canMirror;
return this;
}
@Override
public boolean matches( InventoryCrafting inv, World world )
{
for (int i = 0; i <= 3 - width; ++i)
{
for (int j = 0; j <= 3 - height; ++j)
{
if (checkMatch(inv, i, j, false))
return true;
if (canMirror && checkMatch(inv, i, j, true))
return true;
}
}
return false;
}
private boolean checkMatch(InventoryCrafting inv, int startX, int startY, boolean mirror)
{
for (int x = 0; x < 3; ++x)
{
for(int y = 0; y < 3; ++y)
{
Object obj = null;
if(x >= startX && x < startX + width && y >= startY && y < startY + height)
{
if(mirror)
obj = recipeItems[(width - (x - startX) - 1) + (y - startY) * width];
else
obj = recipeItems[(x - startX) + (y - startY) * width];
}
ItemStack inSlot = inv.getStackInRowAndColumn(x, y);
if(inSlot == null && obj != null)
return false;
if(obj instanceof ItemStack)
{
ItemStack toMatch = (ItemStack)obj;
if(toMatch.getItem() instanceof Saw)
{
if(!(inSlot.getItem() instanceof Saw))
- continue;
+ return false;
}
else
{
if(inSlot.itemID != toMatch.itemID)
- continue;
+ return false;
if(inSlot.getItemDamage() != toMatch.getItemDamage() && toMatch.getItemDamage() != OreDictionary.WILDCARD_VALUE)
- continue;
+ return false;
if(toMatch.getItem() instanceof ISpecialItemCompare)
{
if(!((ISpecialItemCompare)toMatch.getItem()).areItemsEqual(inSlot, toMatch))
- continue;
+ return false;
}
}
}
else if(obj instanceof String)
{
List<ItemStack> toMatchAny = OreDictionary.getOres((String)obj);
boolean matched = false;
for(ItemStack toMatch : toMatchAny)
{
if(inSlot.itemID != toMatch.itemID)
continue;
if(inSlot.getItemDamage() != toMatch.getItemDamage() && toMatch.getItemDamage() != OreDictionary.WILDCARD_VALUE)
continue;
if(toMatch.getItem() instanceof ISpecialItemCompare)
{
if(!((ISpecialItemCompare)toMatch.getItem()).areItemsEqual(inSlot, toMatch))
continue;
}
matched = true;
break;
}
if(!matched)
return false;
}
else if(obj instanceof FluidStack)
{
FluidStack toMatch = (FluidStack)obj;
FluidStack contained = FluidContainerRegistry.getFluidForFilledItem(inSlot);
if(contained == null || !contained.isFluidStackIdentical(toMatch))
return false;
}
}
}
return true;
}
@Override
public ItemStack getCraftingResult( InventoryCrafting inventorycrafting )
{
return output.copy();
}
@Override
public int getRecipeSize()
{
return width * height;
}
@Override
public ItemStack getRecipeOutput()
{
return output;
}
}
| false | true | private boolean checkMatch(InventoryCrafting inv, int startX, int startY, boolean mirror)
{
for (int x = 0; x < 3; ++x)
{
for(int y = 0; y < 3; ++y)
{
Object obj = null;
if(x >= startX && x < startX + width && y >= startY && y < startY + height)
{
if(mirror)
obj = recipeItems[(width - (x - startX) - 1) + (y - startY) * width];
else
obj = recipeItems[(x - startX) + (y - startY) * width];
}
ItemStack inSlot = inv.getStackInRowAndColumn(x, y);
if(inSlot == null && obj != null)
return false;
if(obj instanceof ItemStack)
{
ItemStack toMatch = (ItemStack)obj;
if(toMatch.getItem() instanceof Saw)
{
if(!(inSlot.getItem() instanceof Saw))
continue;
}
else
{
if(inSlot.itemID != toMatch.itemID)
continue;
if(inSlot.getItemDamage() != toMatch.getItemDamage() && toMatch.getItemDamage() != OreDictionary.WILDCARD_VALUE)
continue;
if(toMatch.getItem() instanceof ISpecialItemCompare)
{
if(!((ISpecialItemCompare)toMatch.getItem()).areItemsEqual(inSlot, toMatch))
continue;
}
}
}
else if(obj instanceof String)
{
List<ItemStack> toMatchAny = OreDictionary.getOres((String)obj);
boolean matched = false;
for(ItemStack toMatch : toMatchAny)
{
if(inSlot.itemID != toMatch.itemID)
continue;
if(inSlot.getItemDamage() != toMatch.getItemDamage() && toMatch.getItemDamage() != OreDictionary.WILDCARD_VALUE)
continue;
if(toMatch.getItem() instanceof ISpecialItemCompare)
{
if(!((ISpecialItemCompare)toMatch.getItem()).areItemsEqual(inSlot, toMatch))
continue;
}
matched = true;
break;
}
if(!matched)
return false;
}
else if(obj instanceof FluidStack)
{
FluidStack toMatch = (FluidStack)obj;
FluidStack contained = FluidContainerRegistry.getFluidForFilledItem(inSlot);
if(contained == null || !contained.isFluidStackIdentical(toMatch))
return false;
}
}
}
return true;
}
| private boolean checkMatch(InventoryCrafting inv, int startX, int startY, boolean mirror)
{
for (int x = 0; x < 3; ++x)
{
for(int y = 0; y < 3; ++y)
{
Object obj = null;
if(x >= startX && x < startX + width && y >= startY && y < startY + height)
{
if(mirror)
obj = recipeItems[(width - (x - startX) - 1) + (y - startY) * width];
else
obj = recipeItems[(x - startX) + (y - startY) * width];
}
ItemStack inSlot = inv.getStackInRowAndColumn(x, y);
if(inSlot == null && obj != null)
return false;
if(obj instanceof ItemStack)
{
ItemStack toMatch = (ItemStack)obj;
if(toMatch.getItem() instanceof Saw)
{
if(!(inSlot.getItem() instanceof Saw))
return false;
}
else
{
if(inSlot.itemID != toMatch.itemID)
return false;
if(inSlot.getItemDamage() != toMatch.getItemDamage() && toMatch.getItemDamage() != OreDictionary.WILDCARD_VALUE)
return false;
if(toMatch.getItem() instanceof ISpecialItemCompare)
{
if(!((ISpecialItemCompare)toMatch.getItem()).areItemsEqual(inSlot, toMatch))
return false;
}
}
}
else if(obj instanceof String)
{
List<ItemStack> toMatchAny = OreDictionary.getOres((String)obj);
boolean matched = false;
for(ItemStack toMatch : toMatchAny)
{
if(inSlot.itemID != toMatch.itemID)
continue;
if(inSlot.getItemDamage() != toMatch.getItemDamage() && toMatch.getItemDamage() != OreDictionary.WILDCARD_VALUE)
continue;
if(toMatch.getItem() instanceof ISpecialItemCompare)
{
if(!((ISpecialItemCompare)toMatch.getItem()).areItemsEqual(inSlot, toMatch))
continue;
}
matched = true;
break;
}
if(!matched)
return false;
}
else if(obj instanceof FluidStack)
{
FluidStack toMatch = (FluidStack)obj;
FluidStack contained = FluidContainerRegistry.getFluidForFilledItem(inSlot);
if(contained == null || !contained.isFluidStackIdentical(toMatch))
return false;
}
}
}
return true;
}
|
diff --git a/org.seasar.dolteng.eclipse.plugin/src/main/java/org/seasar/dolteng/eclipse/nature/DoltengNature.java b/org.seasar.dolteng.eclipse.plugin/src/main/java/org/seasar/dolteng/eclipse/nature/DoltengNature.java
index 79d282c..e875090 100644
--- a/org.seasar.dolteng.eclipse.plugin/src/main/java/org/seasar/dolteng/eclipse/nature/DoltengNature.java
+++ b/org.seasar.dolteng.eclipse.plugin/src/main/java/org/seasar/dolteng/eclipse/nature/DoltengNature.java
@@ -1,178 +1,175 @@
/*
* Copyright 2004-2008 the Seasar Foundation and the Others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.seasar.dolteng.eclipse.nature;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectNature;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.preference.IPersistentPreferenceStore;
import org.seasar.dolteng.core.types.AsTypeResolver;
import org.seasar.dolteng.core.types.MxComponentValueResolver;
import org.seasar.dolteng.core.types.TypeMappingRegistry;
import org.seasar.dolteng.core.types.impl.AsTypeResolverImpl;
import org.seasar.dolteng.core.types.impl.BasicTypeMappingRegistry;
import org.seasar.dolteng.core.types.impl.KuinaTypeMappingRegistry;
import org.seasar.dolteng.core.types.impl.MxComponentValueResolverImpl;
import org.seasar.dolteng.core.types.impl.StandardTypeMappingRegistry;
import org.seasar.dolteng.eclipse.Constants;
import org.seasar.dolteng.eclipse.DoltengCore;
import org.seasar.dolteng.eclipse.DoltengProject;
import org.seasar.dolteng.eclipse.preferences.DoltengPreferences;
import org.seasar.dolteng.eclipse.preferences.impl.DoltengPreferencesImpl;
/**
* @author taichi
*
*/
public class DoltengNature implements DoltengProject, IProjectNature {
protected IProject project;
protected DoltengPreferences preference;
protected BasicTypeMappingRegistry registry;
protected AsTypeResolverImpl resolver;
protected MxComponentValueResolverImpl mxResolver;
public DoltengNature() {
super();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.resources.IProjectNature#configure()
*/
public void configure() {
init();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.resources.IProjectNature#deconfigure()
*/
public void deconfigure() {
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.resources.IProjectNature#getProject()
*/
public IProject getProject() {
return this.project;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.core.resources.IProjectNature#setProject(org.eclipse.core
* .resources.IProject)
*/
public void setProject(IProject project) {
this.project = project;
}
/*
* (non-Javadoc)
*
* @see org.seasar.dolteng.eclipse.DoltengProject#getProjectPreferences()
*/
public synchronized DoltengPreferences getProjectPreferences() {
if (this.preference == null) {
init();
}
return this.preference;
}
/*
* (non-Javadoc)
*
* @see org.seasar.dolteng.eclipse.DoltengProject#getTypeMappingRegistry()
*/
public synchronized TypeMappingRegistry getTypeMappingRegistry() {
if (this.registry == null) {
init();
}
return this.registry;
}
public synchronized AsTypeResolver getAsTypeResolver() {
if (this.resolver == null) {
init();
}
return this.resolver;
}
public synchronized MxComponentValueResolver getMxComponentValueResolver() {
if (this.mxResolver == null) {
init();
}
return this.mxResolver;
}
public void init() {
try {
this.preference = new DoltengPreferencesImpl(getProject());
if (Constants.DAO_TYPE_KUINADAO
.equals(this.preference.getDaoType())) {
this.registry = new KuinaTypeMappingRegistry();
- } else if (Constants.DAO_TYPE_S2JDBC.equals(this.preference
- .getDaoType())) {
- this.registry = new BasicTypeMappingRegistry();
} else {
this.registry = new StandardTypeMappingRegistry();
}
this.registry.initialize();
this.resolver = new AsTypeResolverImpl();
this.resolver.initialize();
this.mxResolver = new MxComponentValueResolverImpl();
this.mxResolver.initialize();
} catch (Exception e) {
DoltengCore.log(e);
}
}
public synchronized void destroy() {
try {
IPersistentPreferenceStore store = getProjectPreferences()
.getRawPreferences();
store.save();
} catch (Exception e) {
DoltengCore.log(e);
}
}
public static DoltengNature getInstance(IProject project) {
if (project != null && project.isOpen()) {
try {
IProjectNature nature = project.getNature(Constants.ID_NATURE);
if (nature instanceof DoltengNature) {
return (DoltengNature) nature;
}
} catch (CoreException e) {
DoltengCore.log(e);
}
}
return null;
}
}
| true | true | public void init() {
try {
this.preference = new DoltengPreferencesImpl(getProject());
if (Constants.DAO_TYPE_KUINADAO
.equals(this.preference.getDaoType())) {
this.registry = new KuinaTypeMappingRegistry();
} else if (Constants.DAO_TYPE_S2JDBC.equals(this.preference
.getDaoType())) {
this.registry = new BasicTypeMappingRegistry();
} else {
this.registry = new StandardTypeMappingRegistry();
}
this.registry.initialize();
this.resolver = new AsTypeResolverImpl();
this.resolver.initialize();
this.mxResolver = new MxComponentValueResolverImpl();
this.mxResolver.initialize();
} catch (Exception e) {
DoltengCore.log(e);
}
}
| public void init() {
try {
this.preference = new DoltengPreferencesImpl(getProject());
if (Constants.DAO_TYPE_KUINADAO
.equals(this.preference.getDaoType())) {
this.registry = new KuinaTypeMappingRegistry();
} else {
this.registry = new StandardTypeMappingRegistry();
}
this.registry.initialize();
this.resolver = new AsTypeResolverImpl();
this.resolver.initialize();
this.mxResolver = new MxComponentValueResolverImpl();
this.mxResolver.initialize();
} catch (Exception e) {
DoltengCore.log(e);
}
}
|
diff --git a/MyTracks/src/com/google/android/apps/mytracks/io/gdata/GDataWrapper.java b/MyTracks/src/com/google/android/apps/mytracks/io/gdata/GDataWrapper.java
index 335dca66..d6ed2083 100644
--- a/MyTracks/src/com/google/android/apps/mytracks/io/gdata/GDataWrapper.java
+++ b/MyTracks/src/com/google/android/apps/mytracks/io/gdata/GDataWrapper.java
@@ -1,299 +1,299 @@
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.io.gdata;
import com.google.android.apps.mytracks.MyTracksConstants;
import com.google.android.apps.mytracks.io.AuthManager;
import android.util.Log;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* GDataWrapper provides a wrapper around GData operations that maintains the
* GData client, and provides a method to run GData queries with proper error
* handling. After a query is run, the wrapper can be queried about the error
* that occurred.
*
* @param C the GData service client
* @author Sandor Dornbush
*/
public class GDataWrapper<C> {
public static class AuthenticationException extends Exception {
private Exception exception;
private static final long serialVersionUID = 1L;
public AuthenticationException(Exception caught) {
this.exception = caught;
}
public Exception getException() {
return exception;
}
};
public static class ParseException extends Exception {
private Exception exception;
private static final long serialVersionUID = 1L;
public ParseException(Exception caught) {
this.exception = caught;
}
public Exception getException() {
return exception;
}
};
public static class ConflictDetectedException extends Exception {
private Exception exception;
private static final long serialVersionUID = 1L;
public ConflictDetectedException(Exception caught) {
this.exception = caught;
}
public Exception getException() {
return exception;
}
};
public static class HttpException extends Exception {
private static final long serialVersionUID = 1L;
private int statusCode;
private String statusMessage;
public HttpException(int statusCode, String statusMessage) {
super();
this.statusCode = statusCode;
this.statusMessage = statusMessage;
}
public int getStatusCode() {
return statusCode;
}
public String getStatusMessage() {
return statusMessage;
}
};
/**
* A QueryFunction is passed in when executing a query. The query function of
* the class is called with the GData client as a parameter. The function
* should execute whatever operations it desires on the client without concern
* for whether the client will throw an error.
*/
public interface QueryFunction<C> {
public abstract void query(C client)
throws AuthenticationException, IOException, ParseException,
ConflictDetectedException, HttpException;
}
/**
* A AuthenticatedFunction is passed in when executing the google
* authenticated service. The authenticated function of the class is called
* with the current authentication token for the service. The function should
* execute whatever operations with the google service without concern for
* whether the client will throw an error.
*/
public interface AuthenticatedFunction {
public abstract void run(String authenticationToken)
throws AuthenticationException, IOException;
}
// The types of error that may be encountered
// No error occurred.
public static final int ERROR_NO_ERROR = 0;
// There was an authentication error, the auth token may be invalid.
public static final int ERROR_AUTH = 1;
// There was an internal error on the server side.
public static final int ERROR_INTERNAL = 2;
// There was an error connecting to the server.
public static final int ERROR_CONNECTION = 3;
// The item queried did not exit.
public static final int ERROR_NOT_FOUND = 4;
// There was an error parsing or serializing locally.
public static final int ERROR_LOCAL = 5;
// There was a conflict, update the entry and try again.
public static final int ERROR_CONFLICT = 6;
// A query was run after cleaning up the wrapper, so the client was invalid.
public static final int ERROR_CLEANED_UP = 7;
// An unknown error occurred.
public static final int ERROR_UNKNOWN = 100;
private static final int AUTH_TOKEN_INVALIDATE_REFRESH_NUM_RETRIES = 1;
private static final int AUTH_TOKEN_INVALIDATE_REFRESH_TIMEOUT = 5000;
private String errorMessage;
private int errorType;
private C gdataServiceClient;
private AuthManager auth;
private boolean retryOnAuthFailure;
public GDataWrapper() {
errorType = ERROR_NO_ERROR;
errorMessage = null;
auth = null;
retryOnAuthFailure = false;
}
public void setClient(C gdataServiceClient) {
this.gdataServiceClient = gdataServiceClient;
}
public boolean runAuthenticatedFunction(
final AuthenticatedFunction function) {
return runCommon(function, null);
}
public boolean runQuery(final QueryFunction<C> query) {
return runCommon(null, query);
}
/**
* Runs an arbitrary piece of code.
*/
private boolean runCommon(final AuthenticatedFunction function,
final QueryFunction<C> query) {
for (int i = 0; i <= AUTH_TOKEN_INVALIDATE_REFRESH_NUM_RETRIES; i++) {
runOne(function, query);
if (errorType == ERROR_NO_ERROR) {
return true;
}
Log.d(MyTracksConstants.TAG, "GData error encountered: " + errorMessage);
if (errorType == ERROR_AUTH && auth != null) {
if (!retryOnAuthFailure || !invalidateAndRefreshAuthToken()) {
return false;
}
}
Log.d(MyTracksConstants.TAG, "retrying function/query");
}
return false;
}
/**
* Execute a given function or query. If one is executed, errorType and
* errorMessage will contain the result/status of the function/query.
*/
private void runOne(final AuthenticatedFunction function,
final QueryFunction<C> query) {
try {
if (function != null) {
function.run(this.auth.getAuthToken());
} else if (query != null) {
query.query(gdataServiceClient);
} else {
throw new IllegalArgumentException(
"invalid invocation of runOne; one of function/query " +
"must be non-null");
}
errorType = ERROR_NO_ERROR;
errorMessage = null;
} catch (AuthenticationException e) {
Log.e(MyTracksConstants.TAG, "AuthenticationException", e);
errorType = ERROR_AUTH;
errorMessage = e.getMessage();
} catch (HttpException e) {
- Log.e(MyTracksConstants.TAG, "HttpException", e);
+ Log.e(MyTracksConstants.TAG, "HttpException, code " + e.getStatusCode(), e);
errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("401")) {
errorType = ERROR_AUTH;
} else {
errorType = ERROR_CONNECTION;
}
} catch (FileNotFoundException e) {
Log.e(MyTracksConstants.TAG, "Exception", e);
errorType = ERROR_AUTH;
errorMessage = e.getMessage();
} catch (IOException e) {
Log.e(MyTracksConstants.TAG, "Exception", e);
errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("503")) {
errorType = ERROR_INTERNAL;
} else {
errorType = ERROR_CONNECTION;
}
} catch (ParseException e) {
Log.e(MyTracksConstants.TAG, "Exception", e);
errorType = ERROR_LOCAL;
errorMessage = e.getMessage();
} catch (ConflictDetectedException e) {
Log.e(MyTracksConstants.TAG, "Exception", e);
errorType = ERROR_CONFLICT;
errorMessage = e.getMessage();
}
}
/**
* Invalidates and refreshes the auth token. Blocks until the refresh has
* completed or until we deem the refresh as having timed out.
*
* @return true If the invalidate/refresh succeeds, false if it fails or
* times out.
*/
private boolean invalidateAndRefreshAuthToken() {
Log.d(MyTracksConstants.TAG, "Retrying due to auth failure");
// This FutureTask doesn't do anything -- it exists simply to be
// blocked upon using get().
FutureTask<?> whenFinishedFuture = new FutureTask<Object>(new Runnable() {
public void run() {}
}, null);
auth.invalidateAndRefresh(whenFinishedFuture);
try {
Log.d(MyTracksConstants.TAG, "waiting for invalidate");
whenFinishedFuture.get(AUTH_TOKEN_INVALIDATE_REFRESH_TIMEOUT,
TimeUnit.MILLISECONDS);
Log.d(MyTracksConstants.TAG, "invalidate finished");
return true;
} catch (InterruptedException e) {
Log.e(MyTracksConstants.TAG, "Failed to invalidate", e);
} catch (ExecutionException e) {
Log.e(MyTracksConstants.TAG, "Failed to invalidate", e);
} catch (TimeoutException e) {
Log.e(MyTracksConstants.TAG, "Invalidate didn't complete in time", e);
} finally {
whenFinishedFuture.cancel(false);
}
return false;
}
public int getErrorType() {
return errorType;
}
public String getErrorMessage() {
return errorMessage;
}
public void setAuthManager(AuthManager auth) {
this.auth = auth;
}
public AuthManager getAuthManager() {
return auth;
}
public void setRetryOnAuthFailure(boolean retry) {
retryOnAuthFailure = retry;
}
}
| true | true | private void runOne(final AuthenticatedFunction function,
final QueryFunction<C> query) {
try {
if (function != null) {
function.run(this.auth.getAuthToken());
} else if (query != null) {
query.query(gdataServiceClient);
} else {
throw new IllegalArgumentException(
"invalid invocation of runOne; one of function/query " +
"must be non-null");
}
errorType = ERROR_NO_ERROR;
errorMessage = null;
} catch (AuthenticationException e) {
Log.e(MyTracksConstants.TAG, "AuthenticationException", e);
errorType = ERROR_AUTH;
errorMessage = e.getMessage();
} catch (HttpException e) {
Log.e(MyTracksConstants.TAG, "HttpException", e);
errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("401")) {
errorType = ERROR_AUTH;
} else {
errorType = ERROR_CONNECTION;
}
} catch (FileNotFoundException e) {
Log.e(MyTracksConstants.TAG, "Exception", e);
errorType = ERROR_AUTH;
errorMessage = e.getMessage();
} catch (IOException e) {
Log.e(MyTracksConstants.TAG, "Exception", e);
errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("503")) {
errorType = ERROR_INTERNAL;
} else {
errorType = ERROR_CONNECTION;
}
} catch (ParseException e) {
Log.e(MyTracksConstants.TAG, "Exception", e);
errorType = ERROR_LOCAL;
errorMessage = e.getMessage();
} catch (ConflictDetectedException e) {
Log.e(MyTracksConstants.TAG, "Exception", e);
errorType = ERROR_CONFLICT;
errorMessage = e.getMessage();
}
}
| private void runOne(final AuthenticatedFunction function,
final QueryFunction<C> query) {
try {
if (function != null) {
function.run(this.auth.getAuthToken());
} else if (query != null) {
query.query(gdataServiceClient);
} else {
throw new IllegalArgumentException(
"invalid invocation of runOne; one of function/query " +
"must be non-null");
}
errorType = ERROR_NO_ERROR;
errorMessage = null;
} catch (AuthenticationException e) {
Log.e(MyTracksConstants.TAG, "AuthenticationException", e);
errorType = ERROR_AUTH;
errorMessage = e.getMessage();
} catch (HttpException e) {
Log.e(MyTracksConstants.TAG, "HttpException, code " + e.getStatusCode(), e);
errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("401")) {
errorType = ERROR_AUTH;
} else {
errorType = ERROR_CONNECTION;
}
} catch (FileNotFoundException e) {
Log.e(MyTracksConstants.TAG, "Exception", e);
errorType = ERROR_AUTH;
errorMessage = e.getMessage();
} catch (IOException e) {
Log.e(MyTracksConstants.TAG, "Exception", e);
errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("503")) {
errorType = ERROR_INTERNAL;
} else {
errorType = ERROR_CONNECTION;
}
} catch (ParseException e) {
Log.e(MyTracksConstants.TAG, "Exception", e);
errorType = ERROR_LOCAL;
errorMessage = e.getMessage();
} catch (ConflictDetectedException e) {
Log.e(MyTracksConstants.TAG, "Exception", e);
errorType = ERROR_CONFLICT;
errorMessage = e.getMessage();
}
}
|
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/ToggleBreakpointAdapter.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/ToggleBreakpointAdapter.java
index 86a3d1898..ba8765b40 100644
--- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/ToggleBreakpointAdapter.java
+++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/ToggleBreakpointAdapter.java
@@ -1,768 +1,771 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.debug.ui.actions;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.IBreakpointManager;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.model.IBreakpoint;
import org.eclipse.debug.ui.actions.IToggleBreakpointsTarget;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.ITypeNameRequestor;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.core.search.SearchPattern;
import org.eclipse.jdt.debug.core.IJavaBreakpoint;
import org.eclipse.jdt.debug.core.IJavaFieldVariable;
import org.eclipse.jdt.debug.core.IJavaLineBreakpoint;
import org.eclipse.jdt.debug.core.IJavaMethodBreakpoint;
import org.eclipse.jdt.debug.core.IJavaWatchpoint;
import org.eclipse.jdt.debug.core.JDIDebugModel;
import org.eclipse.jdt.internal.corext.util.TypeInfo;
import org.eclipse.jdt.internal.corext.util.TypeInfoRequestor;
import org.eclipse.jdt.internal.debug.ui.BreakpointUtils;
import org.eclipse.jdt.internal.debug.ui.ExceptionHandler;
import org.eclipse.jdt.internal.debug.ui.JDIDebugUIPlugin;
import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.texteditor.IEditorStatusLine;
import org.eclipse.ui.texteditor.ITextEditor;
/**
* Toggles a line breakpoint in a Java editor.
*
* @since 3.0
*/
public class ToggleBreakpointAdapter implements IToggleBreakpointsTarget {
protected void report(final String message, final IWorkbenchPart part) {
JDIDebugUIPlugin.getStandardDisplay().asyncExec(new Runnable() {
public void run() {
IEditorStatusLine statusLine= (IEditorStatusLine) part.getAdapter(IEditorStatusLine.class);
if (statusLine != null) {
if (message != null) {
statusLine.setMessage(true, message, null);
} else {
statusLine.setMessage(true, null, null);
}
}
if (message != null && JDIDebugUIPlugin.getActiveWorkbenchShell() != null) {
JDIDebugUIPlugin.getActiveWorkbenchShell().getDisplay().beep();
}
}
});
}
protected IType getType(ITextSelection selection) {
IMember member= ActionDelegateHelper.getDefault().getCurrentMember(selection);
IType type= null;
if (member instanceof IType) {
type = (IType)member;
} else if (member != null) {
type= member.getDeclaringType();
}
// bug 52385: we don't want local and anonymous types from compilation unit,
// we are getting 'not-always-correct' names for them.
try {
while (type != null && !type.isBinary() && type.isLocal()) {
type= type.getDeclaringType();
}
} catch (JavaModelException e) {
JDIDebugUIPlugin.log(e);
}
return type;
}
/* (non-Javadoc)
* @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#toggleLineBreakpoints(IWorkbenchPart, ISelection)
*/
public void toggleLineBreakpoints(IWorkbenchPart part, ISelection selection) throws CoreException {
toggleLineBreakpoints(part, selection, false);
}
public void toggleLineBreakpoints(IWorkbenchPart part, ISelection selection, boolean bestMatch) {
if (selection instanceof ITextSelection) {
report(null, part);
IEditorPart editorPart = (IEditorPart)part;
ITextSelection textSelection = (ITextSelection)selection;
IType type = getType(textSelection);
IEditorInput editorInput = editorPart.getEditorInput();
IDocument document= ((ITextEditor)editorPart).getDocumentProvider().getDocument(editorInput);
int lineNumber= textSelection.getStartLine() + 1;
int offset= textSelection.getOffset();
try {
if (type == null) {
IClassFile classFile= (IClassFile)editorInput.getAdapter(IClassFile.class);
if (classFile != null) {
type= classFile.getType();
// bug 34856 - if this is an inner type, ensure the breakpoint is not
// being added to the outer type
if (type.getDeclaringType() != null) {
ISourceRange sourceRange= type.getSourceRange();
int start= sourceRange.getOffset();
int end= start + sourceRange.getLength();
if (offset < start || offset > end) {
// not in the inner type
IStatusLineManager statusLine = editorPart.getEditorSite().getActionBars().getStatusLineManager();
statusLine .setErrorMessage(MessageFormat.format(ActionMessages.getString("ManageBreakpointRulerAction.Breakpoints_can_only_be_created_within_the_type_associated_with_the_editor__{0}._1"), new String[] { type.getTypeQualifiedName()})); //$NON-NLS-1$
Display.getCurrent().beep();
return;
}
}
}
}
String typeName= null;
IResource resource;
IJavaLineBreakpoint breakpoint= null;
if (type == null) {
if (editorInput instanceof IFileEditorInput) {
resource= ((IFileEditorInput)editorInput).getFile();
} else {
resource= ResourcesPlugin.getWorkspace().getRoot();
}
} else {
typeName= type.getFullyQualifiedName();
int index= typeName.indexOf('$');
if (index >= 0 ) {
typeName= typeName.substring(0, index);
}
resource= BreakpointUtils.getBreakpointResource(type);
IJavaLineBreakpoint existingBreakpoint= JDIDebugModel.lineBreakpointExists(resource, typeName, lineNumber);
if (existingBreakpoint != null) {
DebugPlugin.getDefault().getBreakpointManager().removeBreakpoint(existingBreakpoint, true);
return;
}
resource= BreakpointUtils.getBreakpointResource(type);
Map attributes = new HashMap(10);
try {
IRegion line= document.getLineInformation(lineNumber - 1);
int start= line.getOffset();
int end= start + line.getLength() - 1;
BreakpointUtils.addJavaBreakpointAttributesWithMemberDetails(attributes, type, start, end);
} catch (BadLocationException ble) {
JDIDebugUIPlugin.log(ble);
}
breakpoint= JDIDebugModel.createLineBreakpoint(resource, typeName, lineNumber, -1, -1, 0, true, attributes);
}
new BreakpointLocationVerifierJob(document, breakpoint, lineNumber, bestMatch, typeName, type, resource, editorPart).schedule();
} catch (CoreException ce) {
ExceptionHandler.handle(ce, ActionMessages.getString("ManageBreakpointActionDelegate.error.title1"), ActionMessages.getString("ManageBreakpointActionDelegate.error.message1")); //$NON-NLS-1$ //$NON-NLS-2$
return;
}
}
}
/*(non-Javadoc)
* @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#canToggleLineBreakpoints(IWorkbenchPart, ISelection)
*/
public boolean canToggleLineBreakpoints(IWorkbenchPart part, ISelection selection) {
return selection instanceof ITextSelection;
}
/* (non-Javadoc)
* @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#toggleMethodBreakpoints(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection)
*/
public void toggleMethodBreakpoints(IWorkbenchPart part, ISelection selection) throws CoreException {
report(null, part);
selection = translateToMembers(part, selection);
if (selection instanceof ITextSelection) {
ITextSelection textSelection = (ITextSelection) selection;
if (selection != null) {
CompilationUnit compilationUnit= parseCompilationUnit((ITextEditor)part);
if (compilationUnit != null) {
BreakpointMethodLocator locator= new BreakpointMethodLocator(textSelection.getOffset());
compilationUnit.accept(locator);
String methodName= locator.getMethodName();
if (methodName == null) {
report(ActionMessages.getString("ManageMethodBreakpointActionDelegate.CantAdd"), part); //$NON-NLS-1$
return;
}
String typeName= locator.getTypeName();
String methodSignature= locator.getMethodSignature();
if (methodSignature == null) {
report(ActionMessages.getString("ManageMethodBreakpointActionDelegate.methodNonAvailable"), part); //$NON-NLS-1$
return;
}
// check if this method breakpoint already exist. If yes, remove it.
IBreakpointManager breakpointManager= DebugPlugin.getDefault().getBreakpointManager();
IBreakpoint[] breakpoints= breakpointManager.getBreakpoints(JDIDebugModel.getPluginIdentifier());
for (int i= 0; i < breakpoints.length; i++) {
IBreakpoint breakpoint= breakpoints[i];
if (breakpoint instanceof IJavaMethodBreakpoint) {
IJavaMethodBreakpoint methodBreakpoint= (IJavaMethodBreakpoint)breakpoint;
if (typeName.equals(methodBreakpoint.getTypeName())
&& methodName.equals(methodBreakpoint.getMethodName())
&& methodSignature.equals(methodBreakpoint.getMethodSignature())) {
breakpointManager.removeBreakpoint(methodBreakpoint, true);
return;
}
}
}
// add the breakpoint
JDIDebugModel.createMethodBreakpoint(getResource((IEditorPart)part), typeName, methodName, methodSignature, true, false, false, -1, -1, -1, 0, true, new HashMap(10));
}
}
} else if (selection instanceof IStructuredSelection) {
IMethod[] members= getMethods((IStructuredSelection)selection);
if (members.length == 0) {
report(ActionMessages.getString("ToggleBreakpointAdapter.9"), part); //$NON-NLS-1$
return;
}
// add or remove the breakpoint
IBreakpointManager breakpointManager= DebugPlugin.getDefault().getBreakpointManager();
for (int i= 0, length= members.length; i < length; i++) {
IMethod method= members[i];
IJavaBreakpoint breakpoint= getBreakpoint(method);
if (breakpoint == null) {
// add breakpoint
int start = -1;
int end = -1;
ISourceRange range = method.getNameRange();
if (range != null) {
start = range.getOffset();
end = start + range.getLength();
}
Map attributes = new HashMap(10);
BreakpointUtils.addJavaBreakpointAttributes(attributes, method);
+ IType type= method.getDeclaringType();
+ String methodSignature= method.getSignature();
String methodName = method.getElementName();
if (method.isConstructor()) {
methodName = "<init>"; //$NON-NLS-1$
+ if (type.isEnum()) {
+ methodSignature= "(Ljava.lang.String;I" + methodSignature.substring(1); //$NON-NLS-1$
+ }
}
- IType type= method.getDeclaringType();
- String methodSignature= method.getSignature();
if (!type.isBinary()) {
//resolve the type names
methodSignature= resolveMethodSignature(type, methodSignature);
if (methodSignature == null) {
IStatus status = new Status(IStatus.ERROR, JDIDebugUIPlugin.getUniqueIdentifier(), IStatus.ERROR, "Source method signature could not be resolved", null); //$NON-NLS-1$
throw new CoreException(status);
}
}
JDIDebugModel.createMethodBreakpoint(BreakpointUtils.getBreakpointResource(method), type.getFullyQualifiedName(), methodName, methodSignature, true, false, false, -1, start, end, 0, true, attributes);
} else {
// remove breakpoint
breakpointManager.removeBreakpoint(breakpoint, true);
}
}
}
}
/* (non-Javadoc)
* @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#canToggleMethodBreakpoints(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection)
*/
public boolean canToggleMethodBreakpoints(IWorkbenchPart part, ISelection selection) {
if (selection instanceof IStructuredSelection) {
IStructuredSelection ss = (IStructuredSelection) selection;
return getMethods(ss).length > 0;
}
return selection instanceof ITextSelection;
}
protected IMethod[] getMethods(IStructuredSelection selection) {
if (selection.isEmpty()) {
return new IMethod[0];
}
List methods = new ArrayList(selection.size());
Iterator iterator = selection.iterator();
while (iterator.hasNext()) {
Object thing = iterator.next();
try {
if (thing instanceof IMethod && !Flags.isAbstract(((IMethod)thing).getFlags())) {
methods.add(thing);
}
} catch (JavaModelException e) {
}
}
return (IMethod[]) methods.toArray(new IMethod[methods.size()]);
}
protected IField[] getFields(IStructuredSelection selection) {
if (selection.isEmpty()) {
return new IField[0];
}
List fields = new ArrayList(selection.size());
Iterator iterator = selection.iterator();
while (iterator.hasNext()) {
Object thing = iterator.next();
if (thing instanceof IField) {
fields.add(thing);
} else if (thing instanceof IJavaFieldVariable) {
IField field= getField((IJavaFieldVariable) thing);
if (field != null) {
fields.add(field);
}
}
}
return (IField[]) fields.toArray(new IField[fields.size()]);
}
private boolean isFields(IStructuredSelection selection) {
if (!selection.isEmpty()) {
Iterator iterator = selection.iterator();
while (iterator.hasNext()) {
Object thing = iterator.next();
if (!(thing instanceof IField || thing instanceof IJavaFieldVariable)) {
return false;
}
}
return true;
}
return false;
}
/* (non-Javadoc)
* @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#toggleWatchpoints(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection)
*/
public void toggleWatchpoints(IWorkbenchPart part, ISelection selection) throws CoreException {
report(null, part);
selection = translateToMembers(part, selection);
if (selection instanceof ITextSelection) {
ITextSelection textSelection= (ITextSelection) selection;
CompilationUnit compilationUnit= parseCompilationUnit((ITextEditor)part);
if (compilationUnit != null) {
BreakpointFieldLocator locator= new BreakpointFieldLocator(textSelection.getOffset());
compilationUnit.accept(locator);
String fieldName= locator.getFieldName();
if (fieldName == null) {
report(ActionMessages.getString("ManageWatchpointActionDelegate.CantAdd"), part); //$NON-NLS-1$
return;
}
String typeName= locator.getTypeName();
// check if the watchpoint already exists. If yes, remove it
IBreakpointManager breakpointManager= DebugPlugin.getDefault().getBreakpointManager();
IBreakpoint[] breakpoints= breakpointManager.getBreakpoints(JDIDebugModel.getPluginIdentifier());
for (int i= 0; i < breakpoints.length; i++) {
IBreakpoint breakpoint= breakpoints[i];
if (breakpoint instanceof IJavaWatchpoint) {
IJavaWatchpoint watchpoint= (IJavaWatchpoint)breakpoint;
if (typeName.equals(watchpoint.getTypeName()) && fieldName.equals(watchpoint.getFieldName())) {
breakpointManager.removeBreakpoint(watchpoint, true);
return;
}
}
}
// add the watchpoint
JDIDebugModel.createWatchpoint(getResource((IEditorPart)part), typeName, fieldName, -1, -1, -1, 0, true, new HashMap(10));
}
} else if (selection instanceof IStructuredSelection) {
IField[] members = getFields((IStructuredSelection)selection);
if (members.length == 0) {
report(ActionMessages.getString("ToggleBreakpointAdapter.10"), part); //$NON-NLS-1$
return;
}
// add or remove watchpoint
IBreakpointManager breakpointManager= DebugPlugin.getDefault().getBreakpointManager();
for (int i= 0, length= members.length; i < length; i++) {
IField element= members[i];
IJavaBreakpoint breakpoint= getBreakpoint(element);
if (breakpoint == null) {
IType type = element.getDeclaringType();
int start = -1;
int end = -1;
ISourceRange range = element.getNameRange();
if (range != null) {
start = range.getOffset();
end = start + range.getLength();
}
Map attributes = new HashMap(10);
BreakpointUtils.addJavaBreakpointAttributes(attributes, element);
JDIDebugModel.createWatchpoint(BreakpointUtils.getBreakpointResource(type), type.getFullyQualifiedName(), element.getElementName(), -1, start, end, 0, true, attributes);
} else {
// remove breakpoint
breakpointManager.removeBreakpoint(breakpoint, true);
}
}
}
}
public static String resolveMethodSignature(IType type, String methodSignature) throws JavaModelException {
String[] parameterTypes= Signature.getParameterTypes(methodSignature);
int length= length= parameterTypes.length;
String[] resolvedParameterTypes= new String[length];
for (int i = 0; i < length; i++) {
resolvedParameterTypes[i]= resolveType(type, parameterTypes[i]);
if (resolvedParameterTypes[i] == null) {
return null;
}
}
String resolvedReturnType= resolveType(type, Signature.getReturnType(methodSignature));
if (resolvedReturnType == null) {
return null;
}
return Signature.createMethodSignature(resolvedParameterTypes, resolvedReturnType);
}
private static String resolveType(IType type, String typeSignature) throws JavaModelException {
int count= Signature.getArrayCount(typeSignature);
String elementTypeSignature= Signature.getElementType(typeSignature);
if (elementTypeSignature.length() == 1) {
// no need to resolve primitive types
return typeSignature;
}
String elementTypeName= Signature.toString(elementTypeSignature);
String[][] resolvedElementTypeNames= type.resolveType(elementTypeName);
if (resolvedElementTypeNames == null || resolvedElementTypeNames.length != 1) {
// the type name cannot be resolved
return null;
}
String resolvedElementTypeName= Signature.toQualifiedName(resolvedElementTypeNames[0]);
String resolvedElementTypeSignature= Signature.createTypeSignature(resolvedElementTypeName, true).replace('.', '/');
return Signature.createArraySignature(resolvedElementTypeSignature, count);
}
protected static IResource getResource(IEditorPart editor) {
IResource resource;
IEditorInput editorInput = editor.getEditorInput();
if (editorInput instanceof IFileEditorInput) {
resource= ((IFileEditorInput)editorInput).getFile();
} else {
resource= ResourcesPlugin.getWorkspace().getRoot();
}
return resource;
}
/**
* Returns a handle to the specified method or <code>null</code> if none.
*
* @param editorPart the editor containing the method
* @param typeName
* @param methodName
* @param signature
* @return handle or <code>null</code>
*/
protected IMethod getMethodHandle(IEditorPart editorPart, String typeName, String methodName, String signature) throws CoreException {
IJavaElement element = (IJavaElement) editorPart.getEditorInput().getAdapter(IJavaElement.class);
IType type = null;
if (element instanceof ICompilationUnit) {
IType[] types = ((ICompilationUnit)element).getAllTypes();
for (int i = 0; i < types.length; i++) {
if (types[i].getFullyQualifiedName().equals(typeName)) {
type = types[i];
break;
}
}
} else if (element instanceof IClassFile) {
type = ((IClassFile)element).getType();
}
if (type != null) {
String[] sigs = Signature.getParameterTypes(signature);
return type.getMethod(methodName, sigs);
}
return null;
}
protected IJavaBreakpoint getBreakpoint(IMember element) {
IBreakpointManager breakpointManager= DebugPlugin.getDefault().getBreakpointManager();
IBreakpoint[] breakpoints= breakpointManager.getBreakpoints(JDIDebugModel.getPluginIdentifier());
if (element instanceof IMethod) {
IMethod method= (IMethod)element;
for (int i= 0; i < breakpoints.length; i++) {
IBreakpoint breakpoint= breakpoints[i];
if (breakpoint instanceof IJavaMethodBreakpoint) {
IJavaMethodBreakpoint methodBreakpoint= (IJavaMethodBreakpoint)breakpoint;
IMember container = null;
try {
container= BreakpointUtils.getMember(methodBreakpoint);
} catch (CoreException e) {
JDIDebugUIPlugin.log(e);
return null;
}
if (container == null) {
try {
if (method.getDeclaringType().getFullyQualifiedName().equals(methodBreakpoint.getTypeName())
&& method.getElementName().equals(methodBreakpoint.getMethodName())
&& method.getSignature().equals(methodBreakpoint.getMethodSignature())) {
return methodBreakpoint;
}
} catch (CoreException e) {
JDIDebugUIPlugin.log(e);
}
} else {
if (container instanceof IMethod) {
if (method.getDeclaringType().getFullyQualifiedName().equals(container.getDeclaringType().getFullyQualifiedName())) {
if (method.isSimilar((IMethod)container)) {
return methodBreakpoint;
}
}
}
}
}
}
} else if (element instanceof IField) {
for (int i= 0; i < breakpoints.length; i++) {
IBreakpoint breakpoint= breakpoints[i];
if (breakpoint instanceof IJavaWatchpoint) {
try {
if (equalFields(element, (IJavaWatchpoint)breakpoint))
return (IJavaBreakpoint)breakpoint;
} catch (CoreException e) {
JDIDebugUIPlugin.log(e);
}
}
}
}
return null;
}
/**
* Compare two fields. The default <code>equals()</code>
* method for <code>IField</code> doesn't give the comparison desired.
*/
private boolean equalFields(IMember breakpointField, IJavaWatchpoint watchpoint) throws CoreException {
return (breakpointField.getElementName().equals(watchpoint.getFieldName()) &&
breakpointField.getDeclaringType().getFullyQualifiedName().equals(watchpoint.getTypeName()));
}
protected CompilationUnit parseCompilationUnit(ITextEditor editor) {
IEditorInput editorInput = editor.getEditorInput();
IDocument document= editor.getDocumentProvider().getDocument(editorInput);
ASTParser parser = ASTParser.newParser(AST.JLS2);
parser.setSource(document.get().toCharArray());
return (CompilationUnit) parser.createAST(null);
}
/* (non-Javadoc)
* @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#canToggleWatchpoints(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection)
*/
public boolean canToggleWatchpoints(IWorkbenchPart part, ISelection selection) {
if (selection instanceof IStructuredSelection) {
IStructuredSelection ss = (IStructuredSelection) selection;
return isFields(ss);
}
return selection instanceof ITextSelection;
}
/**
* Returns a selection of the member in the given text selection,
* or the original selection if none.
*
* @param part
* @param selection
* @return a structured selection of the member in the given text selection,
* or the original selection if none
* @exception CoreException if an exceptoin occurrs
*/
protected ISelection translateToMembers(IWorkbenchPart part, ISelection selection) throws CoreException {
if (selection instanceof ITextSelection && part instanceof IEditorPart) {
ITextSelection textSelection = (ITextSelection)selection;
IEditorPart editorPart = (IEditorPart) part;
IEditorInput editorInput = editorPart.getEditorInput();
IMember m= null;
IClassFile classFile= (IClassFile)editorInput.getAdapter(IClassFile.class);
if (classFile != null) {
IJavaElement e= classFile.getElementAt(textSelection.getOffset());
if (e instanceof IMember) {
m= (IMember)e;
}
} else {
IWorkingCopyManager manager= JavaUI.getWorkingCopyManager();
ICompilationUnit unit= manager.getWorkingCopy(editorInput);
if (unit != null) {
synchronized (unit) {
unit.reconcile(ICompilationUnit.NO_AST /*don't create ast*/, false/*don't force problem detection*/, null/*use primary owner*/, null/*no progress monitor*/);
}
IJavaElement e = unit.getElementAt(textSelection.getOffset());
if (e instanceof IMember) {
m= (IMember)e;
}
}
}
if (m != null) {
return new StructuredSelection(m);
}
}
return selection;
}
/**
* Returns a list of matching types (IType - Java model) that correspond to
* the given type name in the context of the given launch.
*/
protected static List searchForTypes(String typeName, ILaunch launch) {
List types= new ArrayList();
if (launch == null) {
return types;
}
ILaunchConfiguration configuration= launch.getLaunchConfiguration();
IJavaProject[] javaProjects = null;
IWorkspace workspace= ResourcesPlugin.getWorkspace();
if (configuration != null) {
// Launch configuration support
try {
String projectName= configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""); //$NON-NLS-1$
if (projectName.length() != 0) {
javaProjects= new IJavaProject[] {JavaCore.create(workspace.getRoot().getProject(projectName))};
} else {
IProject[] projects= ResourcesPlugin.getWorkspace().getRoot().getProjects();
IProject project;
List projectList= new ArrayList();
for (int i= 0, numProjects= projects.length; i < numProjects; i++) {
project= projects[i];
if (project.isAccessible() && project.hasNature(JavaCore.NATURE_ID)) {
projectList.add(JavaCore.create(project));
}
}
javaProjects= new IJavaProject[projectList.size()];
projectList.toArray(javaProjects);
}
} catch (CoreException e) {
JDIDebugUIPlugin.log(e);
}
}
if (javaProjects == null) {
return types;
}
SearchEngine engine= new SearchEngine();
IJavaSearchScope scope= SearchEngine.createJavaSearchScope(javaProjects, true);
ArrayList typeRefsFound= new ArrayList(3);
ITypeNameRequestor requestor= new TypeInfoRequestor(typeRefsFound);
try {
engine.searchAllTypeNames(
getPackage(typeName),
getTypeName(typeName),
SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE,
IJavaSearchConstants.CLASS,
scope,
requestor,
IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
null);
} catch (JavaModelException x) {
JDIDebugUIPlugin.log(x);
return types;
}
Iterator iter= typeRefsFound.iterator();
TypeInfo typeInfo= null;
while (iter.hasNext()) {
typeInfo= (TypeInfo)iter.next();
try {
types.add(typeInfo.resolveType(scope));
} catch (JavaModelException jme) {
JDIDebugUIPlugin.log(jme);
}
}
return types;
}
/**
* Returns the package name of the given fully qualified type name.
* The package name is assumed to be the dot-separated prefix of the
* type name.
*/
private static char[] getPackage(String fullyQualifiedName) {
int index= fullyQualifiedName.lastIndexOf('.');
if (index == -1) {
return new char[0];
}
return fullyQualifiedName.substring(0, index).toCharArray();
}
/**
* Returns a simple type name from the given fully qualified type name.
* The type name is assumed to be the last contiguous segment of the
* fullyQualifiedName not containing a '.' or '$'
*/
private static char[] getTypeName(String fullyQualifiedName) {
int index= fullyQualifiedName.lastIndexOf('.');
String typeName = fullyQualifiedName;
if (index >= 0) {
typeName= fullyQualifiedName.substring(index + 1);
}
index = typeName.lastIndexOf('$');
if (index >= 0) {
typeName = typeName.substring(index + 1);
}
return typeName.toCharArray();
}
/**
* Return the associated IField (Java model) for the given
* IJavaFieldVariable (JDI model)
*/
private IField getField(IJavaFieldVariable variable) {
String varName= null;
try {
varName= variable.getName();
} catch (DebugException x) {
JDIDebugUIPlugin.log(x);
return null;
}
IField field;
String declaringType= null;
try {
declaringType= variable.getDeclaringType().getName();
} catch (DebugException x) {
JDIDebugUIPlugin.log(x);
return null;
}
List types= searchForTypes(declaringType, variable.getLaunch());
Iterator iter= types.iterator();
while (iter.hasNext()) {
IType type= (IType)iter.next();
field= type.getField(varName);
if (field.exists()) {
return field;
}
}
return null;
}
}
| false | true | public void toggleMethodBreakpoints(IWorkbenchPart part, ISelection selection) throws CoreException {
report(null, part);
selection = translateToMembers(part, selection);
if (selection instanceof ITextSelection) {
ITextSelection textSelection = (ITextSelection) selection;
if (selection != null) {
CompilationUnit compilationUnit= parseCompilationUnit((ITextEditor)part);
if (compilationUnit != null) {
BreakpointMethodLocator locator= new BreakpointMethodLocator(textSelection.getOffset());
compilationUnit.accept(locator);
String methodName= locator.getMethodName();
if (methodName == null) {
report(ActionMessages.getString("ManageMethodBreakpointActionDelegate.CantAdd"), part); //$NON-NLS-1$
return;
}
String typeName= locator.getTypeName();
String methodSignature= locator.getMethodSignature();
if (methodSignature == null) {
report(ActionMessages.getString("ManageMethodBreakpointActionDelegate.methodNonAvailable"), part); //$NON-NLS-1$
return;
}
// check if this method breakpoint already exist. If yes, remove it.
IBreakpointManager breakpointManager= DebugPlugin.getDefault().getBreakpointManager();
IBreakpoint[] breakpoints= breakpointManager.getBreakpoints(JDIDebugModel.getPluginIdentifier());
for (int i= 0; i < breakpoints.length; i++) {
IBreakpoint breakpoint= breakpoints[i];
if (breakpoint instanceof IJavaMethodBreakpoint) {
IJavaMethodBreakpoint methodBreakpoint= (IJavaMethodBreakpoint)breakpoint;
if (typeName.equals(methodBreakpoint.getTypeName())
&& methodName.equals(methodBreakpoint.getMethodName())
&& methodSignature.equals(methodBreakpoint.getMethodSignature())) {
breakpointManager.removeBreakpoint(methodBreakpoint, true);
return;
}
}
}
// add the breakpoint
JDIDebugModel.createMethodBreakpoint(getResource((IEditorPart)part), typeName, methodName, methodSignature, true, false, false, -1, -1, -1, 0, true, new HashMap(10));
}
}
} else if (selection instanceof IStructuredSelection) {
IMethod[] members= getMethods((IStructuredSelection)selection);
if (members.length == 0) {
report(ActionMessages.getString("ToggleBreakpointAdapter.9"), part); //$NON-NLS-1$
return;
}
// add or remove the breakpoint
IBreakpointManager breakpointManager= DebugPlugin.getDefault().getBreakpointManager();
for (int i= 0, length= members.length; i < length; i++) {
IMethod method= members[i];
IJavaBreakpoint breakpoint= getBreakpoint(method);
if (breakpoint == null) {
// add breakpoint
int start = -1;
int end = -1;
ISourceRange range = method.getNameRange();
if (range != null) {
start = range.getOffset();
end = start + range.getLength();
}
Map attributes = new HashMap(10);
BreakpointUtils.addJavaBreakpointAttributes(attributes, method);
String methodName = method.getElementName();
if (method.isConstructor()) {
methodName = "<init>"; //$NON-NLS-1$
}
IType type= method.getDeclaringType();
String methodSignature= method.getSignature();
if (!type.isBinary()) {
//resolve the type names
methodSignature= resolveMethodSignature(type, methodSignature);
if (methodSignature == null) {
IStatus status = new Status(IStatus.ERROR, JDIDebugUIPlugin.getUniqueIdentifier(), IStatus.ERROR, "Source method signature could not be resolved", null); //$NON-NLS-1$
throw new CoreException(status);
}
}
JDIDebugModel.createMethodBreakpoint(BreakpointUtils.getBreakpointResource(method), type.getFullyQualifiedName(), methodName, methodSignature, true, false, false, -1, start, end, 0, true, attributes);
} else {
// remove breakpoint
breakpointManager.removeBreakpoint(breakpoint, true);
}
}
}
}
| public void toggleMethodBreakpoints(IWorkbenchPart part, ISelection selection) throws CoreException {
report(null, part);
selection = translateToMembers(part, selection);
if (selection instanceof ITextSelection) {
ITextSelection textSelection = (ITextSelection) selection;
if (selection != null) {
CompilationUnit compilationUnit= parseCompilationUnit((ITextEditor)part);
if (compilationUnit != null) {
BreakpointMethodLocator locator= new BreakpointMethodLocator(textSelection.getOffset());
compilationUnit.accept(locator);
String methodName= locator.getMethodName();
if (methodName == null) {
report(ActionMessages.getString("ManageMethodBreakpointActionDelegate.CantAdd"), part); //$NON-NLS-1$
return;
}
String typeName= locator.getTypeName();
String methodSignature= locator.getMethodSignature();
if (methodSignature == null) {
report(ActionMessages.getString("ManageMethodBreakpointActionDelegate.methodNonAvailable"), part); //$NON-NLS-1$
return;
}
// check if this method breakpoint already exist. If yes, remove it.
IBreakpointManager breakpointManager= DebugPlugin.getDefault().getBreakpointManager();
IBreakpoint[] breakpoints= breakpointManager.getBreakpoints(JDIDebugModel.getPluginIdentifier());
for (int i= 0; i < breakpoints.length; i++) {
IBreakpoint breakpoint= breakpoints[i];
if (breakpoint instanceof IJavaMethodBreakpoint) {
IJavaMethodBreakpoint methodBreakpoint= (IJavaMethodBreakpoint)breakpoint;
if (typeName.equals(methodBreakpoint.getTypeName())
&& methodName.equals(methodBreakpoint.getMethodName())
&& methodSignature.equals(methodBreakpoint.getMethodSignature())) {
breakpointManager.removeBreakpoint(methodBreakpoint, true);
return;
}
}
}
// add the breakpoint
JDIDebugModel.createMethodBreakpoint(getResource((IEditorPart)part), typeName, methodName, methodSignature, true, false, false, -1, -1, -1, 0, true, new HashMap(10));
}
}
} else if (selection instanceof IStructuredSelection) {
IMethod[] members= getMethods((IStructuredSelection)selection);
if (members.length == 0) {
report(ActionMessages.getString("ToggleBreakpointAdapter.9"), part); //$NON-NLS-1$
return;
}
// add or remove the breakpoint
IBreakpointManager breakpointManager= DebugPlugin.getDefault().getBreakpointManager();
for (int i= 0, length= members.length; i < length; i++) {
IMethod method= members[i];
IJavaBreakpoint breakpoint= getBreakpoint(method);
if (breakpoint == null) {
// add breakpoint
int start = -1;
int end = -1;
ISourceRange range = method.getNameRange();
if (range != null) {
start = range.getOffset();
end = start + range.getLength();
}
Map attributes = new HashMap(10);
BreakpointUtils.addJavaBreakpointAttributes(attributes, method);
IType type= method.getDeclaringType();
String methodSignature= method.getSignature();
String methodName = method.getElementName();
if (method.isConstructor()) {
methodName = "<init>"; //$NON-NLS-1$
if (type.isEnum()) {
methodSignature= "(Ljava.lang.String;I" + methodSignature.substring(1); //$NON-NLS-1$
}
}
if (!type.isBinary()) {
//resolve the type names
methodSignature= resolveMethodSignature(type, methodSignature);
if (methodSignature == null) {
IStatus status = new Status(IStatus.ERROR, JDIDebugUIPlugin.getUniqueIdentifier(), IStatus.ERROR, "Source method signature could not be resolved", null); //$NON-NLS-1$
throw new CoreException(status);
}
}
JDIDebugModel.createMethodBreakpoint(BreakpointUtils.getBreakpointResource(method), type.getFullyQualifiedName(), methodName, methodSignature, true, false, false, -1, start, end, 0, true, attributes);
} else {
// remove breakpoint
breakpointManager.removeBreakpoint(breakpoint, true);
}
}
}
}
|
diff --git a/hazelcast-client/src/main/java/com/hazelcast/client/proxy/ClientMapProxy.java b/hazelcast-client/src/main/java/com/hazelcast/client/proxy/ClientMapProxy.java
index ec449b8044..39f7144dc7 100644
--- a/hazelcast-client/src/main/java/com/hazelcast/client/proxy/ClientMapProxy.java
+++ b/hazelcast-client/src/main/java/com/hazelcast/client/proxy/ClientMapProxy.java
@@ -1,572 +1,571 @@
/*
* Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.client.proxy;
import com.hazelcast.client.nearcache.ClientNearCache;
import com.hazelcast.client.spi.ClientProxy;
import com.hazelcast.client.spi.EventHandler;
import com.hazelcast.config.NearCacheConfig;
import com.hazelcast.core.*;
import com.hazelcast.map.*;
import com.hazelcast.map.client.*;
import com.hazelcast.monitor.LocalMapStats;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.query.Predicate;
import com.hazelcast.spi.impl.PortableEntryEvent;
import com.hazelcast.util.ExceptionUtil;
import com.hazelcast.util.IterationType;
import com.hazelcast.util.QueryResultSet;
import com.hazelcast.util.ThreadUtil;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author mdogan 5/17/13
*/
public final class ClientMapProxy<K, V> extends ClientProxy implements IMap<K, V> {
private final String name;
private ClientNearCache nearCache;
private String nearCacheListenerId;
private AtomicBoolean nearCacheInitialized = new AtomicBoolean();
public ClientMapProxy(String serviceName, String name) {
super(serviceName, name);
this.name = name;
}
public boolean containsKey(Object key) {
Data keyData = toData(key);
MapContainsKeyRequest request = new MapContainsKeyRequest(name, keyData);
Boolean result = invoke(request, keyData);
return result;
}
public boolean containsValue(Object value) {
Data valueData = toData(value);
MapContainsValueRequest request = new MapContainsValueRequest(name, valueData);
Boolean result = invoke(request);
return result;
}
public V get(Object key) {
initNearCache();
final Data keyData = toData(key);
if (nearCache != null){
Object cached = nearCache.get(keyData);
if (cached != null){
return (V) cached;
}
}
MapGetRequest request = new MapGetRequest(name, keyData);
final V result = invoke(request, keyData);
if (nearCache != null){
nearCache.put(keyData, result);
}
return result;
}
public V put(K key, V value) {
return put(key, value, -1, null);
}
public V remove(Object key) {
final Data keyData = toData(key);
MapRemoveRequest request = new MapRemoveRequest(name, keyData, ThreadUtil.getThreadId());
return invoke(request, keyData);
}
public boolean remove(Object key, Object value) {
final Data keyData = toData(key);
final Data valueData = toData(value);
MapRemoveIfSameRequest request = new MapRemoveIfSameRequest(name, keyData, valueData, ThreadUtil.getThreadId());
Boolean result = invoke(request, keyData);
return result;
}
public void delete(Object key) {
final Data keyData = toData(key);
MapDeleteRequest request = new MapDeleteRequest(name, keyData, ThreadUtil.getThreadId());
invoke(request, keyData);
}
public void flush() {
MapFlushRequest request = new MapFlushRequest(name);
invoke(request);
}
public Future<V> getAsync(final K key) {
Future<V> f = getContext().getExecutionService().submit(new Callable<V>() {
public V call() throws Exception {
return get(key);
}
});
return f;
}
public Future<V> putAsync(final K key, final V value) {
Future<V> f = getContext().getExecutionService().submit(new Callable<V>() {
public V call() throws Exception {
return put(key, value);
}
});
return f;
}
public Future<V> removeAsync(final K key) {
Future<V> f = getContext().getExecutionService().submit(new Callable<V>() {
public V call() throws Exception {
return remove(key);
}
});
return f;
}
public boolean tryRemove(K key, long timeout, TimeUnit timeunit) {
final Data keyData = toData(key);
MapTryRemoveRequest request = new MapTryRemoveRequest(name, keyData, ThreadUtil.getThreadId(), timeunit.toMillis(timeout));
Boolean result = invoke(request, keyData);
return result;
}
public boolean tryPut(K key, V value, long timeout, TimeUnit timeunit) {
final Data keyData = toData(key);
final Data valueData = toData(value);
MapTryPutRequest request = new MapTryPutRequest(name, keyData, valueData, ThreadUtil.getThreadId(), timeunit.toMillis(timeout));
Boolean result = invoke(request, keyData);
return result;
}
public V put(K key, V value, long ttl, TimeUnit timeunit) {
final Data keyData = toData(key);
final Data valueData = toData(value);
MapPutRequest request = new MapPutRequest(name, keyData, valueData, ThreadUtil.getThreadId(), getTimeInMillis(ttl, timeunit));
return invoke(request, keyData);
}
public void putTransient(K key, V value, long ttl, TimeUnit timeunit) {
final Data keyData = toData(key);
final Data valueData = toData(value);
MapPutTransientRequest request = new MapPutTransientRequest(name, keyData, valueData, ThreadUtil.getThreadId(), getTimeInMillis(ttl, timeunit));
invoke(request);
}
public V putIfAbsent(K key, V value) {
return putIfAbsent(key, value, -1, null);
}
public V putIfAbsent(K key, V value, long ttl, TimeUnit timeunit) {
final Data keyData = toData(key);
final Data valueData = toData(value);
MapPutIfAbsentRequest request = new MapPutIfAbsentRequest(name, keyData, valueData, ThreadUtil.getThreadId(), getTimeInMillis(ttl, timeunit));
return invoke(request, keyData);
}
public boolean replace(K key, V oldValue, V newValue) {
final Data keyData = toData(key);
final Data oldValueData = toData(oldValue);
final Data newValueData = toData(newValue);
MapReplaceIfSameRequest request = new MapReplaceIfSameRequest(name, keyData, oldValueData, newValueData, ThreadUtil.getThreadId());
Boolean result = invoke(request, keyData);
return result;
}
public V replace(K key, V value) {
final Data keyData = toData(key);
final Data valueData = toData(value);
MapReplaceRequest request = new MapReplaceRequest(name, keyData, valueData, ThreadUtil.getThreadId());
return invoke(request, keyData);
}
public void set(K key, V value, long ttl, TimeUnit timeunit) {
final Data keyData = toData(key);
final Data valueData = toData(value);
MapSetRequest request = new MapSetRequest(name, keyData, valueData, ThreadUtil.getThreadId(), getTimeInMillis(ttl, timeunit));
invoke(request, keyData);
}
public void lock(K key) {
final Data keyData = toData(key);
MapLockRequest request = new MapLockRequest(name, keyData, ThreadUtil.getThreadId());
invoke(request, keyData);
}
public void lock(K key, long leaseTime, TimeUnit timeUnit) {
final Data keyData = toData(key);
MapLockRequest request = new MapLockRequest(name, keyData, ThreadUtil.getThreadId(), getTimeInMillis(leaseTime, timeUnit), -1);
invoke(request, keyData);
}
public boolean isLocked(K key) {
final Data keyData = toData(key);
MapIsLockedRequest request = new MapIsLockedRequest(name, keyData);
Boolean result = invoke(request, keyData);
return result;
}
public boolean tryLock(K key) {
try {
return tryLock(key, 0, null);
} catch (InterruptedException e) {
return false;
}
}
public boolean tryLock(K key, long time, TimeUnit timeunit) throws InterruptedException {
final Data keyData = toData(key);
MapLockRequest request = new MapLockRequest(name, keyData, ThreadUtil.getThreadId(), Long.MAX_VALUE, getTimeInMillis(time, timeunit));
Boolean result = invoke(request, keyData);
return result;
}
public void unlock(K key) {
final Data keyData = toData(key);
MapUnlockRequest request = new MapUnlockRequest(name, keyData, ThreadUtil.getThreadId(), false);
invoke(request, keyData);
}
public void forceUnlock(K key) {
final Data keyData = toData(key);
MapUnlockRequest request = new MapUnlockRequest(name, keyData, ThreadUtil.getThreadId(), true);
invoke(request, keyData);
}
public String addLocalEntryListener(EntryListener<K, V> listener) {
throw new UnsupportedOperationException("Locality is ambiguous for client!!!");
}
public String addInterceptor(MapInterceptor interceptor) {
MapAddInterceptorRequest request = new MapAddInterceptorRequest(name, interceptor);
return invoke(request);
}
public void removeInterceptor(String id) {
MapRemoveInterceptorRequest request = new MapRemoveInterceptorRequest(name, id);
invoke(request);
}
public String addEntryListener(EntryListener<K, V> listener, boolean includeValue) {
MapAddEntryListenerRequest request = new MapAddEntryListenerRequest(name, includeValue);
EventHandler<PortableEntryEvent> handler = createHandler(listener, includeValue);
return listen(request, handler);
}
public boolean removeEntryListener(String id) {
return stopListening(id);
}
public String addEntryListener(EntryListener<K, V> listener, K key, boolean includeValue) {
final Data keyData = toData(key);
MapAddEntryListenerRequest request = new MapAddEntryListenerRequest(name, keyData, includeValue);
EventHandler<PortableEntryEvent> handler = createHandler(listener, includeValue);
return listen(request, keyData, handler);
}
public String addEntryListener(EntryListener<K, V> listener, Predicate<K, V> predicate, K key, boolean includeValue) {
final Data keyData = toData(key);
MapAddEntryListenerRequest request = new MapAddEntryListenerRequest(name, keyData, includeValue, predicate);
EventHandler<PortableEntryEvent> handler = createHandler(listener, includeValue);
return listen(request, keyData, handler);
}
public EntryView<K, V> getEntryView(K key) {
final Data keyData = toData(key);
MapGetEntryViewRequest request = new MapGetEntryViewRequest(name, keyData);
SimpleEntryView entryView = invoke(request, keyData);
if (entryView == null) {
return null;
}
final Data value = (Data) entryView.getValue();
entryView.setKey(key);
entryView.setValue(toObject(value));
return entryView;
}
public boolean evict(K key) {
final Data keyData = toData(key);
MapEvictRequest request = new MapEvictRequest(name, keyData, ThreadUtil.getThreadId());
Boolean result = invoke(request);
return result;
}
public Set<K> keySet() {
MapKeySetRequest request = new MapKeySetRequest(name);
MapKeySet mapKeySet = invoke(request);
Set<Data> keySetData = mapKeySet.getKeySet();
Set<K> keySet = new HashSet<K>(keySetData.size());
for (Data data : keySetData) {
final K key = toObject(data);
keySet.add(key);
}
return keySet;
}
public Map<K, V> getAll(Set<K> keys) {
Set keySet = new HashSet(keys.size());
for (Object key : keys) {
keySet.add(toData(key));
}
MapGetAllRequest request = new MapGetAllRequest(name, keySet);
MapEntrySet mapEntrySet = invoke(request);
Map<K, V> result = new HashMap<K, V>();
Set<Entry<Data, Data>> entrySet = mapEntrySet.getEntrySet();
for (Entry<Data, Data> dataEntry : entrySet) {
result.put((K) toObject(dataEntry.getKey()), (V) toObject(dataEntry.getValue()));
}
return result;
}
public Collection<V> values() {
MapValuesRequest request = new MapValuesRequest(name);
MapValueCollection mapValueCollection = invoke(request);
Collection<Data> collectionData = mapValueCollection.getValues();
Collection<V> collection = new ArrayList<V>(collectionData.size());
for (Data data : collectionData) {
final V value = toObject(data);
collection.add(value);
}
return collection;
}
public Set<Entry<K, V>> entrySet() {
MapEntrySetRequest request = new MapEntrySetRequest(name);
MapEntrySet result = invoke(request);
Set<Entry<K, V>> entrySet = new HashSet<Entry<K, V>>();
Set<Entry<Data, Data>> entries = result.getEntrySet();
for (Entry<Data, Data> dataEntry : entries) {
Data keyData = dataEntry.getKey();
Data valueData = dataEntry.getValue();
K key = toObject(keyData);
V value = toObject(valueData);
entrySet.add(new AbstractMap.SimpleEntry<K, V>(key, value));
}
return entrySet;
}
public Set<K> keySet(Predicate predicate) {
MapQueryRequest request = new MapQueryRequest(name, predicate, IterationType.KEY);
QueryResultSet result = invoke(request);
Set<K> keySet = new HashSet<K>(result.size());
for (Object data : result) {
K key = toObject((Data)data);
keySet.add(key);
}
return keySet;
}
public Set<Entry<K, V>> entrySet(Predicate predicate) {
MapQueryRequest request = new MapQueryRequest(name, predicate, IterationType.ENTRY);
QueryResultSet result = invoke(request);
Set<Entry<K, V>> entrySet = new HashSet<Entry<K, V>>(result.size());
for (Object data : result) {
AbstractMap.SimpleImmutableEntry<Data ,Data > dataEntry = (AbstractMap.SimpleImmutableEntry<Data ,Data >)data;
K key = toObject(dataEntry.getKey());
V value = toObject(dataEntry.getValue());
entrySet.add(new AbstractMap.SimpleEntry<K, V>(key, value));
}
return entrySet;
}
public Collection<V> values(Predicate predicate) {
MapQueryRequest request = new MapQueryRequest(name, predicate, IterationType.VALUE);
QueryResultSet result = invoke(request);
Collection<V> values = new ArrayList<V>(result.size());
for (Object data : result) {
V value = toObject((Data)data);
values.add(value);
}
return values;
}
public Set<K> localKeySet() {
throw new UnsupportedOperationException("Locality is ambiguous for client!!!");
}
public Set<K> localKeySet(Predicate predicate) {
throw new UnsupportedOperationException("Locality is ambiguous for client!!!");
}
public void addIndex(String attribute, boolean ordered) {
MapAddIndexRequest request = new MapAddIndexRequest(name, attribute, ordered);
invoke(request);
}
public LocalMapStats getLocalMapStats() {
throw new UnsupportedOperationException("Locality is ambiguous for client!!!");
}
public Object executeOnKey(K key, EntryProcessor entryProcessor) {
final Data keyData = toData(key);
MapExecuteOnKeyRequest request = new MapExecuteOnKeyRequest(name, entryProcessor, keyData);
return invoke(request, keyData);
}
public Map<K, Object> executeOnEntries(EntryProcessor entryProcessor) {
MapExecuteOnAllKeysRequest request = new MapExecuteOnAllKeysRequest(name, entryProcessor);
MapEntrySet entrySet = invoke(request);
Map<K, Object> result = new HashMap<K, Object>();
for (Entry<Data, Data> dataEntry : entrySet.getEntrySet()) {
final Data keyData = dataEntry.getKey();
final Data valueData = dataEntry.getValue();
K key = toObject(keyData);
result.put(key, toObject(valueData));
}
return result;
}
public void set(K key, V value) {
set(key, value, -1, null);
}
public int size() {
MapSizeRequest request = new MapSizeRequest(name);
Integer result = invoke(request);
return result;
}
public boolean isEmpty() {
return size() == 0;
}
public void putAll(Map<? extends K, ? extends V> m) {
MapEntrySet entrySet = new MapEntrySet();
for (Entry<? extends K, ? extends V> entry : m.entrySet()) {
entrySet.add(new AbstractMap.SimpleImmutableEntry<Data, Data>(toData(entry.getKey()), toData(entry.getValue())));
}
MapPutAllRequest request = new MapPutAllRequest(name, entrySet);
invoke(request);
}
public void clear() {
MapClearRequest request = new MapClearRequest(name);
invoke(request);
}
protected void onDestroy() {
if (nearCacheListenerId != null){
removeEntryListener(nearCacheListenerId);
}
nearCache.clear();
MapDestroyRequest request = new MapDestroyRequest(name);
invoke(request);
}
public String getName() {
return name;
}
private Data toData(Object o) {
return getContext().getSerializationService().toData(o);
}
private <T> T toObject(Data data) {
return (T) getContext().getSerializationService().toObject(data);
}
private <T> T invoke(Object req, Data keyData) {
try {
return getContext().getInvocationService().invokeOnKeyOwner(req, keyData);
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
}
private <T> T invoke(Object req) {
try {
return getContext().getInvocationService().invokeOnRandomTarget(req);
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
}
protected long getTimeInMillis(final long time, final TimeUnit timeunit) {
return timeunit != null ? timeunit.toMillis(time) : time;
}
private EventHandler<PortableEntryEvent> createHandler(final EntryListener<K, V> listener, final boolean includeValue) {
return new EventHandler<PortableEntryEvent>() {
public void handle(PortableEntryEvent event) {
V value = null;
V oldValue = null;
if (includeValue) {
value = toObject(event.getValue());
oldValue = toObject(event.getOldValue());
}
K key = toObject(event.getKey());
Member member = getContext().getClusterService().getMember(event.getUuid());
EntryEvent<K, V> entryEvent = new EntryEvent<K, V>(name, member,
event.getEventType().getType(), key, oldValue, value);
switch (event.getEventType()) {
case ADDED:
listener.entryAdded(entryEvent);
break;
case REMOVED:
listener.entryRemoved(entryEvent);
break;
case UPDATED:
listener.entryUpdated(entryEvent);
break;
case EVICTED:
listener.entryEvicted(entryEvent);
break;
}
}
};
}
private void initNearCache(){
if (nearCacheInitialized.compareAndSet(false, true)){
final NearCacheConfig nearCacheConfig = getContext().getClientConfig().getNearCacheConfig(name);
if (nearCacheConfig == null){
return;
}
nearCache = new ClientNearCache(name, getContext(), nearCacheConfig);
if (nearCache != null && nearCacheConfig.isInvalidateOnChange()){
nearCacheListenerId = addEntryListener(new EntryListener<K, V>() {
public void entryAdded(EntryEvent<K, V> event) {
invalidate(event);
}
public void entryRemoved(EntryEvent<K, V> event) {
invalidate(event);
}
public void entryUpdated(EntryEvent<K, V> event) {
invalidate(event);
}
public void entryEvicted(EntryEvent<K, V> event) {
invalidate(event);
}
void invalidate(EntryEvent<K, V> event){
System.err.println("invalidate");
final Data key = toData(event.getKey());
-// nearCache.invalidate(key);
- nearCache.put(key, event.getValue());
+ nearCache.invalidate(key);
}
- }, true);
+ }, false);
}
}
}
}
| false | true | private void initNearCache(){
if (nearCacheInitialized.compareAndSet(false, true)){
final NearCacheConfig nearCacheConfig = getContext().getClientConfig().getNearCacheConfig(name);
if (nearCacheConfig == null){
return;
}
nearCache = new ClientNearCache(name, getContext(), nearCacheConfig);
if (nearCache != null && nearCacheConfig.isInvalidateOnChange()){
nearCacheListenerId = addEntryListener(new EntryListener<K, V>() {
public void entryAdded(EntryEvent<K, V> event) {
invalidate(event);
}
public void entryRemoved(EntryEvent<K, V> event) {
invalidate(event);
}
public void entryUpdated(EntryEvent<K, V> event) {
invalidate(event);
}
public void entryEvicted(EntryEvent<K, V> event) {
invalidate(event);
}
void invalidate(EntryEvent<K, V> event){
System.err.println("invalidate");
final Data key = toData(event.getKey());
// nearCache.invalidate(key);
nearCache.put(key, event.getValue());
}
}, true);
}
}
}
| private void initNearCache(){
if (nearCacheInitialized.compareAndSet(false, true)){
final NearCacheConfig nearCacheConfig = getContext().getClientConfig().getNearCacheConfig(name);
if (nearCacheConfig == null){
return;
}
nearCache = new ClientNearCache(name, getContext(), nearCacheConfig);
if (nearCache != null && nearCacheConfig.isInvalidateOnChange()){
nearCacheListenerId = addEntryListener(new EntryListener<K, V>() {
public void entryAdded(EntryEvent<K, V> event) {
invalidate(event);
}
public void entryRemoved(EntryEvent<K, V> event) {
invalidate(event);
}
public void entryUpdated(EntryEvent<K, V> event) {
invalidate(event);
}
public void entryEvicted(EntryEvent<K, V> event) {
invalidate(event);
}
void invalidate(EntryEvent<K, V> event){
System.err.println("invalidate");
final Data key = toData(event.getKey());
nearCache.invalidate(key);
}
}, false);
}
}
}
|
diff --git a/source/ru/peppers/MyOrderItemActivity.java b/source/ru/peppers/MyOrderItemActivity.java
index 93e708f..7eb4667 100644
--- a/source/ru/peppers/MyOrderItemActivity.java
+++ b/source/ru/peppers/MyOrderItemActivity.java
@@ -1,629 +1,629 @@
package ru.peppers;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import model.Order;
import myorders.MyCostOrder;
public class MyOrderItemActivity extends BalanceActivity {
protected static final int REQUEST_EXIT = 0;
private CountDownTimer timer;
private TextView counterView;
private MyCostOrder order;
private Dialog dialog;
private Bundle bundle;
private TextView tv;
private Timer myTimer = new Timer();
private Integer refreshperiod = null;
private boolean start = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myorder);
Bundle bundle = getIntent().getExtras();
int index = bundle.getInt("index");
counterView = (TextView) findViewById(R.id.textView1);
tv = (TextView) findViewById(R.id.textView2);
order = (MyCostOrder) TaxiApplication.getDriver().getOrder(index);
ArrayList<String> orderList = order.toArrayList();
int arraySize = orderList.size();
for (int i = 0; i < arraySize; i++) {
tv.append(orderList.get(i));
tv.append("\n");
}
// if (order.getTimerDate() != null) {
// timerInit(order);
// }
Button button = (Button) findViewById(R.id.button1);
button.setText(this.getString(R.string.choose_action));
button.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
initActionDialog();
}
});
getOrder();
}
private void getOrder() {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("action", "get"));
nameValuePairs.add(new BasicNameValuePair("mode", "available"));
nameValuePairs.add(new BasicNameValuePair("module", "mobile"));
nameValuePairs.add(new BasicNameValuePair("object", "order"));
nameValuePairs.add(new BasicNameValuePair("orderid", order.get_index()));
Document doc = PhpData.postData(this, nameValuePairs, PhpData.newURL);
if (doc != null) {
Node responseNode = doc.getElementsByTagName("response").item(0);
Node errorNode = doc.getElementsByTagName("message").item(0);
if (responseNode.getTextContent().equalsIgnoreCase("failure"))
PhpData.errorFromServer(this, errorNode);
else {
try {
initOrder(doc);
} catch (Exception e) {
PhpData.errorHandler(this, e);
}
}
}
}
private void initOrder(Document doc) throws DOMException, ParseException {
tv.setText("");
// nominalcost - рекомендуемая стоимость заказа
// class - класс автомобля (0 - все равно, 1 - Эконом, 2 - Стандарт,
// 3 - Базовый)
// addressdeparture - адрес подачи автомобиля
// departuretime - время подачи(если есть)
// paymenttype - форма оплаты (0 - наличные, 1 - безнал)
// invitationtime - время приглашения (если пригласили)
// quantity - количество заказов от этого клиента
// comment - примечание
// nickname - ник абонента (если есть)
// registrationtime - время регистрации заказа
// addressarrival - куда поедут
Element item = (Element) doc.getElementsByTagName("order").item(0);
Node nominalcostNode = item.getElementsByTagName("nominalcost").item(0);
Node classNode = item.getElementsByTagName("classid").item(0);
Node addressdepartureNode = item.getElementsByTagName("addressdeparture").item(0);
Node departuretimeNode = item.getElementsByTagName("departuretime").item(0);
Node paymenttypeNode = item.getElementsByTagName("paymenttype").item(0);
Node quantityNode = item.getElementsByTagName("quantity").item(0);
Node commentNode = item.getElementsByTagName("comment").item(0);
Node nicknameNode = item.getElementsByTagName("nickname").item(0);
Node addressarrivalNode = item.getElementsByTagName("addressarrival").item(0);
Node orderIdNode = item.getElementsByTagName("orderid").item(0);
Node invitationNode = item.getElementsByTagName("invitationtime").item(0);
- Node accepttimeNode = item.getElementsByTagName("accepttime").item(0);
+ // Node accepttimeNode = item.getElementsByTagName("accepttime").item(0);
Date accepttime = null;
Integer nominalcost = null;
Integer carClass = 0;
String addressdeparture = null;
Date departuretime = null;
Integer paymenttype = null;
Integer quantity = null;
String comment = null;
String nickname = null;
Date invitationtime = null;
String addressarrival = null;
String orderId = null;
// if(departuretime==null)
// //TODO:не предварительный
// else
// //TODO:предварительный
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
if (!classNode.getTextContent().equalsIgnoreCase(""))
carClass = Integer.valueOf(classNode.getTextContent());
if (!nominalcostNode.getTextContent().equalsIgnoreCase(""))
nominalcost = Integer.parseInt(nominalcostNode.getTextContent());
// if (!registrationtimeNode.getTextContent().equalsIgnoreCase(""))
// registrationtime = format.parse(registrationtimeNode.getTextContent());
if (!addressdepartureNode.getTextContent().equalsIgnoreCase(""))
addressdeparture = addressdepartureNode.getTextContent();
if (!addressarrivalNode.getTextContent().equalsIgnoreCase(""))
addressarrival = addressarrivalNode.getTextContent();
if (!paymenttypeNode.getTextContent().equalsIgnoreCase(""))
paymenttype = Integer.parseInt(paymenttypeNode.getTextContent());
if (!departuretimeNode.getTextContent().equalsIgnoreCase(""))
departuretime = format.parse(departuretimeNode.getTextContent());
if (!commentNode.getTextContent().equalsIgnoreCase(""))
comment = commentNode.getTextContent();
if (!orderIdNode.getTextContent().equalsIgnoreCase(""))
orderId = orderIdNode.getTextContent();
if (!invitationNode.getTextContent().equalsIgnoreCase(""))
invitationtime = format.parse(invitationNode.getTextContent());
- if (!accepttimeNode.getTextContent().equalsIgnoreCase(""))
- accepttime = format.parse(accepttimeNode.getTextContent());
+ //if (!accepttimeNode.getTextContent().equalsIgnoreCase(""))
+ // accepttime = format.parse(accepttimeNode.getTextContent());
order = new MyCostOrder(this, orderId, nominalcost, addressdeparture, carClass, comment,
addressarrival, paymenttype, invitationtime, departuretime,accepttime);
if (!nicknameNode.getTextContent().equalsIgnoreCase("")) {
nickname = nicknameNode.getTextContent();
if (!quantityNode.getTextContent().equalsIgnoreCase(""))
quantity = Integer.parseInt(quantityNode.getTextContent());
order.setAbonent(nickname);
order.setRides(quantity);
}
ArrayList<String> orderList = order.toArrayList();
int arraySize = orderList.size();
for (int i = 0; i < arraySize; i++) {
tv.append(orderList.get(i));
tv.append("\n");
}
// TODO:UPDATE ORDER
Node refreshperiodNode = doc.getElementsByTagName("refreshperiod").item(0);
Integer newrefreshperiod = null;
if (!refreshperiodNode.getTextContent().equalsIgnoreCase(""))
newrefreshperiod = Integer.valueOf(refreshperiodNode.getTextContent());
boolean update = false;
Log.d("My_tag", refreshperiod + " " + newrefreshperiod + " " + update);
if (newrefreshperiod != null) {
if (refreshperiod != newrefreshperiod) {
refreshperiod = newrefreshperiod;
update = true;
}
}
Log.d("My_tag", refreshperiod + " " + newrefreshperiod + " " + update);
if (update && refreshperiod != null) {
if (start) {
myTimer.cancel();
start = true;
Log.d("My_tag", "cancel timer");
}
final Handler uiHandler = new Handler();
TimerTask timerTask = new TimerTask() { // Определяем задачу
@Override
public void run() {
uiHandler.post(new Runnable() {
@Override
public void run() {
getOrder();
}
});
}
};
myTimer.schedule(timerTask, 1000 * refreshperiod, 1000 * refreshperiod);
}
}
@Override
protected void onPause() {
super.onPause();
myTimer.cancel();
if (timer != null)
timer.cancel();
}
private OnClickListener onContextMenuItemListener() {
return new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
dialog.dismiss();
switch (item) {
case 0:
inviteDialog();
break;
case 1:
priceDialog();
break;
case 2:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("action", "callback"));
nameValuePairs.add(new BasicNameValuePair("module", "mobile"));
nameValuePairs.add(new BasicNameValuePair("object", "driver"));
nameValuePairs.add(new BasicNameValuePair("orderid", order.get_index()));
Document doc = PhpData.postData(MyOrderItemActivity.this, nameValuePairs,
PhpData.newURL);
if (doc != null) {
Node responseNode = doc.getElementsByTagName("response").item(0);
Node errorNode = doc.getElementsByTagName("message").item(0);
if (responseNode.getTextContent().equalsIgnoreCase("failure"))
PhpData.errorFromServer(MyOrderItemActivity.this, errorNode);
else {
new AlertDialog.Builder(MyOrderItemActivity.this).setTitle("Звонок")
.setMessage("Ваш запрос принят. Пожалуйста ожидайте звонка")
.setNeutralButton("Ок", null).show();
}
}
break;
case 3:
timeDialog();
break;
default:
break;
}
}
};
}
private void inviteDialog() {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("action", (order.get_invitationtime() == null) ? "invite"
: "hurry"));
nameValuePairs.add(new BasicNameValuePair("module", "mobile"));
nameValuePairs.add(new BasicNameValuePair("object", "client"));
nameValuePairs.add(new BasicNameValuePair("orderid", order.get_index()));
Document doc = PhpData.postData(this, nameValuePairs, PhpData.newURL);
if (doc != null) {
Node responseNode = doc.getElementsByTagName("response").item(0);
Node errorNode = doc.getElementsByTagName("message").item(0);
if (responseNode.getTextContent().equalsIgnoreCase("failure"))
PhpData.errorFromServer(MyOrderItemActivity.this, errorNode);
else {
new AlertDialog.Builder(MyOrderItemActivity.this).setTitle(this.getString(R.string.Ok))
.setMessage(this.getString(R.string.invite_sended))
.setNeutralButton(this.getString(R.string.close), null).show();
}
}
}
private void timeDialog() {
AlertDialog.Builder alert = new AlertDialog.Builder(MyOrderItemActivity.this);
alert.setTitle(this.getString(R.string.time));
final String cs[] = new String[] { "3", "5", "7", "10", "15" };// , "20", "25", "30", "35"};
alert.setItems(cs, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// https://www.abs-taxi.ru/fcgi-bin/office/cman.fcgi?module=mobile;object=order;action=delay;time=7
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("action", "delay"));
nameValuePairs.add(new BasicNameValuePair("module", "mobile"));
nameValuePairs.add(new BasicNameValuePair("object", "order"));
nameValuePairs.add(new BasicNameValuePair("minutes", cs[which]));
nameValuePairs.add(new BasicNameValuePair("orderid", order.get_index()));
Document doc = PhpData.postData(MyOrderItemActivity.this, nameValuePairs, PhpData.newURL);
if (doc != null) {
Node responseNode = doc.getElementsByTagName("response").item(0);
Node errorNode = doc.getElementsByTagName("message").item(0);
if (responseNode.getTextContent().equalsIgnoreCase("failure"))
PhpData.errorFromServer(MyOrderItemActivity.this, errorNode);
else {
dialog.dismiss();
// final Order order = TaxiApplication.getDriver().getOrder(index);
// if (order.getTimerDate() != null) {
// Calendar cal = Calendar.getInstance();
// cal.add(Calendar.MINUTE, Integer.valueOf((String) cs[which]));
//
// order.setTimerDate(cal.getTime());
// timer.cancel();
// timerInit(order);
// }
new AlertDialog.Builder(MyOrderItemActivity.this)
.setTitle(MyOrderItemActivity.this.getString(R.string.Ok))
.setMessage(MyOrderItemActivity.this.getString(R.string.order_delayed))
.setNeutralButton(MyOrderItemActivity.this.getString(R.string.close), null)
.show();
}
}
}
});
alert.show();
}
private void initActionDialog() {
ArrayList<String> arrayList = new ArrayList<String>();
if (order.get_invitationtime() == null)
arrayList.add(this.getString(R.string.invite));
else
arrayList.add("Поторопить");
arrayList.add(this.getString(R.string.close));
arrayList.add(this.getString(R.string.call_office));
if (order.get_invitationtime() == null)
arrayList.add(this.getString(R.string.delay));
// final CharSequence[] items = { this.getString(R.string.invite) : ,
// this.getString(R.string.delay), this.getString(R.string.close),
// this.getString(R.string.call_office)};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(this.getString(R.string.choose_action));
builder.setItems(arrayList.toArray(new String[arrayList.size()]), onContextMenuItemListener());
AlertDialog alert = builder.create();
alert.show();
}
private void timerInit(final Order order) {
long diffInMs = order.getTimerDate().getTime() - new Date().getTime();
timer = new CountDownTimer(diffInMs, 1000) {
public void onTick(long millisUntilFinished) {
int seconds = ((int) millisUntilFinished / 1000) % 60;
String secondsStr = String.valueOf(seconds);
if (seconds <= 9)
secondsStr = "0" + seconds;
counterView.setText(((int) millisUntilFinished / 1000) / 60 + ":" + secondsStr);
if ((((int) millisUntilFinished / 1000) / 60) == 1
&& (((int) millisUntilFinished / 1000) % 60) == 0) {
initActionDialog();
}
}
public void onFinish() {
counterView.setText(MyOrderItemActivity.this.getString(R.string.ended_timer));
alertDelay(order);
MediaPlayer mp = MediaPlayer.create(getBaseContext(), (R.raw.sound));
mp.start();
}
}.start();
}
private void alertDelay(final Order order) {
AlertDialog.Builder alert = new AlertDialog.Builder(MyOrderItemActivity.this);
alert.setTitle(this.getString(R.string.time));
final CharSequence cs[];
cs = new String[] { "3", "5", "7", "10", "15", "20", "25", "30", "35" };
alert.setItems(cs, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Bundle extras = getIntent().getExtras();
// int id = extras.getInt("id");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("action", "saveminutes"));
nameValuePairs.add(new BasicNameValuePair("order_id", String.valueOf(order.get_index())));
// nameValuePairs.add(new BasicNameValuePair("id",
// String.valueOf(id)));
nameValuePairs.add(new BasicNameValuePair("minutes", String.valueOf(cs[which])));
Document doc = PhpData.postData(MyOrderItemActivity.this, nameValuePairs);
if (doc != null) {
Node errorNode = doc.getElementsByTagName("error").item(0);
if (Integer.parseInt(errorNode.getTextContent()) == 1)
PhpData.errorHandler(MyOrderItemActivity.this, null);
else {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.MINUTE, Integer.valueOf((String) cs[which]));
order.setTimerDate(cal.getTime());
timerInit(order);
}
}
}
});
alert.show();
}
private void priceDialog() {
// View view = getLayoutInflater().inflate(R.layout.custom_dialog,
// null);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
int isLightTheme = settings.getInt("theme", 0);
if (isLightTheme != 0)
dialog = new Dialog(this, android.R.style.Theme_Light);
else
dialog = new Dialog(this, android.R.style.Theme_Black);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle(this.getString(R.string.price));
dialog.show();
Button btn = (Button) dialog.findViewById(R.id.button1);
EditText input = (EditText) dialog.findViewById(R.id.editText1);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
btn.setOnClickListener(onSavePrice(dialog));
LinearLayout ll = (LinearLayout) dialog.findViewById(R.id.layout1);
if (order.get_paymenttype() == 1 || (order.getAbonent() != null && order.get_paymenttype() == 0))// безнал
ll.setVisibility(View.VISIBLE);
if (order.getAbonent() != null && order.get_paymenttype() == 0)
((TextView) dialog.findViewById(R.id.textView2)).setText("Сдача");
final CheckBox cb = (CheckBox) dialog.findViewById(R.id.checkBox1);
final TextView tv = (TextView) dialog.findViewById(R.id.textView3);
Button btn1 = (Button) dialog.findViewById(R.id.button2);
Button btn2 = (Button) dialog.findViewById(R.id.button3);
tv.setText(MyOrderItemActivity.this.getText(R.string.end_point) + " " + order.get_addressarrival());
btn1.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(MyOrderItemActivity.this, DistrictActivity.class);
intent.putExtra("close", true);
startActivityForResult(intent, REQUEST_EXIT);
}
});
btn2.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View arg0) {
bundle = null;
tv.setText(MyOrderItemActivity.this.getText(R.string.end_point) + " "
+ order.get_addressarrival());
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_EXIT) {
if (resultCode == RESULT_OK) {
bundle = data.getExtras();
TextView tv = (TextView) dialog.findViewById(R.id.textView3);
String district = bundle.getString("districtname");
String subdistrict = bundle.getString("subdistrictname");
String rayonString = "";
if (district != null) {
rayonString = district;
if (subdistrict != null)
rayonString += ", " + subdistrict;
}
tv.setText("Район: " + rayonString);
}
}
}
private Button.OnClickListener onSavePrice(final Dialog dialog) {
return new Button.OnClickListener() {
@Override
public void onClick(View v) {
EditText input = (EditText) dialog.findViewById(R.id.editText1);
EditText cashless = (EditText) dialog.findViewById(R.id.editText2);
RadioGroup radioGroup = (RadioGroup) dialog.findViewById(R.id.radioGroup1);
int checkedRadioButtonId = radioGroup.getCheckedRadioButtonId();
String state = "1";
if (checkedRadioButtonId == R.id.radio0) {
state = "1";
} else if (checkedRadioButtonId == R.id.radio1) {
state = "0";
}
if (input.getText().length() != 0) {
String value = input.getText().toString();
String cashvalue;
if (cashless.getText().length() == 0 && order.get_paymenttype() == 1)
cashvalue = value;
else {
cashvalue = "0";
if (order.get_paymenttype() == 1)
cashvalue = cashless.getText().toString();
else if (order.getAbonent() != null)
cashvalue = "-" + cashless.getText().toString();
}
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("action", "close"));
nameValuePairs.add(new BasicNameValuePair("module", "mobile"));
nameValuePairs.add(new BasicNameValuePair("object", "order"));
nameValuePairs.add(new BasicNameValuePair("orderid", order.get_index()));
// if (order.get_nominalcost() != null)
// orderCost = String.valueOf(order.get_nominalcost());
nameValuePairs.add(new BasicNameValuePair("cost", value));
nameValuePairs.add(new BasicNameValuePair("cashless", cashvalue));
nameValuePairs.add(new BasicNameValuePair("state", state));
if (bundle != null) {
nameValuePairs
.add(new BasicNameValuePair("districtid", bundle.getString("district")));
// nameValuePairs.add(new
// BasicNameValuePair("subdistrictid",
// bundle.getString("subdistrict")));
}
Document doc = PhpData.postData(MyOrderItemActivity.this, nameValuePairs, PhpData.newURL);
if (doc != null) {
Node responseNode = doc.getElementsByTagName("response").item(0);
Node errorNode = doc.getElementsByTagName("message").item(0);
if (responseNode.getTextContent().equalsIgnoreCase("failure"))
PhpData.errorFromServer(MyOrderItemActivity.this, errorNode);
else {
dialog.dismiss();
new AlertDialog.Builder(MyOrderItemActivity.this)
.setTitle(MyOrderItemActivity.this.getString(R.string.Ok))
.setMessage(MyOrderItemActivity.this.getString(R.string.order_closed))
.setNeutralButton(MyOrderItemActivity.this.getString(R.string.close),
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (timer != null)
timer.cancel();
setResult(RESULT_OK);
finish();
}
}).show();
}
}
}
}
}
;
}
}
| false | true | private void initOrder(Document doc) throws DOMException, ParseException {
tv.setText("");
// nominalcost - рекомендуемая стоимость заказа
// class - класс автомобля (0 - все равно, 1 - Эконом, 2 - Стандарт,
// 3 - Базовый)
// addressdeparture - адрес подачи автомобиля
// departuretime - время подачи(если есть)
// paymenttype - форма оплаты (0 - наличные, 1 - безнал)
// invitationtime - время приглашения (если пригласили)
// quantity - количество заказов от этого клиента
// comment - примечание
// nickname - ник абонента (если есть)
// registrationtime - время регистрации заказа
// addressarrival - куда поедут
Element item = (Element) doc.getElementsByTagName("order").item(0);
Node nominalcostNode = item.getElementsByTagName("nominalcost").item(0);
Node classNode = item.getElementsByTagName("classid").item(0);
Node addressdepartureNode = item.getElementsByTagName("addressdeparture").item(0);
Node departuretimeNode = item.getElementsByTagName("departuretime").item(0);
Node paymenttypeNode = item.getElementsByTagName("paymenttype").item(0);
Node quantityNode = item.getElementsByTagName("quantity").item(0);
Node commentNode = item.getElementsByTagName("comment").item(0);
Node nicknameNode = item.getElementsByTagName("nickname").item(0);
Node addressarrivalNode = item.getElementsByTagName("addressarrival").item(0);
Node orderIdNode = item.getElementsByTagName("orderid").item(0);
Node invitationNode = item.getElementsByTagName("invitationtime").item(0);
Node accepttimeNode = item.getElementsByTagName("accepttime").item(0);
Date accepttime = null;
Integer nominalcost = null;
Integer carClass = 0;
String addressdeparture = null;
Date departuretime = null;
Integer paymenttype = null;
Integer quantity = null;
String comment = null;
String nickname = null;
Date invitationtime = null;
String addressarrival = null;
String orderId = null;
// if(departuretime==null)
// //TODO:не предварительный
// else
// //TODO:предварительный
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
if (!classNode.getTextContent().equalsIgnoreCase(""))
carClass = Integer.valueOf(classNode.getTextContent());
if (!nominalcostNode.getTextContent().equalsIgnoreCase(""))
nominalcost = Integer.parseInt(nominalcostNode.getTextContent());
// if (!registrationtimeNode.getTextContent().equalsIgnoreCase(""))
// registrationtime = format.parse(registrationtimeNode.getTextContent());
if (!addressdepartureNode.getTextContent().equalsIgnoreCase(""))
addressdeparture = addressdepartureNode.getTextContent();
if (!addressarrivalNode.getTextContent().equalsIgnoreCase(""))
addressarrival = addressarrivalNode.getTextContent();
if (!paymenttypeNode.getTextContent().equalsIgnoreCase(""))
paymenttype = Integer.parseInt(paymenttypeNode.getTextContent());
if (!departuretimeNode.getTextContent().equalsIgnoreCase(""))
departuretime = format.parse(departuretimeNode.getTextContent());
if (!commentNode.getTextContent().equalsIgnoreCase(""))
comment = commentNode.getTextContent();
if (!orderIdNode.getTextContent().equalsIgnoreCase(""))
orderId = orderIdNode.getTextContent();
if (!invitationNode.getTextContent().equalsIgnoreCase(""))
invitationtime = format.parse(invitationNode.getTextContent());
if (!accepttimeNode.getTextContent().equalsIgnoreCase(""))
accepttime = format.parse(accepttimeNode.getTextContent());
order = new MyCostOrder(this, orderId, nominalcost, addressdeparture, carClass, comment,
addressarrival, paymenttype, invitationtime, departuretime,accepttime);
if (!nicknameNode.getTextContent().equalsIgnoreCase("")) {
nickname = nicknameNode.getTextContent();
if (!quantityNode.getTextContent().equalsIgnoreCase(""))
quantity = Integer.parseInt(quantityNode.getTextContent());
order.setAbonent(nickname);
order.setRides(quantity);
}
ArrayList<String> orderList = order.toArrayList();
int arraySize = orderList.size();
for (int i = 0; i < arraySize; i++) {
tv.append(orderList.get(i));
tv.append("\n");
}
// TODO:UPDATE ORDER
Node refreshperiodNode = doc.getElementsByTagName("refreshperiod").item(0);
Integer newrefreshperiod = null;
if (!refreshperiodNode.getTextContent().equalsIgnoreCase(""))
newrefreshperiod = Integer.valueOf(refreshperiodNode.getTextContent());
boolean update = false;
Log.d("My_tag", refreshperiod + " " + newrefreshperiod + " " + update);
if (newrefreshperiod != null) {
if (refreshperiod != newrefreshperiod) {
refreshperiod = newrefreshperiod;
update = true;
}
}
Log.d("My_tag", refreshperiod + " " + newrefreshperiod + " " + update);
if (update && refreshperiod != null) {
if (start) {
myTimer.cancel();
start = true;
Log.d("My_tag", "cancel timer");
}
final Handler uiHandler = new Handler();
TimerTask timerTask = new TimerTask() { // Определяем задачу
@Override
public void run() {
uiHandler.post(new Runnable() {
@Override
public void run() {
getOrder();
}
});
}
};
myTimer.schedule(timerTask, 1000 * refreshperiod, 1000 * refreshperiod);
}
}
| private void initOrder(Document doc) throws DOMException, ParseException {
tv.setText("");
// nominalcost - рекомендуемая стоимость заказа
// class - класс автомобля (0 - все равно, 1 - Эконом, 2 - Стандарт,
// 3 - Базовый)
// addressdeparture - адрес подачи автомобиля
// departuretime - время подачи(если есть)
// paymenttype - форма оплаты (0 - наличные, 1 - безнал)
// invitationtime - время приглашения (если пригласили)
// quantity - количество заказов от этого клиента
// comment - примечание
// nickname - ник абонента (если есть)
// registrationtime - время регистрации заказа
// addressarrival - куда поедут
Element item = (Element) doc.getElementsByTagName("order").item(0);
Node nominalcostNode = item.getElementsByTagName("nominalcost").item(0);
Node classNode = item.getElementsByTagName("classid").item(0);
Node addressdepartureNode = item.getElementsByTagName("addressdeparture").item(0);
Node departuretimeNode = item.getElementsByTagName("departuretime").item(0);
Node paymenttypeNode = item.getElementsByTagName("paymenttype").item(0);
Node quantityNode = item.getElementsByTagName("quantity").item(0);
Node commentNode = item.getElementsByTagName("comment").item(0);
Node nicknameNode = item.getElementsByTagName("nickname").item(0);
Node addressarrivalNode = item.getElementsByTagName("addressarrival").item(0);
Node orderIdNode = item.getElementsByTagName("orderid").item(0);
Node invitationNode = item.getElementsByTagName("invitationtime").item(0);
// Node accepttimeNode = item.getElementsByTagName("accepttime").item(0);
Date accepttime = null;
Integer nominalcost = null;
Integer carClass = 0;
String addressdeparture = null;
Date departuretime = null;
Integer paymenttype = null;
Integer quantity = null;
String comment = null;
String nickname = null;
Date invitationtime = null;
String addressarrival = null;
String orderId = null;
// if(departuretime==null)
// //TODO:не предварительный
// else
// //TODO:предварительный
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
if (!classNode.getTextContent().equalsIgnoreCase(""))
carClass = Integer.valueOf(classNode.getTextContent());
if (!nominalcostNode.getTextContent().equalsIgnoreCase(""))
nominalcost = Integer.parseInt(nominalcostNode.getTextContent());
// if (!registrationtimeNode.getTextContent().equalsIgnoreCase(""))
// registrationtime = format.parse(registrationtimeNode.getTextContent());
if (!addressdepartureNode.getTextContent().equalsIgnoreCase(""))
addressdeparture = addressdepartureNode.getTextContent();
if (!addressarrivalNode.getTextContent().equalsIgnoreCase(""))
addressarrival = addressarrivalNode.getTextContent();
if (!paymenttypeNode.getTextContent().equalsIgnoreCase(""))
paymenttype = Integer.parseInt(paymenttypeNode.getTextContent());
if (!departuretimeNode.getTextContent().equalsIgnoreCase(""))
departuretime = format.parse(departuretimeNode.getTextContent());
if (!commentNode.getTextContent().equalsIgnoreCase(""))
comment = commentNode.getTextContent();
if (!orderIdNode.getTextContent().equalsIgnoreCase(""))
orderId = orderIdNode.getTextContent();
if (!invitationNode.getTextContent().equalsIgnoreCase(""))
invitationtime = format.parse(invitationNode.getTextContent());
//if (!accepttimeNode.getTextContent().equalsIgnoreCase(""))
// accepttime = format.parse(accepttimeNode.getTextContent());
order = new MyCostOrder(this, orderId, nominalcost, addressdeparture, carClass, comment,
addressarrival, paymenttype, invitationtime, departuretime,accepttime);
if (!nicknameNode.getTextContent().equalsIgnoreCase("")) {
nickname = nicknameNode.getTextContent();
if (!quantityNode.getTextContent().equalsIgnoreCase(""))
quantity = Integer.parseInt(quantityNode.getTextContent());
order.setAbonent(nickname);
order.setRides(quantity);
}
ArrayList<String> orderList = order.toArrayList();
int arraySize = orderList.size();
for (int i = 0; i < arraySize; i++) {
tv.append(orderList.get(i));
tv.append("\n");
}
// TODO:UPDATE ORDER
Node refreshperiodNode = doc.getElementsByTagName("refreshperiod").item(0);
Integer newrefreshperiod = null;
if (!refreshperiodNode.getTextContent().equalsIgnoreCase(""))
newrefreshperiod = Integer.valueOf(refreshperiodNode.getTextContent());
boolean update = false;
Log.d("My_tag", refreshperiod + " " + newrefreshperiod + " " + update);
if (newrefreshperiod != null) {
if (refreshperiod != newrefreshperiod) {
refreshperiod = newrefreshperiod;
update = true;
}
}
Log.d("My_tag", refreshperiod + " " + newrefreshperiod + " " + update);
if (update && refreshperiod != null) {
if (start) {
myTimer.cancel();
start = true;
Log.d("My_tag", "cancel timer");
}
final Handler uiHandler = new Handler();
TimerTask timerTask = new TimerTask() { // Определяем задачу
@Override
public void run() {
uiHandler.post(new Runnable() {
@Override
public void run() {
getOrder();
}
});
}
};
myTimer.schedule(timerTask, 1000 * refreshperiod, 1000 * refreshperiod);
}
}
|
diff --git a/java/client/src/org/openqa/selenium/android/library/ViewClientWrapper.java b/java/client/src/org/openqa/selenium/android/library/ViewClientWrapper.java
index a330029bd..c6ce62367 100644
--- a/java/client/src/org/openqa/selenium/android/library/ViewClientWrapper.java
+++ b/java/client/src/org/openqa/selenium/android/library/ViewClientWrapper.java
@@ -1,78 +1,82 @@
/*
Copyright 2011 Software Freedom Conservatory.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openqa.selenium.android.library;
import org.openqa.selenium.WebDriverException;
/**
* This class wraps a view client that must have the *same* API as
* WebViewClient. The underlying client will be used by WebDriver to listen to
* interesting events on the page.
*
* <p/>Sample usage:
* // If the underlying view is a WebView you can use WebDriver's default
* // view client DefaultViewClient as follow.
* ViewClientWrapper viewWrapper = new ViewClientWrapper(
* "android.webkit.WebViewClient", new DefaultViewClient());
*
* // If the underlying view is a WebView and it has custom WebViewClient
* // settings, use the DefaultViewClient as follow:
* class MyCustomClient extends WebViewClient {
* ...
* }
*
* MyCustomClient myClient = new MyCustomClient();
* ViewClientWrapper viewWrapper = new ViewClientWrapper(
* "android.webkit.WebViewClient", new DefaultViewClient(myClient));
*/
public class ViewClientWrapper implements DriverProvider {
private final String className;
private final Object client;
/**
*
* @param className the fully qualified class name of the client's
* class name.
* @param client the client to use. Typically this client will be a
* WebViewClient (or extend the latter). If not this client must have
* the same API as WebViewClient. Additionally this client view must
* implement the DriverProvider interface.
*/
public ViewClientWrapper(String className, Object client) {
this.className = className;
this.client = client;
}
/* package */ Class getClassForUnderlyingClient() {
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
throw new WebDriverException("Failed to get class for underlying view with class name: "
+ className, e);
}
}
/* package */ Object getUnderlyingClient() {
return client;
}
public void setDriver(AndroidWebDriver driver) {
- Class[] argsClass = {AndroidWebDriver.class};
- Object[] args = {driver};
- ReflexionHelper.invoke(client, "setDriver", argsClass, args);
+ try {
+ ((DefaultViewClient)client).setDriver(driver);
+ } catch (ClassCastException e) {
+ Class[] argsClass = {AndroidWebDriver.class};
+ Object[] args = {driver};
+ ReflexionHelper.invoke(client, "setDriver", argsClass, args);
+ }
}
}
| true | true | public void setDriver(AndroidWebDriver driver) {
Class[] argsClass = {AndroidWebDriver.class};
Object[] args = {driver};
ReflexionHelper.invoke(client, "setDriver", argsClass, args);
}
| public void setDriver(AndroidWebDriver driver) {
try {
((DefaultViewClient)client).setDriver(driver);
} catch (ClassCastException e) {
Class[] argsClass = {AndroidWebDriver.class};
Object[] args = {driver};
ReflexionHelper.invoke(client, "setDriver", argsClass, args);
}
}
|
diff --git a/srcj/com/sun/electric/tool/user/menus/FileMenu.java b/srcj/com/sun/electric/tool/user/menus/FileMenu.java
index 9b6668062..6f06f0cc3 100644
--- a/srcj/com/sun/electric/tool/user/menus/FileMenu.java
+++ b/srcj/com/sun/electric/tool/user/menus/FileMenu.java
@@ -1,1682 +1,1682 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: FileMenu.java
*
* Copyright (c) 2003 Sun Microsystems and Static Free Software
*
* Electric(tm) is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Electric(tm) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.user.menus;
import static com.sun.electric.tool.user.menus.EMenuItem.SEPARATOR;
import com.sun.electric.database.IdMapper;
import com.sun.electric.database.Snapshot;
import com.sun.electric.database.geometry.PolyBase;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.hierarchy.EDatabase;
import com.sun.electric.database.hierarchy.Library;
import com.sun.electric.database.hierarchy.View;
import com.sun.electric.database.text.Setting;
import com.sun.electric.database.text.TextUtils;
import com.sun.electric.database.variable.EditWindow_;
import com.sun.electric.database.variable.VarContext;
import com.sun.electric.technology.Layer;
import com.sun.electric.tool.Client;
import com.sun.electric.tool.Job;
import com.sun.electric.tool.JobException;
import com.sun.electric.tool.JobManager;
import com.sun.electric.tool.cvspm.CVS;
import com.sun.electric.tool.cvspm.Commit;
import com.sun.electric.tool.cvspm.Edit;
import com.sun.electric.tool.cvspm.Update;
import com.sun.electric.tool.io.FileType;
import com.sun.electric.tool.io.IOTool;
import com.sun.electric.tool.io.input.GDSMap;
import com.sun.electric.tool.io.input.Input;
import com.sun.electric.tool.io.input.LibraryFiles;
import com.sun.electric.tool.io.output.Output;
import com.sun.electric.tool.io.output.PostScript;
import com.sun.electric.tool.project.AddCellJob;
import com.sun.electric.tool.project.AddLibraryJob;
import com.sun.electric.tool.project.CancelCheckOutJob;
import com.sun.electric.tool.project.CheckInJob;
import com.sun.electric.tool.project.CheckOutJob;
import com.sun.electric.tool.project.DeleteCellJob;
import com.sun.electric.tool.project.HistoryDialog;
import com.sun.electric.tool.project.LibraryDialog;
import com.sun.electric.tool.project.UpdateJob;
import com.sun.electric.tool.simulation.Simulation;
import com.sun.electric.tool.user.ActivityLogger;
import com.sun.electric.tool.user.CircuitChangeJobs;
import com.sun.electric.tool.user.CircuitChanges;
import com.sun.electric.tool.user.Clipboard;
import com.sun.electric.tool.user.User;
import com.sun.electric.tool.user.dialogs.ChangeCurrentLib;
import com.sun.electric.tool.user.dialogs.OpenFile;
import com.sun.electric.tool.user.dialogs.OptionReconcile;
import com.sun.electric.tool.user.dialogs.ProjectSettingsFrame;
import com.sun.electric.tool.user.projectSettings.ProjSettings;
import com.sun.electric.tool.user.ui.*;
import com.sun.electric.tool.user.waveform.WaveformWindow;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.HeadlessException;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.Rectangle2D;
import java.awt.print.PageFormat;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.prefs.BackingStoreException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.RepaintManager;
import javax.swing.SwingUtilities;
/**
* Class to handle the commands in the "File" pulldown menu.
*/
public class FileMenu {
static EMenu makeMenu() {
/****************************** THE FILE MENU ******************************/
// mnemonic keys available: D T WXYZ
return new EMenu("_File",
new EMenuItem("_New Library...") { public void run() {
newLibraryCommand(); }},
ToolBar.openLibraryCommand, // O
// mnemonic keys available: A F HIJK NO QR VW YZ
new EMenu("_Import",
new EMenuItem("_CIF (Caltech Intermediate Format)...") { public void run() {
importLibraryCommand(FileType.CIF); }},
new EMenuItem("_GDS II (Stream)...") { public void run() {
importLibraryCommand(FileType.GDS); }},
new EMenuItem("GDS _Map File...") { public void run() {
GDSMap.importMapFile(); }},
new EMenuItem("_EDIF (Electronic Design Interchange Format)...") { public void run() {
importLibraryCommand(FileType.EDIF); }},
new EMenuItem("_LEF (Library Exchange Format)...") { public void run() {
importLibraryCommand(FileType.LEF); }},
new EMenuItem("_DEF (Design Exchange Format)...") { public void run() {
importLibraryCommand(FileType.DEF); }},
new EMenuItem("_DEF (Design Exchange Format) to current cell...") { public void run() {
importToCurrentCellCommand(FileType.DEF); }},
new EMenuItem("D_XF (AutoCAD)...") { public void run() {
importLibraryCommand(FileType.DXF); }},
new EMenuItem("S_UE (Schematic User Environment)...") { public void run() {
importLibraryCommand(FileType.SUE); }},
new EMenuItem("_Verilog...") { public void run() {
importLibraryCommand(FileType.VERILOG); }},
IOTool.hasDais() ? new EMenuItem("Dais (_Sun CAD)...") { public void run() {
importLibraryCommand(FileType.DAIS); }} : null,
IOTool.hasDais() ? new EMenuItem("Dais (_Sun CAD) to current library...") { public void run() {
importToCurrentCellCommand(FileType.DAIS); }} : null,
SEPARATOR,
new EMenuItem("ELI_B...") { public void run() {
importLibraryCommand(FileType.ELIB); }},
new EMenuItem("_Readable Dump...") { public void run() {
importLibraryCommand(FileType.READABLEDUMP); }},
new EMenuItem("_Text Cell Contents...") { public void run() {
TextWindow.readTextCell(); }},
new EMenuItem("_Preferences...") { public void run() {
Job.getUserInterface().importPrefs(); }},
new EMenuItem("Project Settings...") { public void run() {
ProjSettings.importSettings(); }},
new EMenuItem("XML Error Logger...") { public void run() {
ErrorLoggerTree.importLogger(); }}
),
SEPARATOR,
new EMenuItem("_Close Library") { public void run() {
closeLibraryCommand(Library.getCurrent()); }},
ToolBar.saveLibraryCommand, // V
new EMenuItem("Save Library _As...") { public void run() {
if (checkInvariants()) saveAsLibraryCommand(Library.getCurrent()); }},
new EMenuItem("_Save All Libraries", 'S') { public void run() {
if (checkInvariants()) saveAllLibrariesCommand(); }},
new EMenuItem("Save All Libraries in _Format...") { public void run() {
if (checkInvariants()) saveAllLibrariesInFormatCommand(); }},
// mnemonic keys available: D J M Q UVWVYZ
new EMenu("_Export",
new EMenuItem("_CIF (Caltech Intermediate Format)...") { public void run() {
exportCommand(FileType.CIF, false); }},
new EMenuItem("_GDS II (Stream)...") { public void run() {
exportCommand(FileType.GDS, false); }},
new EMenuItem("ED_IF (Electronic Design Interchange Format)...") { public void run() {
exportCommand(FileType.EDIF, false); }},
new EMenuItem("LE_F (Library Exchange Format)...") { public void run() {
exportCommand(FileType.LEF, false); }},
new EMenuItem("_L...") { public void run() {
exportCommand(FileType.L, false); }},
IOTool.hasSkill() ? new EMenuItem("S_kill (Cadence Commands)...") { public void run() {
exportCommand(FileType.SKILL, false); }} : null,
IOTool.hasSkill() ? new EMenuItem("Skill Exports _Only (Cadence Commands)...") { public void run() {
exportCommand(FileType.SKILLEXPORTSONLY, false); }} : null,
SEPARATOR,
new EMenuItem("_Eagle...") { public void run() {
exportCommand(FileType.EAGLE, false); }},
new EMenuItem("EC_AD...") { public void run() {
exportCommand(FileType.ECAD, false); }},
new EMenuItem("Pad_s...") { public void run() {
exportCommand(FileType.PADS, false); }},
SEPARATOR,
new EMenuItem("_Text Cell Contents...") { public void run() {
TextWindow.writeTextCell(); }},
new EMenuItem("_PostScript...") { public void run() {
exportCommand(FileType.POSTSCRIPT, false); }},
new EMenuItem("P_NG (Portable Network Graphics)...") { public void run() {
exportCommand(FileType.PNG, false); }},
new EMenuItem("_HPGL...") { public void run() {
exportCommand(FileType.HPGL, false); }},
new EMenuItem("D_XF (AutoCAD)...") { public void run() {
exportCommand(FileType.DXF, false); }},
SEPARATOR,
new EMenuItem("ELI_B (Version 6)...") { public void run() {
saveLibraryCommand(Library.getCurrent(), FileType.ELIB, true, false, false); }},
- new EMenuItem(Job.getDebug() ? "_JELIB (Version 8.04k)" : "_JELIB (Version 8.03)") { public void run() {
+ new EMenuItem("_JELIB (Version 8.03)...") { public void run() { // really since 8.04k
saveOldJelib(); }},
new EMenuItem("P_references...") { public void run() {
Job.getUserInterface().exportPrefs(); }},
new EMenuItem("Project Settings...") { public void run() {
ProjSettings.exportSettings(); }}
),
SEPARATOR,
new EMenuItem("Change Current _Library...") { public void run() {
ChangeCurrentLib.showDialog(); }},
new EMenuItem("List Li_braries") { public void run() {
CircuitChanges.listLibrariesCommand(); }},
new EMenuItem("Rena_me Library...") { public void run() {
CircuitChanges.renameLibrary(Library.getCurrent()); }},
new EMenuItem("Mar_k All Libraries for Saving") { public void run() {
CircuitChangeJobs.markAllLibrariesForSavingCommand(); }},
// mnemonic keys available: AB DEFGHIJKLMNOPQ STUVWXYZ
new EMenu("C_heck Libraries",
new EMenuItem("_Check") { public void run() {
CircuitChanges.checkAndRepairCommand(false); }},
new EMenuItem("_Repair") { public void run() {
CircuitChanges.checkAndRepairCommand(true); }}),
SEPARATOR,
// mnemonic keys available: C EFG JK MN PQ ST VWXYZ
new EMenu("P_roject Management",
new EMenuItem("_Update") { public void run() {
UpdateJob.updateProject(); }},
new EMenuItem("Check _Out This Cell") { public void run() {
CheckOutJob.checkOutThisCell(); }},
new EMenuItem("Check _In This Cell...") { public void run() {
CheckInJob.checkInThisCell(); }},
SEPARATOR,
new EMenuItem("Roll_back and Release Check-Out") { public void run() {
CancelCheckOutJob.cancelCheckOutThisCell(); }},
new EMenuItem("_Add This Cell") { public void run() {
AddCellJob.addThisCell(); }},
new EMenuItem("_Remove This Cell") { public void run() {
DeleteCellJob.removeThisCell(); }},
new EMenuItem("Show _History of This Cell...") { public void run() {
HistoryDialog.examineThisHistory(); }},
SEPARATOR,
new EMenuItem("Get Library From Repository...") { public void run() {
LibraryDialog.getALibrary(); }},
new EMenuItem("Add Current _Library To Repository") { public void run() {
AddLibraryJob.addThisLibrary(); }},
new EMenuItem("Ad_d All Libraries To Repository") { public void run() {
AddLibraryJob.addAllLibraries(); }}),
// mnemonic keys available: ABCDEFGHIJKLMNOPQRSTUVWXYZ
new EMenu("C_VS",
new EMenuItem("Commit All Open Libraries") { public void run() {
Commit.commitAllLibraries(); }},
new EMenuItem("Update Open Libraries") { public void run() {
Update.updateOpenLibraries(Update.UPDATE); }},
new EMenuItem("Get Status Open Libraries") { public void run() {
Update.updateOpenLibraries(Update.STATUS); }},
new EMenuItem("List Editors Open Libraries") { public void run() {
Edit.listEditorsOpenLibraries(); }},
SEPARATOR,
new EMenuItem("Update Project Libraries") { public void run() {
Update.updateProject(Update.UPDATE); }},
new EMenuItem("Get Status Project Libraries") { public void run() {
Update.updateProject(Update.STATUS); }},
new EMenuItem("List Editors Project Libraries") { public void run() {
Edit.listEditorsProject(); }},
SEPARATOR,
new EMenuItem("Checkout From Repository") { public void run() {
CVS.checkoutFromRepository(); }})
{
@Override
public boolean isEnabled() { return CVS.isEnabled(); }
@Override
protected void registerItem() {
super.registerItem();
registerUpdatable();
}
},
SEPARATOR,
new EMenuItem("Pa_ge Setup...") { public void run() {
pageSetupCommand(); }},
new EMenuItem("_Print...") { public void run() {
printCommand(); }},
SEPARATOR,
ToolBar.preferencesCommand, // R
new EMenuItem("Pro_ject Settings...") { public void run() {
ProjectSettingsFrame.projectSettingsCommand(); }},
SEPARATOR,
!Client.isOSMac() ? new EMenuItem("_Quit", 'Q') { public void run() {
quitCommand(); }} : null,
new EMenuItem("Force Q_uit (and Save)") { public void run() {
forceQuit(); }});
}
// ------------------------------ File Menu -----------------------------------
public static void newLibraryCommand()
{
String newLibName = JOptionPane.showInputDialog("New Library Name", "");
if (newLibName == null) return;
new NewLibrary(newLibName);
}
private static class NewLibrary extends Job {
private String newLibName;
public NewLibrary(String newLibName) {
super("New Library", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.newLibName = newLibName;
startJob();
}
public boolean doIt() throws JobException
{
Library lib = Library.newInstance(newLibName, null);
if (lib == null) return false;
lib.setCurrent();
System.out.println("New "+lib+" created");
return true;
}
public void terminateOK()
{
EditWindow.repaintAll();
ToolBar.setSaveLibraryButton();
}
}
/**
* This method implements the command to read a library.
* It is interactive, and pops up a dialog box.
*/
public static void openLibraryCommand()
{
String fileName = OpenFile.chooseInputFile(FileType.LIBRARYFORMATS, null);
if (fileName != null)
{
// start a job to do the input
URL fileURL = TextUtils.makeURLToFile(fileName);
String libName = TextUtils.getFileNameWithoutExtension(fileURL);
Library deleteLib = Library.findLibrary(libName);
if (deleteLib != null)
{
// library already exists, prompt for save
if (FileMenu.preventLoss(deleteLib, 2)) return;
WindowFrame.removeLibraryReferences(deleteLib);
}
FileType type = getLibraryFormat(fileName, FileType.DEFAULTLIB);
new ReadLibrary(fileURL, type, TextUtils.getFilePath(fileURL), deleteLib, null);
}
}
/**
* This method implements the command to read a library.
* It takes library URL from a parameter.
* @param file URL of a library
*/
public static void openLibraryCommand(URL file)
{
String fileName = file.getFile();
FileType defType = getLibraryFormat(fileName, null);
if (defType == null) {
// no valid extension, search for file with extension
URL f = TextUtils.makeURLToFile(fileName + "." + FileType.JELIB.getExtensions()[0]);
if (TextUtils.URLExists(f, null)) {
defType = FileType.JELIB;
file = f;
}
}
if (defType == null) {
// no valid extension, search for file with extension
URL f = TextUtils.makeURLToFile(fileName + "." + FileType.ELIB.getExtensions()[0]);
if (TextUtils.URLExists(f, null)) {
defType = FileType.ELIB;
file = f;
}
}
if (defType == null) {
// no valid extension, search for file with extension
URL f = TextUtils.makeURLToFile(fileName + "." + FileType.DELIB.getExtensions()[0]);
if (TextUtils.URLExists(f, null)) {
defType = FileType.DELIB;
file = f;
}
}
if (defType == null) {
// no valid extension, search for file with extension
URL f = TextUtils.makeURLToFile(fileName + "." + FileType.READABLEDUMP.getExtensions()[0]);
if (TextUtils.URLExists(f, null)) {
defType = FileType.READABLEDUMP;
file = f;
}
}
if (defType == null) defType = FileType.DEFAULTLIB;
new ReadLibrary(file, defType, TextUtils.getFilePath(file), null, null);
}
/** Get the type from the fileName, or if no valid Library type found, return defaultType.
*/
public static FileType getLibraryFormat(String fileName, FileType defaultType) {
if (fileName != null)
{
if (fileName.endsWith(File.separator)) {
fileName = fileName.substring(0, fileName.length()-File.separator.length());
}
for (FileType type : FileType.libraryTypes)
{
if (fileName.endsWith("."+type.getExtensions()[0])) return type;
}
}
return defaultType;
}
/**
* Class to read a library in a new thread.
* For a non-interactive script, use ReadLibrary job = new ReadLibrary(filename, format).
*/
public static class ReadLibrary extends Job
{
private URL fileURL;
private FileType type;
private File projsettings;
private Library deleteLib;
private String cellName; // cell to view once the library is open
private Library lib;
public ReadLibrary(URL fileURL, FileType type, Library deleteLib, String cellName) {
this(fileURL, type, null, deleteLib, cellName);
}
public ReadLibrary(URL fileURL, FileType type, String settingsDirectory, Library deleteLib, String cellName)
{
super("Read External Library", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.fileURL = fileURL;
this.type = type;
this.deleteLib = deleteLib;
this.cellName = cellName;
Map<Setting,Object> projectSettings = null;
if (settingsDirectory != null) {
projsettings = new File(settingsDirectory, "projsettings.xml");
if (!projsettings.exists())
projsettings = null;
}
if (projsettings == null) {
projectSettings = LibraryFiles.readProjectsSettingsFromLibrary(fileURL, type);
if (projectSettings != null) {
Map<Setting,Object> settingsToReconcile = Setting.reconcileSettings(projectSettings);
if (!settingsToReconcile.isEmpty()) {
String libName = TextUtils.getFileNameWithoutExtension(fileURL);
OptionReconcile dialog = new OptionReconcile(TopLevel.getCurrentJFrame(), settingsToReconcile, libName, this);
dialog.setVisible(true);
return; // startJob will be executed by reconcilation dialog
}
}
}
startJob();
}
public boolean doIt() throws JobException
{
// see if the former library can be deleted
if (deleteLib != null)
{
if (!deleteLib.kill("replace")) return false;
deleteLib = null;
}
// read project settings
if (projsettings != null)
ProjSettings.readSettings(projsettings, false);
lib = LibraryFiles.readLibrary(fileURL, null, type, false);
if (lib == null) return false;
fieldVariableChanged("lib");
// new library open: check for default "noname" library and close if empty
Library noname = Library.findLibrary("noname");
if (noname != null) {
// Only when noname is not exactly the library read that could be empty
if (noname == lib)
{
// Making sure the URL is propoerly setup since the dummy noname library is
// retrieved from LibraryFiles.readLibrary()
if (lib.getLibFile() == null)
lib.setLibFile(fileURL);
}
else if (!noname.getCells().hasNext()) {
noname.kill("delete");
}
}
User.setCurrentLibrary(lib);
return true;
}
public void terminateOK()
{
Cell showThisCell = (cellName != null) ?
lib.findNodeProto(cellName) :
Job.getUserInterface().getCurrentCell(lib);
doneOpeningLibrary(showThisCell);
// Repair libraries.
CircuitChanges.checkAndRepairCommand(true);
}
}
/**
* Class to import a library in a new thread.
*/
public static class ImportLibrary extends Job
{
private URL fileURL;
private FileType type;
private Library createLib;
private Library deleteLib;
private boolean useCurrentLib;
private long startMemory, startTime;
public ImportLibrary(URL fileURL, FileType type, Library deleteLib)
{
super("Import External Library", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.fileURL = fileURL;
this.type = type;
this.deleteLib = deleteLib;
this.useCurrentLib = false;
if (type == FileType.DAIS)
{
startTime = System.currentTimeMillis();
startMemory = com.sun.electric.Main.getMemoryUsage();
}
startJob();
}
// this version imports to current library
public ImportLibrary(URL fileURL, FileType type)
{
super("Import to Current Library", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.fileURL = fileURL;
this.type = type;
this.deleteLib = null;
this.useCurrentLib = true;
startJob();
}
public boolean doIt() throws JobException
{
// see if the former library can be deleted
if (deleteLib != null)
{
if (!deleteLib.kill("replace")) return false;
deleteLib = null;
}
if (useCurrentLib) {
createLib = Input.importToCurrentLibrary(fileURL, type);
} else {
createLib = Input.importLibrary(fileURL, type);
}
if (createLib == null) return false;
// new library open: check for default "noname" library and close if empty
Library noname = Library.findLibrary("noname");
if (noname != null)
{
if (!noname.getCells().hasNext())
{
noname.kill("delete");
}
}
fieldVariableChanged("createLib");
return true;
}
public void terminateOK()
{
User.setCurrentLibrary(createLib);
Cell showThisCell = Job.getUserInterface().getCurrentCell(createLib);
doneOpeningLibrary(showThisCell);
if (type == FileType.DAIS)
{
long endTime = System.currentTimeMillis();
float finalTime = (endTime - startTime) / 1000F;
long end = com.sun.electric.Main.getMemoryUsage();
long amt = (end-startMemory)/1024/1024;
System.out.println("*** DAIS INPUT TOOK " + finalTime + " seconds, " + amt + " megabytes");
}
}
}
/**
* Method to clean up from opening a library.
* Called from the "terminateOK()" method of a job.
*/
private static void doneOpeningLibrary(final Cell cell)
{
if (cell == null) System.out.println("No current cell in this library");
else if (!Job.BATCHMODE)
{
CreateCellWindow creator = new CreateCellWindow(cell);
if (!SwingUtilities.isEventDispatchThread()) {
SwingUtilities.invokeLater(creator);
} else {
creator.run();
}
}
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
// Redo explorer trees to add new library
WindowFrame.wantToRedoLibraryTree();
WindowFrame.wantToOpenCurrentLibrary(true, cell);
}});
}
/**
* Class to display a new window.
*/
public static class CreateCellWindow implements Runnable {
private Cell cell;
public CreateCellWindow(Cell cell) { this.cell = cell; }
public void run() {
// check if edit window open with null cell, use that one if exists
for (Iterator<WindowFrame> it = WindowFrame.getWindows(); it.hasNext(); )
{
WindowFrame wf = it.next();
WindowContent content = wf.getContent();
if (content.getCell() == null)
{
wf.setCellWindow(cell, null);
//wf.requestFocus();
ToolBar.setSaveLibraryButton();
return;
}
}
WindowFrame.createEditWindow(cell);
// no clean for now.
ToolBar.setSaveLibraryButton();
}
}
/**
* This method implements the command to import a file to a library
* It is interactive, and pops up a dialog box.
*/
public static void importToCurrentCellCommand(FileType type)
{
String fileName = null;
if (type == FileType.DAIS)
{
fileName = OpenFile.chooseDirectory(type.getDescription());
} else
{
fileName = OpenFile.chooseInputFile(type, null);
}
if (fileName != null)
{
// start a job to do the input
URL fileURL = TextUtils.makeURLToFile(fileName);
//import to the current library
new ImportLibrary(fileURL, type);
}
}
/**
* This method implements the command to import a library (Readable Dump or JELIB format).
* It is interactive, and pops up a dialog box.
*/
public static void importLibraryCommand(FileType type)
{
String fileName = null;
if (type == FileType.DAIS)
{
fileName = OpenFile.chooseDirectory(type.getDescription());
} else
{
fileName = OpenFile.chooseInputFile(type, null);
}
if (fileName != null)
{
// start a job to do the input
URL fileURL = TextUtils.makeURLToFile(fileName);
String libName = TextUtils.getFileNameWithoutExtension(fileURL);
Library deleteLib = Library.findLibrary(libName);
if (deleteLib != null)
{
// library already exists, prompt for save
if (FileMenu.preventLoss(deleteLib, 2)) return;
WindowFrame.removeLibraryReferences(deleteLib);
}
if (type == FileType.ELIB || type == FileType.READABLEDUMP)
new ReadLibrary(fileURL, type, deleteLib, null);
else
new ImportLibrary(fileURL, type, deleteLib);
}
}
public static void closeLibraryCommand(Library lib)
{
if (lib == null) return;
Set<Cell> found = Library.findReferenceInCell(lib);
// if all references are from the clipboard, request that the clipboard be cleared, too
boolean clearClipboard = false, nonClipboard = false;
for (Cell cell : found)
{
if (cell.getLibrary().isHidden()) clearClipboard = true; else
nonClipboard = true;
}
// You can't close it because there are open cells that refer to library elements
if (nonClipboard)
{
System.out.println("Cannot close " + lib + ":");
System.out.print("\t Cells ");
for (Cell cell : found)
{
System.out.print("'" + cell.getName() + "'(" + cell.getLibrary().getName() + ") ");
}
System.out.println("refer to it.");
return;
}
if (preventLoss(lib, 1)) return;
WindowFrame.removeLibraryReferences(lib);
new CloseLibrary(lib, clearClipboard);
}
private static class CloseLibrary extends Job {
private Library lib;
private boolean clearClipboard;
public CloseLibrary(Library lib, boolean clearClipboard) {
super("Close "+lib, User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.lib = lib;
this.clearClipboard = clearClipboard;
startJob();
}
public boolean doIt() throws JobException {
if (clearClipboard)
{
Clipboard.clear();
}
if (lib.kill("delete"))
{
System.out.println("Library '" + lib.getName() + "' closed");
}
return true;
}
public void terminateOK()
{
// set some other library to be current
if (Library.getCurrent() == null)
{
List<Library> remainingLibs = Library.getVisibleLibraries();
if (remainingLibs.size() > 0)
User.setCurrentLibrary(remainingLibs.get(0));
}
WindowFrame.wantToRedoTitleNames();
EditWindow.repaintAll();
// Disable save icon if no more libraries are open
ToolBar.setSaveLibraryButton();
}
}
/**
* This method implements the command to save a library.
* It is interactive, and pops up a dialog box.
* @param lib the Library to save.
* @return true if library saved, false otherwise.
*/
public static boolean saveLibraryCommand(Library lib) {
return lib != null && saveLibraryCommand(lib, FileType.DEFAULTLIB, false, true, false);
}
/**
* This method implements the command to save a library.
* It is interactive, and pops up a dialog box.
* @param lib the Library to save.
* @param type the format of the library (OpenFile.Type.ELIB, OpenFile.Type.READABLEDUMP, or OpenFile.Type.JELIB).
* @param compatibleWith6 true to write a library that is compatible with version 6 Electric.
* @param forceToType
* @param saveAs true if this is a "save as" and should always prompt for a file name.
* @return true if library saved, false otherwise.
*/
public static boolean saveLibraryCommand(Library lib, FileType type, boolean compatibleWith6, boolean forceToType, boolean saveAs)
{
// scan for Dummy Cells, warn user that they still exist
List<String> dummyCells = new ArrayList<String>();
dummyCells.add("WARNING: "+lib+" contains the following Dummy cells:");
for (Iterator<Cell> it = lib.getCells(); it.hasNext(); ) {
Cell c = it.next();
if (c.getVar(LibraryFiles.IO_DUMMY_OBJECT) != null) {
dummyCells.add(" "+c.noLibDescribe());
}
}
if (dummyCells.size() > 1) {
dummyCells.add("Do you really want to write this library?");
String [] options = {"Continue Writing", "Cancel" };
String message = dummyCells.toString();
int val = Job.getUserInterface().askForChoice(message,
"Dummy Cells Found in "+lib, options, options[1]);
if (val == 1) return false;
}
String [] extensions = type.getExtensions();
String extension = extensions[0];
String fileName = null;
if (!saveAs && lib.isFromDisk())
{
if (type == FileType.JELIB || type == FileType.DELIB ||
(type == FileType.ELIB && !compatibleWith6))
{
fileName = lib.getLibFile().getPath();
if (forceToType)
{
type = OpenFile.getOpenFileType(fileName, FileType.DEFAULTLIB);
}
}
// check to see that file is writable
if (fileName != null) {
File file = new File(fileName);
if (file.exists() && !file.canWrite()) fileName = null;
/*
try {
if (!file.createNewFile()) fileName = null;
} catch (java.io.IOException e) {
System.out.println(e.getMessage());
fileName = null;
}
*/
}
}
if (fileName == null)
{
fileName = OpenFile.chooseOutputFile(FileType.libraryTypes, null, lib.getName() + "." + extension);
if (fileName == null) return false;
type = getLibraryFormat(fileName, type);
// // mark for saving, all libraries that depend on this
// for(Iterator<Library> it = Library.getLibraries(); it.hasNext(); )
// {
// Library oLib = it.next();
// if (oLib.isHidden()) continue;
// if (oLib == lib) continue;
// if (oLib.isChangedMajor()) continue;
//
// // see if any cells in this library reference the renamed one
// if (oLib.referencesLib(lib))
// oLib.setChanged();
// }
}
// save the library
new SaveLibrary(lib, fileName, type, compatibleWith6);
return true;
}
private static void saveOldJelib() {
String currentDir = User.getWorkingDirectory();
System.out.println("Saving libraries in oldJelib directory under " + currentDir); System.out.flush();
File oldJelibDir = new File(currentDir, "oldJelib");
if (!oldJelibDir.exists() && !oldJelibDir.mkdir()) {
JOptionPane.showMessageDialog(TopLevel.getCurrentJFrame(), new String [] {"Could not create oldJelib directory",
oldJelibDir.getAbsolutePath()}, "Error creating oldJelib directory", JOptionPane.ERROR_MESSAGE);
return;
}
Output.writePanicSnapshot(EDatabase.clientDatabase().backupUnsafe(), oldJelibDir, true);
}
/**
* Class to save a library in a new thread.
* For a non-interactive script, use SaveLibrary job = new SaveLibrary(filename).
* Saves as an elib.
*/
private static class SaveLibrary extends Job
{
private Library lib;
private String newName;
private FileType type;
private boolean compatibleWith6;
private IdMapper idMapper;
public SaveLibrary(Library lib, String newName, FileType type, boolean compatibleWith6)
{
super("Write "+lib, User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER); // CHANGE because of possible renaming
this.lib = lib;
this.newName = newName;
this.type = type;
this.compatibleWith6 = compatibleWith6;
startJob();
}
public boolean doIt() throws JobException
{
boolean success = false;
try
{
// rename the library if requested
if (newName != null) {
URL libURL = TextUtils.makeURLToFile(newName);
lib.setLibFile(libURL);
idMapper = lib.setName(TextUtils.getFileNameWithoutExtension(libURL));
if (idMapper != null)
lib = EDatabase.serverDatabase().getLib(idMapper.get(lib.getId()));
}
fieldVariableChanged("idMapper");
success = !Output.writeLibrary(lib, type, compatibleWith6, false, false);
} catch (Exception e)
{
e.printStackTrace(System.out);
throw new JobException("Exception caught when saving files: " +
e.getMessage() + "Please check your disk libraries");
}
if (!success)
throw new JobException("Error saving files. Please check your disk libraries");
return success;
}
public void terminateOK() {
User.fixStaleCellReferences(idMapper);
}
}
/**
* This method implements the command to save a library to a different file.
* It is interactive, and pops up a dialog box.
*/
public static void saveAsLibraryCommand(Library lib)
{
saveLibraryCommand(lib, FileType.DEFAULTLIB, false, true, true);
WindowFrame.wantToRedoTitleNames();
}
/**
* This method implements the command to save all libraries.
*/
public static void saveAllLibrariesCommand()
{
saveAllLibrariesCommand(FileType.DEFAULTLIB, false, true);
}
public static void saveAllLibrariesCommand(FileType type, boolean compatibleWith6, boolean forceToType)
{
HashMap<Library,FileType> libsToSave = new HashMap<Library,FileType>();
for(Iterator<Library> it = Library.getLibraries(); it.hasNext(); )
{
Library lib = it.next();
if (lib.isHidden()) continue;
if (!lib.isChanged()) continue;
if (lib.getLibFile() != null)
type = getLibraryFormat(lib.getLibFile().getFile(), type);
libsToSave.put(lib, type);
}
boolean justSkip = false;
for(Iterator<Library> it = libsToSave.keySet().iterator(); it.hasNext(); )
{
Library lib = it.next();
type = libsToSave.get(lib);
if (!saveLibraryCommand(lib, type, compatibleWith6, forceToType, false))
{
if (justSkip) continue;
if (it.hasNext())
{
String [] options = {"Cancel", "Skip this Library"};
int ret = JOptionPane.showOptionDialog(TopLevel.getCurrentJFrame(),
"Cancel all library saving, or just skip saving this library?", "Save Cancelled",
JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, "Cancel");
if (ret == 1) { justSkip = true; continue; }
}
break;
}
}
}
public static void saveAllLibrariesInFormatCommand() {
Object[] formats = {FileType.JELIB, FileType.ELIB, FileType.READABLEDUMP, FileType.DELIB};
Object format = JOptionPane.showInputDialog(TopLevel.getCurrentJFrame(),
"Output file format for all libraries:", "Save All Libraries In Format...",
JOptionPane.PLAIN_MESSAGE,
null, formats, FileType.DEFAULTLIB);
if (format == null) return; // cancel operation
FileType outType = (FileType)format;
new SaveAllLibrariesInFormatJob(outType);
}
public static class SaveAllLibrariesInFormatJob extends Job {
private FileType outType;
public SaveAllLibrariesInFormatJob(FileType outType) {
super("Save All Libraries", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.outType = outType;
startJob();
}
public boolean doIt() {
for (Iterator<Library> it = Library.getLibraries(); it.hasNext(); ) {
Library lib = it.next();
if (lib.isHidden()) continue;
if (!lib.isFromDisk()) continue;
if (lib.getLibFile() != null) {
// set library file to new format
String fullName = lib.getLibFile().getFile();
//if (fullName.endsWith("spiceparts.txt")) continue; // ignore spiceparts library
// match ".<word><endline>"
fullName = fullName.replaceAll("\\.\\w*?$", "."+outType.getExtensions()[0]);
lib.setLibFile(TextUtils.makeURLToFile(fullName));
}
lib.setChanged();
}
saveAllLibrariesCommand(outType, false, false);
return true;
}
}
/**
* This method checks database invariants.
* @return true if database is valid or user forced saving.
*/
private static boolean checkInvariants()
{
// // check database invariants
// if (!EDatabase.clientDatabase().checkInvariants())
// {
// String [] messages = {
// "Database invariants are not valid",
// "You may use \"Force Quit (and Save)\" to save in a panic directory",
// "Do you really want to write libraries into the working directory?"};
// Object [] options = {"Continue Writing", "Cancel", "ForceQuit" };
// int val = JOptionPane.showOptionDialog(TopLevel.getCurrentJFrame(), messages,
// "Invalid database invariants", JOptionPane.DEFAULT_OPTION,
// JOptionPane.WARNING_MESSAGE, null, options, options[1]);
// if (val == 1) return false;
// if (val == 2)
// {
// forceQuit();
// return false;
// }
// }
return true;
}
/**
* This method implements the export cell command for different export types.
* It is interactive, and pops up a dialog box.
*/
public static void exportCommand(FileType type, boolean isNetlist)
{
// synchronization of PostScript is done first because no window is needed
if (type == FileType.POSTSCRIPT)
{
if (PostScript.syncAll()) return;
}
WindowFrame wf = WindowFrame.getCurrentWindowFrame(false);
WindowContent wnd = (wf != null) ? wf.getContent() : null;
if (wnd == null)
{
System.out.println("No current window");
return;
}
Cell cell = wnd.getCell();
if (cell == null)
{
System.out.println("No cell in this window");
return;
}
VarContext context = (wnd instanceof EditWindow) ? ((EditWindow)wnd).getVarContext() : null;
List<PolyBase> override = null;
if (type == FileType.POSTSCRIPT)
{
if (cell.getView() == View.DOC)
{
System.out.println("Document cells can't be exported as postscript.");
JOptionPane.showMessageDialog(TopLevel.getCurrentJFrame(), "Document cells can't be exported as postscript.\n" +
"Try \"Export -> Text Cell Contents\"",
"Exporting PS", JOptionPane.ERROR_MESSAGE);
return;
}
if (IOTool.isPrintEncapsulated()) type = FileType.EPS;
if (wnd instanceof WaveformWindow)
{
// waveform windows provide a list of polygons to print
WaveformWindow ww = (WaveformWindow)wnd;
override = ww.getPolysForPrinting();
}
}
String [] extensions = type.getExtensions();
String filePath = cell.getName() + "." + extensions[0];
// special case for spice
if (type == FileType.SPICE &&
!Simulation.getSpiceRunChoice().equals(Simulation.spiceRunChoiceDontRun))
{
// check if user specified working dir
if (Simulation.getSpiceUseRunDir())
filePath = Simulation.getSpiceRunDir() + File.separator + filePath;
else
filePath = User.getWorkingDirectory() + File.separator + filePath;
// check for automatic overwrite
if (User.isShowFileSelectionForNetlists() && !Simulation.getSpiceOutputOverwrite()) {
String saveDir = User.getWorkingDirectory();
filePath = OpenFile.chooseOutputFile(type, null, filePath);
User.setWorkingDirectory(saveDir);
if (filePath == null) return;
}
Output.exportCellCommand(cell, context, filePath, type, override);
return;
}
if (User.isShowFileSelectionForNetlists() || !isNetlist)
{
filePath = OpenFile.chooseOutputFile(type, null, filePath);
if (filePath == null) return;
} else
{
filePath = User.getWorkingDirectory() + File.separator + filePath;
}
// Special case for PNG format
if (type == FileType.PNG)
{
new ExportImage(cell.toString(), wnd, filePath);
return;
}
Output.exportCellCommand(cell, context, filePath, type, override);
}
private static class ExportImage extends Job
{
private String filePath;
private WindowContent wnd;
public ExportImage(String description, WindowContent wnd, String filePath)
{
super("Export "+description+" ("+FileType.PNG+")", User.getUserTool(), Job.Type.EXAMINE, null, null, Job.Priority.USER);
this.wnd = wnd;
this.filePath = filePath;
startJob();
}
public boolean doIt() throws JobException
{
PrinterJob pj = PrinterJob.getPrinterJob();
ElectricPrinter ep = getOutputPreferences(wnd, pj);
// Export has to be done in same thread as offscreen raster (valid for 3D at least)
wnd.writeImage(ep, filePath);
// BufferedImage img = wnd.getOffScreenImage(ep);
// PNG.writeImage(img, filePath);
return true;
}
}
private static PageFormat pageFormat = null;
public static void pageSetupCommand() {
PrinterJob pj = PrinterJob.getPrinterJob();
if (pageFormat == null)
pageFormat = pj.pageDialog(pj.defaultPage());
else
pageFormat = pj.pageDialog(pageFormat);
}
private static ElectricPrinter getOutputPreferences(WindowContent context, PrinterJob pj)
{
if (pageFormat == null)
{
pageFormat = pj.defaultPage();
pageFormat.setOrientation(PageFormat.LANDSCAPE);
pageFormat = pj.validatePage(pageFormat);
}
ElectricPrinter ep = new ElectricPrinter(context, pageFormat, pj);
pj.setPrintable(ep, pageFormat);
return (ep);
}
/**
* This method implements the command to print the current window.
*/
public static void printCommand()
{
WindowFrame wf = WindowFrame.getCurrentWindowFrame();
if (wf == null)
{
System.out.println("No current window to print");
return;
}
Cell cell = WindowFrame.needCurCell();
if (cell == null) return;
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setJobName(wf.getTitle());
PrintService [] printers = new PrintService[0];
try
{
SecurityManager secman = System.getSecurityManager();
secman.checkPrintJobAccess();
// printers = PrinterJob.lookupPrintServices();
printers = PrintServiceLookup.lookupPrintServices(null, null);
} catch(Exception e) {}
// see if a default printer should be mentioned
String pName = IOTool.getPrinterName();
PrintService printerToUse = null;
for(PrintService printer : printers)
{
if (pName.equals(printer.getName()))
{
printerToUse = printer;
break;
}
}
if (printerToUse != null)
{
try
{
pj.setPrintService(printerToUse);
} catch (PrinterException e)
{
System.out.println("Printing error " + e);
}
}
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
if (pj.printDialog(aset))
{
// disable double-buffering so prints look better
JPanel overall = wf.getContent().getPanel();
RepaintManager currentManager = RepaintManager.currentManager(overall);
currentManager.setDoubleBufferingEnabled(false);
ElectricPrinter ep = getOutputPreferences(wf.getContent(), pj);
Dimension oldSize = overall.getSize();
ep.setOldSize(oldSize);
// determine area to print
EditWindow_ wnd = null;
if (wf.getContent() instanceof EditWindow) wnd = (EditWindow_)wf.getContent();
Rectangle2D printBounds = Output.getAreaToPrint(cell, false, wnd);
ep.setRenderArea(printBounds);
// initialize for content-specific printing
if (!wf.getContent().initializePrinting(ep, pageFormat))
{
String message = "Problems initializing printers. Check printer setup.";
System.out.println(message);
JOptionPane.showMessageDialog(TopLevel.getCurrentJFrame(), message,
"Printing Cell", JOptionPane.ERROR_MESSAGE);
return;
}
printerToUse = pj.getPrintService();
if (printerToUse != null)
IOTool.setPrinterName(printerToUse.getName());
SwingUtilities.invokeLater(new PrintJobAWT(wf, pj, oldSize, aset));
}
}
private static class PrintJobAWT implements Runnable
{
private WindowFrame wf;
private PrinterJob pj;
private Dimension oldSize;
private PrintRequestAttributeSet aset;
PrintJobAWT(WindowFrame wf, PrinterJob pj, Dimension oldSize, PrintRequestAttributeSet aset)
{
this.wf = wf;
this.pj = pj;
this.oldSize = oldSize;
this.aset = aset;
}
public void run()
{
try {
pj.print(aset);
} catch (PrinterException pe)
{
System.out.println("Print aborted.");
}
JPanel overall = wf.getContent().getPanel();
RepaintManager currentManager = RepaintManager.currentManager(overall);
currentManager.setDoubleBufferingEnabled(true);
if (oldSize != null)
{
overall.setSize(oldSize);
overall.validate();
}
}
}
/**
* This method implements the command to quit Electric.
*/
public static boolean quitCommand()
{
if (preventLoss(null, 0)) return false;
try {
new QuitJob();
} catch (java.lang.NoClassDefFoundError e)
{
// Ignoring this one
return true;
} catch (Exception e)
{
// Don't quit in this case.
return false;
}
return true;
}
/**
* Class to clear the date information on a Cell.
* Used by regressions to reset date information so that files match.
*/
public static class ClearCellDate extends Job
{
private String cellName;
private Cell cell;
public ClearCellDate(String cellName)
{
super("Clear Cell Dates", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.cellName = cellName;
startJob();
}
public ClearCellDate(Cell cell)
{
super("Clear Cell Dates", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.cell = cell;
startJob();
}
public boolean doIt() throws JobException
{
if (cell == null && cellName != null)
cell = (Cell)Cell.findNodeProto(cellName);
if (cell != null)
{
cell.lowLevelSetRevisionDate(new Date(0));
cell.lowLevelSetCreationDate(new Date(0));
}
return true;
}
}
/**
* Class to quit Electric in a Job.
* The quit function is done in a Job so that it can force all other jobs to finish.
*/
public static class QuitJob extends Job
{
public QuitJob()
{
super("Quitting", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
startJob();
}
public boolean doIt() throws JobException
{
return true;
}
public void terminateOK()
{
try {
Library.saveExpandStatus();
} catch (BackingStoreException e)
{
int response = JOptionPane.showConfirmDialog(TopLevel.getCurrentJFrame(),
"Cannot save cell expand status. Do you still want to quit?", "Cell Status Error",
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (response != JOptionPane.YES_OPTION)
{
return;
}
}
// save changes to layer visibility
Layer.preserveVisibility();
// save changes to waveform window signals
WaveformWindow.preserveSignalOrder();
ActivityLogger.finished();
System.exit(0);
}
}
/**
* Method to ensure that one or more libraries are saved.
* @param desiredLib the library to check for being saved.
* If desiredLib is null, all libraries are checked.
* @param action the type of action that will occur:
* 0: quit;
* 1: close a library;
* 2: replace a library.
* @return true if the operation should be aborted;
* false to continue with the quit/close/replace.
*/
public static boolean preventLoss(Library desiredLib, int action)
{
boolean checkedInvariants = false;
boolean saveCancelled = false;
for(Iterator<Library> it = Library.getLibraries(); it.hasNext(); )
{
Library lib = it.next();
if (desiredLib != null && desiredLib != lib) continue;
if (lib.isHidden()) continue;
if (!lib.isChanged()) continue;
// Abort if database invariants are not valid
if (!checkedInvariants)
{
if (!checkInvariants()) return true;
checkedInvariants = true;
}
// warn about this library
String theAction = "Save before quitting?";
if (action == 1) theAction = "Save before closing?"; else
if (action == 2) theAction = "Save before replacing?";
String [] options = {"Yes", "No", "Cancel", "No to All"};
int ret = showFileMenuOptionDialog(TopLevel.getCurrentJFrame(),
"Library '" + lib.getName() + "' has changed. " + theAction,
"Save Library?", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
null, options, options[0], null);
if (ret == 0)
{
// save the library
if (!saveLibraryCommand(lib, FileType.DEFAULTLIB, false, true, false))
saveCancelled = true;
continue;
}
if (ret == 1) continue;
if (ret == 2 || ret == -1) return true;
if (ret == 3) break;
}
if (saveCancelled) return true;
return false;
}
/**
* Based on JOptionPane but allows ToolTip text
* @param parentComponent
* @param message
* @param title
* @param optionType
* @param messageType
* @param icon
* @param options
* @param initialValue
* @return the return value of the JOptionPane choice. Returns -1 if aborted
* @throws HeadlessException
*/
public static int showFileMenuOptionDialog(Component parentComponent,
Object message, String title, int optionType, int messageType,
Icon icon, Object[] options, Object initialValue, String toolTipMessage)
throws HeadlessException
{
JOptionPane pane = new JOptionPane(message, messageType, optionType, icon,
options, initialValue);
pane.setInitialValue(initialValue);
pane.setComponentOrientation(((parentComponent == null) ?
JOptionPane.getRootFrame() : parentComponent).getComponentOrientation());
pane.setMessageType(messageType);
JDialog dialog = pane.createDialog(parentComponent, title);
pane.selectInitialValue();
pane.setToolTipText(toolTipMessage);
dialog.setVisible(true);
dialog.dispose();
Object selectedValue = pane.getValue();
if(selectedValue == null)
return JOptionPane.CLOSED_OPTION;
if(options == null) {
if(selectedValue instanceof Integer)
return ((Integer)selectedValue); // using autoboxing
return JOptionPane.CLOSED_OPTION;
}
for(int counter = 0, maxCounter = options.length;
counter < maxCounter; counter++) {
if(options[counter].equals(selectedValue))
return counter;
}
return JOptionPane.CLOSED_OPTION;
}
static class CellMouseMotionAdapter extends MouseMotionAdapter {
JOptionPane pane;
CellMouseMotionAdapter(JOptionPane p) {
pane = p;}
public void mouseMoved(MouseEvent e) {
System.out.println(" Point " + pane.getToolTipLocation(e));}
}
/**
* Unsafe way to force Electric to quit. If this method returns,
* it obviously did not kill electric (because of user input or some other reason).
*/
public static void forceQuit() {
// check if libraries need to be saved
boolean dirty = false;
for(Iterator<Library> it = Library.getLibraries(); it.hasNext(); )
{
Library lib = it.next();
if (lib.isHidden()) continue;
if (!lib.isChanged()) continue;
dirty = true;
break;
}
if (dirty) {
String [] options = { "Force Save and Quit", "Cancel", "Quit without Saving"};
int i = JOptionPane.showOptionDialog(TopLevel.getCurrentJFrame(),
new String [] {"Warning! Libraries Changed! Saving changes now may create bad libraries!"},
"Force Quit", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null,
options, options[1]);
if (i == 0) {
// force save
if (!forceSave(false)) {
JOptionPane.showMessageDialog(TopLevel.getCurrentJFrame(),
"Error during forced library save, not quiting", "Saving Failed", JOptionPane.ERROR_MESSAGE);
return;
}
ActivityLogger.finished();
System.exit(1);
}
if (i == 1) return;
if (i == 2) {
ActivityLogger.finished();
System.exit(1);
}
}
int i = JOptionPane.showConfirmDialog(TopLevel.getCurrentJFrame(), new String [] {"Warning! You are about to kill Electric!",
"Do you really want to force quit?"}, "Force Quit", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (i == JOptionPane.YES_OPTION) {
ActivityLogger.finished();
System.exit(1);
}
}
/**
* Force saving of libraries. This does not run in a Job, and could generate corrupt libraries.
* This saves all libraries to a new directory called "panic" in the current directory.
* @param confirm true to pop up confirmation dialog, false to just try to save
* @return true if libraries saved (if they needed saving), false otherwise
*/
public static boolean forceSave(boolean confirm) {
if (confirm) {
String [] options = { "Cancel", "Force Save"};
int i = JOptionPane.showOptionDialog(TopLevel.getCurrentJFrame(),
new String [] {"Warning! Saving changes now may create bad libraries!",
"Libraries will be saved to \"Panic\" directory in current directory",
"Do you really want to force save?"},
"Force Save", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null,
options, options[0]);
if (i == 0) return false;
}
// try to create the panic directory
String currentDir = User.getWorkingDirectory();
System.out.println("Saving libraries in panic directory under " + currentDir); System.out.flush();
File panicDir = new File(currentDir, "panic");
if (!panicDir.exists() && !panicDir.mkdir()) {
JOptionPane.showMessageDialog(TopLevel.getCurrentJFrame(), new String [] {"Could not create panic directory",
panicDir.getAbsolutePath()}, "Error creating panic directory", JOptionPane.ERROR_MESSAGE);
return false;
}
// set libraries to save to panic dir
Snapshot panicSnapshot = JobManager.findValidSnapshot();
boolean ok = !Output.writePanicSnapshot(panicSnapshot, panicDir, false);
if (ok) {
JOptionPane.showMessageDialog(TopLevel.getCurrentJFrame(), new String [] {"Libraries are saved to panic directory",
panicDir.getAbsolutePath()}, "Libraries are saved", JOptionPane.INFORMATION_MESSAGE);
}
return ok;
}
// public static boolean forceSave(boolean confirm) {
// boolean dirty = false;
// for(Iterator<Library> it = Library.getLibraries(); it.hasNext(); )
// {
// Library lib = it.next();
// if (lib.isHidden()) continue;
// if (!lib.isChanged()) continue;
// dirty = true;
// break;
// }
// if (!dirty) {
// System.out.println("Libraries have not changed, not saving");
// return true;
// }
// if (confirm) {
// String [] options = { "Cancel", "Force Save"};
// int i = JOptionPane.showOptionDialog(TopLevel.getCurrentJFrame(),
// new String [] {"Warning! Saving changes now may create bad libraries!",
// "Libraries will be saved to \"Panic\" directory in current directory",
// "Do you really want to force save?"},
// "Force Save", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null,
// options, options[0]);
// if (i == 0) return false;
// }
// // try to create the panic directory
// String currentDir = User.getWorkingDirectory();
// System.out.println("Saving libraries in panic directory under " + currentDir); System.out.flush();
// File panicDir = new File(currentDir, "panic");
// if (!panicDir.exists() && !panicDir.mkdir()) {
// JOptionPane.showMessageDialog(TopLevel.getCurrentJFrame(), new String [] {"Could not create panic directory",
// panicDir.getAbsolutePath()}, "Error creating panic directory", JOptionPane.ERROR_MESSAGE);
// return false;
// }
// // set libraries to save to panic dir
// boolean retValue = true;
// FileType type = FileType.DEFAULTLIB;
// for(Iterator<Library> it = Library.getLibraries(); it.hasNext(); )
// {
// Library lib = it.next();
// if (lib.isHidden()) continue;
// System.out.print("."); System.out.flush();
// URL libURL = lib.getLibFile();
// File newLibFile = null;
// if (libURL == null || libURL.getPath() == null) {
// newLibFile = new File(panicDir.getAbsolutePath(), lib.getName()+type.getExtensions()[0]);
// } else {
// File libFile = new File(libURL.getPath());
// String fileName = libFile.getName();
// if (fileName == null) fileName = lib.getName() + type.getExtensions()[0];
// newLibFile = new File(panicDir.getAbsolutePath(), fileName);
// }
// URL newLibURL = TextUtils.makeURLToFile(newLibFile.getAbsolutePath());
// lib.setLibFile(newLibURL);
// boolean error = Output.writeLibrary(lib, type, false, false);
// if (error) {
// System.out.println("Error saving "+lib);
// retValue = false;
// }
// }
// System.out.println(" Libraries saved");
// return retValue;
// }
}
| true | true | static EMenu makeMenu() {
/****************************** THE FILE MENU ******************************/
// mnemonic keys available: D T WXYZ
return new EMenu("_File",
new EMenuItem("_New Library...") { public void run() {
newLibraryCommand(); }},
ToolBar.openLibraryCommand, // O
// mnemonic keys available: A F HIJK NO QR VW YZ
new EMenu("_Import",
new EMenuItem("_CIF (Caltech Intermediate Format)...") { public void run() {
importLibraryCommand(FileType.CIF); }},
new EMenuItem("_GDS II (Stream)...") { public void run() {
importLibraryCommand(FileType.GDS); }},
new EMenuItem("GDS _Map File...") { public void run() {
GDSMap.importMapFile(); }},
new EMenuItem("_EDIF (Electronic Design Interchange Format)...") { public void run() {
importLibraryCommand(FileType.EDIF); }},
new EMenuItem("_LEF (Library Exchange Format)...") { public void run() {
importLibraryCommand(FileType.LEF); }},
new EMenuItem("_DEF (Design Exchange Format)...") { public void run() {
importLibraryCommand(FileType.DEF); }},
new EMenuItem("_DEF (Design Exchange Format) to current cell...") { public void run() {
importToCurrentCellCommand(FileType.DEF); }},
new EMenuItem("D_XF (AutoCAD)...") { public void run() {
importLibraryCommand(FileType.DXF); }},
new EMenuItem("S_UE (Schematic User Environment)...") { public void run() {
importLibraryCommand(FileType.SUE); }},
new EMenuItem("_Verilog...") { public void run() {
importLibraryCommand(FileType.VERILOG); }},
IOTool.hasDais() ? new EMenuItem("Dais (_Sun CAD)...") { public void run() {
importLibraryCommand(FileType.DAIS); }} : null,
IOTool.hasDais() ? new EMenuItem("Dais (_Sun CAD) to current library...") { public void run() {
importToCurrentCellCommand(FileType.DAIS); }} : null,
SEPARATOR,
new EMenuItem("ELI_B...") { public void run() {
importLibraryCommand(FileType.ELIB); }},
new EMenuItem("_Readable Dump...") { public void run() {
importLibraryCommand(FileType.READABLEDUMP); }},
new EMenuItem("_Text Cell Contents...") { public void run() {
TextWindow.readTextCell(); }},
new EMenuItem("_Preferences...") { public void run() {
Job.getUserInterface().importPrefs(); }},
new EMenuItem("Project Settings...") { public void run() {
ProjSettings.importSettings(); }},
new EMenuItem("XML Error Logger...") { public void run() {
ErrorLoggerTree.importLogger(); }}
),
SEPARATOR,
new EMenuItem("_Close Library") { public void run() {
closeLibraryCommand(Library.getCurrent()); }},
ToolBar.saveLibraryCommand, // V
new EMenuItem("Save Library _As...") { public void run() {
if (checkInvariants()) saveAsLibraryCommand(Library.getCurrent()); }},
new EMenuItem("_Save All Libraries", 'S') { public void run() {
if (checkInvariants()) saveAllLibrariesCommand(); }},
new EMenuItem("Save All Libraries in _Format...") { public void run() {
if (checkInvariants()) saveAllLibrariesInFormatCommand(); }},
// mnemonic keys available: D J M Q UVWVYZ
new EMenu("_Export",
new EMenuItem("_CIF (Caltech Intermediate Format)...") { public void run() {
exportCommand(FileType.CIF, false); }},
new EMenuItem("_GDS II (Stream)...") { public void run() {
exportCommand(FileType.GDS, false); }},
new EMenuItem("ED_IF (Electronic Design Interchange Format)...") { public void run() {
exportCommand(FileType.EDIF, false); }},
new EMenuItem("LE_F (Library Exchange Format)...") { public void run() {
exportCommand(FileType.LEF, false); }},
new EMenuItem("_L...") { public void run() {
exportCommand(FileType.L, false); }},
IOTool.hasSkill() ? new EMenuItem("S_kill (Cadence Commands)...") { public void run() {
exportCommand(FileType.SKILL, false); }} : null,
IOTool.hasSkill() ? new EMenuItem("Skill Exports _Only (Cadence Commands)...") { public void run() {
exportCommand(FileType.SKILLEXPORTSONLY, false); }} : null,
SEPARATOR,
new EMenuItem("_Eagle...") { public void run() {
exportCommand(FileType.EAGLE, false); }},
new EMenuItem("EC_AD...") { public void run() {
exportCommand(FileType.ECAD, false); }},
new EMenuItem("Pad_s...") { public void run() {
exportCommand(FileType.PADS, false); }},
SEPARATOR,
new EMenuItem("_Text Cell Contents...") { public void run() {
TextWindow.writeTextCell(); }},
new EMenuItem("_PostScript...") { public void run() {
exportCommand(FileType.POSTSCRIPT, false); }},
new EMenuItem("P_NG (Portable Network Graphics)...") { public void run() {
exportCommand(FileType.PNG, false); }},
new EMenuItem("_HPGL...") { public void run() {
exportCommand(FileType.HPGL, false); }},
new EMenuItem("D_XF (AutoCAD)...") { public void run() {
exportCommand(FileType.DXF, false); }},
SEPARATOR,
new EMenuItem("ELI_B (Version 6)...") { public void run() {
saveLibraryCommand(Library.getCurrent(), FileType.ELIB, true, false, false); }},
new EMenuItem(Job.getDebug() ? "_JELIB (Version 8.04k)" : "_JELIB (Version 8.03)") { public void run() {
saveOldJelib(); }},
new EMenuItem("P_references...") { public void run() {
Job.getUserInterface().exportPrefs(); }},
new EMenuItem("Project Settings...") { public void run() {
ProjSettings.exportSettings(); }}
),
SEPARATOR,
new EMenuItem("Change Current _Library...") { public void run() {
ChangeCurrentLib.showDialog(); }},
new EMenuItem("List Li_braries") { public void run() {
CircuitChanges.listLibrariesCommand(); }},
new EMenuItem("Rena_me Library...") { public void run() {
CircuitChanges.renameLibrary(Library.getCurrent()); }},
new EMenuItem("Mar_k All Libraries for Saving") { public void run() {
CircuitChangeJobs.markAllLibrariesForSavingCommand(); }},
// mnemonic keys available: AB DEFGHIJKLMNOPQ STUVWXYZ
new EMenu("C_heck Libraries",
new EMenuItem("_Check") { public void run() {
CircuitChanges.checkAndRepairCommand(false); }},
new EMenuItem("_Repair") { public void run() {
CircuitChanges.checkAndRepairCommand(true); }}),
SEPARATOR,
// mnemonic keys available: C EFG JK MN PQ ST VWXYZ
new EMenu("P_roject Management",
new EMenuItem("_Update") { public void run() {
UpdateJob.updateProject(); }},
new EMenuItem("Check _Out This Cell") { public void run() {
CheckOutJob.checkOutThisCell(); }},
new EMenuItem("Check _In This Cell...") { public void run() {
CheckInJob.checkInThisCell(); }},
SEPARATOR,
new EMenuItem("Roll_back and Release Check-Out") { public void run() {
CancelCheckOutJob.cancelCheckOutThisCell(); }},
new EMenuItem("_Add This Cell") { public void run() {
AddCellJob.addThisCell(); }},
new EMenuItem("_Remove This Cell") { public void run() {
DeleteCellJob.removeThisCell(); }},
new EMenuItem("Show _History of This Cell...") { public void run() {
HistoryDialog.examineThisHistory(); }},
SEPARATOR,
new EMenuItem("Get Library From Repository...") { public void run() {
LibraryDialog.getALibrary(); }},
new EMenuItem("Add Current _Library To Repository") { public void run() {
AddLibraryJob.addThisLibrary(); }},
new EMenuItem("Ad_d All Libraries To Repository") { public void run() {
AddLibraryJob.addAllLibraries(); }}),
// mnemonic keys available: ABCDEFGHIJKLMNOPQRSTUVWXYZ
new EMenu("C_VS",
new EMenuItem("Commit All Open Libraries") { public void run() {
Commit.commitAllLibraries(); }},
new EMenuItem("Update Open Libraries") { public void run() {
Update.updateOpenLibraries(Update.UPDATE); }},
new EMenuItem("Get Status Open Libraries") { public void run() {
Update.updateOpenLibraries(Update.STATUS); }},
new EMenuItem("List Editors Open Libraries") { public void run() {
Edit.listEditorsOpenLibraries(); }},
SEPARATOR,
new EMenuItem("Update Project Libraries") { public void run() {
Update.updateProject(Update.UPDATE); }},
new EMenuItem("Get Status Project Libraries") { public void run() {
Update.updateProject(Update.STATUS); }},
new EMenuItem("List Editors Project Libraries") { public void run() {
Edit.listEditorsProject(); }},
SEPARATOR,
new EMenuItem("Checkout From Repository") { public void run() {
CVS.checkoutFromRepository(); }})
{
@Override
public boolean isEnabled() { return CVS.isEnabled(); }
@Override
protected void registerItem() {
super.registerItem();
registerUpdatable();
}
},
SEPARATOR,
new EMenuItem("Pa_ge Setup...") { public void run() {
pageSetupCommand(); }},
new EMenuItem("_Print...") { public void run() {
printCommand(); }},
SEPARATOR,
ToolBar.preferencesCommand, // R
new EMenuItem("Pro_ject Settings...") { public void run() {
ProjectSettingsFrame.projectSettingsCommand(); }},
SEPARATOR,
!Client.isOSMac() ? new EMenuItem("_Quit", 'Q') { public void run() {
quitCommand(); }} : null,
new EMenuItem("Force Q_uit (and Save)") { public void run() {
forceQuit(); }});
}
| static EMenu makeMenu() {
/****************************** THE FILE MENU ******************************/
// mnemonic keys available: D T WXYZ
return new EMenu("_File",
new EMenuItem("_New Library...") { public void run() {
newLibraryCommand(); }},
ToolBar.openLibraryCommand, // O
// mnemonic keys available: A F HIJK NO QR VW YZ
new EMenu("_Import",
new EMenuItem("_CIF (Caltech Intermediate Format)...") { public void run() {
importLibraryCommand(FileType.CIF); }},
new EMenuItem("_GDS II (Stream)...") { public void run() {
importLibraryCommand(FileType.GDS); }},
new EMenuItem("GDS _Map File...") { public void run() {
GDSMap.importMapFile(); }},
new EMenuItem("_EDIF (Electronic Design Interchange Format)...") { public void run() {
importLibraryCommand(FileType.EDIF); }},
new EMenuItem("_LEF (Library Exchange Format)...") { public void run() {
importLibraryCommand(FileType.LEF); }},
new EMenuItem("_DEF (Design Exchange Format)...") { public void run() {
importLibraryCommand(FileType.DEF); }},
new EMenuItem("_DEF (Design Exchange Format) to current cell...") { public void run() {
importToCurrentCellCommand(FileType.DEF); }},
new EMenuItem("D_XF (AutoCAD)...") { public void run() {
importLibraryCommand(FileType.DXF); }},
new EMenuItem("S_UE (Schematic User Environment)...") { public void run() {
importLibraryCommand(FileType.SUE); }},
new EMenuItem("_Verilog...") { public void run() {
importLibraryCommand(FileType.VERILOG); }},
IOTool.hasDais() ? new EMenuItem("Dais (_Sun CAD)...") { public void run() {
importLibraryCommand(FileType.DAIS); }} : null,
IOTool.hasDais() ? new EMenuItem("Dais (_Sun CAD) to current library...") { public void run() {
importToCurrentCellCommand(FileType.DAIS); }} : null,
SEPARATOR,
new EMenuItem("ELI_B...") { public void run() {
importLibraryCommand(FileType.ELIB); }},
new EMenuItem("_Readable Dump...") { public void run() {
importLibraryCommand(FileType.READABLEDUMP); }},
new EMenuItem("_Text Cell Contents...") { public void run() {
TextWindow.readTextCell(); }},
new EMenuItem("_Preferences...") { public void run() {
Job.getUserInterface().importPrefs(); }},
new EMenuItem("Project Settings...") { public void run() {
ProjSettings.importSettings(); }},
new EMenuItem("XML Error Logger...") { public void run() {
ErrorLoggerTree.importLogger(); }}
),
SEPARATOR,
new EMenuItem("_Close Library") { public void run() {
closeLibraryCommand(Library.getCurrent()); }},
ToolBar.saveLibraryCommand, // V
new EMenuItem("Save Library _As...") { public void run() {
if (checkInvariants()) saveAsLibraryCommand(Library.getCurrent()); }},
new EMenuItem("_Save All Libraries", 'S') { public void run() {
if (checkInvariants()) saveAllLibrariesCommand(); }},
new EMenuItem("Save All Libraries in _Format...") { public void run() {
if (checkInvariants()) saveAllLibrariesInFormatCommand(); }},
// mnemonic keys available: D J M Q UVWVYZ
new EMenu("_Export",
new EMenuItem("_CIF (Caltech Intermediate Format)...") { public void run() {
exportCommand(FileType.CIF, false); }},
new EMenuItem("_GDS II (Stream)...") { public void run() {
exportCommand(FileType.GDS, false); }},
new EMenuItem("ED_IF (Electronic Design Interchange Format)...") { public void run() {
exportCommand(FileType.EDIF, false); }},
new EMenuItem("LE_F (Library Exchange Format)...") { public void run() {
exportCommand(FileType.LEF, false); }},
new EMenuItem("_L...") { public void run() {
exportCommand(FileType.L, false); }},
IOTool.hasSkill() ? new EMenuItem("S_kill (Cadence Commands)...") { public void run() {
exportCommand(FileType.SKILL, false); }} : null,
IOTool.hasSkill() ? new EMenuItem("Skill Exports _Only (Cadence Commands)...") { public void run() {
exportCommand(FileType.SKILLEXPORTSONLY, false); }} : null,
SEPARATOR,
new EMenuItem("_Eagle...") { public void run() {
exportCommand(FileType.EAGLE, false); }},
new EMenuItem("EC_AD...") { public void run() {
exportCommand(FileType.ECAD, false); }},
new EMenuItem("Pad_s...") { public void run() {
exportCommand(FileType.PADS, false); }},
SEPARATOR,
new EMenuItem("_Text Cell Contents...") { public void run() {
TextWindow.writeTextCell(); }},
new EMenuItem("_PostScript...") { public void run() {
exportCommand(FileType.POSTSCRIPT, false); }},
new EMenuItem("P_NG (Portable Network Graphics)...") { public void run() {
exportCommand(FileType.PNG, false); }},
new EMenuItem("_HPGL...") { public void run() {
exportCommand(FileType.HPGL, false); }},
new EMenuItem("D_XF (AutoCAD)...") { public void run() {
exportCommand(FileType.DXF, false); }},
SEPARATOR,
new EMenuItem("ELI_B (Version 6)...") { public void run() {
saveLibraryCommand(Library.getCurrent(), FileType.ELIB, true, false, false); }},
new EMenuItem("_JELIB (Version 8.03)...") { public void run() { // really since 8.04k
saveOldJelib(); }},
new EMenuItem("P_references...") { public void run() {
Job.getUserInterface().exportPrefs(); }},
new EMenuItem("Project Settings...") { public void run() {
ProjSettings.exportSettings(); }}
),
SEPARATOR,
new EMenuItem("Change Current _Library...") { public void run() {
ChangeCurrentLib.showDialog(); }},
new EMenuItem("List Li_braries") { public void run() {
CircuitChanges.listLibrariesCommand(); }},
new EMenuItem("Rena_me Library...") { public void run() {
CircuitChanges.renameLibrary(Library.getCurrent()); }},
new EMenuItem("Mar_k All Libraries for Saving") { public void run() {
CircuitChangeJobs.markAllLibrariesForSavingCommand(); }},
// mnemonic keys available: AB DEFGHIJKLMNOPQ STUVWXYZ
new EMenu("C_heck Libraries",
new EMenuItem("_Check") { public void run() {
CircuitChanges.checkAndRepairCommand(false); }},
new EMenuItem("_Repair") { public void run() {
CircuitChanges.checkAndRepairCommand(true); }}),
SEPARATOR,
// mnemonic keys available: C EFG JK MN PQ ST VWXYZ
new EMenu("P_roject Management",
new EMenuItem("_Update") { public void run() {
UpdateJob.updateProject(); }},
new EMenuItem("Check _Out This Cell") { public void run() {
CheckOutJob.checkOutThisCell(); }},
new EMenuItem("Check _In This Cell...") { public void run() {
CheckInJob.checkInThisCell(); }},
SEPARATOR,
new EMenuItem("Roll_back and Release Check-Out") { public void run() {
CancelCheckOutJob.cancelCheckOutThisCell(); }},
new EMenuItem("_Add This Cell") { public void run() {
AddCellJob.addThisCell(); }},
new EMenuItem("_Remove This Cell") { public void run() {
DeleteCellJob.removeThisCell(); }},
new EMenuItem("Show _History of This Cell...") { public void run() {
HistoryDialog.examineThisHistory(); }},
SEPARATOR,
new EMenuItem("Get Library From Repository...") { public void run() {
LibraryDialog.getALibrary(); }},
new EMenuItem("Add Current _Library To Repository") { public void run() {
AddLibraryJob.addThisLibrary(); }},
new EMenuItem("Ad_d All Libraries To Repository") { public void run() {
AddLibraryJob.addAllLibraries(); }}),
// mnemonic keys available: ABCDEFGHIJKLMNOPQRSTUVWXYZ
new EMenu("C_VS",
new EMenuItem("Commit All Open Libraries") { public void run() {
Commit.commitAllLibraries(); }},
new EMenuItem("Update Open Libraries") { public void run() {
Update.updateOpenLibraries(Update.UPDATE); }},
new EMenuItem("Get Status Open Libraries") { public void run() {
Update.updateOpenLibraries(Update.STATUS); }},
new EMenuItem("List Editors Open Libraries") { public void run() {
Edit.listEditorsOpenLibraries(); }},
SEPARATOR,
new EMenuItem("Update Project Libraries") { public void run() {
Update.updateProject(Update.UPDATE); }},
new EMenuItem("Get Status Project Libraries") { public void run() {
Update.updateProject(Update.STATUS); }},
new EMenuItem("List Editors Project Libraries") { public void run() {
Edit.listEditorsProject(); }},
SEPARATOR,
new EMenuItem("Checkout From Repository") { public void run() {
CVS.checkoutFromRepository(); }})
{
@Override
public boolean isEnabled() { return CVS.isEnabled(); }
@Override
protected void registerItem() {
super.registerItem();
registerUpdatable();
}
},
SEPARATOR,
new EMenuItem("Pa_ge Setup...") { public void run() {
pageSetupCommand(); }},
new EMenuItem("_Print...") { public void run() {
printCommand(); }},
SEPARATOR,
ToolBar.preferencesCommand, // R
new EMenuItem("Pro_ject Settings...") { public void run() {
ProjectSettingsFrame.projectSettingsCommand(); }},
SEPARATOR,
!Client.isOSMac() ? new EMenuItem("_Quit", 'Q') { public void run() {
quitCommand(); }} : null,
new EMenuItem("Force Q_uit (and Save)") { public void run() {
forceQuit(); }});
}
|
diff --git a/BOLT/src/editor/Editor.java b/BOLT/src/editor/Editor.java
index 790a984..acae4cd 100644
--- a/BOLT/src/editor/Editor.java
+++ b/BOLT/src/editor/Editor.java
@@ -1,780 +1,780 @@
package editor;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeSelectionModel;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import util.Compressor;
import util.SpringUtilities;
import entity.EntityBuilder;
import entity.EntityRegistry;
import entity.util.EntityLoader;
public class Editor extends JFrame implements TreeSelectionListener
{
private static final long serialVersionUID = 1L;
File mapFile;
File entListFile;
JScrollPane treePanel;
JTree tree;
JPanel uiPanel;
JSONArray entities;
JSpinner entityPosX, entityPosY, entityPosZ;
JSpinner entityRotX, entityRotY, entityRotZ;
JTextField entityID;
JTable entityCustomValues;
JMenuItem saveFile;
JMenuItem saveUFile;
JMenu view;
public Editor()
{
super("BOLT Editor");
try
{
EntityLoader.findEntities("test/entities/testList.entlist");
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e)
{
e.printStackTrace();
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents();
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
}
public void initComponents()
{
JMenuBar menu = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem newFile = new JMenuItem(new AbstractAction("New")
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
refresh();
if (isChanged())
{
int r = JOptionPane.showConfirmDialog(Editor.this, "\"" + mapFile.getName() + "\" has been modified. Save changes?", "Save Resource", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if (r == JOptionPane.YES_OPTION) newMap();
else if (r == JOptionPane.CANCEL_OPTION) return;
}
newMap();
}
});
newFile.setAccelerator(KeyStroke.getKeyStroke("ctrl N"));
file.add(newFile);
JMenuItem openFile = new JMenuItem(new AbstractAction("Open...")
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
refresh();
if (isChanged())
{
int r = JOptionPane.showConfirmDialog(Editor.this, "\"" + mapFile.getName() + "\" has been modified. Save changes?", "Save Resource", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if (r == JOptionPane.YES_OPTION) saveMap();
else if (r == JOptionPane.CANCEL_OPTION) return;
}
openMap();
}
});
openFile.setAccelerator(KeyStroke.getKeyStroke("ctrl O"));
file.add(openFile);
saveFile = new JMenuItem(new AbstractAction("Save")
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
saveMap();
}
});
saveFile.setEnabled(false);
saveFile.setAccelerator(KeyStroke.getKeyStroke("ctrl S"));
file.add(saveFile);
saveUFile = new JMenuItem(new AbstractAction("Save as...")
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
saveUMap();
}
});
saveUFile.setEnabled(false);
saveUFile.setAccelerator(KeyStroke.getKeyStroke("ctrl shift S"));
file.add(saveUFile);
menu.add(file);
view = new JMenu("View");
JMenuItem raw = new JMenuItem(new AbstractAction("Raw file...")
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
showRawFile();
}
});
view.add(raw);
view.setEnabled(false);
menu.add(view);
JMenu mode = new JMenu("Mode");
JMenuItem ent = new JMenuItem(new AbstractAction("Entity Editor")
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
new EntityEditor();
}
});
mode.add(ent);
menu.add(mode);
setJMenuBar(menu);
JPanel panel = new JPanel(new BorderLayout());
treePanel = new JScrollPane(null, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
treePanel.setPreferredSize(new Dimension(200, 0));
panel.add(treePanel, BorderLayout.LINE_START);
tree = new JTree(new DefaultMutableTreeNode("World"));
tree.setModel(null);
tree.setEnabled(false);
tree.setShowsRootHandles(true);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.addTreeSelectionListener(this);
tree.setExpandsSelectedPaths(true);
tree.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
if (e.getButton() != 3) return;
final int row = tree.getRowForLocation(e.getX(), e.getY());
if (row <= 1) return;
tree.setSelectionRow(row);
JPopupMenu menu = new JPopupMenu();
JMenuItem del = new JMenuItem(new AbstractAction("Delete")
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
entities.remove(row - 2);
DefaultTreeModel dtm = (DefaultTreeModel) tree.getModel();
dtm.removeNodeFromParent((DefaultMutableTreeNode) tree.getSelectionPath().getLastPathComponent());
refresh();
}
});
menu.add(del);
menu.show(e.getComponent(), e.getX(), e.getY());
}
});
treePanel.setViewportView(tree);
uiPanel = new JPanel(new FlowLayout());
uiPanel.setEnabled(false);
uiPanel.setPreferredSize(new Dimension(600, 600));
panel.add(uiPanel, BorderLayout.LINE_END);
setContentPane(panel);
pack();
}
public boolean isChanged()
{
if (mapFile == null) return false;
try
{
return !writeValue(getData()).equals(writeValue(new JSONObject(Compressor.decompressFile(mapFile))));
}
catch (JSONException e)
{
e.printStackTrace();
return true;
}
}
public static String writeValue(Object value)
{
String string = "null";
try
{
if (value instanceof Integer || value instanceof Double || value instanceof Boolean) return value.toString();
else if (value instanceof JSONArray)
{
string = "[";
if (((JSONArray) value).length() > 0)
{
for (int i = 0; i < ((JSONArray) value).length(); i++)
string += writeValue((((JSONArray) value).get(i))) + ",";
string = string.substring(0, string.length() - 1);
}
return string + "]";
}
else if (value instanceof JSONObject)
{
string = "{";
String[] keys = JSONObject.getNames((JSONObject) value);
if (keys != null && keys.length > 0)
{
Arrays.sort(keys);
for (String s : keys)
string += "\"" + s + "\":" + writeValue(((JSONObject) value).get(s)) + ",";
string = string.substring(0, string.length() - 1);
}
return string + "}";
}
else return "\"" + value.toString() + "\"";
}
catch (Exception e)
{
e.printStackTrace();
}
return string;
}
public void showRawFile()
{
try
{
JDialog frame = new JDialog(this, true);
frame.setTitle("BOLT Editor - Raw File Preview");
frame.setSize(400, 400);
frame.setDefaultCloseOperation(HIDE_ON_CLOSE);
JTextArea area = new JTextArea(getData().toString(4));
frame.setContentPane(new JScrollPane(area, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
public void setTitle(String s)
{
super.setTitle(((s != null) ? s + " - " : "") + "BOLT Editor");
}
public String getTitle()
{
return super.getTitle().replaceAll("( - )(BOLT Editor)", "");
}
public void newMap()
{
mapFile = null;
reset();
}
private void reset()
{
saveFile.setEnabled(true);
saveUFile.setEnabled(true);
view.setEnabled(true);
tree.setEnabled(true);
entities = new JSONArray();
DefaultMutableTreeNode root = new DefaultMutableTreeNode("World");
DefaultMutableTreeNode entities = new DefaultMutableTreeNode("Entities");
root.add(entities);
tree.setModel(new DefaultTreeModel(root));
uiPanel.setEnabled(true);
}
public void openMap()
{
JFileChooser jfc = new JFileChooser("C:/");
jfc.setFileFilter(new FileNameExtensionFilter("BOLT Map-Files", "map"));
jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
jfc.setMultiSelectionEnabled(false);
if (jfc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
{
mapFile = jfc.getSelectedFile();
try
{
reset();
setTitle(mapFile.getPath());
JSONObject data = new JSONObject(Compressor.decompressFile(mapFile));
entities = data.getJSONArray("entities");
DefaultTreeModel dtm = (DefaultTreeModel) tree.getModel();
for (int i = 0; i < entities.length(); i++)
{
dtm.insertNodeInto(new DefaultMutableTreeNode("Entity" + i), (DefaultMutableTreeNode) tree.getPathForRow(1).getLastPathComponent(), i);
refresh();
}
tree.expandRow(1);
}
catch (JSONException e)
{
e.printStackTrace();
JOptionPane.showMessageDialog(Editor.this, "Could not open file: \"" + mapFile.getPath() + "\"!", "Error!", JOptionPane.ERROR_MESSAGE);
mapFile = null;
return;
}
}
}
private JSONObject getData()
{
try
{
JSONObject data = new JSONObject();
data.put("entities", entities);
return data;
}
catch (JSONException e)
{
e.printStackTrace();
return null;
}
}
public void saveMap()
{
if (mapFile == null)
{
saveUMap();
return;
}
String string = writeValue(getData());
Compressor.compressFile(mapFile, string);
refresh();
}
public void saveUMap()
{
JFileChooser jfc = new JFileChooser("C:/");
jfc.setFileFilter(new FileNameExtensionFilter("BOLT Map-Files", "map"));
jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
jfc.setMultiSelectionEnabled(false);
if (jfc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
{
mapFile = new File(jfc.getSelectedFile().getPath().replace(".map", "") + ".map");
saveMap();
}
}
private void refresh()
{
if (isChanged())
{
if (!getTitle().startsWith("*")) setTitle("*" + getTitle());
}
else
{
if (mapFile != null) setTitle(mapFile.getPath());
else setTitle(null);
}
revalidate();
repaint();
treePanel.revalidate();
}
private String[] loadEntityList()
{
ArrayList<String> list = new ArrayList<>();
list.add("-- Choose an Entity --");
EntityLoader.findEntities("test/entities/testList.entlist");
for (String key : EntityLoader.entitiesFound.keySet())
{
list.add(key);
}
return list.toArray(new String[] {});
}
@Override
public void valueChanged(TreeSelectionEvent e)
{
uiPanel.setLayout(new FlowLayout());
uiPanel.removeAll();
refresh();
final DefaultMutableTreeNode s = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
if (tree.getRowForPath(e.getPath()) == 1) // Entities
{
final JButton newEntity = new JButton();
final JComboBox<String> entities = new JComboBox<>(loadEntityList());
entities.setSelectedIndex(0);
entities.addItemListener(new ItemListener()
{
@Override
public void itemStateChanged(ItemEvent e)
{
if (e.getStateChange() == ItemEvent.SELECTED)
{
newEntity.setEnabled(entities.getSelectedIndex() > 0);
}
}
});
uiPanel.add(entities);
newEntity.setAction(new AbstractAction("New Entity")
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
DefaultTreeModel dtm = (DefaultTreeModel) tree.getModel();
dtm.insertNodeInto(new DefaultMutableTreeNode(s.getChildCount()), s, s.getChildCount());
tree.expandRow(1);
try
{
EntityBuilder builder = EntityLoader.loadEntity(entities.getSelectedItem().toString().replace(".entity", ""));
EntityRegistry.registerEntityBuilder(builder);
JSONObject object = new JSONObject();
object.put("name", entities.getSelectedItem().toString().replace(".entity", ""));
object.put("id", "" + (s.getChildCount() - 1));
object.put("pos", new JSONArray(new Double[] { 0d, 0d, 0d }));
object.put("rot", new JSONArray(new Double[] { 0d, 0d, 0d }));
JSONObject custom = new JSONObject();
for (String key : builder.customValues.keySet())
{
custom.put(key, builder.customValues.get(key));
}
object.put("custom", custom);
Editor.this.entities.put(object);
refresh();
}
catch (Exception e1)
{
e1.printStackTrace();
}
}
});
newEntity.setEnabled(false);
newEntity.setPreferredSize(new Dimension(300, 24));
uiPanel.add(newEntity);
refresh();
}
if (tree.getRowForPath(e.getPath()) > 1) // Entity1, Entity2, ...
{
try
{
if (entities.length() == 0) return;
final int entityIndex = tree.getRowForPath(e.getPath()) - 2;
if (tree.getRowForPath(e.getPath()) - 2 < 0) return;
JSONObject entity = entities.getJSONObject(tree.getRowForPath(e.getPath()) - 2);
EntityBuilder builder = EntityRegistry.entries.get(entity.getString("name"));
if (builder == null)
{
builder = EntityLoader.loadEntity(entity.getString("name"));
EntityRegistry.registerEntityBuilder(builder);
}
JPanel uiP = new JPanel(new SpringLayout());
uiP.add(new JLabel("Name:"));
JTextField name = new JTextField(builder.fullName + " (" + builder.name + ")");
name.setEditable(false);
uiP.add(name);
uiP.add(new JLabel("Parent:"));
JTextField parent = new JTextField(builder.parent);
parent.setEditable(false);
uiP.add(parent);
// TODO work
uiP.add(new JLabel("ID:"));
entityID = new JTextField(entity.getString("id"));
uiP.add(entityID);
uiP.add(new JLabel("Position:"));
JPanel panel = new JPanel();
entityPosX = new JSpinner(new SpinnerNumberModel(entity.getJSONArray("pos").getDouble(0), -1000000, 1000000, 1));
panel.add(entityPosX);
entityPosY = new JSpinner(new SpinnerNumberModel(entity.getJSONArray("pos").getDouble(1), -1000000, 1000000, 1));
panel.add(entityPosY);
entityPosZ = new JSpinner(new SpinnerNumberModel(entity.getJSONArray("pos").getDouble(2), -1000000, 1000000, 1));
panel.add(entityPosZ);
uiP.add(panel);
uiP.add(new JLabel("Rotation:"));
panel = new JPanel();
entityRotX = new JSpinner(new SpinnerNumberModel(entity.getJSONArray("rot").getDouble(0), -1000000, 1000000, 1));
panel.add(entityRotX);
entityRotY = new JSpinner(new SpinnerNumberModel(entity.getJSONArray("rot").getDouble(1), -1000000, 1000000, 1));
panel.add(entityRotY);
entityRotZ = new JSpinner(new SpinnerNumberModel(entity.getJSONArray("rot").getDouble(2), -1000000, 1000000, 1));
panel.add(entityRotZ);
uiP.add(panel);
uiP.add(new JLabel("Custom Values:"));
final String[][] data = new String[builder.customValues.size()][2];
ArrayList<String> keys = new ArrayList<>(builder.customValues.keySet());
for (int i = 0; i < data.length; i++)
{
data[i] = new String[] { keys.get(i) + " (" + builder.customValues.get(keys.get(i)).getClass().getSimpleName() + ")", ((entity.getJSONObject("custom").has(keys.get(i))) ? entity.getJSONObject("custom").get(keys.get(i)).toString() : builder.customValues.get(keys.get(i)).toString()).toString() };
}
final JButton browse = new JButton("Browse...");
browse.setEnabled(false);
entityCustomValues = new JTable(new DefaultTableModel(data, new String[] { "Name (Type)", "Value" }))
{
private static final long serialVersionUID = 1L;
public boolean isCellEditable(int row, int column)
{
if (column == 0) return false; // name column
if (column == 1 && entityCustomValues.getValueAt(row, 0).toString().contains("(File)")) return false; // file type
return true;
}
};
entityCustomValues.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
JScrollPane jsp = new JScrollPane(entityCustomValues, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
entityCustomValues.setFillsViewportHeight(true);
entityCustomValues.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
entityCustomValues.getSelectionModel().addListSelectionListener(new ListSelectionListener()
{
@Override
public void valueChanged(ListSelectionEvent e)
{
if (e.getValueIsAdjusting() || entityCustomValues.getSelectedRow() == -1) return;
browse.setEnabled(data[entityCustomValues.getSelectedRow()][0].contains("(File)"));
}
});
jsp.setPreferredSize(new Dimension(entityCustomValues.getWidth(), 150));
uiP.add(jsp);
uiP.add(new JLabel());
browse.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
JFileChooser jfc = new JFileChooser("C:/");
jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
jfc.setMultiSelectionEnabled(false);
- if (jfc.showSaveDialog(Editor.this) == JFileChooser.APPROVE_OPTION) entityCustomValues.setValueAt(jfc.getSelectedFile().getPath(), entityCustomValues.getSelectedRow(), 1);
+ if (jfc.showSaveDialog(Editor.this) == JFileChooser.APPROVE_OPTION) entityCustomValues.setValueAt(jfc.getSelectedFile().getPath().replace("\\", "/"), entityCustomValues.getSelectedRow(), 1);
}
});
uiP.add(browse);
uiP.add(new JLabel());
uiP.add(new JButton(new AbstractAction("Apply")
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
try
{
if (entityID.getText().length() == 0)
{
JOptionPane.showMessageDialog(Editor.this, "Please enter a unique identifier for that entity!", "Error!", JOptionPane.ERROR_MESSAGE);
return;
}
entities.getJSONObject(entityIndex).put("id", entityID.getText());
entities.getJSONObject(entityIndex).put("pos", new JSONArray(new Double[] { (double) entityPosX.getValue(), (double) entityPosY.getValue(), (double) entityPosZ.getValue() }));
entities.getJSONObject(entityIndex).put("rot", new JSONArray(new Double[] { (double) entityRotX.getValue(), (double) entityRotY.getValue(), (double) entityRotZ.getValue() }));
EntityBuilder builder = EntityRegistry.entries.get(entities.getJSONObject(entityIndex).getString("name"));
JSONObject custom = new JSONObject();
boolean valid = true;
String message = "";
for (int i = 0; i < entityCustomValues.getModel().getRowCount(); i++)
{
String name = entityCustomValues.getModel().getValueAt(i, 0).toString().replaceAll("( )(\\(.{1,}\\))", "");
String type = builder.customValues.get(name).getClass().getSimpleName();
String content = entityCustomValues.getModel().getValueAt(i, 1).toString();
if (type.equals("Integer"))
{
try
{
custom.put(name, Integer.parseInt(content));
}
catch (Exception e1)
{
message = "\"" + entityCustomValues.getModel().getValueAt(i, 0).toString() + "\": " + e1.getMessage();
valid = false;
break;
}
}
else if (type.equals("Float"))
{
try
{
custom.put(name, Float.parseFloat(content));
}
catch (Exception e1)
{
message = "\"" + entityCustomValues.getModel().getValueAt(i, 0).toString() + "\": " + e1.getMessage();
valid = false;
break;
}
}
else if (type.equals("Byte"))
{
try
{
custom.put(name, Byte.parseByte(content));
}
catch (Exception e1)
{
message = "\"" + entityCustomValues.getModel().getValueAt(i, 0).toString() + "\": " + e1.getMessage();
valid = false;
break;
}
}
else if (type.equals("Boolean"))
{
try
{
custom.put(name, Boolean.parseBoolean(content));
}
catch (Exception e1)
{
message = "\"" + entityCustomValues.getModel().getValueAt(i, 0).toString() + "\": " + e1.getMessage();
valid = false;
break;
}
}
else if (type.equals("File"))
{
try
{
custom.put(name, content);
}
catch (Exception e1)
{
message = "\"" + entityCustomValues.getModel().getValueAt(i, 0).toString() + "\": " + e1.getMessage();
valid = false;
break;
}
}
}
if (!valid)
{
JOptionPane.showMessageDialog(Editor.this, "Please enter your custom values in the same data type as specified in brackets!\n at " + message, "Error!", JOptionPane.ERROR_MESSAGE);
return;
}
entities.getJSONObject(entityIndex).put("custom", custom);
int selectedRow = tree.getSelectionRows()[0];
((DefaultMutableTreeNode) tree.getSelectionPath().getLastPathComponent()).setUserObject(entityID.getText());
((DefaultTreeModel) tree.getModel()).reload();
tree.expandRow(1);
tree.setSelectionRow(selectedRow);
refresh();
}
catch (JSONException e1)
{
e1.printStackTrace();
}
}
}));
SpringUtilities.makeCompactGrid(uiP, 8, 2, 6, 6, 6, 6);
uiPanel.add(uiP);
refresh();
}
catch (Exception e1)
{
e1.printStackTrace();
}
}
}
}
| true | true | public void valueChanged(TreeSelectionEvent e)
{
uiPanel.setLayout(new FlowLayout());
uiPanel.removeAll();
refresh();
final DefaultMutableTreeNode s = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
if (tree.getRowForPath(e.getPath()) == 1) // Entities
{
final JButton newEntity = new JButton();
final JComboBox<String> entities = new JComboBox<>(loadEntityList());
entities.setSelectedIndex(0);
entities.addItemListener(new ItemListener()
{
@Override
public void itemStateChanged(ItemEvent e)
{
if (e.getStateChange() == ItemEvent.SELECTED)
{
newEntity.setEnabled(entities.getSelectedIndex() > 0);
}
}
});
uiPanel.add(entities);
newEntity.setAction(new AbstractAction("New Entity")
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
DefaultTreeModel dtm = (DefaultTreeModel) tree.getModel();
dtm.insertNodeInto(new DefaultMutableTreeNode(s.getChildCount()), s, s.getChildCount());
tree.expandRow(1);
try
{
EntityBuilder builder = EntityLoader.loadEntity(entities.getSelectedItem().toString().replace(".entity", ""));
EntityRegistry.registerEntityBuilder(builder);
JSONObject object = new JSONObject();
object.put("name", entities.getSelectedItem().toString().replace(".entity", ""));
object.put("id", "" + (s.getChildCount() - 1));
object.put("pos", new JSONArray(new Double[] { 0d, 0d, 0d }));
object.put("rot", new JSONArray(new Double[] { 0d, 0d, 0d }));
JSONObject custom = new JSONObject();
for (String key : builder.customValues.keySet())
{
custom.put(key, builder.customValues.get(key));
}
object.put("custom", custom);
Editor.this.entities.put(object);
refresh();
}
catch (Exception e1)
{
e1.printStackTrace();
}
}
});
newEntity.setEnabled(false);
newEntity.setPreferredSize(new Dimension(300, 24));
uiPanel.add(newEntity);
refresh();
}
if (tree.getRowForPath(e.getPath()) > 1) // Entity1, Entity2, ...
{
try
{
if (entities.length() == 0) return;
final int entityIndex = tree.getRowForPath(e.getPath()) - 2;
if (tree.getRowForPath(e.getPath()) - 2 < 0) return;
JSONObject entity = entities.getJSONObject(tree.getRowForPath(e.getPath()) - 2);
EntityBuilder builder = EntityRegistry.entries.get(entity.getString("name"));
if (builder == null)
{
builder = EntityLoader.loadEntity(entity.getString("name"));
EntityRegistry.registerEntityBuilder(builder);
}
JPanel uiP = new JPanel(new SpringLayout());
uiP.add(new JLabel("Name:"));
JTextField name = new JTextField(builder.fullName + " (" + builder.name + ")");
name.setEditable(false);
uiP.add(name);
uiP.add(new JLabel("Parent:"));
JTextField parent = new JTextField(builder.parent);
parent.setEditable(false);
uiP.add(parent);
// TODO work
uiP.add(new JLabel("ID:"));
entityID = new JTextField(entity.getString("id"));
uiP.add(entityID);
uiP.add(new JLabel("Position:"));
JPanel panel = new JPanel();
entityPosX = new JSpinner(new SpinnerNumberModel(entity.getJSONArray("pos").getDouble(0), -1000000, 1000000, 1));
panel.add(entityPosX);
entityPosY = new JSpinner(new SpinnerNumberModel(entity.getJSONArray("pos").getDouble(1), -1000000, 1000000, 1));
panel.add(entityPosY);
entityPosZ = new JSpinner(new SpinnerNumberModel(entity.getJSONArray("pos").getDouble(2), -1000000, 1000000, 1));
panel.add(entityPosZ);
uiP.add(panel);
uiP.add(new JLabel("Rotation:"));
panel = new JPanel();
entityRotX = new JSpinner(new SpinnerNumberModel(entity.getJSONArray("rot").getDouble(0), -1000000, 1000000, 1));
panel.add(entityRotX);
entityRotY = new JSpinner(new SpinnerNumberModel(entity.getJSONArray("rot").getDouble(1), -1000000, 1000000, 1));
panel.add(entityRotY);
entityRotZ = new JSpinner(new SpinnerNumberModel(entity.getJSONArray("rot").getDouble(2), -1000000, 1000000, 1));
panel.add(entityRotZ);
uiP.add(panel);
uiP.add(new JLabel("Custom Values:"));
final String[][] data = new String[builder.customValues.size()][2];
ArrayList<String> keys = new ArrayList<>(builder.customValues.keySet());
for (int i = 0; i < data.length; i++)
{
data[i] = new String[] { keys.get(i) + " (" + builder.customValues.get(keys.get(i)).getClass().getSimpleName() + ")", ((entity.getJSONObject("custom").has(keys.get(i))) ? entity.getJSONObject("custom").get(keys.get(i)).toString() : builder.customValues.get(keys.get(i)).toString()).toString() };
}
final JButton browse = new JButton("Browse...");
browse.setEnabled(false);
entityCustomValues = new JTable(new DefaultTableModel(data, new String[] { "Name (Type)", "Value" }))
{
private static final long serialVersionUID = 1L;
public boolean isCellEditable(int row, int column)
{
if (column == 0) return false; // name column
if (column == 1 && entityCustomValues.getValueAt(row, 0).toString().contains("(File)")) return false; // file type
return true;
}
};
entityCustomValues.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
JScrollPane jsp = new JScrollPane(entityCustomValues, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
entityCustomValues.setFillsViewportHeight(true);
entityCustomValues.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
entityCustomValues.getSelectionModel().addListSelectionListener(new ListSelectionListener()
{
@Override
public void valueChanged(ListSelectionEvent e)
{
if (e.getValueIsAdjusting() || entityCustomValues.getSelectedRow() == -1) return;
browse.setEnabled(data[entityCustomValues.getSelectedRow()][0].contains("(File)"));
}
});
jsp.setPreferredSize(new Dimension(entityCustomValues.getWidth(), 150));
uiP.add(jsp);
uiP.add(new JLabel());
browse.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
JFileChooser jfc = new JFileChooser("C:/");
jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
jfc.setMultiSelectionEnabled(false);
if (jfc.showSaveDialog(Editor.this) == JFileChooser.APPROVE_OPTION) entityCustomValues.setValueAt(jfc.getSelectedFile().getPath(), entityCustomValues.getSelectedRow(), 1);
}
});
uiP.add(browse);
uiP.add(new JLabel());
uiP.add(new JButton(new AbstractAction("Apply")
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
try
{
if (entityID.getText().length() == 0)
{
JOptionPane.showMessageDialog(Editor.this, "Please enter a unique identifier for that entity!", "Error!", JOptionPane.ERROR_MESSAGE);
return;
}
entities.getJSONObject(entityIndex).put("id", entityID.getText());
entities.getJSONObject(entityIndex).put("pos", new JSONArray(new Double[] { (double) entityPosX.getValue(), (double) entityPosY.getValue(), (double) entityPosZ.getValue() }));
entities.getJSONObject(entityIndex).put("rot", new JSONArray(new Double[] { (double) entityRotX.getValue(), (double) entityRotY.getValue(), (double) entityRotZ.getValue() }));
EntityBuilder builder = EntityRegistry.entries.get(entities.getJSONObject(entityIndex).getString("name"));
JSONObject custom = new JSONObject();
boolean valid = true;
String message = "";
for (int i = 0; i < entityCustomValues.getModel().getRowCount(); i++)
{
String name = entityCustomValues.getModel().getValueAt(i, 0).toString().replaceAll("( )(\\(.{1,}\\))", "");
String type = builder.customValues.get(name).getClass().getSimpleName();
String content = entityCustomValues.getModel().getValueAt(i, 1).toString();
if (type.equals("Integer"))
{
try
{
custom.put(name, Integer.parseInt(content));
}
catch (Exception e1)
{
message = "\"" + entityCustomValues.getModel().getValueAt(i, 0).toString() + "\": " + e1.getMessage();
valid = false;
break;
}
}
else if (type.equals("Float"))
{
try
{
custom.put(name, Float.parseFloat(content));
}
catch (Exception e1)
{
message = "\"" + entityCustomValues.getModel().getValueAt(i, 0).toString() + "\": " + e1.getMessage();
valid = false;
break;
}
}
else if (type.equals("Byte"))
{
try
{
custom.put(name, Byte.parseByte(content));
}
catch (Exception e1)
{
message = "\"" + entityCustomValues.getModel().getValueAt(i, 0).toString() + "\": " + e1.getMessage();
valid = false;
break;
}
}
else if (type.equals("Boolean"))
{
try
{
custom.put(name, Boolean.parseBoolean(content));
}
catch (Exception e1)
{
message = "\"" + entityCustomValues.getModel().getValueAt(i, 0).toString() + "\": " + e1.getMessage();
valid = false;
break;
}
}
else if (type.equals("File"))
{
try
{
custom.put(name, content);
}
catch (Exception e1)
{
message = "\"" + entityCustomValues.getModel().getValueAt(i, 0).toString() + "\": " + e1.getMessage();
valid = false;
break;
}
}
}
if (!valid)
{
JOptionPane.showMessageDialog(Editor.this, "Please enter your custom values in the same data type as specified in brackets!\n at " + message, "Error!", JOptionPane.ERROR_MESSAGE);
return;
}
entities.getJSONObject(entityIndex).put("custom", custom);
int selectedRow = tree.getSelectionRows()[0];
((DefaultMutableTreeNode) tree.getSelectionPath().getLastPathComponent()).setUserObject(entityID.getText());
((DefaultTreeModel) tree.getModel()).reload();
tree.expandRow(1);
tree.setSelectionRow(selectedRow);
refresh();
}
catch (JSONException e1)
{
e1.printStackTrace();
}
}
}));
SpringUtilities.makeCompactGrid(uiP, 8, 2, 6, 6, 6, 6);
uiPanel.add(uiP);
refresh();
}
catch (Exception e1)
{
e1.printStackTrace();
}
}
}
| public void valueChanged(TreeSelectionEvent e)
{
uiPanel.setLayout(new FlowLayout());
uiPanel.removeAll();
refresh();
final DefaultMutableTreeNode s = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
if (tree.getRowForPath(e.getPath()) == 1) // Entities
{
final JButton newEntity = new JButton();
final JComboBox<String> entities = new JComboBox<>(loadEntityList());
entities.setSelectedIndex(0);
entities.addItemListener(new ItemListener()
{
@Override
public void itemStateChanged(ItemEvent e)
{
if (e.getStateChange() == ItemEvent.SELECTED)
{
newEntity.setEnabled(entities.getSelectedIndex() > 0);
}
}
});
uiPanel.add(entities);
newEntity.setAction(new AbstractAction("New Entity")
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
DefaultTreeModel dtm = (DefaultTreeModel) tree.getModel();
dtm.insertNodeInto(new DefaultMutableTreeNode(s.getChildCount()), s, s.getChildCount());
tree.expandRow(1);
try
{
EntityBuilder builder = EntityLoader.loadEntity(entities.getSelectedItem().toString().replace(".entity", ""));
EntityRegistry.registerEntityBuilder(builder);
JSONObject object = new JSONObject();
object.put("name", entities.getSelectedItem().toString().replace(".entity", ""));
object.put("id", "" + (s.getChildCount() - 1));
object.put("pos", new JSONArray(new Double[] { 0d, 0d, 0d }));
object.put("rot", new JSONArray(new Double[] { 0d, 0d, 0d }));
JSONObject custom = new JSONObject();
for (String key : builder.customValues.keySet())
{
custom.put(key, builder.customValues.get(key));
}
object.put("custom", custom);
Editor.this.entities.put(object);
refresh();
}
catch (Exception e1)
{
e1.printStackTrace();
}
}
});
newEntity.setEnabled(false);
newEntity.setPreferredSize(new Dimension(300, 24));
uiPanel.add(newEntity);
refresh();
}
if (tree.getRowForPath(e.getPath()) > 1) // Entity1, Entity2, ...
{
try
{
if (entities.length() == 0) return;
final int entityIndex = tree.getRowForPath(e.getPath()) - 2;
if (tree.getRowForPath(e.getPath()) - 2 < 0) return;
JSONObject entity = entities.getJSONObject(tree.getRowForPath(e.getPath()) - 2);
EntityBuilder builder = EntityRegistry.entries.get(entity.getString("name"));
if (builder == null)
{
builder = EntityLoader.loadEntity(entity.getString("name"));
EntityRegistry.registerEntityBuilder(builder);
}
JPanel uiP = new JPanel(new SpringLayout());
uiP.add(new JLabel("Name:"));
JTextField name = new JTextField(builder.fullName + " (" + builder.name + ")");
name.setEditable(false);
uiP.add(name);
uiP.add(new JLabel("Parent:"));
JTextField parent = new JTextField(builder.parent);
parent.setEditable(false);
uiP.add(parent);
// TODO work
uiP.add(new JLabel("ID:"));
entityID = new JTextField(entity.getString("id"));
uiP.add(entityID);
uiP.add(new JLabel("Position:"));
JPanel panel = new JPanel();
entityPosX = new JSpinner(new SpinnerNumberModel(entity.getJSONArray("pos").getDouble(0), -1000000, 1000000, 1));
panel.add(entityPosX);
entityPosY = new JSpinner(new SpinnerNumberModel(entity.getJSONArray("pos").getDouble(1), -1000000, 1000000, 1));
panel.add(entityPosY);
entityPosZ = new JSpinner(new SpinnerNumberModel(entity.getJSONArray("pos").getDouble(2), -1000000, 1000000, 1));
panel.add(entityPosZ);
uiP.add(panel);
uiP.add(new JLabel("Rotation:"));
panel = new JPanel();
entityRotX = new JSpinner(new SpinnerNumberModel(entity.getJSONArray("rot").getDouble(0), -1000000, 1000000, 1));
panel.add(entityRotX);
entityRotY = new JSpinner(new SpinnerNumberModel(entity.getJSONArray("rot").getDouble(1), -1000000, 1000000, 1));
panel.add(entityRotY);
entityRotZ = new JSpinner(new SpinnerNumberModel(entity.getJSONArray("rot").getDouble(2), -1000000, 1000000, 1));
panel.add(entityRotZ);
uiP.add(panel);
uiP.add(new JLabel("Custom Values:"));
final String[][] data = new String[builder.customValues.size()][2];
ArrayList<String> keys = new ArrayList<>(builder.customValues.keySet());
for (int i = 0; i < data.length; i++)
{
data[i] = new String[] { keys.get(i) + " (" + builder.customValues.get(keys.get(i)).getClass().getSimpleName() + ")", ((entity.getJSONObject("custom").has(keys.get(i))) ? entity.getJSONObject("custom").get(keys.get(i)).toString() : builder.customValues.get(keys.get(i)).toString()).toString() };
}
final JButton browse = new JButton("Browse...");
browse.setEnabled(false);
entityCustomValues = new JTable(new DefaultTableModel(data, new String[] { "Name (Type)", "Value" }))
{
private static final long serialVersionUID = 1L;
public boolean isCellEditable(int row, int column)
{
if (column == 0) return false; // name column
if (column == 1 && entityCustomValues.getValueAt(row, 0).toString().contains("(File)")) return false; // file type
return true;
}
};
entityCustomValues.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
JScrollPane jsp = new JScrollPane(entityCustomValues, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
entityCustomValues.setFillsViewportHeight(true);
entityCustomValues.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
entityCustomValues.getSelectionModel().addListSelectionListener(new ListSelectionListener()
{
@Override
public void valueChanged(ListSelectionEvent e)
{
if (e.getValueIsAdjusting() || entityCustomValues.getSelectedRow() == -1) return;
browse.setEnabled(data[entityCustomValues.getSelectedRow()][0].contains("(File)"));
}
});
jsp.setPreferredSize(new Dimension(entityCustomValues.getWidth(), 150));
uiP.add(jsp);
uiP.add(new JLabel());
browse.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
JFileChooser jfc = new JFileChooser("C:/");
jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
jfc.setMultiSelectionEnabled(false);
if (jfc.showSaveDialog(Editor.this) == JFileChooser.APPROVE_OPTION) entityCustomValues.setValueAt(jfc.getSelectedFile().getPath().replace("\\", "/"), entityCustomValues.getSelectedRow(), 1);
}
});
uiP.add(browse);
uiP.add(new JLabel());
uiP.add(new JButton(new AbstractAction("Apply")
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
try
{
if (entityID.getText().length() == 0)
{
JOptionPane.showMessageDialog(Editor.this, "Please enter a unique identifier for that entity!", "Error!", JOptionPane.ERROR_MESSAGE);
return;
}
entities.getJSONObject(entityIndex).put("id", entityID.getText());
entities.getJSONObject(entityIndex).put("pos", new JSONArray(new Double[] { (double) entityPosX.getValue(), (double) entityPosY.getValue(), (double) entityPosZ.getValue() }));
entities.getJSONObject(entityIndex).put("rot", new JSONArray(new Double[] { (double) entityRotX.getValue(), (double) entityRotY.getValue(), (double) entityRotZ.getValue() }));
EntityBuilder builder = EntityRegistry.entries.get(entities.getJSONObject(entityIndex).getString("name"));
JSONObject custom = new JSONObject();
boolean valid = true;
String message = "";
for (int i = 0; i < entityCustomValues.getModel().getRowCount(); i++)
{
String name = entityCustomValues.getModel().getValueAt(i, 0).toString().replaceAll("( )(\\(.{1,}\\))", "");
String type = builder.customValues.get(name).getClass().getSimpleName();
String content = entityCustomValues.getModel().getValueAt(i, 1).toString();
if (type.equals("Integer"))
{
try
{
custom.put(name, Integer.parseInt(content));
}
catch (Exception e1)
{
message = "\"" + entityCustomValues.getModel().getValueAt(i, 0).toString() + "\": " + e1.getMessage();
valid = false;
break;
}
}
else if (type.equals("Float"))
{
try
{
custom.put(name, Float.parseFloat(content));
}
catch (Exception e1)
{
message = "\"" + entityCustomValues.getModel().getValueAt(i, 0).toString() + "\": " + e1.getMessage();
valid = false;
break;
}
}
else if (type.equals("Byte"))
{
try
{
custom.put(name, Byte.parseByte(content));
}
catch (Exception e1)
{
message = "\"" + entityCustomValues.getModel().getValueAt(i, 0).toString() + "\": " + e1.getMessage();
valid = false;
break;
}
}
else if (type.equals("Boolean"))
{
try
{
custom.put(name, Boolean.parseBoolean(content));
}
catch (Exception e1)
{
message = "\"" + entityCustomValues.getModel().getValueAt(i, 0).toString() + "\": " + e1.getMessage();
valid = false;
break;
}
}
else if (type.equals("File"))
{
try
{
custom.put(name, content);
}
catch (Exception e1)
{
message = "\"" + entityCustomValues.getModel().getValueAt(i, 0).toString() + "\": " + e1.getMessage();
valid = false;
break;
}
}
}
if (!valid)
{
JOptionPane.showMessageDialog(Editor.this, "Please enter your custom values in the same data type as specified in brackets!\n at " + message, "Error!", JOptionPane.ERROR_MESSAGE);
return;
}
entities.getJSONObject(entityIndex).put("custom", custom);
int selectedRow = tree.getSelectionRows()[0];
((DefaultMutableTreeNode) tree.getSelectionPath().getLastPathComponent()).setUserObject(entityID.getText());
((DefaultTreeModel) tree.getModel()).reload();
tree.expandRow(1);
tree.setSelectionRow(selectedRow);
refresh();
}
catch (JSONException e1)
{
e1.printStackTrace();
}
}
}));
SpringUtilities.makeCompactGrid(uiP, 8, 2, 6, 6, 6, 6);
uiPanel.add(uiP);
refresh();
}
catch (Exception e1)
{
e1.printStackTrace();
}
}
}
|
diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/TextOperationAction.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/TextOperationAction.java
index 4aba59c67..3dbf9f2e6 100644
--- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/TextOperationAction.java
+++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/TextOperationAction.java
@@ -1,161 +1,165 @@
/**********************************************************************
Copyright (c) 2000, 2002 IBM Corp. and others.
All rights reserved. This program and the accompanying materials
are made available under the terms of the Common Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/cpl-v10.html
Contributors:
IBM Corporation - Initial implementation
**********************************************************************/
package org.eclipse.ui.texteditor;
import java.util.ResourceBundle;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.ui.IWorkbenchPartSite;
/**
* An action which gets a text operation target from its text editor.
* <p>
* The action is initially associated with a text editor via the constructor,
* but can subsequently be changed using <code>setEditor</code>.
* </p>
* <p>
* If this class is used as is, it works by asking the text editor for its
* text operation target adapter (using <code>getAdapter(ITextOperationTarget.class)</code>.
* The action runs this operation with the pre-configured opcode.
* </p>
*/
public final class TextOperationAction extends TextEditorAction {
/** The text operation code */
private int fOperationCode= -1;
/** The text operation target */
private ITextOperationTarget fOperationTarget;
/**
* Indicates whether this action can be executed on read only editors
* @since 2.0
*/
private boolean fRunsOnReadOnly= false;
/**
* Creates and initializes the action for the given text editor and operation
* code. The action configures its visual representation from the given resource
* bundle. The action works by asking the text editor at the time for its
* text operation target adapter (using
* <code>getAdapter(ITextOperationTarget.class)</code>. The action runs that
* operation with the given opcode.
*
* @param bundle the resource bundle
* @param prefix a prefix to be prepended to the various resource keys
* (described in <code>ResourceAction</code> constructor), or
* <code>null</code> if none
* @param editor the text editor
* @param operationCode the operation code
* @see ResourceAction#ResourceAction
*/
public TextOperationAction(ResourceBundle bundle, String prefix, ITextEditor editor, int operationCode) {
super(bundle, prefix, editor);
fOperationCode= operationCode;
update();
}
/**
* Creates and initializes the action for the given text editor and operation
* code. The action configures its visual representation from the given resource
* bundle. The action works by asking the text editor at the time for its
* text operation target adapter (using
* <code>getAdapter(ITextOperationTarget.class)</code>. The action runs that
* operation with the given opcode.
*
* @param bundle the resource bundle
* @param prefix a prefix to be prepended to the various resource keys
* (described in <code>ResourceAction</code> constructor), or
* <code>null</code> if none
* @param editor the text editor
* @param operationCode the operation code
* @param runsOnReadOnly <code>true</code> if action can be executed on read-only files
*
* @see ResourceAction#ResourceAction
* @since 2.0
*/
public TextOperationAction(ResourceBundle bundle, String prefix, ITextEditor editor, int operationCode, boolean runsOnReadOnly) {
super(bundle, prefix, editor);
fOperationCode= operationCode;
fRunsOnReadOnly= runsOnReadOnly;
update();
}
/**
* The <code>TextOperationAction</code> implementation of this
* <code>IAction</code> method runs the operation with the current
* operation code.
*/
public void run() {
if (fOperationCode == -1 || fOperationTarget == null)
return;
ITextEditor editor= getTextEditor();
if (editor == null)
return;
- if (editor instanceof ITextEditorExtension2)
- if (!fRunsOnReadOnly && ! ((ITextEditorExtension2) editor).validateEditorInputState())
- return;
+ if (!fRunsOnReadOnly) {
+ if (editor instanceof ITextEditorExtension2) {
+ ITextEditorExtension2 extension= (ITextEditorExtension2) editor;
+ if (!extension.validateEditorInputState())
+ return;
+ }
+ }
Display display= null;
IWorkbenchPartSite site= editor.getSite();
Shell shell= site.getShell();
if (shell != null && !shell.isDisposed())
display= shell.getDisplay();
BusyIndicator.showWhile(display, new Runnable() {
public void run() {
fOperationTarget.doOperation(fOperationCode);
}
});
}
/**
* The <code>TextOperationAction</code> implementation of this
* <code>IUpdate</code> method discovers the operation through the current
* editor's <code>ITextOperationTarget</code> adapter, and sets the
* enabled state accordingly.
*/
public void update() {
ITextEditor editor= getTextEditor();
if (editor instanceof ITextEditorExtension2) {
ITextEditorExtension2 extension= (ITextEditorExtension2) editor;
if (!extension.isEditorInputModifiable() && !fRunsOnReadOnly) {
setEnabled(false);
return;
}
}
if (fOperationTarget == null && editor!= null && fOperationCode != -1)
fOperationTarget= (ITextOperationTarget) editor.getAdapter(ITextOperationTarget.class);
boolean isEnabled= (fOperationTarget != null && fOperationTarget.canDoOperation(fOperationCode));
setEnabled(isEnabled);
}
/*
* @see TextEditorAction#setEditor(ITextEditor)
*/
public void setEditor(ITextEditor editor) {
super.setEditor(editor);
fOperationTarget= null;
}
}
| true | true | public void run() {
if (fOperationCode == -1 || fOperationTarget == null)
return;
ITextEditor editor= getTextEditor();
if (editor == null)
return;
if (editor instanceof ITextEditorExtension2)
if (!fRunsOnReadOnly && ! ((ITextEditorExtension2) editor).validateEditorInputState())
return;
Display display= null;
IWorkbenchPartSite site= editor.getSite();
Shell shell= site.getShell();
if (shell != null && !shell.isDisposed())
display= shell.getDisplay();
BusyIndicator.showWhile(display, new Runnable() {
public void run() {
fOperationTarget.doOperation(fOperationCode);
}
});
}
| public void run() {
if (fOperationCode == -1 || fOperationTarget == null)
return;
ITextEditor editor= getTextEditor();
if (editor == null)
return;
if (!fRunsOnReadOnly) {
if (editor instanceof ITextEditorExtension2) {
ITextEditorExtension2 extension= (ITextEditorExtension2) editor;
if (!extension.validateEditorInputState())
return;
}
}
Display display= null;
IWorkbenchPartSite site= editor.getSite();
Shell shell= site.getShell();
if (shell != null && !shell.isDisposed())
display= shell.getDisplay();
BusyIndicator.showWhile(display, new Runnable() {
public void run() {
fOperationTarget.doOperation(fOperationCode);
}
});
}
|
diff --git a/src/main/java/org/glom/web/server/OnlineGlomServiceImpl.java b/src/main/java/org/glom/web/server/OnlineGlomServiceImpl.java
index cd8b744..8ddefd3 100644
--- a/src/main/java/org/glom/web/server/OnlineGlomServiceImpl.java
+++ b/src/main/java/org/glom/web/server/OnlineGlomServiceImpl.java
@@ -1,454 +1,457 @@
/*
* Copyright (C) 2010, 2011 Openismus GmbH
*
* This file is part of GWT-Glom.
*
* GWT-Glom is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* GWT-Glom is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GWT-Glom. If not, see <http://www.gnu.org/licenses/>.
*/
package org.glom.web.server;
import java.io.File;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Properties;
import javax.servlet.ServletException;
import org.glom.libglom.BakeryDocument.LoadFailureCodes;
import org.glom.libglom.Document;
import org.glom.libglom.Glom;
import org.glom.web.client.OnlineGlomService;
import org.glom.web.shared.DataItem;
import org.glom.web.shared.DetailsLayoutAndData;
import org.glom.web.shared.DocumentInfo;
import org.glom.web.shared.Documents;
import org.glom.web.shared.NavigationRecord;
import org.glom.web.shared.TypedDataItem;
import org.glom.web.shared.layout.LayoutGroup;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.mchange.v2.c3p0.DataSources;
/**
* The servlet class for setting up the server side of Online Glom. The public methods in this class are the methods
* that can be called by the client side code.
*
* @author Ben Konrath <[email protected]>
*/
@SuppressWarnings("serial")
public class OnlineGlomServiceImpl extends RemoteServiceServlet implements OnlineGlomService {
private static final String GLOM_FILE_EXTENSION = ".glom";
// convenience class to for dealing with the Online Glom configuration file
private class OnlineGlomProperties extends Properties {
public String getKey(String value) {
for (String key : stringPropertyNames()) {
if (getProperty(key).trim().equals(value))
return key;
}
return null;
}
}
private final Hashtable<String, ConfiguredDocument> documentMapping = new Hashtable<String, ConfiguredDocument>();
private Exception configurtionException = null;
/*
* This is called when the servlet is started or restarted.
*
* (non-Javadoc)
*
* @see javax.servlet.GenericServlet#init()
*/
@Override
public void init() throws ServletException {
// All of the initialisation code is surrounded by a try/catch block so that the servlet can be in an
// initialised state and the error message can be retrived by the client code.
try {
// Find the configuration file. See this thread for background info:
// http://stackoverflow.com/questions/2161054/where-to-place-properties-files-in-a-jsp-servlet-web-application
// FIXME move onlineglom.properties to the WEB-INF folder (option number 2 from the stackoverflow question)
OnlineGlomProperties config = new OnlineGlomProperties();
InputStream is = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("onlineglom.properties");
if (is == null) {
String errorMessage = "onlineglom.properties not found.";
Log.fatal(errorMessage);
throw new Exception(errorMessage);
}
config.load(is); // can throw an IOException
// check if we can read the configured glom file directory
String documentDirName = config.getProperty("glom.document.directory");
File documentDir = new File(documentDirName);
if (!documentDir.isDirectory()) {
String errorMessage = documentDirName + " is not a directory.";
Log.fatal(errorMessage);
throw new Exception(errorMessage);
}
if (!documentDir.canRead()) {
String errorMessage = "Can't read the files in directory " + documentDirName + " .";
Log.fatal(errorMessage);
throw new Exception(errorMessage);
}
// get and check the glom files in the specified directory
File[] glomFiles = documentDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(GLOM_FILE_EXTENSION);
}
});
// don't continue if there aren't any Glom files to configure
if (glomFiles.length <= 0) {
String errorMessage = "Unable to find any Glom documents in the configured directory "
+ documentDirName
+ " . Check the onlineglom.properties file to ensure that 'glom.document.directory' is set to the correct directory.";
Log.error(errorMessage);
throw new Exception(errorMessage);
}
// Check to see if the native library of java libglom is visible to the JVM
- if (!isNativeLibraryVisibleToJVM())
- throw new Exception("The java-libglom shared library is not visible to the JVM."
- + " Ensure that 'java.library.path' is set with the path to the java-libglom shared library.");
+ if (!isNativeLibraryVisibleToJVM()) {
+ String errorMessage = "The java-libglom shared library is not visible to the JVM."
+ + " Ensure that 'java.library.path' is set with the path to the java-libglom shared library.";
+ Log.error(errorMessage);
+ throw new Exception(errorMessage);
+ }
// intitize libglom
Glom.libglom_init(); // can throw an UnsatisfiedLinkError exception
// Allow a fake connection, so sqlbuilder_get_full_query() can work:
Glom.set_fake_connection();
for (File glomFile : glomFiles) {
Document document = new Document();
document.set_file_uri("file://" + glomFile.getAbsolutePath());
int error = 0;
boolean retval = document.load(error);
if (retval == false) {
String message;
if (LoadFailureCodes.LOAD_FAILURE_CODE_NOT_FOUND == LoadFailureCodes.swigToEnum(error)) {
message = "Could not find file: " + glomFile.getAbsolutePath();
} else {
message = "An unknown error occurred when trying to load file: " + glomFile.getAbsolutePath();
}
Log.error(message);
// continue with for loop because there may be other documents in the directory
continue;
}
ConfiguredDocument configuredDocument = new ConfiguredDocument(document); // can throw a
// PropertyVetoException
// check if a username and password have been set and work for the current document
String filename = glomFile.getName();
String key = config.getKey(filename);
if (key != null) {
String[] keyArray = key.split("\\.");
if (keyArray.length == 3 && "filename".equals(keyArray[2])) {
// username/password could be set, let's check to see if it works
String usernameKey = key.replaceAll(keyArray[2], "username");
String passwordKey = key.replaceAll(keyArray[2], "password");
configuredDocument.setUsernameAndPassword(config.getProperty(usernameKey).trim(),
config.getProperty(passwordKey)); // can throw an SQLException
}
}
// check the if the global username and password have been set and work with this document
if (!configuredDocument.isAuthenticated()) {
configuredDocument.setUsernameAndPassword(config.getProperty("glom.document.username").trim(),
config.getProperty("glom.document.password")); // can throw an SQLException
}
// The key for the hash table is the file name without the .glom extension and with spaces ( ) replaced
// with pluses (+). The space/plus replacement makes the key more friendly for URLs.
String documentID = filename.substring(0, glomFile.getName().length() - GLOM_FILE_EXTENSION.length())
.replace(' ', '+');
configuredDocument.setDocumentID(documentID);
documentMapping.put(documentID, configuredDocument);
}
} catch (Exception e) {
// Don't throw the Exception so that servlet will be initialised and the error message can be retrieved.
configurtionException = e;
}
}
/**
* Checks if the java-libglom native library is visible to the JVM.
*
* @return true if the java-libglom native library is visible to the JVM, false if it's not
*/
private boolean isNativeLibraryVisibleToJVM() {
String javaLibraryPath = System.getProperty("java.library.path");
// Go through all the library paths and check for the java_libglom .so.
for (String libDirName : javaLibraryPath.split(":")) {
File libDir = new File(libDirName);
if (!libDir.isDirectory())
continue;
if (!libDir.canRead())
continue;
File[] libs = libDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.matches("libjava_libglom-[0-9]\\.[0-9].+\\.so");
}
});
// if at least one directory had the .so, we're done
if (libs.length > 0)
return true;
}
return false;
}
/*
* This is called when the servlet is stopped or restarted.
*
* @see javax.servlet.GenericServlet#destroy()
*/
@Override
public void destroy() {
Glom.libglom_deinit();
for (String documenTitle : documentMapping.keySet()) {
ConfiguredDocument configuredDoc = documentMapping.get(documenTitle);
try {
DataSources.destroy(configuredDoc.getCpds());
} catch (SQLException e) {
Log.error(documenTitle, "Error cleaning up the ComboPooledDataSource.", e);
}
}
}
/*
* (non-Javadoc)
*
* @see org.glom.web.client.OnlineGlomService#getConfigurationErrorMessage()
*/
@Override
public String getConfigurationErrorMessage() {
if (configurtionException == null)
return "No configuration errors to report.";
else
return configurtionException.getMessage();
}
/*
* (non-Javadoc)
*
* @see org.glom.web.client.OnlineGlomService#getDocumentInfo(java.lang.String)
*/
@Override
public DocumentInfo getDocumentInfo(String documentID) {
ConfiguredDocument configuredDoc = documentMapping.get(documentID);
// FIXME check for authentication
return configuredDoc.getDocumentInfo();
}
/*
* (non-Javadoc)
*
* @see org.glom.web.client.OnlineGlomService#getListViewLayout(java.lang.String, java.lang.String)
*/
@Override
public LayoutGroup getListViewLayout(String documentID, String tableName) {
ConfiguredDocument configuredDoc = documentMapping.get(documentID);
// FIXME check for authentication
return configuredDoc.getListViewLayoutGroup(tableName);
}
/*
* (non-Javadoc)
*
* @see org.glom.web.client.OnlineGlomService#getListViewData(java.lang.String, java.lang.String, int, int)
*/
@Override
public ArrayList<DataItem[]> getListViewData(String documentID, String tableName, int start, int length) {
ConfiguredDocument configuredDoc = documentMapping.get(documentID);
if (!configuredDoc.isAuthenticated()) {
return new ArrayList<DataItem[]>();
}
return configuredDoc.getListViewData(tableName, start, length, false, 0, false);
}
/*
* (non-Javadoc)
*
* @see org.glom.web.client.OnlineGlomService#getSortedListViewData(java.lang.String, java.lang.String, int, int,
* int, boolean)
*/
@Override
public ArrayList<DataItem[]> getSortedListViewData(String documentID, String tableName, int start, int length,
int sortColumnIndex, boolean isAscending) {
ConfiguredDocument configuredDoc = documentMapping.get(documentID);
if (!configuredDoc.isAuthenticated()) {
return new ArrayList<DataItem[]>();
}
return configuredDoc.getListViewData(tableName, start, length, true, sortColumnIndex, isAscending);
}
/*
* (non-Javadoc)
*
* @see org.glom.web.client.OnlineGlomService#getDocuments()
*/
@Override
public Documents getDocuments() {
Documents documents = new Documents();
for (String documentID : documentMapping.keySet()) {
ConfiguredDocument configuredDoc = documentMapping.get(documentID);
documents.addDocument(documentID, configuredDoc.getDocument().get_database_title());
}
return documents;
}
/*
* (non-Javadoc)
*
* @see org.glom.web.client.OnlineGlomService#isAuthenticated(java.lang.String)
*/
public boolean isAuthenticated(String documentID) {
return documentMapping.get(documentID).isAuthenticated();
}
/*
* (non-Javadoc)
*
* @see org.glom.web.client.OnlineGlomService#checkAuthentication(java.lang.String, java.lang.String,
* java.lang.String)
*/
@Override
public boolean checkAuthentication(String documentID, String username, String password) {
ConfiguredDocument configuredDoc = documentMapping.get(documentID);
try {
return configuredDoc.setUsernameAndPassword(username, password);
} catch (SQLException e) {
Log.error(documentID, "Unknown SQL Error checking the database authentication.", e);
return false;
}
}
/*
* (non-Javadoc)
*
* @see org.glom.web.client.OnlineGlomService#getDetailsData(java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public DataItem[] getDetailsData(String documentID, String tableName, TypedDataItem primaryKeyValue) {
ConfiguredDocument configuredDoc = documentMapping.get(documentID);
// FIXME check for authentication
return configuredDoc.getDetailsData(tableName, primaryKeyValue);
}
/*
* (non-Javadoc)
*
* @see org.glom.web.client.OnlineGlomService#getDetailsLayoutAndData(java.lang.String, java.lang.String,
* java.lang.String)
*/
@Override
public DetailsLayoutAndData getDetailsLayoutAndData(String documentID, String tableName,
TypedDataItem primaryKeyValue) {
ConfiguredDocument configuredDoc = documentMapping.get(documentID);
if (configuredDoc == null)
return null;
// FIXME check for authentication
DetailsLayoutAndData initalDetailsView = new DetailsLayoutAndData();
initalDetailsView.setLayout(configuredDoc.getDetailsLayoutGroup(tableName));
initalDetailsView.setData(configuredDoc.getDetailsData(tableName, primaryKeyValue));
return initalDetailsView;
}
/*
* (non-Javadoc)
*
* @see org.glom.web.client.OnlineGlomService#getRelatedListData(java.lang.String, java.lang.String, int, int)
*/
@Override
public ArrayList<DataItem[]> getRelatedListData(String documentID, String tableName, String relationshipName,
TypedDataItem foreignKeyValue, int start, int length) {
ConfiguredDocument configuredDoc = documentMapping.get(documentID);
// FIXME check for authentication
return configuredDoc.getRelatedListData(tableName, relationshipName, foreignKeyValue, start, length, false, 0,
false);
}
/*
* (non-Javadoc)
*
* @see org.glom.web.client.OnlineGlomService#getSortedRelatedListData(java.lang.String, java.lang.String, int, int,
* int, boolean)
*/
@Override
public ArrayList<DataItem[]> getSortedRelatedListData(String documentID, String tableName, String relationshipName,
TypedDataItem foreignKeyValue, int start, int length, int sortColumnIndex, boolean ascending) {
ConfiguredDocument configuredDoc = documentMapping.get(documentID);
// FIXME check for authentication
return configuredDoc.getRelatedListData(tableName, relationshipName, foreignKeyValue, start, length, true,
sortColumnIndex, ascending);
}
public int getRelatedListRowCount(String documentID, String tableName, String relationshipName,
TypedDataItem foreignKeyValue) {
ConfiguredDocument configuredDoc = documentMapping.get(documentID);
// FIXME check for authentication
return configuredDoc.getRelatedListRowCount(tableName, relationshipName, foreignKeyValue);
}
/*
* (non-Javadoc)
*
* @see org.glom.web.client.OnlineGlomService#getSuitableRecordToViewDetails(java.lang.String, java.lang.String,
* java.lang.String, java.lang.String)
*/
@Override
public NavigationRecord getSuitableRecordToViewDetails(String documentID, String tableName,
String relationshipName, TypedDataItem primaryKeyValue) {
ConfiguredDocument configuredDoc = documentMapping.get(documentID);
// FIXME check for authentication
return configuredDoc.getSuitableRecordToViewDetails(tableName, relationshipName, primaryKeyValue);
}
}
| true | true | public void init() throws ServletException {
// All of the initialisation code is surrounded by a try/catch block so that the servlet can be in an
// initialised state and the error message can be retrived by the client code.
try {
// Find the configuration file. See this thread for background info:
// http://stackoverflow.com/questions/2161054/where-to-place-properties-files-in-a-jsp-servlet-web-application
// FIXME move onlineglom.properties to the WEB-INF folder (option number 2 from the stackoverflow question)
OnlineGlomProperties config = new OnlineGlomProperties();
InputStream is = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("onlineglom.properties");
if (is == null) {
String errorMessage = "onlineglom.properties not found.";
Log.fatal(errorMessage);
throw new Exception(errorMessage);
}
config.load(is); // can throw an IOException
// check if we can read the configured glom file directory
String documentDirName = config.getProperty("glom.document.directory");
File documentDir = new File(documentDirName);
if (!documentDir.isDirectory()) {
String errorMessage = documentDirName + " is not a directory.";
Log.fatal(errorMessage);
throw new Exception(errorMessage);
}
if (!documentDir.canRead()) {
String errorMessage = "Can't read the files in directory " + documentDirName + " .";
Log.fatal(errorMessage);
throw new Exception(errorMessage);
}
// get and check the glom files in the specified directory
File[] glomFiles = documentDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(GLOM_FILE_EXTENSION);
}
});
// don't continue if there aren't any Glom files to configure
if (glomFiles.length <= 0) {
String errorMessage = "Unable to find any Glom documents in the configured directory "
+ documentDirName
+ " . Check the onlineglom.properties file to ensure that 'glom.document.directory' is set to the correct directory.";
Log.error(errorMessage);
throw new Exception(errorMessage);
}
// Check to see if the native library of java libglom is visible to the JVM
if (!isNativeLibraryVisibleToJVM())
throw new Exception("The java-libglom shared library is not visible to the JVM."
+ " Ensure that 'java.library.path' is set with the path to the java-libglom shared library.");
// intitize libglom
Glom.libglom_init(); // can throw an UnsatisfiedLinkError exception
// Allow a fake connection, so sqlbuilder_get_full_query() can work:
Glom.set_fake_connection();
for (File glomFile : glomFiles) {
Document document = new Document();
document.set_file_uri("file://" + glomFile.getAbsolutePath());
int error = 0;
boolean retval = document.load(error);
if (retval == false) {
String message;
if (LoadFailureCodes.LOAD_FAILURE_CODE_NOT_FOUND == LoadFailureCodes.swigToEnum(error)) {
message = "Could not find file: " + glomFile.getAbsolutePath();
} else {
message = "An unknown error occurred when trying to load file: " + glomFile.getAbsolutePath();
}
Log.error(message);
// continue with for loop because there may be other documents in the directory
continue;
}
ConfiguredDocument configuredDocument = new ConfiguredDocument(document); // can throw a
// PropertyVetoException
// check if a username and password have been set and work for the current document
String filename = glomFile.getName();
String key = config.getKey(filename);
if (key != null) {
String[] keyArray = key.split("\\.");
if (keyArray.length == 3 && "filename".equals(keyArray[2])) {
// username/password could be set, let's check to see if it works
String usernameKey = key.replaceAll(keyArray[2], "username");
String passwordKey = key.replaceAll(keyArray[2], "password");
configuredDocument.setUsernameAndPassword(config.getProperty(usernameKey).trim(),
config.getProperty(passwordKey)); // can throw an SQLException
}
}
// check the if the global username and password have been set and work with this document
if (!configuredDocument.isAuthenticated()) {
configuredDocument.setUsernameAndPassword(config.getProperty("glom.document.username").trim(),
config.getProperty("glom.document.password")); // can throw an SQLException
}
// The key for the hash table is the file name without the .glom extension and with spaces ( ) replaced
// with pluses (+). The space/plus replacement makes the key more friendly for URLs.
String documentID = filename.substring(0, glomFile.getName().length() - GLOM_FILE_EXTENSION.length())
.replace(' ', '+');
configuredDocument.setDocumentID(documentID);
documentMapping.put(documentID, configuredDocument);
}
} catch (Exception e) {
// Don't throw the Exception so that servlet will be initialised and the error message can be retrieved.
configurtionException = e;
}
}
| public void init() throws ServletException {
// All of the initialisation code is surrounded by a try/catch block so that the servlet can be in an
// initialised state and the error message can be retrived by the client code.
try {
// Find the configuration file. See this thread for background info:
// http://stackoverflow.com/questions/2161054/where-to-place-properties-files-in-a-jsp-servlet-web-application
// FIXME move onlineglom.properties to the WEB-INF folder (option number 2 from the stackoverflow question)
OnlineGlomProperties config = new OnlineGlomProperties();
InputStream is = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("onlineglom.properties");
if (is == null) {
String errorMessage = "onlineglom.properties not found.";
Log.fatal(errorMessage);
throw new Exception(errorMessage);
}
config.load(is); // can throw an IOException
// check if we can read the configured glom file directory
String documentDirName = config.getProperty("glom.document.directory");
File documentDir = new File(documentDirName);
if (!documentDir.isDirectory()) {
String errorMessage = documentDirName + " is not a directory.";
Log.fatal(errorMessage);
throw new Exception(errorMessage);
}
if (!documentDir.canRead()) {
String errorMessage = "Can't read the files in directory " + documentDirName + " .";
Log.fatal(errorMessage);
throw new Exception(errorMessage);
}
// get and check the glom files in the specified directory
File[] glomFiles = documentDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(GLOM_FILE_EXTENSION);
}
});
// don't continue if there aren't any Glom files to configure
if (glomFiles.length <= 0) {
String errorMessage = "Unable to find any Glom documents in the configured directory "
+ documentDirName
+ " . Check the onlineglom.properties file to ensure that 'glom.document.directory' is set to the correct directory.";
Log.error(errorMessage);
throw new Exception(errorMessage);
}
// Check to see if the native library of java libglom is visible to the JVM
if (!isNativeLibraryVisibleToJVM()) {
String errorMessage = "The java-libglom shared library is not visible to the JVM."
+ " Ensure that 'java.library.path' is set with the path to the java-libglom shared library.";
Log.error(errorMessage);
throw new Exception(errorMessage);
}
// intitize libglom
Glom.libglom_init(); // can throw an UnsatisfiedLinkError exception
// Allow a fake connection, so sqlbuilder_get_full_query() can work:
Glom.set_fake_connection();
for (File glomFile : glomFiles) {
Document document = new Document();
document.set_file_uri("file://" + glomFile.getAbsolutePath());
int error = 0;
boolean retval = document.load(error);
if (retval == false) {
String message;
if (LoadFailureCodes.LOAD_FAILURE_CODE_NOT_FOUND == LoadFailureCodes.swigToEnum(error)) {
message = "Could not find file: " + glomFile.getAbsolutePath();
} else {
message = "An unknown error occurred when trying to load file: " + glomFile.getAbsolutePath();
}
Log.error(message);
// continue with for loop because there may be other documents in the directory
continue;
}
ConfiguredDocument configuredDocument = new ConfiguredDocument(document); // can throw a
// PropertyVetoException
// check if a username and password have been set and work for the current document
String filename = glomFile.getName();
String key = config.getKey(filename);
if (key != null) {
String[] keyArray = key.split("\\.");
if (keyArray.length == 3 && "filename".equals(keyArray[2])) {
// username/password could be set, let's check to see if it works
String usernameKey = key.replaceAll(keyArray[2], "username");
String passwordKey = key.replaceAll(keyArray[2], "password");
configuredDocument.setUsernameAndPassword(config.getProperty(usernameKey).trim(),
config.getProperty(passwordKey)); // can throw an SQLException
}
}
// check the if the global username and password have been set and work with this document
if (!configuredDocument.isAuthenticated()) {
configuredDocument.setUsernameAndPassword(config.getProperty("glom.document.username").trim(),
config.getProperty("glom.document.password")); // can throw an SQLException
}
// The key for the hash table is the file name without the .glom extension and with spaces ( ) replaced
// with pluses (+). The space/plus replacement makes the key more friendly for URLs.
String documentID = filename.substring(0, glomFile.getName().length() - GLOM_FILE_EXTENSION.length())
.replace(' ', '+');
configuredDocument.setDocumentID(documentID);
documentMapping.put(documentID, configuredDocument);
}
} catch (Exception e) {
// Don't throw the Exception so that servlet will be initialised and the error message can be retrieved.
configurtionException = e;
}
}
|
diff --git a/src/sc2build/optimizer/EntityLoader.java b/src/sc2build/optimizer/EntityLoader.java
index 3c5a6bc..bbcbf62 100644
--- a/src/sc2build/optimizer/EntityLoader.java
+++ b/src/sc2build/optimizer/EntityLoader.java
@@ -1,175 +1,175 @@
package sc2build.optimizer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import sc2build.optimizer.SC2Planner.Entity;
import sc2build.optimizer.SC2Planner.Cost;
import sc2build.optimizer.SC2Planner.NeedEntity;
import sc2build.optimizer.SC2Planner.Race;
public class EntityLoader
{
private final static Map<String, Race> data = new HashMap<>();
public JSONArray loadData() throws IOException, JSONException
{
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader("./js/data.js"));
String line = null;
while ((line = br.readLine()) != null)
{
sb.append(line);
}
String dataJson = sb.toString();
JSONArray arr = new JSONArray(dataJson);
return arr;
}
public List<Entity> load(String name)
{
Race race = EntityLoader.data.get(name);
return race.entities;
}
public void init()
{
try
{
JSONArray arr = this.loadData();
for (int i = 0; i < arr.length(); i++)
{
JSONObject raceEntity = arr.getJSONObject(i);
Race race = new Race();
race.entities = new ArrayList<>();
String raceName = raceEntity.getString("name");
JSONArray entitiesArray = raceEntity.getJSONArray("entities");
for (int j = 0; j < entitiesArray.length(); j++)
{
JSONObject entityObj = entitiesArray.getJSONObject(j);
Entity ent = new Entity();
this.loadEntity(ent, entityObj);
race.entities.add(ent);
}
EntityLoader.data.put(raceName, race);
}
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
private void loadEntity(Entity ent, JSONObject obj) throws JSONException
{
if (ent == null || obj == null) return;
ent.name = obj.getString("name");
ent.adding = obj.getString("adding");
ent.currentError = obj.getString("currentError");
ent.multi = obj.getString("multi");
ent.save = obj.getString("save");
ent.style = obj.getString("style");
String sectionStr = obj.getString("section");
- if (sectionStr != null)
+ if (sectionStr.length() > 0)
{
ent.section = Section.valueOf(sectionStr);
}
ent.autocheck = obj.getBoolean("autocheck");
ent.time = obj.getInt("time");
ent.start = obj.getInt("start");
ent.amount = obj.getInt("amount");
ent.cap = obj.getInt("cap");
ent.eventualError = obj.getBoolean("eventualError");
ent.idle = obj.getInt("idle");
ent.addsto = obj.getString("addsto");
ent.atmost = new SC2Planner.AtMost();
JSONObject atMostObj = obj.getJSONObject("atmost");
if (atMostObj != null)
{
ent.atmost.amount = atMostObj.getInt("amount");
ent.atmost.as = atMostObj.getString("as");
ent.atmost.error = atMostObj.getString("error");
ent.atmost.name = atMostObj.getString("name");
}
ent.conditions = new ArrayList<>();
JSONArray condArr = obj.getJSONArray("conditions");
if (condArr != null)
{
for (int i=0; i < condArr.length(); i++)
{
ent.conditions.add(condArr.getString(i));
}
}
ent.costs = new ArrayList<>();
JSONArray costArr = obj.getJSONArray("costs");
if (costArr != null)
{
for (int i=0; i < costArr.length(); i++)
{
Cost cost = new Cost();
JSONObject costObj = costArr.getJSONObject(i);
cost.amount = costObj.getInt("amount");
cost.name = costObj.getString("name");
cost.error = costObj.getString("error");
ent.costs.add(cost);
}
}
ent.need = new ArrayList<>();
JSONArray needArr = obj.getJSONArray("need");
if (needArr != null)
{
for (int i=0; i < needArr.length(); i++)
{
NeedEntity needEntity = new NeedEntity();
JSONObject needObj = needArr.getJSONObject(i);
needEntity.error = needObj.getString("error");
needEntity.name = needObj.getString("name");
ent.need.add(needEntity);
}
}
ent.products = new ArrayList<>();
JSONArray productArr = obj.getJSONArray("products");
if (productArr != null)
{
for (int i=0; i < productArr.length(); i++)
{
Entity prodEntity = new Entity();
this.loadEntity(prodEntity, productArr.getJSONObject(i));
ent.products.add(prodEntity);
}
}
//ent.value = new int[0];
}
}
| true | true | private void loadEntity(Entity ent, JSONObject obj) throws JSONException
{
if (ent == null || obj == null) return;
ent.name = obj.getString("name");
ent.adding = obj.getString("adding");
ent.currentError = obj.getString("currentError");
ent.multi = obj.getString("multi");
ent.save = obj.getString("save");
ent.style = obj.getString("style");
String sectionStr = obj.getString("section");
if (sectionStr != null)
{
ent.section = Section.valueOf(sectionStr);
}
ent.autocheck = obj.getBoolean("autocheck");
ent.time = obj.getInt("time");
ent.start = obj.getInt("start");
ent.amount = obj.getInt("amount");
ent.cap = obj.getInt("cap");
ent.eventualError = obj.getBoolean("eventualError");
ent.idle = obj.getInt("idle");
ent.addsto = obj.getString("addsto");
ent.atmost = new SC2Planner.AtMost();
JSONObject atMostObj = obj.getJSONObject("atmost");
if (atMostObj != null)
{
ent.atmost.amount = atMostObj.getInt("amount");
ent.atmost.as = atMostObj.getString("as");
ent.atmost.error = atMostObj.getString("error");
ent.atmost.name = atMostObj.getString("name");
}
ent.conditions = new ArrayList<>();
JSONArray condArr = obj.getJSONArray("conditions");
if (condArr != null)
{
for (int i=0; i < condArr.length(); i++)
{
ent.conditions.add(condArr.getString(i));
}
}
ent.costs = new ArrayList<>();
JSONArray costArr = obj.getJSONArray("costs");
if (costArr != null)
{
for (int i=0; i < costArr.length(); i++)
{
Cost cost = new Cost();
JSONObject costObj = costArr.getJSONObject(i);
cost.amount = costObj.getInt("amount");
cost.name = costObj.getString("name");
cost.error = costObj.getString("error");
ent.costs.add(cost);
}
}
ent.need = new ArrayList<>();
JSONArray needArr = obj.getJSONArray("need");
if (needArr != null)
{
for (int i=0; i < needArr.length(); i++)
{
NeedEntity needEntity = new NeedEntity();
JSONObject needObj = needArr.getJSONObject(i);
needEntity.error = needObj.getString("error");
needEntity.name = needObj.getString("name");
ent.need.add(needEntity);
}
}
ent.products = new ArrayList<>();
JSONArray productArr = obj.getJSONArray("products");
if (productArr != null)
{
for (int i=0; i < productArr.length(); i++)
{
Entity prodEntity = new Entity();
this.loadEntity(prodEntity, productArr.getJSONObject(i));
ent.products.add(prodEntity);
}
}
//ent.value = new int[0];
}
| private void loadEntity(Entity ent, JSONObject obj) throws JSONException
{
if (ent == null || obj == null) return;
ent.name = obj.getString("name");
ent.adding = obj.getString("adding");
ent.currentError = obj.getString("currentError");
ent.multi = obj.getString("multi");
ent.save = obj.getString("save");
ent.style = obj.getString("style");
String sectionStr = obj.getString("section");
if (sectionStr.length() > 0)
{
ent.section = Section.valueOf(sectionStr);
}
ent.autocheck = obj.getBoolean("autocheck");
ent.time = obj.getInt("time");
ent.start = obj.getInt("start");
ent.amount = obj.getInt("amount");
ent.cap = obj.getInt("cap");
ent.eventualError = obj.getBoolean("eventualError");
ent.idle = obj.getInt("idle");
ent.addsto = obj.getString("addsto");
ent.atmost = new SC2Planner.AtMost();
JSONObject atMostObj = obj.getJSONObject("atmost");
if (atMostObj != null)
{
ent.atmost.amount = atMostObj.getInt("amount");
ent.atmost.as = atMostObj.getString("as");
ent.atmost.error = atMostObj.getString("error");
ent.atmost.name = atMostObj.getString("name");
}
ent.conditions = new ArrayList<>();
JSONArray condArr = obj.getJSONArray("conditions");
if (condArr != null)
{
for (int i=0; i < condArr.length(); i++)
{
ent.conditions.add(condArr.getString(i));
}
}
ent.costs = new ArrayList<>();
JSONArray costArr = obj.getJSONArray("costs");
if (costArr != null)
{
for (int i=0; i < costArr.length(); i++)
{
Cost cost = new Cost();
JSONObject costObj = costArr.getJSONObject(i);
cost.amount = costObj.getInt("amount");
cost.name = costObj.getString("name");
cost.error = costObj.getString("error");
ent.costs.add(cost);
}
}
ent.need = new ArrayList<>();
JSONArray needArr = obj.getJSONArray("need");
if (needArr != null)
{
for (int i=0; i < needArr.length(); i++)
{
NeedEntity needEntity = new NeedEntity();
JSONObject needObj = needArr.getJSONObject(i);
needEntity.error = needObj.getString("error");
needEntity.name = needObj.getString("name");
ent.need.add(needEntity);
}
}
ent.products = new ArrayList<>();
JSONArray productArr = obj.getJSONArray("products");
if (productArr != null)
{
for (int i=0; i < productArr.length(); i++)
{
Entity prodEntity = new Entity();
this.loadEntity(prodEntity, productArr.getJSONObject(i));
ent.products.add(prodEntity);
}
}
//ent.value = new int[0];
}
|
diff --git a/component/web/src/main/java/org/exoplatform/web/application/JavascriptManager.java b/component/web/src/main/java/org/exoplatform/web/application/JavascriptManager.java
index fa8a86776..a3597242e 100644
--- a/component/web/src/main/java/org/exoplatform/web/application/JavascriptManager.java
+++ b/component/web/src/main/java/org/exoplatform/web/application/JavascriptManager.java
@@ -1,166 +1,166 @@
/**
* Copyright (C) 2009 eXo Platform SAS.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.exoplatform.web.application;
import org.exoplatform.commons.utils.PropertyManager;
import org.exoplatform.container.ExoContainerContext;
import org.exoplatform.web.application.javascript.JavascriptConfigService;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
/**
* Created by The eXo Platform SAS
* Mar 27, 2007
*/
public class JavascriptManager
{
/** . */
private ArrayList<String> data = new ArrayList<String>(100);
/** . */
private ArrayList<String> customizedOnloadJavascript = null;
/** . */
private JavascriptConfigService jsSrevice_;
public JavascriptManager()
{
jsSrevice_ =
(JavascriptConfigService)ExoContainerContext.getCurrentContainer().getComponentInstanceOfType(
JavascriptConfigService.class);
}
public void addJavascript(CharSequence s)
{
if (s != null)
{
data.add(s instanceof String ? (String)s : s.toString());
data.add(" \n");
}
}
public void importJavascript(CharSequence s)
{
if (s != null)
{
if (!jsSrevice_.isModuleLoaded(s) || PropertyManager.isDevelopping())
{
data.add("eXo.require('");
data.add(s instanceof String ? (String)s : s.toString());
data.add("'); \n");
}
}
}
public void importJavascript(String s, String location)
{
if (s != null && location != null)
{
if (!jsSrevice_.isModuleLoaded(s) || PropertyManager.isDevelopping())
{
data.add("eXo.require('");
data.add(s);
data.add("', '");
data.add(location);
if (!location.endsWith("/"))
{
data.add("/");
}
- data.add("', '");
+ data.add("'); \n");
}
}
}
public void addOnLoadJavascript(CharSequence s)
{
if (s != null)
{
String id = Integer.toString(Math.abs(s.hashCode()));
data.add("eXo.core.Browser.addOnLoadCallback('mid");
data.add(id);
data.add("',");
data.add(s instanceof String ? (String)s : s.toString());
data.add("); \n");
}
}
public void addOnResizeJavascript(CharSequence s)
{
if (s != null)
{
String id = Integer.toString(Math.abs(s.hashCode()));
data.add("eXo.core.Browser.addOnResizeCallback('mid");
data.add(id);
data.add("',");
data.add(s instanceof String ? (String)s : s.toString());
data.add("); \n");
}
}
public void addOnScrollJavascript(CharSequence s)
{
if (s != null)
{
String id = Integer.toString(Math.abs(s.hashCode()));
data.add("eXo.core.Browser.addOnScrollCallback('mid");
data.add(id);
data.add("',");
data.add(s instanceof String ? (String)s : s.toString());
data.add("); \n");
}
}
public void writeJavascript(Writer writer) throws IOException
{
for (int i = 0;i < data.size();i++)
{
String s = data.get(i);
writer.write(s);
}
}
public void addCustomizedOnLoadScript(CharSequence s)
{
if (s != null)
{
if (customizedOnloadJavascript == null)
{
customizedOnloadJavascript = new ArrayList<String>(30);
}
customizedOnloadJavascript.add(s instanceof String ? (String)s : s.toString());
customizedOnloadJavascript.add("\n");
}
}
public void writeCustomizedOnLoadScript(Writer writer) throws IOException
{
if (customizedOnloadJavascript != null)
{
for (int i = 0;i < customizedOnloadJavascript.size();i++)
{
String s = customizedOnloadJavascript.get(i);
writer.write(s);
}
}
}
}
| true | true | public void importJavascript(String s, String location)
{
if (s != null && location != null)
{
if (!jsSrevice_.isModuleLoaded(s) || PropertyManager.isDevelopping())
{
data.add("eXo.require('");
data.add(s);
data.add("', '");
data.add(location);
if (!location.endsWith("/"))
{
data.add("/");
}
data.add("', '");
}
}
}
| public void importJavascript(String s, String location)
{
if (s != null && location != null)
{
if (!jsSrevice_.isModuleLoaded(s) || PropertyManager.isDevelopping())
{
data.add("eXo.require('");
data.add(s);
data.add("', '");
data.add(location);
if (!location.endsWith("/"))
{
data.add("/");
}
data.add("'); \n");
}
}
}
|
diff --git a/src/web/org/codehaus/groovy/grails/web/metaclass/RedirectDynamicMethod.java b/src/web/org/codehaus/groovy/grails/web/metaclass/RedirectDynamicMethod.java
index 3d69eca78..03ee3cf18 100644
--- a/src/web/org/codehaus/groovy/grails/web/metaclass/RedirectDynamicMethod.java
+++ b/src/web/org/codehaus/groovy/grails/web/metaclass/RedirectDynamicMethod.java
@@ -1,188 +1,188 @@
/*
* Copyright 2004-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.web.metaclass;
import groovy.lang.Closure;
import groovy.lang.GroovyObject;
import groovy.lang.MissingMethodException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.grails.commons.GrailsClassUtils;
import org.codehaus.groovy.grails.scaffolding.GrailsScaffolder;
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes;
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsControllerHelper;
import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.ControllerExecutionException;
import org.springframework.validation.Errors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
/**
* Implements the "redirect" Controller method for action redirection
*
* @author Graeme Rocher
* @since Oct 27, 2005
*/
public class RedirectDynamicMethod extends AbstractDynamicControllerMethod {
public static final String METHOD_SIGNATURE = "redirect";
public static final String ARGUMENT_URI = "uri";
public static final String ARGUMENT_URL = "url";
public static final String ARGUMENT_CONTROLLER = "controller";
public static final String ARGUMENT_ACTION = "action";
public static final String ARGUMENT_ID = "id";
public static final String ARGUMENT_PARAMS = "params";
public static final String ARGUMENT_ERRORS = "errors";
private GrailsControllerHelper helper;
private static final Log LOG = LogFactory.getLog(RedirectDynamicMethod.class);
public RedirectDynamicMethod(GrailsControllerHelper helper, HttpServletRequest request, HttpServletResponse response) {
super(METHOD_SIGNATURE, request, response);
if(helper == null)
throw new IllegalStateException("Constructor argument 'helper' cannot be null");
this.helper = helper;
}
public Object invoke(Object target, Object[] arguments) {
if(arguments.length == 0)
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
Object actionRef = null;
String controllerName = null;
Object id = null;
Object uri = null;
String url = null;
Map params;
Errors errors;
GroovyObject controller = (GroovyObject)target;
if(arguments[0] instanceof Map) {
Map argMap = (Map)arguments[0];
if(argMap.containsKey(ARGUMENT_URI)) {
uri = argMap.get(ARGUMENT_URI);
}
else if(argMap.containsKey(ARGUMENT_URL)) {
url = argMap.get(ARGUMENT_URL).toString();
}
else {
actionRef = argMap.get(ARGUMENT_ACTION);
controllerName = (String)argMap.get(ARGUMENT_CONTROLLER);
id = argMap.get(ARGUMENT_ID);
}
params = (Map)argMap.get(ARGUMENT_PARAMS);
errors = (Errors)argMap.get(ARGUMENT_ERRORS);
}
else {
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
// if there are errors add it to the list of errors
Errors controllerErrors = (Errors)controller.getProperty( ControllerDynamicMethods.ERRORS_PROPERTY );
if(controllerErrors != null) {
controllerErrors.addAllErrors(errors);
}
else {
controller.setProperty( ControllerDynamicMethods.ERRORS_PROPERTY, errors);
}
String actualUri;
GrailsApplicationAttributes attrs = helper.getGrailsAttributes();
if(uri != null) {
- actualUri = uri.toString();
+ actualUri = attrs.getApplicationUri(request) + uri.toString();
}
else if(url != null) {
actualUri = url;
}
else {
String actionName = null;
if(actionRef instanceof String) {
actionName = (String)actionRef;
}
else if(actionRef instanceof Closure) {
Closure c = (Closure)actionRef;
PropertyDescriptor prop = GrailsClassUtils.getPropertyDescriptorForValue(target,c);
if(prop != null) {
actionName = prop.getName();
}
else {
GrailsScaffolder scaffolder = helper.getScaffolderForController(target.getClass().getName());
if(scaffolder != null) {
actionName = scaffolder.getActionName(c);
}
}
}
else {
actionName = ""; // default action
}
if(actionName != null) {
StringBuffer actualUriBuf = new StringBuffer(attrs.getApplicationUri(request));
if(actionName.indexOf('/') > -1) {
actualUriBuf.append(actionName);
}
else {
if(controllerName != null) {
actualUriBuf.append('/')
.append(controllerName);
}
else {
actualUriBuf.append(attrs.getControllerUri(request));
}
}
actualUriBuf.append('/')
.append(actionName);
if(id != null) {
actualUriBuf.append('/')
.append(id);
}
if(params != null) {
actualUriBuf.append('?');
for (Iterator i = params.keySet().iterator(); i.hasNext();) {
Object name = i.next();
actualUriBuf.append(name)
.append('=')
.append(params.get(name));
if(i.hasNext())
actualUriBuf.append('&');
}
}
actualUri = actualUriBuf.toString();
}
else {
throw new ControllerExecutionException("Action not found in redirect for name ["+actionName+"]");
}
}
if(LOG.isDebugEnabled()) {
LOG.debug("Dynamic method [redirect] forwarding request to ["+actualUri +"]");
}
try {
response.sendRedirect(response.encodeRedirectURL(actualUri));
} catch (IOException e) {
throw new ControllerExecutionException("Error redirecting request for url ["+actualUri +"]: " + e.getMessage(),e);
}
return null;
}
}
| true | true | public Object invoke(Object target, Object[] arguments) {
if(arguments.length == 0)
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
Object actionRef = null;
String controllerName = null;
Object id = null;
Object uri = null;
String url = null;
Map params;
Errors errors;
GroovyObject controller = (GroovyObject)target;
if(arguments[0] instanceof Map) {
Map argMap = (Map)arguments[0];
if(argMap.containsKey(ARGUMENT_URI)) {
uri = argMap.get(ARGUMENT_URI);
}
else if(argMap.containsKey(ARGUMENT_URL)) {
url = argMap.get(ARGUMENT_URL).toString();
}
else {
actionRef = argMap.get(ARGUMENT_ACTION);
controllerName = (String)argMap.get(ARGUMENT_CONTROLLER);
id = argMap.get(ARGUMENT_ID);
}
params = (Map)argMap.get(ARGUMENT_PARAMS);
errors = (Errors)argMap.get(ARGUMENT_ERRORS);
}
else {
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
// if there are errors add it to the list of errors
Errors controllerErrors = (Errors)controller.getProperty( ControllerDynamicMethods.ERRORS_PROPERTY );
if(controllerErrors != null) {
controllerErrors.addAllErrors(errors);
}
else {
controller.setProperty( ControllerDynamicMethods.ERRORS_PROPERTY, errors);
}
String actualUri;
GrailsApplicationAttributes attrs = helper.getGrailsAttributes();
if(uri != null) {
actualUri = uri.toString();
}
else if(url != null) {
actualUri = url;
}
else {
String actionName = null;
if(actionRef instanceof String) {
actionName = (String)actionRef;
}
else if(actionRef instanceof Closure) {
Closure c = (Closure)actionRef;
PropertyDescriptor prop = GrailsClassUtils.getPropertyDescriptorForValue(target,c);
if(prop != null) {
actionName = prop.getName();
}
else {
GrailsScaffolder scaffolder = helper.getScaffolderForController(target.getClass().getName());
if(scaffolder != null) {
actionName = scaffolder.getActionName(c);
}
}
}
else {
actionName = ""; // default action
}
if(actionName != null) {
StringBuffer actualUriBuf = new StringBuffer(attrs.getApplicationUri(request));
if(actionName.indexOf('/') > -1) {
actualUriBuf.append(actionName);
}
else {
if(controllerName != null) {
actualUriBuf.append('/')
.append(controllerName);
}
else {
actualUriBuf.append(attrs.getControllerUri(request));
}
}
actualUriBuf.append('/')
.append(actionName);
if(id != null) {
actualUriBuf.append('/')
.append(id);
}
if(params != null) {
actualUriBuf.append('?');
for (Iterator i = params.keySet().iterator(); i.hasNext();) {
Object name = i.next();
actualUriBuf.append(name)
.append('=')
.append(params.get(name));
if(i.hasNext())
actualUriBuf.append('&');
}
}
actualUri = actualUriBuf.toString();
}
else {
throw new ControllerExecutionException("Action not found in redirect for name ["+actionName+"]");
}
}
if(LOG.isDebugEnabled()) {
LOG.debug("Dynamic method [redirect] forwarding request to ["+actualUri +"]");
}
try {
response.sendRedirect(response.encodeRedirectURL(actualUri));
} catch (IOException e) {
throw new ControllerExecutionException("Error redirecting request for url ["+actualUri +"]: " + e.getMessage(),e);
}
return null;
}
| public Object invoke(Object target, Object[] arguments) {
if(arguments.length == 0)
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
Object actionRef = null;
String controllerName = null;
Object id = null;
Object uri = null;
String url = null;
Map params;
Errors errors;
GroovyObject controller = (GroovyObject)target;
if(arguments[0] instanceof Map) {
Map argMap = (Map)arguments[0];
if(argMap.containsKey(ARGUMENT_URI)) {
uri = argMap.get(ARGUMENT_URI);
}
else if(argMap.containsKey(ARGUMENT_URL)) {
url = argMap.get(ARGUMENT_URL).toString();
}
else {
actionRef = argMap.get(ARGUMENT_ACTION);
controllerName = (String)argMap.get(ARGUMENT_CONTROLLER);
id = argMap.get(ARGUMENT_ID);
}
params = (Map)argMap.get(ARGUMENT_PARAMS);
errors = (Errors)argMap.get(ARGUMENT_ERRORS);
}
else {
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
// if there are errors add it to the list of errors
Errors controllerErrors = (Errors)controller.getProperty( ControllerDynamicMethods.ERRORS_PROPERTY );
if(controllerErrors != null) {
controllerErrors.addAllErrors(errors);
}
else {
controller.setProperty( ControllerDynamicMethods.ERRORS_PROPERTY, errors);
}
String actualUri;
GrailsApplicationAttributes attrs = helper.getGrailsAttributes();
if(uri != null) {
actualUri = attrs.getApplicationUri(request) + uri.toString();
}
else if(url != null) {
actualUri = url;
}
else {
String actionName = null;
if(actionRef instanceof String) {
actionName = (String)actionRef;
}
else if(actionRef instanceof Closure) {
Closure c = (Closure)actionRef;
PropertyDescriptor prop = GrailsClassUtils.getPropertyDescriptorForValue(target,c);
if(prop != null) {
actionName = prop.getName();
}
else {
GrailsScaffolder scaffolder = helper.getScaffolderForController(target.getClass().getName());
if(scaffolder != null) {
actionName = scaffolder.getActionName(c);
}
}
}
else {
actionName = ""; // default action
}
if(actionName != null) {
StringBuffer actualUriBuf = new StringBuffer(attrs.getApplicationUri(request));
if(actionName.indexOf('/') > -1) {
actualUriBuf.append(actionName);
}
else {
if(controllerName != null) {
actualUriBuf.append('/')
.append(controllerName);
}
else {
actualUriBuf.append(attrs.getControllerUri(request));
}
}
actualUriBuf.append('/')
.append(actionName);
if(id != null) {
actualUriBuf.append('/')
.append(id);
}
if(params != null) {
actualUriBuf.append('?');
for (Iterator i = params.keySet().iterator(); i.hasNext();) {
Object name = i.next();
actualUriBuf.append(name)
.append('=')
.append(params.get(name));
if(i.hasNext())
actualUriBuf.append('&');
}
}
actualUri = actualUriBuf.toString();
}
else {
throw new ControllerExecutionException("Action not found in redirect for name ["+actionName+"]");
}
}
if(LOG.isDebugEnabled()) {
LOG.debug("Dynamic method [redirect] forwarding request to ["+actualUri +"]");
}
try {
response.sendRedirect(response.encodeRedirectURL(actualUri));
} catch (IOException e) {
throw new ControllerExecutionException("Error redirecting request for url ["+actualUri +"]: " + e.getMessage(),e);
}
return null;
}
|
diff --git a/backend/manager/modules/restapi/jaxrs/src/main/java/org/ovirt/engine/api/restapi/rsdl/RsdlBuilder.java b/backend/manager/modules/restapi/jaxrs/src/main/java/org/ovirt/engine/api/restapi/rsdl/RsdlBuilder.java
index cd3f22d81..3e801dfd9 100644
--- a/backend/manager/modules/restapi/jaxrs/src/main/java/org/ovirt/engine/api/restapi/rsdl/RsdlBuilder.java
+++ b/backend/manager/modules/restapi/jaxrs/src/main/java/org/ovirt/engine/api/restapi/rsdl/RsdlBuilder.java
@@ -1,539 +1,539 @@
/*
* Copyright (c) 2010 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ovirt.engine.api.restapi.rsdl;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import org.ovirt.engine.api.common.util.FileUtils;
import org.ovirt.engine.api.common.util.ReflectionHelper;
import org.ovirt.engine.api.model.Actionable;
import org.ovirt.engine.api.model.Body;
import org.ovirt.engine.api.model.DetailedLink;
import org.ovirt.engine.api.model.DetailedLinks;
import org.ovirt.engine.api.model.Header;
import org.ovirt.engine.api.model.Headers;
import org.ovirt.engine.api.model.HttpMethod;
import org.ovirt.engine.api.model.Parameter;
import org.ovirt.engine.api.model.ParametersSet;
import org.ovirt.engine.api.model.RSDL;
import org.ovirt.engine.api.model.Request;
import org.ovirt.engine.api.model.Response;
import org.ovirt.engine.api.model.Schema;
import org.ovirt.engine.api.model.Url;
import org.ovirt.engine.api.resource.CreationResource;
import org.ovirt.engine.api.resource.RsdlIgnore;
import org.ovirt.engine.api.restapi.resource.BackendApiResource;
import org.ovirt.engine.core.utils.log.Log;
import org.ovirt.engine.core.utils.log.LogFactory;
import org.yaml.snakeyaml.Yaml;
public class RsdlBuilder {
private static final String COLLECTION_PARAMETER_RSDL = "collection";
private static final String COLLECTION_PARAMETER_YAML = "--COLLECTION";
private RSDL rsdl;
private String entryPoint;
private BackendApiResource apiResource;
private Map<String, Action> parametersMetaData;
private String rel;
private String href;
private Schema schema;
private String description;
private static final String ACTION = "Action";
private static final String DELETE = "delete";
private static final String UPDATE = "update";
private static final String GET = "get";
private static final String ADD = "add";
protected static final Log LOG = LogFactory.getLog(RsdlBuilder.class);
private static final String RESOURCES_PACKAGE = "org.ovirt.engine.api.resource";
private static final String PARAMS_METADATA = "rsdl_metadata_v-3.1.yaml";
public RsdlBuilder(BackendApiResource apiResource) {
this.apiResource = apiResource;
this.entryPoint = apiResource.getUriInfo().getBaseUri().getPath();
this.parametersMetaData = loadParametersMetaData();
}
public Map<String, Action> loadParametersMetaData() {
parametersMetaData = new HashMap<String, Action>();
try {
InputStream stream = FileUtils.get(RESOURCES_PACKAGE, PARAMS_METADATA);
if (stream != null) {
Object result = new Yaml().load(stream);
for (Action action : ((MetaData)result).getActions()) {
parametersMetaData.put(action.getName(), action);
}
}
LOG.error("Parameters metatdata file not found.");
} catch (Exception e) {
LOG.error("Loading parameters metatdata failed.", e);
}
return parametersMetaData;
}
private RSDL construct() throws ClassNotFoundException, IOException {
RSDL rsdl = new RSDL();
rsdl.setLinks(new DetailedLinks());
for (DetailedLink link : getLinks()) {
rsdl.getLinks().getLinks().add(link);
}
return rsdl;
}
public RSDL build() {
try {
rsdl = construct();
rsdl.setRel(getRel());
rsdl.setHref(getHref());
rsdl.setDescription(getDescription());
rsdl.setSchema(getSchema());
} catch (Exception e) {
e.printStackTrace();
LOG.error("RSDL generation failure.", e);
}
return rsdl;
}
public RsdlBuilder rel(String rel) {
this.rel = rel;
return this;
}
public RsdlBuilder href(String href) {
this.href = href;
return this;
}
public RsdlBuilder schema(Schema schema) {
this.schema = schema;
return this;
}
public RsdlBuilder description(String description) {
this.description = description;
return this;
}
public String getHref() {
return this.href;
}
public String getRel() {
return this.rel;
}
public Schema getSchema() {
return schema;
}
public String getDescription() {
return this.description;
}
@Override
public String toString() {
return "RSDL Href: " + getHref() +
", Description:" + getDescription() +
", Links: " + (rsdl != null ? (rsdl.isSetLinks() ? rsdl.getLinks().getLinks().size() : "0") : "0") + ".";
}
public class LinkBuilder {
private DetailedLink link = new DetailedLink();;
public LinkBuilder url(String url) {
link.setHref(url);
return this;
}
public LinkBuilder rel(String rel) {
link.setRel(rel);
return this;
}
public LinkBuilder requestParameter(final String requestParameter) {
link.setRequest(new Request());
link.getRequest().setBody(new Body(){{setType(requestParameter);}});
return this;
}
public LinkBuilder responseType(final String responseType) {
link.setResponse(new Response(){{setType(responseType);}});
return this;
}
public LinkBuilder httpMethod(HttpMethod httpMethod) {
if(!link.isSetRequest()) {
link.setRequest(new Request());
}
link.getRequest().setHttpMethod(httpMethod);
return this;
}
public DetailedLink build() {
if (!link.getRequest().isSetBody()) {
link.getRequest().setBody(new Body());
}
return addParametersMetadata(link);
}
}
public Collection<DetailedLink> getLinks() throws ClassNotFoundException, IOException {
//SortedSet<Link> results = new TreeSet<Link>();
List<DetailedLink> results = new ArrayList<DetailedLink>();
List<Class<?>> classes = ReflectionHelper.getClasses(RESOURCES_PACKAGE);
for (String path : apiResource.getRels()) {
Class<?> resource = findResource(path, classes);
results.addAll(describe(resource, entryPoint + "/" + path, new HashMap<String, Type>()));
}
return results;
}
private Class<?> findResource(String path, List<Class<?>> classes) throws ClassNotFoundException, IOException {
path = "/" + path;
for (Class<?> clazz : classes) {
if (path.equals(getPath(clazz))) {
return clazz;
}
}
return null;
}
private String getPath(Class<?> clazz) {
Path pathAnnotation = clazz.getAnnotation(Path.class);
return pathAnnotation==null ? null : pathAnnotation.value();
}
public List<DetailedLink> describe(Class<?> resource, String prefix, Map<String, Type> parametersMap) throws ClassNotFoundException {
//SortedSet<Link> results = new TreeSet<Link>();
List<DetailedLink> results = new ArrayList<DetailedLink>();
if (resource!=null) {
for (Method m : resource.getMethods()) {
if (isConcreteReturnType(m, resource)) {
handleMethod(prefix, results, m, resource, parametersMap);
}
}
}
return results;
}
private boolean isConcreteReturnType(Method method, Class<?> resource) {
for (Method m : resource.getMethods()) {
if (!m.equals(method)
&& m.getName().equals(method.getName())
&& parameterTypesEqual(m.getParameterTypes(), method.getParameterTypes())
&& method.getReturnType().isAssignableFrom(m.getReturnType())) {
return false;
}
}
return true;
}
private boolean parameterTypesEqual(Class<?>[] types1, Class<?>[] types2) {
if (types1.length!=types2.length) {
return false;
} else {
for (int i=0; i<types1.length; i++) {
if (!(types1[i].isAssignableFrom(types2[i]) || types2[i].isAssignableFrom(types1[i]))) {
return false;
}
}
return true;
}
}
private void addToGenericParamsMap (Class<?> resource, Type[] paramTypes, Type[] genericParamTypes, Map<String, Type> parametersMap) {
for (int i=0; i<genericParamTypes.length; i++) {
if (paramTypes[i].toString().length() == 1) {
//if the parameter type is generic - don't add to map, as it might override a more meaningful value:
//for example, without this check we could replace <"R", "Template"> with <"R", "R">, and lose information.
} else {
//if the length is greater than 1, we have an actual type (e.g: "CdRoms"), and we want to add it to the
//map, even if it overrides an existing value.
parametersMap.put(genericParamTypes[i].toString(), paramTypes[i]);
}
}
}
private void handleMethod(String prefix, Collection<DetailedLink> results, Method m, Class<?> resource, Map<String, Type> parametersMap) throws ClassNotFoundException {
if (isRequiresDescription(m)) {
Class<?> returnType = findReturnType(m, resource, parametersMap);
String returnTypeStr = getReturnTypeStr(returnType);
if (m.isAnnotationPresent(javax.ws.rs.GET.class)) {
handleGet(prefix, results, returnTypeStr);
} else if (m.isAnnotationPresent(PUT.class)) {
handlePut(prefix, results, returnTypeStr);
} else if (m.isAnnotationPresent(javax.ws.rs.DELETE.class)) {
handleDelete(prefix, results, m);
} else if (m.isAnnotationPresent(Path.class)) {
String path = m.getAnnotation(Path.class).value();
if (isAction(m)) {
handleAction(prefix, results, returnTypeStr, path);
} else {
if (isSingleEntityResource(m)) {
path = "{" + getSingleForm(prefix) + ":id}";
}
if (m.getGenericReturnType() instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType)m.getGenericReturnType();
addToGenericParamsMap(resource, parameterizedType.getActualTypeArguments(), m.getReturnType().getTypeParameters(), parametersMap);
}
results.addAll(describe(returnType, prefix + "/" + path, new HashMap<String, Type>(parametersMap)));
}
} else {
if (m.getName().equals(ADD)) {
handleAdd(prefix, results, m);
}
}
}
}
private void handleAction(String prefix, Collection<DetailedLink> results, String returnValueStr, String path) {
results.add(new RsdlBuilder.LinkBuilder().url(prefix + "/" + path).rel(path).requestParameter(ACTION).responseType(returnValueStr).httpMethod(HttpMethod.POST).build());
}
private void handleDelete(String prefix, Collection<DetailedLink> results, Method m) {
if (m.getParameterTypes().length>1) {
Class<?>[] parameterTypes = m.getParameterTypes();
Annotation[][] parameterAnnotations = m.getParameterAnnotations();
for (int i=0; i<parameterTypes.length; i++) {
//ignore the id parameter (string), that's annotated with @PathParam
if (!( parameterTypes[i].equals(String.class) && (!(parameterAnnotations[i].length==0)))) {
results.add(new RsdlBuilder.LinkBuilder().url(prefix + "/{" + getSingleForm(prefix) + ":id}").rel(DELETE).requestParameter(parameterTypes[i].getSimpleName()).httpMethod(HttpMethod.DELETE).build());
return; //we can break, because we excpect only one parameter.
}
}
} else {
results.add(new RsdlBuilder.LinkBuilder().url(prefix + "/{" + getSingleForm(prefix) + ":id}").rel(DELETE).httpMethod(HttpMethod.DELETE).build());
}
}
private void handlePut(String prefix, Collection<DetailedLink> results, String returnValueStr) {
results.add(new RsdlBuilder.LinkBuilder().url(prefix).rel(UPDATE).requestParameter(returnValueStr).responseType(returnValueStr).httpMethod(HttpMethod.PUT).build());
}
private void handleGet(String prefix, Collection<DetailedLink> results, String returnValueStr) {
DetailedLink link = new RsdlBuilder.LinkBuilder().url(prefix).rel(GET).responseType(returnValueStr).httpMethod(HttpMethod.GET).build();
results.add(link);
}
private DetailedLink addParametersMetadata(DetailedLink link) {
String link_name = link.getHref() + "|rel=" + link.getRel();
if (this.parametersMetaData.containsKey(link_name)) {
Action action = this.parametersMetaData.get(link_name);
if (action.getRequest() != null) {
addUrlParams(link, action);
addHeaderParams(link, action);
addBodyParams(link, action);
}
}
return link;
}
private void addBodyParams(DetailedLink link, Action action) {
if (action.getRequest().getBody() != null) {
if (action.getRequest().getBody().getSignatures() != null) {
for (Signature signature : action.getRequest().getBody().getSignatures()) {
ParametersSet ps = new ParametersSet();
addBodyParams(ps, signature.getMandatoryArguments().entrySet(), true);
addBodyParams(ps, signature.getOptionalArguments().entrySet(), false);
link.getRequest().getBody().getParametersSets().add(ps);
}
}
}
}
private void addBodyParams(ParametersSet ps, Set<Entry<Object, Object>> entrySet, boolean required) {
for (Entry<Object, Object> paramData : entrySet) {
Parameter param = createBodyParam(paramData, required);
ps.getParameters().add(param);
}
}
private Parameter createBodyParam(Entry<Object, Object> mandatoryKeyValuePair, boolean required) {
Parameter param = new Parameter();
param.setRequired(required);
String paramName = mandatoryKeyValuePair.getKey().toString();
if (paramName.endsWith(COLLECTION_PARAMETER_YAML)) {
param.setName(paramName.substring(0, paramName.length()-(COLLECTION_PARAMETER_YAML.length())));
param.setType(COLLECTION_PARAMETER_RSDL);
@SuppressWarnings("unchecked")
Map<Object, Object> listParams = (Map<Object, Object>)mandatoryKeyValuePair.getValue();
param.setParametersSet(new ParametersSet());
for (Entry<Object, Object> listParamData : listParams.entrySet()) {
Parameter listParam = createBodyParam(listParamData, required);
param.getParametersSet().getParameters().add(listParam);
}
} else {
param.setName(paramName);
param.setType(mandatoryKeyValuePair.getValue().toString());
}
return param;
}
private void addHeaderParams(DetailedLink link, Action action) {
if (action.getRequest().getHeaders() != null && !action.getRequest().getHeaders().isEmpty()) {
link.getRequest().setHeaders(new Headers());
for (Object key : action.getRequest().getHeaders().keySet()) {
Header header = new Header();
header.setName(key.toString());
Object value = action.getRequest().getHeaders().get(key);
if (value != null) {
header.setValue(value.toString());
}
link.getRequest().getHeaders().getHeaders().add(header);
}
}
}
private void addUrlParams(DetailedLink link, Action action) {
if (action.getRequest().getUrlparams() != null && !action.getRequest().getUrlparams().isEmpty()) {
link.getRequest().setUrl(new Url());
ParametersSet ps = new ParametersSet();
for (Object key : action.getRequest().getUrlparams().keySet()) {
Parameter param = new Parameter();
param.setName(key.toString());
Object value = action.getRequest().getUrlparams().get(key);
if (value != null) {
UrlParamData urlParamData = (UrlParamData)value;
param.setType(urlParamData.getType());
param.setContext(urlParamData.getContext());
param.setValue(urlParamData.getValue());
param.setRequired(urlParamData.getRequired()==null ? false : urlParamData.getRequired());
}
ps.getParameters().add(param);
}
link.getRequest().getUrl().getParametersSets().add(ps);
}
}
private void handleAdd(String prefix, Collection<DetailedLink> results, Method m) {
Class<?>[] parameterTypes = m.getParameterTypes();
assert(parameterTypes.length==1);
String s = parameterTypes[0].getSimpleName();
s = handleExcpetionalCases(s, prefix); //TODO: refactor to a more generic solution
results.add(new RsdlBuilder.LinkBuilder().url(prefix).rel(ADD).requestParameter(s).responseType(s).httpMethod(HttpMethod.POST).build());
}
private String handleExcpetionalCases(String s, String prefix) {
if (s.equals("BaseDevice")) {
if (prefix.contains("cdroms")) {
return "CdRom";
}
if (prefix.contains("nics")) {
return "NIC";
}
if (prefix.contains("disks")) {
return "Disk";
}
}
return s;
}
/**
* get the class name, without package prefix
* @param returnValue
* @return
*/
private String getReturnTypeStr(Class<?> returnValue) {
int lastIndexOf = returnValue.getSimpleName().lastIndexOf(".");
String entityType = lastIndexOf==-1 ? returnValue.getSimpleName() : returnValue.getSimpleName().substring(lastIndexOf);
return entityType;
}
private Class<?> findReturnType(Method m, Class<?> resource, Map<String, Type> parametersMap) throws ClassNotFoundException {
for (Type superInterface : resource.getGenericInterfaces()) {
if (superInterface instanceof ParameterizedType) {
ParameterizedType p = (ParameterizedType)superInterface;
Class<?> clazz = Class.forName(p.getRawType().toString().substring(p.getRawType().toString().lastIndexOf(' ')+1));
Map<String, Type> map = new HashMap<String, Type>();
for (int i=0; i<p.getActualTypeArguments().length; i++) {
- if (!map.containsKey(clazz.getTypeParameters()[i])) {
+ if (!map.containsKey(clazz.getTypeParameters()[i].toString())) {
map.put(clazz.getTypeParameters()[i].toString(), p.getActualTypeArguments()[i]);
}
}
if (map.containsKey(m.getGenericReturnType().toString())) {
String type = map.get(m.getGenericReturnType().toString()).toString();
try {
Class<?> returnClass = Class.forName(type.substring(type.lastIndexOf(' ')+1));
return returnClass;
} catch (ClassNotFoundException e) {
break;
}
}
}
}
if (parametersMap.containsKey(m.getGenericReturnType().toString())) {
try {
Type type = parametersMap.get(m.getGenericReturnType().toString());
Class<?> returnClass = Class.forName(type.toString().substring(type.toString().indexOf(' ') +1));
return returnClass;
} catch (ClassNotFoundException e) {
return m.getReturnType();
}
} else {
return m.getReturnType();
}
}
private boolean isSingleEntityResource(Method m) {
Annotation[][] parameterAnnotations = m.getParameterAnnotations();
for (int i=0; i<parameterAnnotations.length; i++) {
for (int j=0; j<parameterAnnotations[j].length; j++) {
if (parameterAnnotations[i][j].annotationType().equals(PathParam.class)) {
return true;
}
}
}
return false;
}
private boolean isAction(Method m) {
return m.isAnnotationPresent(Actionable.class);
}
private boolean isRequiresDescription(Method m) {
if (m.isAnnotationPresent(RsdlIgnore.class)) {
return false;
}
boolean pathRelevant = !(m.isAnnotationPresent(Path.class) && m.getAnnotation(Path.class).value().contains(":"));
boolean returnValueRelevant = !m.getReturnType().equals(CreationResource.class);
return pathRelevant && returnValueRelevant;
}
//might need to truncate the plural 's', for example:
//for "{api}/hosts/{host:id}/nics" return "nic"
//but for "{api}/hosts/{host:id}/storage" return "storage" (don't truncate last character)
private String getSingleForm(String prefix) {
int startIndex = prefix.lastIndexOf('/')+1;
int endPos = prefix.endsWith("s") ? prefix.length() -1 : prefix.length();
return prefix.substring(startIndex, endPos);
}
}
| true | true | private Class<?> findReturnType(Method m, Class<?> resource, Map<String, Type> parametersMap) throws ClassNotFoundException {
for (Type superInterface : resource.getGenericInterfaces()) {
if (superInterface instanceof ParameterizedType) {
ParameterizedType p = (ParameterizedType)superInterface;
Class<?> clazz = Class.forName(p.getRawType().toString().substring(p.getRawType().toString().lastIndexOf(' ')+1));
Map<String, Type> map = new HashMap<String, Type>();
for (int i=0; i<p.getActualTypeArguments().length; i++) {
if (!map.containsKey(clazz.getTypeParameters()[i])) {
map.put(clazz.getTypeParameters()[i].toString(), p.getActualTypeArguments()[i]);
}
}
if (map.containsKey(m.getGenericReturnType().toString())) {
String type = map.get(m.getGenericReturnType().toString()).toString();
try {
Class<?> returnClass = Class.forName(type.substring(type.lastIndexOf(' ')+1));
return returnClass;
} catch (ClassNotFoundException e) {
break;
}
}
}
}
if (parametersMap.containsKey(m.getGenericReturnType().toString())) {
try {
Type type = parametersMap.get(m.getGenericReturnType().toString());
Class<?> returnClass = Class.forName(type.toString().substring(type.toString().indexOf(' ') +1));
return returnClass;
} catch (ClassNotFoundException e) {
return m.getReturnType();
}
} else {
return m.getReturnType();
}
}
| private Class<?> findReturnType(Method m, Class<?> resource, Map<String, Type> parametersMap) throws ClassNotFoundException {
for (Type superInterface : resource.getGenericInterfaces()) {
if (superInterface instanceof ParameterizedType) {
ParameterizedType p = (ParameterizedType)superInterface;
Class<?> clazz = Class.forName(p.getRawType().toString().substring(p.getRawType().toString().lastIndexOf(' ')+1));
Map<String, Type> map = new HashMap<String, Type>();
for (int i=0; i<p.getActualTypeArguments().length; i++) {
if (!map.containsKey(clazz.getTypeParameters()[i].toString())) {
map.put(clazz.getTypeParameters()[i].toString(), p.getActualTypeArguments()[i]);
}
}
if (map.containsKey(m.getGenericReturnType().toString())) {
String type = map.get(m.getGenericReturnType().toString()).toString();
try {
Class<?> returnClass = Class.forName(type.substring(type.lastIndexOf(' ')+1));
return returnClass;
} catch (ClassNotFoundException e) {
break;
}
}
}
}
if (parametersMap.containsKey(m.getGenericReturnType().toString())) {
try {
Type type = parametersMap.get(m.getGenericReturnType().toString());
Class<?> returnClass = Class.forName(type.toString().substring(type.toString().indexOf(' ') +1));
return returnClass;
} catch (ClassNotFoundException e) {
return m.getReturnType();
}
} else {
return m.getReturnType();
}
}
|
diff --git a/cdi/tests/org.jboss.tools.cdi.seam3.bot.test/src/org/jboss/tools/cdi/seam3/bot/test/tests/ResourceOpenOnTest.java b/cdi/tests/org.jboss.tools.cdi.seam3.bot.test/src/org/jboss/tools/cdi/seam3/bot/test/tests/ResourceOpenOnTest.java
index 9360cd5f7..a45725499 100644
--- a/cdi/tests/org.jboss.tools.cdi.seam3.bot.test/src/org/jboss/tools/cdi/seam3/bot/test/tests/ResourceOpenOnTest.java
+++ b/cdi/tests/org.jboss.tools.cdi.seam3.bot.test/src/org/jboss/tools/cdi/seam3/bot/test/tests/ResourceOpenOnTest.java
@@ -1,65 +1,67 @@
/*******************************************************************************
* Copyright (c) 2010-2012 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.cdi.seam3.bot.test.tests;
import org.jboss.tools.cdi.bot.test.CDIConstants;
import org.jboss.tools.cdi.seam3.bot.test.base.SolderTestBase;
import org.junit.Test;
/**
* Test operates on resource openOn in Seam3 using CDI tools
*
* @author Jaroslav Jankovic
*/
public class ResourceOpenOnTest extends SolderTestBase {
@Override
public String getProjectName() {
return "resource";
}
/**
* https://issues.jboss.org/browse/JBIDE-8202
*/
@Test
public void testResourceOpenOn() {
String className = "MyBean.java";
packageExplorer.openFile(getProjectName(), CDIConstants.SRC,
"cdi.seam", className);
- openOnUtil.openOnByOption(CDIConstants.RESOURCE_ANNOTATION, className, "Open Resource");
+ assertTrue(openOnUtil.openOnByOption(CDIConstants.RESOURCE_ANNOTATION,
+ className, "Open Resource"));
String destinationFile = getEd().getTitle();
assertTrue("ERROR: redirected to " + destinationFile,
destinationFile.equals(CDIConstants.BEANS_XML));
- editResourceUtil.moveFileInExplorerBase(projectExplorer, CDIConstants.BEANS_XML,
+ editResourceUtil.moveFileInExplorerBase(packageExplorer, CDIConstants.BEANS_XML,
getProjectName() + "/" + CDIConstants.WEBCONTENT + "/" + CDIConstants.WEB_INF,
getProjectName() + "/" + CDIConstants.WEBCONTENT + "/" + CDIConstants.META_INF);
LOGGER.info("bean.xml was moved to META-INF");
setEd(bot.swtBotEditorExtByTitle(className));
editResourceUtil.replaceInEditor("WEB", "META");
- openOnUtil.openOnByOption(CDIConstants.RESOURCE_ANNOTATION, className, "Open Resource");
+ assertTrue(openOnUtil.openOnByOption(CDIConstants.RESOURCE_ANNOTATION,
+ className, "Open Resource"));
destinationFile = getEd().getTitle();
assertTrue("ERROR: redirected to " + destinationFile,
destinationFile.equals(CDIConstants.BEANS_XML));
}
}
| false | true | public void testResourceOpenOn() {
String className = "MyBean.java";
packageExplorer.openFile(getProjectName(), CDIConstants.SRC,
"cdi.seam", className);
openOnUtil.openOnByOption(CDIConstants.RESOURCE_ANNOTATION, className, "Open Resource");
String destinationFile = getEd().getTitle();
assertTrue("ERROR: redirected to " + destinationFile,
destinationFile.equals(CDIConstants.BEANS_XML));
editResourceUtil.moveFileInExplorerBase(projectExplorer, CDIConstants.BEANS_XML,
getProjectName() + "/" + CDIConstants.WEBCONTENT + "/" + CDIConstants.WEB_INF,
getProjectName() + "/" + CDIConstants.WEBCONTENT + "/" + CDIConstants.META_INF);
LOGGER.info("bean.xml was moved to META-INF");
setEd(bot.swtBotEditorExtByTitle(className));
editResourceUtil.replaceInEditor("WEB", "META");
openOnUtil.openOnByOption(CDIConstants.RESOURCE_ANNOTATION, className, "Open Resource");
destinationFile = getEd().getTitle();
assertTrue("ERROR: redirected to " + destinationFile,
destinationFile.equals(CDIConstants.BEANS_XML));
}
| public void testResourceOpenOn() {
String className = "MyBean.java";
packageExplorer.openFile(getProjectName(), CDIConstants.SRC,
"cdi.seam", className);
assertTrue(openOnUtil.openOnByOption(CDIConstants.RESOURCE_ANNOTATION,
className, "Open Resource"));
String destinationFile = getEd().getTitle();
assertTrue("ERROR: redirected to " + destinationFile,
destinationFile.equals(CDIConstants.BEANS_XML));
editResourceUtil.moveFileInExplorerBase(packageExplorer, CDIConstants.BEANS_XML,
getProjectName() + "/" + CDIConstants.WEBCONTENT + "/" + CDIConstants.WEB_INF,
getProjectName() + "/" + CDIConstants.WEBCONTENT + "/" + CDIConstants.META_INF);
LOGGER.info("bean.xml was moved to META-INF");
setEd(bot.swtBotEditorExtByTitle(className));
editResourceUtil.replaceInEditor("WEB", "META");
assertTrue(openOnUtil.openOnByOption(CDIConstants.RESOURCE_ANNOTATION,
className, "Open Resource"));
destinationFile = getEd().getTitle();
assertTrue("ERROR: redirected to " + destinationFile,
destinationFile.equals(CDIConstants.BEANS_XML));
}
|
diff --git a/src/org/apache/xerces/impl/xs/XSConstraints.java b/src/org/apache/xerces/impl/xs/XSConstraints.java
index 30b07ba47..a553c06c6 100644
--- a/src/org/apache/xerces/impl/xs/XSConstraints.java
+++ b/src/org/apache/xerces/impl/xs/XSConstraints.java
@@ -1,1426 +1,1426 @@
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xerces.impl.xs;
import org.apache.xerces.impl.dv.XSSimpleType;
import org.apache.xerces.impl.dv.XSUnionSimpleType;
import org.apache.xerces.impl.dv.InvalidDatatypeValueException;
import org.apache.xerces.impl.dv.ValidatedInfo;
import org.apache.xerces.impl.XMLErrorReporter;
import org.apache.xerces.impl.xs.models.CMBuilder;
import org.apache.xerces.impl.xs.models.XSCMValidator;
import org.apache.xerces.impl.xs.util.SimpleLocator;
import org.apache.xerces.impl.validation.ValidationContext;
import org.apache.xerces.util.SymbolHash;
import java.util.Vector;
/**
* Constaints shared by traversers and validator
*
* @author Sandy Gao, IBM
*
* @version $Id$
*/
public class XSConstraints {
static final int OCCURRENCE_UNKNOWN = SchemaSymbols.OCCURRENCE_UNBOUNDED-1;
static final XSSimpleType STRING_TYPE = (XSSimpleType)SchemaGrammar.SG_SchemaNS.getGlobalTypeDecl(SchemaSymbols.ATTVAL_STRING);
/**
* check whether derived is valid derived from base, given a subset
* of {restriction, extension}.
*/
public static boolean checkTypeDerivationOk(XSTypeDecl derived, XSTypeDecl base, short block) {
// if derived is anyType, then it's valid only if base is anyType too
if (derived == SchemaGrammar.fAnyType)
return derived == base;
// if derived is anySimpleType, then it's valid only if the base
// is ur-type
if (derived == SchemaGrammar.fAnySimpleType) {
return (base == SchemaGrammar.fAnyType ||
base == SchemaGrammar.fAnySimpleType);
}
// if derived is simple type
if (derived.getXSType() == XSTypeDecl.SIMPLE_TYPE) {
// if base is complex type
if (base.getXSType() == XSTypeDecl.COMPLEX_TYPE) {
// if base is anyType, change base to anySimpleType,
// otherwise, not valid
if (base == SchemaGrammar.fAnyType)
base = SchemaGrammar.fAnySimpleType;
else
return false;
}
return checkSimpleDerivation((XSSimpleType)derived,
(XSSimpleType)base, block);
} else {
return checkComplexDerivation((XSComplexTypeDecl)derived, base, block);
}
}
/**
* check whether simple type derived is valid derived from base,
* given a subset of {restriction, extension}.
*/
public static boolean checkSimpleDerivationOk(XSSimpleType derived, XSTypeDecl base, short block) {
// if derived is anySimpleType, then it's valid only if the base
// is ur-type
if (derived == SchemaGrammar.fAnySimpleType) {
return (base == SchemaGrammar.fAnyType ||
base == SchemaGrammar.fAnySimpleType);
}
// if base is complex type
if (base.getXSType() == XSTypeDecl.COMPLEX_TYPE) {
// if base is anyType, change base to anySimpleType,
// otherwise, not valid
if (base == SchemaGrammar.fAnyType)
base = SchemaGrammar.fAnySimpleType;
else
return false;
}
return checkSimpleDerivation((XSSimpleType)derived,
(XSSimpleType)base, block);
}
/**
* check whether complex type derived is valid derived from base,
* given a subset of {restriction, extension}.
*/
public static boolean checkComplexDerivationOk(XSComplexTypeDecl derived, XSTypeDecl base, short block) {
// if derived is anyType, then it's valid only if base is anyType too
if (derived == SchemaGrammar.fAnyType)
return derived == base;
return checkComplexDerivation((XSComplexTypeDecl)derived, base, block);
}
/**
* Note: this will be a private method, and it assumes that derived is not
* anySimpleType, and base is not anyType. Another method will be
* introduced for public use, which will call this method.
*/
private static boolean checkSimpleDerivation(XSSimpleType derived, XSSimpleType base, short block) {
// 1 They are the same type definition.
if (derived == base)
return true;
// 2 All of the following must be true:
// 2.1 restriction is not in the subset, or in the {final} of its own {base type definition};
if ((block & SchemaSymbols.RESTRICTION) != 0 ||
(derived.getBaseType().getFinalSet() & SchemaSymbols.RESTRICTION) != 0) {
return false;
}
// 2.2 One of the following must be true:
// 2.2.1 D's base type definition is B.
XSSimpleType directBase = (XSSimpleType)derived.getBaseType();
if (directBase == base)
return true;
// 2.2.2 D's base type definition is not the simple ur-type definition and is validly derived from B given the subset, as defined by this constraint.
if (directBase != SchemaGrammar.fAnySimpleType &&
checkSimpleDerivation(directBase, base, block)) {
return true;
}
// 2.2.3 D's {variety} is list or union and B is the simple ur-type definition.
if ((derived.getVariety() == XSSimpleType.VARIETY_LIST ||
derived.getVariety() == XSSimpleType.VARIETY_UNION) &&
base == SchemaGrammar.fAnySimpleType) {
return true;
}
// 2.2.4 B's {variety} is union and D is validly derived from a type definition in B's {member type definitions} given the subset, as defined by this constraint.
if (base.getVariety() == XSSimpleType.VARIETY_UNION) {
XSSimpleType[] subUnionMemberDV = ((XSUnionSimpleType)base).getMemberTypes();
int subUnionSize = subUnionMemberDV.length ;
for (int i=0; i<subUnionSize; i++) {
base = subUnionMemberDV[i];
if (checkSimpleDerivation(derived, base, block))
return true;
}
}
return false;
}
/**
* Note: this will be a private method, and it assumes that derived is not
* anyType. Another method will be introduced for public use,
* which will call this method.
*/
private static boolean checkComplexDerivation(XSComplexTypeDecl derived, XSTypeDecl base, short block) {
// 2.1 B and D must be the same type definition.
if (derived == base)
return true;
// 1 If B and D are not the same type definition, then the {derivation method} of D must not be in the subset.
if ((derived.fDerivedBy & block) != 0)
return false;
// 2 One of the following must be true:
XSTypeDecl directBase = derived.fBaseType;
// 2.2 B must be D's {base type definition}.
if (directBase == base)
return true;
// 2.3 All of the following must be true:
// 2.3.1 D's {base type definition} must not be the ur-type definition.
if (directBase == SchemaGrammar.fAnyType ||
directBase == SchemaGrammar.fAnySimpleType) {
return false;
}
// 2.3.2 The appropriate case among the following must be true:
// 2.3.2.1 If D's {base type definition} is complex, then it must be validly derived from B given the subset as defined by this constraint.
if (directBase.getXSType() == XSTypeDecl.COMPLEX_TYPE)
return checkComplexDerivation((XSComplexTypeDecl)directBase, base, block);
// 2.3.2.2 If D's {base type definition} is simple, then it must be validly derived from B given the subset as defined in Type Derivation OK (Simple) (3.14.6).
if (directBase.getXSType() == XSTypeDecl.SIMPLE_TYPE) {
// if base is complex type
if (base.getXSType() == XSTypeDecl.COMPLEX_TYPE) {
// if base is anyType, change base to anySimpleType,
// otherwise, not valid
if (base == SchemaGrammar.fAnyType)
base = SchemaGrammar.fAnySimpleType;
else
return false;
}
return checkSimpleDerivation((XSSimpleType)directBase,
(XSSimpleType)base, block);
}
return false;
}
/**
* check whether a value is a valid default for some type
* returns the compiled form of the value
* The parameter value could be either a String or a ValidatedInfo object
*/
public static Object ElementDefaultValidImmediate(XSTypeDecl type, Object value, ValidationContext context, ValidatedInfo vinfo) {
XSSimpleType dv = null;
// e-props-correct
// For a string to be a valid default with respect to a type definition the appropriate case among the following must be true:
// 1 If the type definition is a simple type definition, then the string must be valid with respect to that definition as defined by String Valid (3.14.4).
if (type.getXSType() == XSTypeDecl.SIMPLE_TYPE) {
dv = (XSSimpleType)type;
}
// 2 If the type definition is a complex type definition, then all of the following must be true:
else {
// 2.1 its {content type} must be a simple type definition or mixed.
XSComplexTypeDecl ctype = (XSComplexTypeDecl)type;
// 2.2 The appropriate case among the following must be true:
// 2.2.1 If the {content type} is a simple type definition, then the string must be valid with respect to that simple type definition as defined by String Valid (3.14.4).
if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) {
dv = ctype.fXSSimpleType;
}
// 2.2.2 If the {content type} is mixed, then the {content type}'s particle must be emptiable as defined by Particle Emptiable (3.9.6).
else if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_MIXED) {
if (!ctype.fParticle.emptiable())
return null;
}
else {
return null;
}
}
// get the simple type declaration, and validate
Object actualValue = null;
if (dv == null) {
// complex type with mixed. to make sure that we store correct
// information in vinfo and return the correct value, we use
// "string" type for validation
dv = STRING_TYPE;
}
try {
if (value instanceof String) {
actualValue = dv.validate((String)value, context, vinfo);
} else {
ValidatedInfo info = (ValidatedInfo)value;
dv.validate(context, info);
actualValue = info.actualValue;
}
} catch (InvalidDatatypeValueException ide) {
return null;
}
return actualValue;
}
static void reportSchemaError(XMLErrorReporter errorReporter,
SimpleLocator loc,
String key, Object[] args) {
if (loc != null) {
errorReporter.reportError(loc, XSMessageFormatter.SCHEMA_DOMAIN,
key, args, XMLErrorReporter.SEVERITY_ERROR);
}
else {
errorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN,
key, args, XMLErrorReporter.SEVERITY_ERROR);
}
}
/**
* used to check the 3 constraints against each complex type
* (should be each model group):
* Unique Particle Attribution, Particle Derivation (Restriction),
* Element Declrations Consistent.
*/
public static void fullSchemaChecking(XSGrammarBucket grammarBucket,
SubstitutionGroupHandler SGHandler,
CMBuilder cmBuilder,
XMLErrorReporter errorReporter) {
// get all grammars, and put all substitution group information
// in the substitution group handler
SchemaGrammar[] grammars = grammarBucket.getGrammars();
for (int i = grammars.length-1; i >= 0; i--) {
SGHandler.addSubstitutionGroup(grammars[i].getSubstitutionGroups());
}
// before worrying about complexTypes, let's get
// groups redefined by restriction out of the way.
for (int g = grammars.length-1; g >= 0; g--) {
XSGroupDecl [] redefinedGroups = grammars[g].getRedefinedGroupDecls();
SimpleLocator [] rgLocators = grammars[g].getRGLocators();
for(int i=0; i<redefinedGroups.length; ) {
XSGroupDecl derivedGrp = redefinedGroups[i++];
XSParticleDecl derivedParticle = derivedGrp.fParticle;
XSGroupDecl baseGrp = redefinedGroups[i++];
XSParticleDecl baseParticle = baseGrp.fParticle;
if(baseParticle == null) {
if(derivedParticle != null) { // can't be a restriction!
reportSchemaError(errorReporter, rgLocators[i/2-1],
"src-redefine.6.2.2",
new Object[]{derivedGrp.fName, "rcase-Recurse.2"});
}
} else {
try {
particleValidRestriction(SGHandler,
derivedParticle, baseParticle);
} catch (XMLSchemaException e) {
String key = e.getKey();
reportSchemaError(errorReporter, rgLocators[i/2-1],
key,
e.getArgs());
reportSchemaError(errorReporter, rgLocators[i/2-1],
"src-redefine.6.2.2",
new Object[]{derivedGrp.fName, key});
}
}
}
}
// for each complex type, check the 3 constraints.
// types need to be checked
XSComplexTypeDecl[] types;
SimpleLocator [] ctLocators;
// to hold the errors
// REVISIT: do we want to report all errors? or just one?
//XMLSchemaError1D errors = new XMLSchemaError1D();
// whether need to check this type again;
// whether only do UPA checking
boolean further, fullChecked;
// if do all checkings, how many need to be checked again.
int keepType;
// i: grammar; j: type; k: error
// for all grammars
SymbolHash elemTable = new SymbolHash();
for (int i = grammars.length-1, j, k; i >= 0; i--) {
// get whether to skip EDC, and types need to be checked
keepType = 0;
fullChecked = grammars[i].fFullChecked;
types = grammars[i].getUncheckedComplexTypeDecls();
ctLocators = grammars[i].getUncheckedCTLocators();
// for each type
for (j = types.length-1; j >= 0; j--) {
// if we've already full-checked this grammar, then
// skip the EDC constraint
if (!fullChecked) {
// 1. Element Decl Consistent
if (types[j].fParticle!=null) {
elemTable.clear();
try {
checkElementDeclsConsistent(types[j], types[j].fParticle,
elemTable, SGHandler);
}
catch (XMLSchemaException e) {
reportSchemaError(errorReporter, ctLocators[j],
e.getKey(),
e.getArgs());
}
}
}
// 2. Particle Derivation
if (types[j].fBaseType != null &&
types[j].fBaseType != SchemaGrammar.fAnyType &&
types[j].fDerivedBy == SchemaSymbols.RESTRICTION &&
types[j].fParticle !=null &&
(types[j].fBaseType instanceof XSComplexTypeDecl) &&
((XSComplexTypeDecl)(types[j].fBaseType)).fParticle != null) {
try {
particleValidRestriction(SGHandler, types[j].fParticle,
((XSComplexTypeDecl)(types[j].fBaseType)).fParticle);
} catch (XMLSchemaException e) {
reportSchemaError(errorReporter, ctLocators[j],
e.getKey(),
e.getArgs());
reportSchemaError(errorReporter, ctLocators[j],
"derivation-ok-restriction.5.3",
new Object[]{types[j].fName});
}
}
// 3. UPA
// get the content model and check UPA
XSCMValidator cm = types[j].getContentModel(cmBuilder);
further = false;
if (cm != null) {
try {
further = cm.checkUniqueParticleAttribution(SGHandler);
} catch (XMLSchemaException e) {
reportSchemaError(errorReporter, ctLocators[j],
e.getKey(),
e.getArgs());
}
}
// now report all errors
// REVISIT: do we want to report all errors? or just one?
/*for (k = errors.getErrorCodeNum()-1; k >= 0; k--) {
reportSchemaError(errorReporter, ctLocators[j],
errors.getErrorCode(k),
errors.getArgs(k));
}*/
// if we are doing all checkings, and this one needs further
// checking, store it in the type array.
if (!fullChecked && further)
types[keepType++] = types[j];
// clear errors for the next type.
// REVISIT: do we want to report all errors? or just one?
//errors.clear();
}
// we've done with the types in this grammar. if we are checking
// all constraints, need to trim type array to a proper size:
// only contain those need further checking.
// and mark this grammar that it only needs UPA checking.
if (!fullChecked) {
grammars[i].setUncheckedTypeNum(keepType);
grammars[i].fFullChecked = true;
}
}
}
/*
Check that a given particle is a valid restriction of a base particle.
*/
public static void checkElementDeclsConsistent(XSComplexTypeDecl type,
XSParticleDecl particle,
SymbolHash elemDeclHash,
SubstitutionGroupHandler sgHandler)
throws XMLSchemaException {
// check for elements in the tree with the same name and namespace
int pType = particle.fType;
if (pType == XSParticleDecl.PARTICLE_EMPTY ||
pType == XSParticleDecl.PARTICLE_WILDCARD)
return;
if (pType == XSParticleDecl.PARTICLE_ELEMENT) {
XSElementDecl elem = (XSElementDecl)(particle.fValue);
findElemInTable(type, elem, elemDeclHash);
if (elem.isGlobal()) {
// Check for subsitution groups.
XSElementDecl[] subGroup = sgHandler.getSubstitutionGroup(elem);
for (int i = 0; i < subGroup.length; i++) {
findElemInTable(type, subGroup[i], elemDeclHash);
}
}
return;
}
XSParticleDecl left = (XSParticleDecl)particle.fValue;
checkElementDeclsConsistent(type, left, elemDeclHash, sgHandler);
XSParticleDecl right = (XSParticleDecl)particle.fOtherValue;
if (right != null) {
checkElementDeclsConsistent(type, right, elemDeclHash, sgHandler);
}
}
public static void findElemInTable(XSComplexTypeDecl type, XSElementDecl elem,
SymbolHash elemDeclHash)
throws XMLSchemaException {
// How can we avoid this concat? LM.
String name = elem.fName + "," + elem.fTargetNamespace;
XSElementDecl existingElem = null;
if ((existingElem = (XSElementDecl)(elemDeclHash.get(name))) == null) {
// just add it in
elemDeclHash.put(name, elem);
}
else {
// If this is the same check element, we're O.K.
if (elem == existingElem)
return;
if (elem.fType != existingElem.fType) {
// Types are not the same
throw new XMLSchemaException("cos-element-consistent",
new Object[] {type.fName, name});
}
}
}
// Invoke particleValidRestriction with a substitution group handler for each
/*
Check that a given particle is a valid restriction of a base particle.
*/
public static void particleValidRestriction(SubstitutionGroupHandler sgHandler,
XSParticleDecl dParticle,
XSParticleDecl bParticle)
throws XMLSchemaException {
// Invoke particleValidRestriction with a substitution group handler for each
// particle.
particleValidRestriction(dParticle, sgHandler, bParticle, sgHandler);
}
private static void particleValidRestriction(XSParticleDecl dParticle,
SubstitutionGroupHandler dSGHandler,
XSParticleDecl bParticle,
SubstitutionGroupHandler bSGHandler)
throws XMLSchemaException {
Vector dChildren = null;
Vector bChildren = null;
int dMinEffectiveTotalRange=OCCURRENCE_UNKNOWN;
int dMaxEffectiveTotalRange=OCCURRENCE_UNKNOWN;
// Check for empty particles. If either base or derived particle is empty,
// (and the other isn't) it's an error.
if (! (dParticle.isEmpty() == bParticle.isEmpty())) {
throw new XMLSchemaException("cos-particle-restrict", null);
}
//
// Do setup prior to invoking the Particle (Restriction) cases.
// This involves:
// - removing pointless occurrences for groups, and retrieving a vector of
// non-pointless children
// - turning top-level elements with substitution groups into CHOICE groups.
//
int dType = dParticle.fType;
//
// Handle pointless groups for the derived particle
//
if (dType == XSParticleDecl.PARTICLE_SEQUENCE ||
dType == XSParticleDecl.PARTICLE_CHOICE ||
dType == XSParticleDecl.PARTICLE_ALL) {
// Find a group, starting with this particle, with more than 1 child. There
// may be none, and the particle of interest trivially becomes an element or
// wildcard.
XSParticleDecl dtmp = getNonUnaryGroup(dParticle);
if (dtmp != dParticle) {
// Particle has been replaced. Retrieve new type info.
dParticle = dtmp;
dType = dParticle.fType;
}
// Fill in a vector with the children of the particle, removing any
// pointless model groups in the process.
dChildren = removePointlessChildren(dParticle);
}
int dMinOccurs = dParticle.fMinOccurs;
int dMaxOccurs = dParticle.fMaxOccurs;
//
// For elements which are the heads of substitution groups, treat as CHOICE
//
if (dSGHandler != null && dType == XSParticleDecl.PARTICLE_ELEMENT) {
XSElementDecl dElement = (XSElementDecl)dParticle.fValue;
if (dElement.isGlobal()) {
// Check for subsitution groups. Treat any element that has a
// subsitution group as a choice. Fill in the children vector with the
// members of the substitution group
XSElementDecl[] subGroup = dSGHandler.getSubstitutionGroup(dElement);
if (subGroup.length >0 ) {
// Now, set the type to be CHOICE. The "group" will have the same
// occurrence information as the original particle.
dType = XSParticleDecl.PARTICLE_CHOICE;
dMinOccurs = dParticle.fMinOccurs;
dMaxOccurs = dParticle.fMaxOccurs;
dMinEffectiveTotalRange = dMinOccurs;
dMaxEffectiveTotalRange = dMaxOccurs;
// Fill in the vector of children
dChildren = new Vector(subGroup.length+1);
for (int i = 0; i < subGroup.length; i++) {
addElementToParticleVector(dChildren, subGroup[i]);
}
addElementToParticleVector(dChildren, dElement);
// Set the handler to null, to indicate that we've finished handling
// substitution groups for this particle.
dSGHandler = null;
}
}
}
int bType = bParticle.fType;
//
// Handle pointless groups for the base particle
//
if (bType == XSParticleDecl.PARTICLE_SEQUENCE ||
bType == XSParticleDecl.PARTICLE_CHOICE ||
bType == XSParticleDecl.PARTICLE_ALL) {
// Find a group, starting with this particle, with more than 1 child. There
// may be none, and the particle of interest trivially becomes an element or
// wildcard.
XSParticleDecl btmp = getNonUnaryGroup(bParticle);
if (btmp != bParticle) {
// Particle has been replaced. Retrieve new type info.
bParticle = btmp;
bType = bParticle.fType;
}
// Fill in a vector with the children of the particle, removing any
// pointless model groups in the process.
bChildren = removePointlessChildren(bParticle);
}
int bMinOccurs = bParticle.fMinOccurs;
int bMaxOccurs = bParticle.fMaxOccurs;
if (bSGHandler != null && bType == XSParticleDecl.PARTICLE_ELEMENT) {
XSElementDecl bElement = (XSElementDecl)bParticle.fValue;
if (bElement.isGlobal()) {
// Check for subsitution groups. Treat any element that has a
// subsitution group as a choice. Fill in the children vector with the
// members of the substitution group
XSElementDecl[] bsubGroup = bSGHandler.getSubstitutionGroup(bElement);
if (bsubGroup.length >0 ) {
// Now, set the type to be CHOICE
bType = XSParticleDecl.PARTICLE_CHOICE;
bMinOccurs = bParticle.fMinOccurs;
bMaxOccurs = bParticle.fMaxOccurs;
bChildren = new Vector(bsubGroup.length+1);
for (int i = 0; i < bsubGroup.length; i++) {
addElementToParticleVector(bChildren, bsubGroup[i]);
}
addElementToParticleVector(bChildren, bElement);
// Set the handler to null, to indicate that we've finished handling
// substitution groups for this particle.
bSGHandler = null;
}
}
}
//
// O.K. - Figure out which particle derivation rule applies and call it
//
switch (dType) {
case XSParticleDecl.PARTICLE_ELEMENT:
{
switch (bType) {
// Elt:Elt NameAndTypeOK
case XSParticleDecl.PARTICLE_ELEMENT:
{
checkNameAndTypeOK((XSElementDecl)dParticle.fValue,dMinOccurs,dMaxOccurs,
(XSElementDecl)bParticle.fValue,bMinOccurs,bMaxOccurs);
return;
}
// Elt:Any NSCompat
case XSParticleDecl.PARTICLE_WILDCARD:
{
checkNSCompat((XSElementDecl)dParticle.fValue,dMinOccurs,dMaxOccurs,
(XSWildcardDecl)bParticle.fValue,bMinOccurs,bMaxOccurs);
return;
}
// Elt:All RecurseAsIfGroup
case XSParticleDecl.PARTICLE_CHOICE:
{
// Treat the element as if it were in a group of the same type
// as the base Particle
dChildren = new Vector();
dChildren.addElement(dParticle);
checkRecurseLax(dChildren, dMinOccurs, dMaxOccurs, dSGHandler,
bChildren, bMinOccurs, bMaxOccurs, bSGHandler);
return;
}
case XSParticleDecl.PARTICLE_SEQUENCE:
case XSParticleDecl.PARTICLE_ALL:
{
// Treat the element as if it were in a group of the same type
// as the base Particle
dChildren = new Vector();
dChildren.addElement(dParticle);
checkRecurse(dChildren, dMinOccurs, dMaxOccurs, dSGHandler,
bChildren, bMinOccurs, bMaxOccurs, bSGHandler);
return;
}
default:
{
throw new XMLSchemaException("Internal-Error",
new Object[]{"in particleValidRestriction"});
}
}
}
case XSParticleDecl.PARTICLE_WILDCARD:
{
switch (bType) {
// Any:Any NSSubset
case XSParticleDecl.PARTICLE_WILDCARD:
{
checkNSSubset((XSWildcardDecl)dParticle.fValue, dMinOccurs, dMaxOccurs,
(XSWildcardDecl)bParticle.fValue, bMinOccurs, bMaxOccurs);
return;
}
case XSParticleDecl.PARTICLE_CHOICE:
case XSParticleDecl.PARTICLE_SEQUENCE:
case XSParticleDecl.PARTICLE_ALL:
case XSParticleDecl.PARTICLE_ELEMENT:
{
throw new XMLSchemaException("cos-particle-restrict.2",
new Object[]{"any:choice,sequence,all,elt"});
}
default:
{
throw new XMLSchemaException("Internal-Error",
new Object[]{"in particleValidRestriction"});
}
}
}
case XSParticleDecl.PARTICLE_ALL:
{
switch (bType) {
// All:Any NSRecurseCheckCardinality
case XSParticleDecl.PARTICLE_WILDCARD:
{
- if (dMinEffectiveTotalRange != OCCURRENCE_UNKNOWN)
+ if (dMinEffectiveTotalRange == OCCURRENCE_UNKNOWN)
dMinEffectiveTotalRange = dParticle.minEffectiveTotalRange();
- if (dMaxEffectiveTotalRange != OCCURRENCE_UNKNOWN)
+ if (dMaxEffectiveTotalRange == OCCURRENCE_UNKNOWN)
dMaxEffectiveTotalRange = dParticle.maxEffectiveTotalRange();
checkNSRecurseCheckCardinality(dChildren, dMinEffectiveTotalRange,
dMaxEffectiveTotalRange,
dSGHandler,
bParticle,bMinOccurs,bMaxOccurs);
return;
}
case XSParticleDecl.PARTICLE_ALL:
{
checkRecurse(dChildren, dMinOccurs, dMaxOccurs, dSGHandler,
bChildren, bMinOccurs, bMaxOccurs, bSGHandler);
return;
}
case XSParticleDecl.PARTICLE_CHOICE:
case XSParticleDecl.PARTICLE_SEQUENCE:
case XSParticleDecl.PARTICLE_ELEMENT:
{
throw new XMLSchemaException("cos-particle-restrict.2",
new Object[]{"all:choice,sequence,elt"});
}
default:
{
throw new XMLSchemaException("Internal-Error",
new Object[]{"in particleValidRestriction"});
}
}
}
case XSParticleDecl.PARTICLE_CHOICE:
{
switch (bType) {
// Choice:Any NSRecurseCheckCardinality
case XSParticleDecl.PARTICLE_WILDCARD:
{
- if (dMinEffectiveTotalRange != OCCURRENCE_UNKNOWN)
+ if (dMinEffectiveTotalRange == OCCURRENCE_UNKNOWN)
dMinEffectiveTotalRange = dParticle.minEffectiveTotalRange();
- if (dMaxEffectiveTotalRange != OCCURRENCE_UNKNOWN)
+ if (dMaxEffectiveTotalRange == OCCURRENCE_UNKNOWN)
dMaxEffectiveTotalRange = dParticle.maxEffectiveTotalRange();
checkNSRecurseCheckCardinality(dChildren, dMinEffectiveTotalRange,
dMaxEffectiveTotalRange,
dSGHandler,
bParticle,bMinOccurs,bMaxOccurs);
return;
}
case XSParticleDecl.PARTICLE_CHOICE:
{
checkRecurseLax(dChildren, dMinOccurs, dMaxOccurs, dSGHandler,
bChildren, bMinOccurs, bMaxOccurs, bSGHandler);
return;
}
case XSParticleDecl.PARTICLE_ALL:
case XSParticleDecl.PARTICLE_SEQUENCE:
case XSParticleDecl.PARTICLE_ELEMENT:
{
throw new XMLSchemaException("cos-particle-restrict.2",
new Object[]{"choice:all,sequence,elt"});
}
default:
{
throw new XMLSchemaException("Internal-Error",
new Object[]{"in particleValidRestriction"});
}
}
}
case XSParticleDecl.PARTICLE_SEQUENCE:
{
switch (bType) {
// Choice:Any NSRecurseCheckCardinality
case XSParticleDecl.PARTICLE_WILDCARD:
{
- if (dMinEffectiveTotalRange != OCCURRENCE_UNKNOWN)
+ if (dMinEffectiveTotalRange == OCCURRENCE_UNKNOWN)
dMinEffectiveTotalRange = dParticle.minEffectiveTotalRange();
- if (dMaxEffectiveTotalRange != OCCURRENCE_UNKNOWN)
+ if (dMaxEffectiveTotalRange == OCCURRENCE_UNKNOWN)
dMaxEffectiveTotalRange = dParticle.maxEffectiveTotalRange();
checkNSRecurseCheckCardinality(dChildren, dMinEffectiveTotalRange,
dMaxEffectiveTotalRange,
dSGHandler,
bParticle,bMinOccurs,bMaxOccurs);
return;
}
case XSParticleDecl.PARTICLE_ALL:
{
checkRecurseUnordered(dChildren, dMinOccurs, dMaxOccurs, dSGHandler,
bChildren, bMinOccurs, bMaxOccurs, bSGHandler);
return;
}
case XSParticleDecl.PARTICLE_SEQUENCE:
{
checkRecurse(dChildren, dMinOccurs, dMaxOccurs, dSGHandler,
bChildren, bMinOccurs, bMaxOccurs, bSGHandler);
return;
}
case XSParticleDecl.PARTICLE_CHOICE:
{
int min1 = dMinOccurs * dChildren.size();
int max1 = (dMaxOccurs == SchemaSymbols.OCCURRENCE_UNBOUNDED)?
dMaxOccurs : dMaxOccurs * dChildren.size();
checkMapAndSum(dChildren, min1, max1, dSGHandler,
bChildren, bMinOccurs, bMaxOccurs, bSGHandler);
return;
}
case XSParticleDecl.PARTICLE_ELEMENT:
{
throw new XMLSchemaException("cos-particle-restrict.2",
new Object[]{"seq:elt"});
}
default:
{
throw new XMLSchemaException("Internal-Error",
new Object[]{"in particleValidRestriction"});
}
}
}
}
}
private static void addElementToParticleVector (Vector v, XSElementDecl d) {
XSParticleDecl p = new XSParticleDecl();
p.fValue = d;
p.fType = XSParticleDecl.PARTICLE_ELEMENT;
v.addElement(p);
}
private static XSParticleDecl getNonUnaryGroup(XSParticleDecl p) {
if (p.fType == XSParticleDecl.PARTICLE_ELEMENT ||
p.fType == XSParticleDecl.PARTICLE_WILDCARD)
return p;
if (p.fMinOccurs==1 && p.fMaxOccurs==1 &&
p.fValue!=null && p.fOtherValue==null)
return getNonUnaryGroup((XSParticleDecl)p.fValue);
else
return p;
}
private static Vector removePointlessChildren(XSParticleDecl p) {
if (p.fType == XSParticleDecl.PARTICLE_ELEMENT ||
p.fType == XSParticleDecl.PARTICLE_WILDCARD ||
p.fType == XSParticleDecl.PARTICLE_EMPTY)
return null;
Vector children = new Vector();
gatherChildren(p.fType, (XSParticleDecl)p.fValue, children);
if (p.fOtherValue != null) {
gatherChildren(p.fType, (XSParticleDecl)p.fOtherValue, children);
}
return children;
}
private static void gatherChildren(int parentType, XSParticleDecl p, Vector children) {
int min = p.fMinOccurs;
int max = p.fMaxOccurs;
int type = p.fType;
if (type == XSParticleDecl.PARTICLE_EMPTY)
return;
if (type == XSParticleDecl.PARTICLE_ELEMENT ||
type== XSParticleDecl.PARTICLE_WILDCARD) {
children.addElement(p);
return;
}
XSParticleDecl left = (XSParticleDecl)p.fValue;
XSParticleDecl right = (XSParticleDecl)p.fOtherValue;
if (! (min==1 && max==1)) {
children.addElement(p);
}
else if (parentType == type) {
gatherChildren(type,left,children);
if (right != null) {
gatherChildren(type,right,children);
}
}
else if (!p.isEmpty()) {
children.addElement(p);
}
}
private static void checkNameAndTypeOK(XSElementDecl dElement, int dMin, int dMax,
XSElementDecl bElement, int bMin, int bMax)
throws XMLSchemaException {
//
// Check that the names are the same
//
if (dElement.fName != bElement.fName ||
dElement.fTargetNamespace != bElement.fTargetNamespace) {
throw new XMLSchemaException(
"rcase-NameAndTypeOK.1",new Object[]{dElement.fName,
dElement.fTargetNamespace, bElement.fName, bElement.fTargetNamespace});
}
//
// Check nillable
//
if (! (bElement.isNillable() || !dElement.isNillable())) {
throw new XMLSchemaException("rcase-NameAndTypeOK.2",
new Object[]{dElement.fName});
}
//
// Check occurrence range
//
if (!checkOccurrenceRange(dMin, dMax, bMin, bMax)) {
throw new XMLSchemaException("rcase-NameAndTypeOK.3",
new Object[]{dElement.fName});
}
//
// Check for consistent fixed values
//
if (bElement.getConstraintType() == XSElementDecl.FIXED_VALUE) {
// derived one has to have a fixed value
if (dElement.getConstraintType() != XSElementDecl.FIXED_VALUE) {
throw new XMLSchemaException("rcase-NameAndTypeOK.4",
new Object[]{dElement.fName});
}
// get simple type
XSSimpleType dv = null;
if (dElement.fType.getXSType() == XSTypeDecl.SIMPLE_TYPE)
dv = (XSSimpleType)dElement.fType;
else if (((XSComplexTypeDecl)dElement.fType).fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE)
dv = ((XSComplexTypeDecl)dElement.fType).fXSSimpleType;
// if there is no simple type, then compare based on string
if (dv == null && !bElement.fDefault.normalizedValue.equals(dElement.fDefault.normalizedValue) ||
dv != null && !dv.isEqual(bElement.fDefault.actualValue, dElement.fDefault.actualValue)) {
throw new XMLSchemaException("rcase-NameAndTypeOK.4",
new Object[]{dElement.fName});
}
}
//
// Check identity constraints
//
checkIDConstraintRestriction(dElement, bElement);
//
// Check for disallowed substitutions
//
int blockSet1 = dElement.fBlock;
int blockSet2 = bElement.fBlock;
if (((blockSet1 & blockSet2)!=blockSet2) ||
(blockSet1==SchemaSymbols.EMPTY_SET && blockSet2!=SchemaSymbols.EMPTY_SET))
throw new XMLSchemaException("rcase-NameAndTypeOK.6",
new Object[]{dElement.fName});
//
// Check that the derived element's type is derived from the base's.
//
if (!checkTypeDerivationOk(dElement.fType, bElement.fType,
(short)(SchemaSymbols.EXTENSION|SchemaSymbols.LIST|SchemaSymbols.UNION))) {
throw new XMLSchemaException("rcase-NameAndTypeOK.7",
new Object[]{dElement.fName});
}
}
private static void checkIDConstraintRestriction(XSElementDecl derivedElemDecl,
XSElementDecl baseElemDecl)
throws XMLSchemaException {
// TODO
} // checkIDConstraintRestriction
private static boolean checkOccurrenceRange(int min1, int max1, int min2, int max2) {
if ((min1 >= min2) &&
((max2==SchemaSymbols.OCCURRENCE_UNBOUNDED) ||
(max1!=SchemaSymbols.OCCURRENCE_UNBOUNDED && max1<=max2)))
return true;
else
return false;
}
private static void checkNSCompat(XSElementDecl elem, int min1, int max1,
XSWildcardDecl wildcard, int min2, int max2)
throws XMLSchemaException {
// check Occurrence ranges
if (!checkOccurrenceRange(min1,max1,min2,max2)) {
throw new XMLSchemaException("rcase-NSCompat.2",
new Object[]{elem.fName});
}
// check wildcard allows namespace of element
if (!wildcard.allowNamespace(elem.fTargetNamespace)) {
throw new XMLSchemaException("rcase-NSCompat.1",
new Object[]{elem.fName,elem.fTargetNamespace});
}
}
private static void checkNSSubset(XSWildcardDecl dWildcard, int min1, int max1,
XSWildcardDecl bWildcard, int min2, int max2)
throws XMLSchemaException {
// check Occurrence ranges
if (!checkOccurrenceRange(min1,max1,min2,max2)) {
throw new XMLSchemaException("rcase-NSSubset.2",null);
}
// check wildcard subset
if (!dWildcard.isSubsetOf(bWildcard)) {
throw new XMLSchemaException("rcase-NSSubset.1",null);
}
}
private static void checkNSRecurseCheckCardinality(Vector children, int min1, int max1,
SubstitutionGroupHandler dSGHandler,
XSParticleDecl wildcard, int min2, int max2)
throws XMLSchemaException {
// check Occurrence ranges
if (!checkOccurrenceRange(min1,max1,min2,max2)) {
throw new XMLSchemaException("rcase-NSRecurseCheckCardinality.2", null);
}
// Check that each member of the group is a valid restriction of the wildcard
int count = children.size();
try {
for (int i = 0; i < count; i++) {
XSParticleDecl particle1 = (XSParticleDecl)children.elementAt(i);
particleValidRestriction(particle1, dSGHandler, wildcard, null);
}
}
catch (XMLSchemaException e) {
throw new XMLSchemaException("rcase-NSRecurseCheckCardinality.1", null);
}
}
private static void checkRecurse(Vector dChildren, int min1, int max1,
SubstitutionGroupHandler dSGHandler,
Vector bChildren, int min2, int max2,
SubstitutionGroupHandler bSGHandler)
throws XMLSchemaException {
// check Occurrence ranges
if (!checkOccurrenceRange(min1,max1,min2,max2)) {
throw new XMLSchemaException("rcase-Recurse.1", null);
}
int count1= dChildren.size();
int count2= bChildren.size();
int current = 0;
label: for (int i = 0; i<count1; i++) {
XSParticleDecl particle1 = (XSParticleDecl)dChildren.elementAt(i);
for (int j = current; j<count2; j++) {
XSParticleDecl particle2 = (XSParticleDecl)bChildren.elementAt(j);
current +=1;
try {
particleValidRestriction(particle1, dSGHandler, particle2, bSGHandler);
continue label;
}
catch (XMLSchemaException e) {
if (!particle2.emptiable())
throw new XMLSchemaException("rcase-Recurse.2", null);
}
}
throw new XMLSchemaException("rcase-Recurse.2", null);
}
// Now, see if there are some elements in the base we didn't match up
for (int j=current; j < count2; j++) {
XSParticleDecl particle2 = (XSParticleDecl)bChildren.elementAt(j);
if (!particle2.emptiable()) {
throw new XMLSchemaException("rcase-Recurse.2", null);
}
}
}
private static void checkRecurseUnordered(Vector dChildren, int min1, int max1,
SubstitutionGroupHandler dSGHandler,
Vector bChildren, int min2, int max2,
SubstitutionGroupHandler bSGHandler)
throws XMLSchemaException {
// check Occurrence ranges
if (!checkOccurrenceRange(min1,max1,min2,max2)) {
throw new XMLSchemaException("rcase-RecurseUnordered.1", null);
}
int count1= dChildren.size();
int count2 = bChildren.size();
boolean foundIt[] = new boolean[count2];
label: for (int i = 0; i<count1; i++) {
XSParticleDecl particle1 = (XSParticleDecl)dChildren.elementAt(i);
for (int j = 0; j<count2; j++) {
XSParticleDecl particle2 = (XSParticleDecl)bChildren.elementAt(j);
try {
particleValidRestriction(particle1, dSGHandler, particle2, bSGHandler);
if (foundIt[j])
throw new XMLSchemaException("rcase-RecurseUnordered.2", null);
else
foundIt[j]=true;
continue label;
}
catch (XMLSchemaException e) {
}
}
// didn't find a match. Detect an error
throw new XMLSchemaException("rcase-RecurseUnordered.2", null);
}
// Now, see if there are some elements in the base we didn't match up
for (int j=0; j < count2; j++) {
XSParticleDecl particle2 = (XSParticleDecl)bChildren.elementAt(j);
if (!foundIt[j] && !particle2.emptiable()) {
throw new XMLSchemaException("rcase-RecurseUnordered.2", null);
}
}
}
private static void checkRecurseLax(Vector dChildren, int min1, int max1,
SubstitutionGroupHandler dSGHandler,
Vector bChildren, int min2, int max2,
SubstitutionGroupHandler bSGHandler)
throws XMLSchemaException {
// check Occurrence ranges
if (!checkOccurrenceRange(min1,max1,min2,max2)) {
throw new XMLSchemaException("rcase-RecurseLax.1", null);
}
int count1= dChildren.size();
int count2 = bChildren.size();
int current = 0;
label: for (int i = 0; i<count1; i++) {
XSParticleDecl particle1 = (XSParticleDecl)dChildren.elementAt(i);
for (int j = current; j<count2; j++) {
XSParticleDecl particle2 = (XSParticleDecl)bChildren.elementAt(j);
current +=1;
try {
particleValidRestriction(particle1, dSGHandler, particle2, bSGHandler);
continue label;
}
catch (XMLSchemaException e) {
}
}
// didn't find a match. Detect an error
throw new XMLSchemaException("rcase-RecurseLax.2", null);
}
}
private static void checkMapAndSum(Vector dChildren, int min1, int max1,
SubstitutionGroupHandler dSGHandler,
Vector bChildren, int min2, int max2,
SubstitutionGroupHandler bSGHandler)
throws XMLSchemaException {
// See if the sequence group is a valid restriction of the choice
// Here is an example of a valid restriction:
// <choice minOccurs="2">
// <a/>
// <b/>
// <c/>
// </choice>
//
// <sequence>
// <b/>
// <a/>
// </sequence>
// check Occurrence ranges
if (!checkOccurrenceRange(min1,max1,min2,max2)) {
throw new XMLSchemaException("rcase-MapAndSum.2", null);
}
int count1 = dChildren.size();
int count2 = bChildren.size();
label: for (int i = 0; i<count1; i++) {
XSParticleDecl particle1 = (XSParticleDecl)dChildren.elementAt(i);
for (int j = 0; j<count2; j++) {
XSParticleDecl particle2 = (XSParticleDecl)bChildren.elementAt(j);
try {
particleValidRestriction(particle1, dSGHandler, particle2, bSGHandler);
continue label;
}
catch (XMLSchemaException e) {
}
}
// didn't find a match. Detect an error
throw new XMLSchemaException("rcase-MapAndSum.1", null);
}
}
// to check whether two element overlap, as defined in constraint UPA
public static boolean overlapUPA(XSElementDecl element1,
XSElementDecl element2,
SubstitutionGroupHandler sgHandler) {
// if the two element have the same name and namespace,
if (element1.fName == element2.fName &&
element1.fTargetNamespace == element2.fTargetNamespace) {
return true;
}
// or if there is an element decl in element1's substitution group,
// who has the same name/namespace with element2
XSElementDecl[] subGroup = sgHandler.getSubstitutionGroup(element1);
for (int i = subGroup.length-1; i >= 0; i--) {
if (subGroup[i].fName == element2.fName &&
subGroup[i].fTargetNamespace == element2.fTargetNamespace) {
return true;
}
}
// or if there is an element decl in element2's substitution group,
// who has the same name/namespace with element1
subGroup = sgHandler.getSubstitutionGroup(element2);
for (int i = subGroup.length-1; i >= 0; i--) {
if (subGroup[i].fName == element1.fName &&
subGroup[i].fTargetNamespace == element1.fTargetNamespace) {
return true;
}
}
return false;
}
// to check whether an element overlaps with a wildcard,
// as defined in constraint UPA
public static boolean overlapUPA(XSElementDecl element,
XSWildcardDecl wildcard,
SubstitutionGroupHandler sgHandler) {
// if the wildcard allows the element
if (wildcard.allowNamespace(element.fTargetNamespace))
return true;
// or if the wildcard allows any element in the substitution group
XSElementDecl[] subGroup = sgHandler.getSubstitutionGroup(element);
for (int i = subGroup.length-1; i >= 0; i--) {
if (wildcard.allowNamespace(subGroup[i].fTargetNamespace))
return true;
}
return false;
}
public static boolean overlapUPA(XSWildcardDecl wildcard1,
XSWildcardDecl wildcard2) {
// if the intersection of the two wildcard is not empty list
XSWildcardDecl intersect = wildcard1.performIntersectionWith(wildcard2, wildcard1.fProcessContents);
if (intersect == null ||
intersect.fType != XSWildcardDecl.WILDCARD_LIST ||
intersect.fNamespaceList.length != 0) {
return true;
}
return false;
}
// call one of the above methods according to the type of decls
public static boolean overlapUPA(Object decl1, Object decl2,
SubstitutionGroupHandler sgHandler) {
if (decl1 instanceof XSElementDecl) {
if (decl2 instanceof XSElementDecl) {
return overlapUPA((XSElementDecl)decl1,
(XSElementDecl)decl2,
sgHandler);
} else {
return overlapUPA((XSElementDecl)decl1,
(XSWildcardDecl)decl2,
sgHandler);
}
} else {
if (decl2 instanceof XSElementDecl) {
return overlapUPA((XSElementDecl)decl2,
(XSWildcardDecl)decl1,
sgHandler);
} else {
return overlapUPA((XSWildcardDecl)decl1,
(XSWildcardDecl)decl2);
}
}
}
} // class XSContraints
| false | true | private static void particleValidRestriction(XSParticleDecl dParticle,
SubstitutionGroupHandler dSGHandler,
XSParticleDecl bParticle,
SubstitutionGroupHandler bSGHandler)
throws XMLSchemaException {
Vector dChildren = null;
Vector bChildren = null;
int dMinEffectiveTotalRange=OCCURRENCE_UNKNOWN;
int dMaxEffectiveTotalRange=OCCURRENCE_UNKNOWN;
// Check for empty particles. If either base or derived particle is empty,
// (and the other isn't) it's an error.
if (! (dParticle.isEmpty() == bParticle.isEmpty())) {
throw new XMLSchemaException("cos-particle-restrict", null);
}
//
// Do setup prior to invoking the Particle (Restriction) cases.
// This involves:
// - removing pointless occurrences for groups, and retrieving a vector of
// non-pointless children
// - turning top-level elements with substitution groups into CHOICE groups.
//
int dType = dParticle.fType;
//
// Handle pointless groups for the derived particle
//
if (dType == XSParticleDecl.PARTICLE_SEQUENCE ||
dType == XSParticleDecl.PARTICLE_CHOICE ||
dType == XSParticleDecl.PARTICLE_ALL) {
// Find a group, starting with this particle, with more than 1 child. There
// may be none, and the particle of interest trivially becomes an element or
// wildcard.
XSParticleDecl dtmp = getNonUnaryGroup(dParticle);
if (dtmp != dParticle) {
// Particle has been replaced. Retrieve new type info.
dParticle = dtmp;
dType = dParticle.fType;
}
// Fill in a vector with the children of the particle, removing any
// pointless model groups in the process.
dChildren = removePointlessChildren(dParticle);
}
int dMinOccurs = dParticle.fMinOccurs;
int dMaxOccurs = dParticle.fMaxOccurs;
//
// For elements which are the heads of substitution groups, treat as CHOICE
//
if (dSGHandler != null && dType == XSParticleDecl.PARTICLE_ELEMENT) {
XSElementDecl dElement = (XSElementDecl)dParticle.fValue;
if (dElement.isGlobal()) {
// Check for subsitution groups. Treat any element that has a
// subsitution group as a choice. Fill in the children vector with the
// members of the substitution group
XSElementDecl[] subGroup = dSGHandler.getSubstitutionGroup(dElement);
if (subGroup.length >0 ) {
// Now, set the type to be CHOICE. The "group" will have the same
// occurrence information as the original particle.
dType = XSParticleDecl.PARTICLE_CHOICE;
dMinOccurs = dParticle.fMinOccurs;
dMaxOccurs = dParticle.fMaxOccurs;
dMinEffectiveTotalRange = dMinOccurs;
dMaxEffectiveTotalRange = dMaxOccurs;
// Fill in the vector of children
dChildren = new Vector(subGroup.length+1);
for (int i = 0; i < subGroup.length; i++) {
addElementToParticleVector(dChildren, subGroup[i]);
}
addElementToParticleVector(dChildren, dElement);
// Set the handler to null, to indicate that we've finished handling
// substitution groups for this particle.
dSGHandler = null;
}
}
}
int bType = bParticle.fType;
//
// Handle pointless groups for the base particle
//
if (bType == XSParticleDecl.PARTICLE_SEQUENCE ||
bType == XSParticleDecl.PARTICLE_CHOICE ||
bType == XSParticleDecl.PARTICLE_ALL) {
// Find a group, starting with this particle, with more than 1 child. There
// may be none, and the particle of interest trivially becomes an element or
// wildcard.
XSParticleDecl btmp = getNonUnaryGroup(bParticle);
if (btmp != bParticle) {
// Particle has been replaced. Retrieve new type info.
bParticle = btmp;
bType = bParticle.fType;
}
// Fill in a vector with the children of the particle, removing any
// pointless model groups in the process.
bChildren = removePointlessChildren(bParticle);
}
int bMinOccurs = bParticle.fMinOccurs;
int bMaxOccurs = bParticle.fMaxOccurs;
if (bSGHandler != null && bType == XSParticleDecl.PARTICLE_ELEMENT) {
XSElementDecl bElement = (XSElementDecl)bParticle.fValue;
if (bElement.isGlobal()) {
// Check for subsitution groups. Treat any element that has a
// subsitution group as a choice. Fill in the children vector with the
// members of the substitution group
XSElementDecl[] bsubGroup = bSGHandler.getSubstitutionGroup(bElement);
if (bsubGroup.length >0 ) {
// Now, set the type to be CHOICE
bType = XSParticleDecl.PARTICLE_CHOICE;
bMinOccurs = bParticle.fMinOccurs;
bMaxOccurs = bParticle.fMaxOccurs;
bChildren = new Vector(bsubGroup.length+1);
for (int i = 0; i < bsubGroup.length; i++) {
addElementToParticleVector(bChildren, bsubGroup[i]);
}
addElementToParticleVector(bChildren, bElement);
// Set the handler to null, to indicate that we've finished handling
// substitution groups for this particle.
bSGHandler = null;
}
}
}
//
// O.K. - Figure out which particle derivation rule applies and call it
//
switch (dType) {
case XSParticleDecl.PARTICLE_ELEMENT:
{
switch (bType) {
// Elt:Elt NameAndTypeOK
case XSParticleDecl.PARTICLE_ELEMENT:
{
checkNameAndTypeOK((XSElementDecl)dParticle.fValue,dMinOccurs,dMaxOccurs,
(XSElementDecl)bParticle.fValue,bMinOccurs,bMaxOccurs);
return;
}
// Elt:Any NSCompat
case XSParticleDecl.PARTICLE_WILDCARD:
{
checkNSCompat((XSElementDecl)dParticle.fValue,dMinOccurs,dMaxOccurs,
(XSWildcardDecl)bParticle.fValue,bMinOccurs,bMaxOccurs);
return;
}
// Elt:All RecurseAsIfGroup
case XSParticleDecl.PARTICLE_CHOICE:
{
// Treat the element as if it were in a group of the same type
// as the base Particle
dChildren = new Vector();
dChildren.addElement(dParticle);
checkRecurseLax(dChildren, dMinOccurs, dMaxOccurs, dSGHandler,
bChildren, bMinOccurs, bMaxOccurs, bSGHandler);
return;
}
case XSParticleDecl.PARTICLE_SEQUENCE:
case XSParticleDecl.PARTICLE_ALL:
{
// Treat the element as if it were in a group of the same type
// as the base Particle
dChildren = new Vector();
dChildren.addElement(dParticle);
checkRecurse(dChildren, dMinOccurs, dMaxOccurs, dSGHandler,
bChildren, bMinOccurs, bMaxOccurs, bSGHandler);
return;
}
default:
{
throw new XMLSchemaException("Internal-Error",
new Object[]{"in particleValidRestriction"});
}
}
}
case XSParticleDecl.PARTICLE_WILDCARD:
{
switch (bType) {
// Any:Any NSSubset
case XSParticleDecl.PARTICLE_WILDCARD:
{
checkNSSubset((XSWildcardDecl)dParticle.fValue, dMinOccurs, dMaxOccurs,
(XSWildcardDecl)bParticle.fValue, bMinOccurs, bMaxOccurs);
return;
}
case XSParticleDecl.PARTICLE_CHOICE:
case XSParticleDecl.PARTICLE_SEQUENCE:
case XSParticleDecl.PARTICLE_ALL:
case XSParticleDecl.PARTICLE_ELEMENT:
{
throw new XMLSchemaException("cos-particle-restrict.2",
new Object[]{"any:choice,sequence,all,elt"});
}
default:
{
throw new XMLSchemaException("Internal-Error",
new Object[]{"in particleValidRestriction"});
}
}
}
case XSParticleDecl.PARTICLE_ALL:
{
switch (bType) {
// All:Any NSRecurseCheckCardinality
case XSParticleDecl.PARTICLE_WILDCARD:
{
if (dMinEffectiveTotalRange != OCCURRENCE_UNKNOWN)
dMinEffectiveTotalRange = dParticle.minEffectiveTotalRange();
if (dMaxEffectiveTotalRange != OCCURRENCE_UNKNOWN)
dMaxEffectiveTotalRange = dParticle.maxEffectiveTotalRange();
checkNSRecurseCheckCardinality(dChildren, dMinEffectiveTotalRange,
dMaxEffectiveTotalRange,
dSGHandler,
bParticle,bMinOccurs,bMaxOccurs);
return;
}
case XSParticleDecl.PARTICLE_ALL:
{
checkRecurse(dChildren, dMinOccurs, dMaxOccurs, dSGHandler,
bChildren, bMinOccurs, bMaxOccurs, bSGHandler);
return;
}
case XSParticleDecl.PARTICLE_CHOICE:
case XSParticleDecl.PARTICLE_SEQUENCE:
case XSParticleDecl.PARTICLE_ELEMENT:
{
throw new XMLSchemaException("cos-particle-restrict.2",
new Object[]{"all:choice,sequence,elt"});
}
default:
{
throw new XMLSchemaException("Internal-Error",
new Object[]{"in particleValidRestriction"});
}
}
}
case XSParticleDecl.PARTICLE_CHOICE:
{
switch (bType) {
// Choice:Any NSRecurseCheckCardinality
case XSParticleDecl.PARTICLE_WILDCARD:
{
if (dMinEffectiveTotalRange != OCCURRENCE_UNKNOWN)
dMinEffectiveTotalRange = dParticle.minEffectiveTotalRange();
if (dMaxEffectiveTotalRange != OCCURRENCE_UNKNOWN)
dMaxEffectiveTotalRange = dParticle.maxEffectiveTotalRange();
checkNSRecurseCheckCardinality(dChildren, dMinEffectiveTotalRange,
dMaxEffectiveTotalRange,
dSGHandler,
bParticle,bMinOccurs,bMaxOccurs);
return;
}
case XSParticleDecl.PARTICLE_CHOICE:
{
checkRecurseLax(dChildren, dMinOccurs, dMaxOccurs, dSGHandler,
bChildren, bMinOccurs, bMaxOccurs, bSGHandler);
return;
}
case XSParticleDecl.PARTICLE_ALL:
case XSParticleDecl.PARTICLE_SEQUENCE:
case XSParticleDecl.PARTICLE_ELEMENT:
{
throw new XMLSchemaException("cos-particle-restrict.2",
new Object[]{"choice:all,sequence,elt"});
}
default:
{
throw new XMLSchemaException("Internal-Error",
new Object[]{"in particleValidRestriction"});
}
}
}
case XSParticleDecl.PARTICLE_SEQUENCE:
{
switch (bType) {
// Choice:Any NSRecurseCheckCardinality
case XSParticleDecl.PARTICLE_WILDCARD:
{
if (dMinEffectiveTotalRange != OCCURRENCE_UNKNOWN)
dMinEffectiveTotalRange = dParticle.minEffectiveTotalRange();
if (dMaxEffectiveTotalRange != OCCURRENCE_UNKNOWN)
dMaxEffectiveTotalRange = dParticle.maxEffectiveTotalRange();
checkNSRecurseCheckCardinality(dChildren, dMinEffectiveTotalRange,
dMaxEffectiveTotalRange,
dSGHandler,
bParticle,bMinOccurs,bMaxOccurs);
return;
}
case XSParticleDecl.PARTICLE_ALL:
{
checkRecurseUnordered(dChildren, dMinOccurs, dMaxOccurs, dSGHandler,
bChildren, bMinOccurs, bMaxOccurs, bSGHandler);
return;
}
case XSParticleDecl.PARTICLE_SEQUENCE:
{
checkRecurse(dChildren, dMinOccurs, dMaxOccurs, dSGHandler,
bChildren, bMinOccurs, bMaxOccurs, bSGHandler);
return;
}
case XSParticleDecl.PARTICLE_CHOICE:
{
int min1 = dMinOccurs * dChildren.size();
int max1 = (dMaxOccurs == SchemaSymbols.OCCURRENCE_UNBOUNDED)?
dMaxOccurs : dMaxOccurs * dChildren.size();
checkMapAndSum(dChildren, min1, max1, dSGHandler,
bChildren, bMinOccurs, bMaxOccurs, bSGHandler);
return;
}
case XSParticleDecl.PARTICLE_ELEMENT:
{
throw new XMLSchemaException("cos-particle-restrict.2",
new Object[]{"seq:elt"});
}
default:
{
throw new XMLSchemaException("Internal-Error",
new Object[]{"in particleValidRestriction"});
}
}
}
}
}
| private static void particleValidRestriction(XSParticleDecl dParticle,
SubstitutionGroupHandler dSGHandler,
XSParticleDecl bParticle,
SubstitutionGroupHandler bSGHandler)
throws XMLSchemaException {
Vector dChildren = null;
Vector bChildren = null;
int dMinEffectiveTotalRange=OCCURRENCE_UNKNOWN;
int dMaxEffectiveTotalRange=OCCURRENCE_UNKNOWN;
// Check for empty particles. If either base or derived particle is empty,
// (and the other isn't) it's an error.
if (! (dParticle.isEmpty() == bParticle.isEmpty())) {
throw new XMLSchemaException("cos-particle-restrict", null);
}
//
// Do setup prior to invoking the Particle (Restriction) cases.
// This involves:
// - removing pointless occurrences for groups, and retrieving a vector of
// non-pointless children
// - turning top-level elements with substitution groups into CHOICE groups.
//
int dType = dParticle.fType;
//
// Handle pointless groups for the derived particle
//
if (dType == XSParticleDecl.PARTICLE_SEQUENCE ||
dType == XSParticleDecl.PARTICLE_CHOICE ||
dType == XSParticleDecl.PARTICLE_ALL) {
// Find a group, starting with this particle, with more than 1 child. There
// may be none, and the particle of interest trivially becomes an element or
// wildcard.
XSParticleDecl dtmp = getNonUnaryGroup(dParticle);
if (dtmp != dParticle) {
// Particle has been replaced. Retrieve new type info.
dParticle = dtmp;
dType = dParticle.fType;
}
// Fill in a vector with the children of the particle, removing any
// pointless model groups in the process.
dChildren = removePointlessChildren(dParticle);
}
int dMinOccurs = dParticle.fMinOccurs;
int dMaxOccurs = dParticle.fMaxOccurs;
//
// For elements which are the heads of substitution groups, treat as CHOICE
//
if (dSGHandler != null && dType == XSParticleDecl.PARTICLE_ELEMENT) {
XSElementDecl dElement = (XSElementDecl)dParticle.fValue;
if (dElement.isGlobal()) {
// Check for subsitution groups. Treat any element that has a
// subsitution group as a choice. Fill in the children vector with the
// members of the substitution group
XSElementDecl[] subGroup = dSGHandler.getSubstitutionGroup(dElement);
if (subGroup.length >0 ) {
// Now, set the type to be CHOICE. The "group" will have the same
// occurrence information as the original particle.
dType = XSParticleDecl.PARTICLE_CHOICE;
dMinOccurs = dParticle.fMinOccurs;
dMaxOccurs = dParticle.fMaxOccurs;
dMinEffectiveTotalRange = dMinOccurs;
dMaxEffectiveTotalRange = dMaxOccurs;
// Fill in the vector of children
dChildren = new Vector(subGroup.length+1);
for (int i = 0; i < subGroup.length; i++) {
addElementToParticleVector(dChildren, subGroup[i]);
}
addElementToParticleVector(dChildren, dElement);
// Set the handler to null, to indicate that we've finished handling
// substitution groups for this particle.
dSGHandler = null;
}
}
}
int bType = bParticle.fType;
//
// Handle pointless groups for the base particle
//
if (bType == XSParticleDecl.PARTICLE_SEQUENCE ||
bType == XSParticleDecl.PARTICLE_CHOICE ||
bType == XSParticleDecl.PARTICLE_ALL) {
// Find a group, starting with this particle, with more than 1 child. There
// may be none, and the particle of interest trivially becomes an element or
// wildcard.
XSParticleDecl btmp = getNonUnaryGroup(bParticle);
if (btmp != bParticle) {
// Particle has been replaced. Retrieve new type info.
bParticle = btmp;
bType = bParticle.fType;
}
// Fill in a vector with the children of the particle, removing any
// pointless model groups in the process.
bChildren = removePointlessChildren(bParticle);
}
int bMinOccurs = bParticle.fMinOccurs;
int bMaxOccurs = bParticle.fMaxOccurs;
if (bSGHandler != null && bType == XSParticleDecl.PARTICLE_ELEMENT) {
XSElementDecl bElement = (XSElementDecl)bParticle.fValue;
if (bElement.isGlobal()) {
// Check for subsitution groups. Treat any element that has a
// subsitution group as a choice. Fill in the children vector with the
// members of the substitution group
XSElementDecl[] bsubGroup = bSGHandler.getSubstitutionGroup(bElement);
if (bsubGroup.length >0 ) {
// Now, set the type to be CHOICE
bType = XSParticleDecl.PARTICLE_CHOICE;
bMinOccurs = bParticle.fMinOccurs;
bMaxOccurs = bParticle.fMaxOccurs;
bChildren = new Vector(bsubGroup.length+1);
for (int i = 0; i < bsubGroup.length; i++) {
addElementToParticleVector(bChildren, bsubGroup[i]);
}
addElementToParticleVector(bChildren, bElement);
// Set the handler to null, to indicate that we've finished handling
// substitution groups for this particle.
bSGHandler = null;
}
}
}
//
// O.K. - Figure out which particle derivation rule applies and call it
//
switch (dType) {
case XSParticleDecl.PARTICLE_ELEMENT:
{
switch (bType) {
// Elt:Elt NameAndTypeOK
case XSParticleDecl.PARTICLE_ELEMENT:
{
checkNameAndTypeOK((XSElementDecl)dParticle.fValue,dMinOccurs,dMaxOccurs,
(XSElementDecl)bParticle.fValue,bMinOccurs,bMaxOccurs);
return;
}
// Elt:Any NSCompat
case XSParticleDecl.PARTICLE_WILDCARD:
{
checkNSCompat((XSElementDecl)dParticle.fValue,dMinOccurs,dMaxOccurs,
(XSWildcardDecl)bParticle.fValue,bMinOccurs,bMaxOccurs);
return;
}
// Elt:All RecurseAsIfGroup
case XSParticleDecl.PARTICLE_CHOICE:
{
// Treat the element as if it were in a group of the same type
// as the base Particle
dChildren = new Vector();
dChildren.addElement(dParticle);
checkRecurseLax(dChildren, dMinOccurs, dMaxOccurs, dSGHandler,
bChildren, bMinOccurs, bMaxOccurs, bSGHandler);
return;
}
case XSParticleDecl.PARTICLE_SEQUENCE:
case XSParticleDecl.PARTICLE_ALL:
{
// Treat the element as if it were in a group of the same type
// as the base Particle
dChildren = new Vector();
dChildren.addElement(dParticle);
checkRecurse(dChildren, dMinOccurs, dMaxOccurs, dSGHandler,
bChildren, bMinOccurs, bMaxOccurs, bSGHandler);
return;
}
default:
{
throw new XMLSchemaException("Internal-Error",
new Object[]{"in particleValidRestriction"});
}
}
}
case XSParticleDecl.PARTICLE_WILDCARD:
{
switch (bType) {
// Any:Any NSSubset
case XSParticleDecl.PARTICLE_WILDCARD:
{
checkNSSubset((XSWildcardDecl)dParticle.fValue, dMinOccurs, dMaxOccurs,
(XSWildcardDecl)bParticle.fValue, bMinOccurs, bMaxOccurs);
return;
}
case XSParticleDecl.PARTICLE_CHOICE:
case XSParticleDecl.PARTICLE_SEQUENCE:
case XSParticleDecl.PARTICLE_ALL:
case XSParticleDecl.PARTICLE_ELEMENT:
{
throw new XMLSchemaException("cos-particle-restrict.2",
new Object[]{"any:choice,sequence,all,elt"});
}
default:
{
throw new XMLSchemaException("Internal-Error",
new Object[]{"in particleValidRestriction"});
}
}
}
case XSParticleDecl.PARTICLE_ALL:
{
switch (bType) {
// All:Any NSRecurseCheckCardinality
case XSParticleDecl.PARTICLE_WILDCARD:
{
if (dMinEffectiveTotalRange == OCCURRENCE_UNKNOWN)
dMinEffectiveTotalRange = dParticle.minEffectiveTotalRange();
if (dMaxEffectiveTotalRange == OCCURRENCE_UNKNOWN)
dMaxEffectiveTotalRange = dParticle.maxEffectiveTotalRange();
checkNSRecurseCheckCardinality(dChildren, dMinEffectiveTotalRange,
dMaxEffectiveTotalRange,
dSGHandler,
bParticle,bMinOccurs,bMaxOccurs);
return;
}
case XSParticleDecl.PARTICLE_ALL:
{
checkRecurse(dChildren, dMinOccurs, dMaxOccurs, dSGHandler,
bChildren, bMinOccurs, bMaxOccurs, bSGHandler);
return;
}
case XSParticleDecl.PARTICLE_CHOICE:
case XSParticleDecl.PARTICLE_SEQUENCE:
case XSParticleDecl.PARTICLE_ELEMENT:
{
throw new XMLSchemaException("cos-particle-restrict.2",
new Object[]{"all:choice,sequence,elt"});
}
default:
{
throw new XMLSchemaException("Internal-Error",
new Object[]{"in particleValidRestriction"});
}
}
}
case XSParticleDecl.PARTICLE_CHOICE:
{
switch (bType) {
// Choice:Any NSRecurseCheckCardinality
case XSParticleDecl.PARTICLE_WILDCARD:
{
if (dMinEffectiveTotalRange == OCCURRENCE_UNKNOWN)
dMinEffectiveTotalRange = dParticle.minEffectiveTotalRange();
if (dMaxEffectiveTotalRange == OCCURRENCE_UNKNOWN)
dMaxEffectiveTotalRange = dParticle.maxEffectiveTotalRange();
checkNSRecurseCheckCardinality(dChildren, dMinEffectiveTotalRange,
dMaxEffectiveTotalRange,
dSGHandler,
bParticle,bMinOccurs,bMaxOccurs);
return;
}
case XSParticleDecl.PARTICLE_CHOICE:
{
checkRecurseLax(dChildren, dMinOccurs, dMaxOccurs, dSGHandler,
bChildren, bMinOccurs, bMaxOccurs, bSGHandler);
return;
}
case XSParticleDecl.PARTICLE_ALL:
case XSParticleDecl.PARTICLE_SEQUENCE:
case XSParticleDecl.PARTICLE_ELEMENT:
{
throw new XMLSchemaException("cos-particle-restrict.2",
new Object[]{"choice:all,sequence,elt"});
}
default:
{
throw new XMLSchemaException("Internal-Error",
new Object[]{"in particleValidRestriction"});
}
}
}
case XSParticleDecl.PARTICLE_SEQUENCE:
{
switch (bType) {
// Choice:Any NSRecurseCheckCardinality
case XSParticleDecl.PARTICLE_WILDCARD:
{
if (dMinEffectiveTotalRange == OCCURRENCE_UNKNOWN)
dMinEffectiveTotalRange = dParticle.minEffectiveTotalRange();
if (dMaxEffectiveTotalRange == OCCURRENCE_UNKNOWN)
dMaxEffectiveTotalRange = dParticle.maxEffectiveTotalRange();
checkNSRecurseCheckCardinality(dChildren, dMinEffectiveTotalRange,
dMaxEffectiveTotalRange,
dSGHandler,
bParticle,bMinOccurs,bMaxOccurs);
return;
}
case XSParticleDecl.PARTICLE_ALL:
{
checkRecurseUnordered(dChildren, dMinOccurs, dMaxOccurs, dSGHandler,
bChildren, bMinOccurs, bMaxOccurs, bSGHandler);
return;
}
case XSParticleDecl.PARTICLE_SEQUENCE:
{
checkRecurse(dChildren, dMinOccurs, dMaxOccurs, dSGHandler,
bChildren, bMinOccurs, bMaxOccurs, bSGHandler);
return;
}
case XSParticleDecl.PARTICLE_CHOICE:
{
int min1 = dMinOccurs * dChildren.size();
int max1 = (dMaxOccurs == SchemaSymbols.OCCURRENCE_UNBOUNDED)?
dMaxOccurs : dMaxOccurs * dChildren.size();
checkMapAndSum(dChildren, min1, max1, dSGHandler,
bChildren, bMinOccurs, bMaxOccurs, bSGHandler);
return;
}
case XSParticleDecl.PARTICLE_ELEMENT:
{
throw new XMLSchemaException("cos-particle-restrict.2",
new Object[]{"seq:elt"});
}
default:
{
throw new XMLSchemaException("Internal-Error",
new Object[]{"in particleValidRestriction"});
}
}
}
}
}
|
diff --git a/framework/src/org/apache/cordova/Notification.java b/framework/src/org/apache/cordova/Notification.java
index 9fb423a7..b5834c3e 100755
--- a/framework/src/org/apache/cordova/Notification.java
+++ b/framework/src/org/apache/cordova/Notification.java
@@ -1,366 +1,366 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova;
import org.apache.cordova.api.CordovaInterface;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Vibrator;
/**
* This class provides access to notifications on the device.
*/
public class Notification extends Plugin {
public int confirmResult = -1;
public ProgressDialog spinnerDialog = null;
public ProgressDialog progressDialog = null;
/**
* Constructor.
*/
public Notification() {
}
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
try {
if (action.equals("beep")) {
this.beep(args.getLong(0));
}
else if (action.equals("vibrate")) {
this.vibrate(args.getLong(0));
}
else if (action.equals("alert")) {
this.alert(args.getString(0),args.getString(1),args.getString(2), callbackId);
PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
r.setKeepCallback(true);
return r;
}
else if (action.equals("confirm")) {
this.confirm(args.getString(0),args.getString(1),args.getString(2), callbackId);
PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
r.setKeepCallback(true);
return r;
}
else if (action.equals("activityStart")) {
this.activityStart(args.getString(0),args.getString(1));
}
else if (action.equals("activityStop")) {
this.activityStop();
}
else if (action.equals("progressStart")) {
this.progressStart(args.getString(0),args.getString(1));
}
else if (action.equals("progressValue")) {
this.progressValue(args.getInt(0));
}
else if (action.equals("progressStop")) {
this.progressStop();
}
return new PluginResult(status, result);
} catch (JSONException e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
/**
* Identifies if action to be executed returns a value and should be run synchronously.
*
* @param action The action to execute
* @return T=returns value
*/
public boolean isSynch(String action) {
if (action.equals("alert")) {
return true;
}
else if (action.equals("confirm")) {
return true;
}
else if (action.equals("activityStart")) {
return true;
}
else if (action.equals("activityStop")) {
return true;
}
else if (action.equals("progressStart")) {
return true;
}
else if (action.equals("progressValue")) {
return true;
}
else if (action.equals("progressStop")) {
return true;
}
else {
return false;
}
}
//--------------------------------------------------------------------------
// LOCAL METHODS
//--------------------------------------------------------------------------
/**
* Beep plays the default notification ringtone.
*
* @param count Number of times to play notification
*/
public void beep(long count) {
Uri ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone notification = RingtoneManager.getRingtone(this.ctx.getContext(), ringtone);
// If phone is not set to silent mode
if (notification != null) {
for (long i = 0; i < count; ++i) {
notification.play();
long timeout = 5000;
while (notification.isPlaying() && (timeout > 0)) {
timeout = timeout - 100;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
}
}
}
/**
* Vibrates the device for the specified amount of time.
*
* @param time Time to vibrate in ms.
*/
public void vibrate(long time){
// Start the vibration, 0 defaults to half a second.
if (time == 0) {
time = 500;
}
Vibrator vibrator = (Vibrator) this.ctx.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(time);
}
/**
* Builds and shows a native Android alert with given Strings
* @param message The message the alert should display
* @param title The title of the alert
* @param buttonLabel The label of the button
* @param callbackId The callback id
*/
public synchronized void alert(final String message, final String title, final String buttonLabel, final String callbackId) {
final CordovaInterface ctx = this.ctx;
final Notification notification = this;
Runnable runnable = new Runnable() {
public void run() {
AlertDialog.Builder dlg = new AlertDialog.Builder(ctx.getContext());
dlg.setMessage(message);
dlg.setTitle(title);
dlg.setCancelable(false);
dlg.setPositiveButton(buttonLabel,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
notification.success(new PluginResult(PluginResult.Status.OK, 0), callbackId);
}
});
dlg.create();
dlg.show();
};
};
this.ctx.runOnUiThread(runnable);
}
/**
* Builds and shows a native Android confirm dialog with given title, message, buttons.
* This dialog only shows up to 3 buttons. Any labels after that will be ignored.
* The index of the button pressed will be returned to the JavaScript callback identified by callbackId.
*
* @param message The message the dialog should display
* @param title The title of the dialog
* @param buttonLabels A comma separated list of button labels (Up to 3 buttons)
* @param callbackId The callback id
*/
public synchronized void confirm(final String message, final String title, String buttonLabels, final String callbackId) {
final CordovaInterface ctx = this.ctx;
final Notification notification = this;
final String[] fButtons = buttonLabels.split(",");
Runnable runnable = new Runnable() {
public void run() {
AlertDialog.Builder dlg = new AlertDialog.Builder(ctx.getContext());
dlg.setMessage(message);
dlg.setTitle(title);
dlg.setCancelable(false);
// First button
if (fButtons.length > 0) {
- dlg.setPositiveButton(fButtons[0],
+ dlg.setNegativeButton(fButtons[0],
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
notification.success(new PluginResult(PluginResult.Status.OK, 1), callbackId);
}
});
}
// Second button
if (fButtons.length > 1) {
dlg.setNeutralButton(fButtons[1],
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
notification.success(new PluginResult(PluginResult.Status.OK, 2), callbackId);
}
});
}
// Third button
if (fButtons.length > 2) {
- dlg.setNegativeButton(fButtons[2],
+ dlg.setPositiveButton(fButtons[2],
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
notification.success(new PluginResult(PluginResult.Status.OK, 3), callbackId);
}
}
);
}
dlg.create();
dlg.show();
};
};
this.ctx.runOnUiThread(runnable);
}
/**
* Show the spinner.
*
* @param title Title of the dialog
* @param message The message of the dialog
*/
public synchronized void activityStart(final String title, final String message) {
if (this.spinnerDialog != null) {
this.spinnerDialog.dismiss();
this.spinnerDialog = null;
}
final Notification notification = this;
final CordovaInterface ctx = this.ctx;
Runnable runnable = new Runnable() {
public void run() {
notification.spinnerDialog = ProgressDialog.show(ctx.getContext(), title , message, true, true,
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
notification.spinnerDialog = null;
}
});
}
};
this.ctx.runOnUiThread(runnable);
}
/**
* Stop spinner.
*/
public synchronized void activityStop() {
if (this.spinnerDialog != null) {
this.spinnerDialog.dismiss();
this.spinnerDialog = null;
}
}
/**
* Show the progress dialog.
*
* @param title Title of the dialog
* @param message The message of the dialog
*/
public synchronized void progressStart(final String title, final String message) {
if (this.progressDialog != null) {
this.progressDialog.dismiss();
this.progressDialog = null;
}
final Notification notification = this;
final CordovaInterface ctx = this.ctx;
Runnable runnable = new Runnable() {
public void run() {
notification.progressDialog = new ProgressDialog(ctx.getContext());
notification.progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
notification.progressDialog.setTitle(title);
notification.progressDialog.setMessage(message);
notification.progressDialog.setCancelable(true);
notification.progressDialog.setMax(100);
notification.progressDialog.setProgress(0);
notification.progressDialog.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
notification.progressDialog = null;
}
});
notification.progressDialog.show();
}
};
this.ctx.runOnUiThread(runnable);
}
/**
* Set value of progress bar.
*
* @param value 0-100
*/
public synchronized void progressValue(int value) {
if (this.progressDialog != null) {
this.progressDialog.setProgress(value);
}
}
/**
* Stop progress dialog.
*/
public synchronized void progressStop() {
if (this.progressDialog != null) {
this.progressDialog.dismiss();
this.progressDialog = null;
}
}
}
| false | true | public synchronized void confirm(final String message, final String title, String buttonLabels, final String callbackId) {
final CordovaInterface ctx = this.ctx;
final Notification notification = this;
final String[] fButtons = buttonLabels.split(",");
Runnable runnable = new Runnable() {
public void run() {
AlertDialog.Builder dlg = new AlertDialog.Builder(ctx.getContext());
dlg.setMessage(message);
dlg.setTitle(title);
dlg.setCancelable(false);
// First button
if (fButtons.length > 0) {
dlg.setPositiveButton(fButtons[0],
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
notification.success(new PluginResult(PluginResult.Status.OK, 1), callbackId);
}
});
}
// Second button
if (fButtons.length > 1) {
dlg.setNeutralButton(fButtons[1],
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
notification.success(new PluginResult(PluginResult.Status.OK, 2), callbackId);
}
});
}
// Third button
if (fButtons.length > 2) {
dlg.setNegativeButton(fButtons[2],
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
notification.success(new PluginResult(PluginResult.Status.OK, 3), callbackId);
}
}
);
}
dlg.create();
dlg.show();
};
};
this.ctx.runOnUiThread(runnable);
}
| public synchronized void confirm(final String message, final String title, String buttonLabels, final String callbackId) {
final CordovaInterface ctx = this.ctx;
final Notification notification = this;
final String[] fButtons = buttonLabels.split(",");
Runnable runnable = new Runnable() {
public void run() {
AlertDialog.Builder dlg = new AlertDialog.Builder(ctx.getContext());
dlg.setMessage(message);
dlg.setTitle(title);
dlg.setCancelable(false);
// First button
if (fButtons.length > 0) {
dlg.setNegativeButton(fButtons[0],
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
notification.success(new PluginResult(PluginResult.Status.OK, 1), callbackId);
}
});
}
// Second button
if (fButtons.length > 1) {
dlg.setNeutralButton(fButtons[1],
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
notification.success(new PluginResult(PluginResult.Status.OK, 2), callbackId);
}
});
}
// Third button
if (fButtons.length > 2) {
dlg.setPositiveButton(fButtons[2],
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
notification.success(new PluginResult(PluginResult.Status.OK, 3), callbackId);
}
}
);
}
dlg.create();
dlg.show();
};
};
this.ctx.runOnUiThread(runnable);
}
|
diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/ExpandModules.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/ExpandModules.java
index b72bf80f9..7dcb27033 100644
--- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/ExpandModules.java
+++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/ExpandModules.java
@@ -1,28 +1,31 @@
/*******************************************************************************
* Copyright (c) 2002 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM - Initial API and implementation
******************************************************************************/
package org.eclipse.team.internal.ccvs.core.client;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.team.internal.ccvs.core.CVSException;
public class ExpandModules extends Request {
protected ExpandModules() { }
protected String getRequestId() {
return "expand-modules"; //$NON-NLS-1$
}
public IStatus execute(Session session, String[] modules, IProgressMonitor monitor) throws CVSException {
// Reset the module expansions before the responses arrive
session.resetModuleExpansion();
+ for (int i = 0; i < modules.length; ++i) {
+ session.sendArgument(modules[i]);
+ }
return executeRequest(session, Command.DEFAULT_OUTPUT_LISTENER, monitor);
}
}
| true | true | public IStatus execute(Session session, String[] modules, IProgressMonitor monitor) throws CVSException {
// Reset the module expansions before the responses arrive
session.resetModuleExpansion();
return executeRequest(session, Command.DEFAULT_OUTPUT_LISTENER, monitor);
}
| public IStatus execute(Session session, String[] modules, IProgressMonitor monitor) throws CVSException {
// Reset the module expansions before the responses arrive
session.resetModuleExpansion();
for (int i = 0; i < modules.length; ++i) {
session.sendArgument(modules[i]);
}
return executeRequest(session, Command.DEFAULT_OUTPUT_LISTENER, monitor);
}
|
diff --git a/src/main/java/org/agmip/ui/quadui/ApplyDomeTask.java b/src/main/java/org/agmip/ui/quadui/ApplyDomeTask.java
index 4ee6c34..e32fb89 100644
--- a/src/main/java/org/agmip/ui/quadui/ApplyDomeTask.java
+++ b/src/main/java/org/agmip/ui/quadui/ApplyDomeTask.java
@@ -1,228 +1,231 @@
package org.agmip.ui.quadui;
import java.io.File;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.agmip.dome.DomeUtil;
import org.agmip.dome.Engine;
import org.agmip.translators.csv.DomeInput;
import org.agmip.util.MapUtil;
import org.apache.pivot.util.concurrent.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ApplyDomeTask extends Task<HashMap> {
private static Logger log = LoggerFactory.getLogger(ApplyDomeTask.class);
private HashMap<String, HashMap<String, Object>> domes = new HashMap<String, HashMap<String, Object>>();
// private HashMap<String, ArrayList<String>> links = new HashMap<String, ArrayList<String>>();
// private HashMap<String, ArrayList<String>> wthLinks = new HashMap<String, ArrayList<String>>();
// private HashMap<String, ArrayList<String>> soilLinks = new HashMap<String, ArrayList<String>>();
private HashMap source;
private String mode;
// public ApplyDomeTask(String linkFile, String fieldFile, String strategyFile, String mode, HashMap m) {
public ApplyDomeTask(String fieldFile, String strategyFile, String mode, HashMap m) {
this.source = m;
this.mode = mode;
// Setup the domes here.
if (mode.equals("strategy")) {
loadDomeFile(strategyFile);
}
loadDomeFile(fieldFile);
}
// private void loadDomeLinkFile(String fileName) {
// String fileNameTest = fileName.toUpperCase();
//
// log.debug("Loading LINK file: {}", fileName);
//
// if (fileNameTest.endsWith(".ZIP")) {
// log.debug("Entering Zip file handling");
// ZipFile z = null;
// try {
// z = new ZipFile(fileName);
// Enumeration entries = z.entries();
// while (entries.hasMoreElements()) {
// // Do we handle nested zips? Not yet.
// ZipEntry entry = (ZipEntry) entries.nextElement();
// File zipFileName = new File(entry.getName());
// if (zipFileName.getName().toLowerCase().endsWith(".csv") && ! zipFileName.getName().startsWith(".")) {
// log.debug("Processing file: {}", zipFileName.getName());
// DomeInput translator = new DomeInput();
// translator.readCSV(z.getInputStream(entry));
// HashMap<String, Object> dome = translator.getDome();
// log.debug("dome info: {}", dome.toString());
// String domeName = DomeUtil.generateDomeName(dome);
// if (! domeName.equals("----")) {
//// links.put(domeName, new HashMap<String, Object>(dome));
// }
// }
// }
// z.close();
// } catch (Exception ex) {
// log.error("Error processing DOME file: {}", ex.getMessage());
// HashMap<String, Object> d = new HashMap<String, Object>();
// d.put("errors", ex.getMessage());
// }
// } else if (fileNameTest.endsWith(".CSV")) {
// log.debug("Entering single file DOME handling");
// try {
// DomeInput translator = new DomeInput();
// HashMap<String, Object> dome = (HashMap<String, Object>) translator.readFile(fileName);
// String domeName = DomeUtil.generateDomeName(dome);
// log.debug("Dome name: {}", domeName);
// log.debug("Dome layout: {}", dome.toString());
//
//// links.put(domeName, dome);
// } catch (Exception ex) {
// log.error("Error processing DOME file: {}", ex.getMessage());
// HashMap<String, Object> d = new HashMap<String, Object>();
// d.put("errors", ex.getMessage());
// }
// }
// }
private void loadDomeFile(String fileName) {
String fileNameTest = fileName.toUpperCase();
log.debug("Loading DOME file: {}", fileName);
if (fileNameTest.endsWith(".ZIP")) {
log.debug("Entering Zip file handling");
ZipFile z = null;
try {
z = new ZipFile(fileName);
Enumeration entries = z.entries();
while (entries.hasMoreElements()) {
// Do we handle nested zips? Not yet.
ZipEntry entry = (ZipEntry) entries.nextElement();
File zipFileName = new File(entry.getName());
if (zipFileName.getName().toLowerCase().endsWith(".csv") && !zipFileName.getName().startsWith(".")) {
log.debug("Processing file: {}", zipFileName.getName());
DomeInput translator = new DomeInput();
translator.readCSV(z.getInputStream(entry));
HashMap<String, Object> dome = translator.getDome();
log.debug("dome info: {}", dome.toString());
String domeName = DomeUtil.generateDomeName(dome);
if (!domeName.equals("----")) {
domes.put(domeName, new HashMap<String, Object>(dome));
}
}
}
z.close();
} catch (Exception ex) {
log.error("Error processing DOME file: {}", ex.getMessage());
HashMap<String, Object> d = new HashMap<String, Object>();
d.put("errors", ex.getMessage());
}
} else if (fileNameTest.endsWith(".CSV")) {
log.debug("Entering single file DOME handling");
try {
DomeInput translator = new DomeInput();
HashMap<String, Object> dome = (HashMap<String, Object>) translator.readFile(fileName);
String domeName = DomeUtil.generateDomeName(dome);
log.debug("Dome name: {}", domeName);
log.debug("Dome layout: {}", dome.toString());
domes.put(domeName, dome);
} catch (Exception ex) {
log.error("Error processing DOME file: {}", ex.getMessage());
HashMap<String, Object> d = new HashMap<String, Object>();
d.put("errors", ex.getMessage());
}
}
}
@Override
public HashMap<String, Object> execute() {
// First extract all the domes and put them in a HashMap by DOME_NAME
// The read the DOME_NAME field of the CSV file
// Split the DOME_NAME, and then apply sequentially to the HashMap.
// PLEASE NOTE: This can be a massive undertaking if the source map
// is really large. Need to find optimization points.
HashMap<String, Object> output = new HashMap<String, Object>();
//HashMap<String, ArrayList<HashMap<String, String>>> dome;
// Load the dome
if (domes.isEmpty()) {
log.info("No DOME to apply.");
HashMap<String, Object> d = new HashMap<String, Object>();
//d.put("domeinfo", new HashMap<String, String>());
d.put("domeoutput", source);
return d;
}
// Flatten the data and apply the dome.
Engine domeEngine;
ArrayList<HashMap<String, Object>> flattenedData = MapUtil.flatPack(source);
if (mode.equals("strategy")) {
log.debug("Domes: {}", domes.toString());
log.debug("Entering Strategy mode!");
Engine generatorEngine;
ArrayList<HashMap<String, Object>> strategyResults = new ArrayList<HashMap<String, Object>>();
for (HashMap<String, Object> entry : flattenedData) {
String domeName = MapUtil.getValueOr(entry, "seasonal_strategy", "");
String tmp[] = domeName.split("[|]");
String strategyName;
if (tmp.length > 1) {
log.warn("Multiple seasonal strategy dome is not supported yet, only the first dome will be applied");
}
strategyName = tmp[0];
log.debug("Looking for ss: {}", strategyName);
if (!strategyName.equals("")) {
if (domes.containsKey(strategyName)) {
log.debug("Found strategyName");
entry.put("dome_applied", "Y");
entry.put("seasonal_dome_applied", "Y");
generatorEngine = new Engine(domes.get(strategyName), true);
- generatorEngine.apply(entry);
- ArrayList<HashMap<String, Object>> newEntries = generatorEngine.runGenerators(entry);
+ ArrayList<HashMap<String, Object>> newEntries = generatorEngine.applyStg(entry);
log.debug("New Entries to add: {}", newEntries.size());
strategyResults.addAll(newEntries);
} else {
log.error("Cannot find strategy: {}", strategyName);
}
}
}
log.debug("=== FINISHED GENERATION ===");
log.debug("Generated count: {}", strategyResults.size());
ArrayList<HashMap<String, Object>> exp = MapUtil.getRawPackageContents(source, "experiments");
exp.clear();
exp.addAll(strategyResults);
flattenedData = MapUtil.flatPack(source);
}
for (HashMap<String, Object> entry : flattenedData) {
String domeName = MapUtil.getValueOr(entry, "field_overlay", "");
if (!domeName.equals("")) {
String tmp[] = domeName.split("[|]");
int tmpLength = tmp.length;
for (int i = 0; i < tmpLength; i++) {
String tmpDomeId = tmp[i].toUpperCase();
log.debug("Looking for dome_name: {}", tmpDomeId);
if (domes.containsKey(tmpDomeId)) {
domeEngine = new Engine(domes.get(tmpDomeId));
entry.put("dome_applied", "Y");
entry.put("field_dome_applied", "Y");
domeEngine.apply(entry);
+ ArrayList<String> strategyList = domeEngine.getGenerators();
+ if (!strategyList.isEmpty()) {
+ log.warn("The following DOME commands in the field overlay file are ignored : {}", strategyList.toString());
+ }
} else {
log.error("Cannot find overlay: {}", tmpDomeId);
}
}
}
}
output.put("domeoutput", MapUtil.bundle(flattenedData));
return output;
}
}
| false | true | public HashMap<String, Object> execute() {
// First extract all the domes and put them in a HashMap by DOME_NAME
// The read the DOME_NAME field of the CSV file
// Split the DOME_NAME, and then apply sequentially to the HashMap.
// PLEASE NOTE: This can be a massive undertaking if the source map
// is really large. Need to find optimization points.
HashMap<String, Object> output = new HashMap<String, Object>();
//HashMap<String, ArrayList<HashMap<String, String>>> dome;
// Load the dome
if (domes.isEmpty()) {
log.info("No DOME to apply.");
HashMap<String, Object> d = new HashMap<String, Object>();
//d.put("domeinfo", new HashMap<String, String>());
d.put("domeoutput", source);
return d;
}
// Flatten the data and apply the dome.
Engine domeEngine;
ArrayList<HashMap<String, Object>> flattenedData = MapUtil.flatPack(source);
if (mode.equals("strategy")) {
log.debug("Domes: {}", domes.toString());
log.debug("Entering Strategy mode!");
Engine generatorEngine;
ArrayList<HashMap<String, Object>> strategyResults = new ArrayList<HashMap<String, Object>>();
for (HashMap<String, Object> entry : flattenedData) {
String domeName = MapUtil.getValueOr(entry, "seasonal_strategy", "");
String tmp[] = domeName.split("[|]");
String strategyName;
if (tmp.length > 1) {
log.warn("Multiple seasonal strategy dome is not supported yet, only the first dome will be applied");
}
strategyName = tmp[0];
log.debug("Looking for ss: {}", strategyName);
if (!strategyName.equals("")) {
if (domes.containsKey(strategyName)) {
log.debug("Found strategyName");
entry.put("dome_applied", "Y");
entry.put("seasonal_dome_applied", "Y");
generatorEngine = new Engine(domes.get(strategyName), true);
generatorEngine.apply(entry);
ArrayList<HashMap<String, Object>> newEntries = generatorEngine.runGenerators(entry);
log.debug("New Entries to add: {}", newEntries.size());
strategyResults.addAll(newEntries);
} else {
log.error("Cannot find strategy: {}", strategyName);
}
}
}
log.debug("=== FINISHED GENERATION ===");
log.debug("Generated count: {}", strategyResults.size());
ArrayList<HashMap<String, Object>> exp = MapUtil.getRawPackageContents(source, "experiments");
exp.clear();
exp.addAll(strategyResults);
flattenedData = MapUtil.flatPack(source);
}
for (HashMap<String, Object> entry : flattenedData) {
String domeName = MapUtil.getValueOr(entry, "field_overlay", "");
if (!domeName.equals("")) {
String tmp[] = domeName.split("[|]");
int tmpLength = tmp.length;
for (int i = 0; i < tmpLength; i++) {
String tmpDomeId = tmp[i].toUpperCase();
log.debug("Looking for dome_name: {}", tmpDomeId);
if (domes.containsKey(tmpDomeId)) {
domeEngine = new Engine(domes.get(tmpDomeId));
entry.put("dome_applied", "Y");
entry.put("field_dome_applied", "Y");
domeEngine.apply(entry);
} else {
log.error("Cannot find overlay: {}", tmpDomeId);
}
}
}
}
output.put("domeoutput", MapUtil.bundle(flattenedData));
return output;
}
| public HashMap<String, Object> execute() {
// First extract all the domes and put them in a HashMap by DOME_NAME
// The read the DOME_NAME field of the CSV file
// Split the DOME_NAME, and then apply sequentially to the HashMap.
// PLEASE NOTE: This can be a massive undertaking if the source map
// is really large. Need to find optimization points.
HashMap<String, Object> output = new HashMap<String, Object>();
//HashMap<String, ArrayList<HashMap<String, String>>> dome;
// Load the dome
if (domes.isEmpty()) {
log.info("No DOME to apply.");
HashMap<String, Object> d = new HashMap<String, Object>();
//d.put("domeinfo", new HashMap<String, String>());
d.put("domeoutput", source);
return d;
}
// Flatten the data and apply the dome.
Engine domeEngine;
ArrayList<HashMap<String, Object>> flattenedData = MapUtil.flatPack(source);
if (mode.equals("strategy")) {
log.debug("Domes: {}", domes.toString());
log.debug("Entering Strategy mode!");
Engine generatorEngine;
ArrayList<HashMap<String, Object>> strategyResults = new ArrayList<HashMap<String, Object>>();
for (HashMap<String, Object> entry : flattenedData) {
String domeName = MapUtil.getValueOr(entry, "seasonal_strategy", "");
String tmp[] = domeName.split("[|]");
String strategyName;
if (tmp.length > 1) {
log.warn("Multiple seasonal strategy dome is not supported yet, only the first dome will be applied");
}
strategyName = tmp[0];
log.debug("Looking for ss: {}", strategyName);
if (!strategyName.equals("")) {
if (domes.containsKey(strategyName)) {
log.debug("Found strategyName");
entry.put("dome_applied", "Y");
entry.put("seasonal_dome_applied", "Y");
generatorEngine = new Engine(domes.get(strategyName), true);
ArrayList<HashMap<String, Object>> newEntries = generatorEngine.applyStg(entry);
log.debug("New Entries to add: {}", newEntries.size());
strategyResults.addAll(newEntries);
} else {
log.error("Cannot find strategy: {}", strategyName);
}
}
}
log.debug("=== FINISHED GENERATION ===");
log.debug("Generated count: {}", strategyResults.size());
ArrayList<HashMap<String, Object>> exp = MapUtil.getRawPackageContents(source, "experiments");
exp.clear();
exp.addAll(strategyResults);
flattenedData = MapUtil.flatPack(source);
}
for (HashMap<String, Object> entry : flattenedData) {
String domeName = MapUtil.getValueOr(entry, "field_overlay", "");
if (!domeName.equals("")) {
String tmp[] = domeName.split("[|]");
int tmpLength = tmp.length;
for (int i = 0; i < tmpLength; i++) {
String tmpDomeId = tmp[i].toUpperCase();
log.debug("Looking for dome_name: {}", tmpDomeId);
if (domes.containsKey(tmpDomeId)) {
domeEngine = new Engine(domes.get(tmpDomeId));
entry.put("dome_applied", "Y");
entry.put("field_dome_applied", "Y");
domeEngine.apply(entry);
ArrayList<String> strategyList = domeEngine.getGenerators();
if (!strategyList.isEmpty()) {
log.warn("The following DOME commands in the field overlay file are ignored : {}", strategyList.toString());
}
} else {
log.error("Cannot find overlay: {}", tmpDomeId);
}
}
}
}
output.put("domeoutput", MapUtil.bundle(flattenedData));
return output;
}
|
diff --git a/src/com/ubhave/dataformatter/json/pull/WifiFormatter.java b/src/com/ubhave/dataformatter/json/pull/WifiFormatter.java
index 92b9892..1166166 100644
--- a/src/com/ubhave/dataformatter/json/pull/WifiFormatter.java
+++ b/src/com/ubhave/dataformatter/json/pull/WifiFormatter.java
@@ -1,110 +1,110 @@
/* **************************************************
Copyright (c) 2012, University of Cambridge
Neal Lathia, [email protected]
This library was developed as part of the EPSRC Ubhave (Ubiquitous and
Social Computing for Positive Behaviour Change) Project. For more
information, please visit http://www.emotionsense.org
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
************************************************** */
package com.ubhave.dataformatter.json.pull;
import java.util.ArrayList;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import com.ubhave.dataformatter.json.PullSensorJSONFormatter;
import com.ubhave.sensormanager.config.SensorConfig;
import com.ubhave.sensormanager.data.SensorData;
import com.ubhave.sensormanager.data.pullsensor.WifiData;
import com.ubhave.sensormanager.data.pullsensor.WifiScanResult;
public class WifiFormatter extends PullSensorJSONFormatter
{
private final static String SCAN_RESULT = "scanResult";
private final static String SSID = "ssid";
private final static String BSSID = "bssid";
private final static String CAPABILITIES = "capabilities";
private final static String LEVEL = "level";
private final static String FREQUENCY = "frequency";
private final static String UNAVAILABLE = "unavailable";
private final static String SENSE_CYCLES = "senseCycles";
@SuppressWarnings("unchecked")
@Override
protected void addSensorSpecificData(JSONObject json, SensorData data)
{
WifiData wifiData = (WifiData) data;
ArrayList<WifiScanResult> results = wifiData.getWifiScanData();
JSONArray resultJSON = new JSONArray();
if (results != null)
{
for (WifiScanResult result : results)
{
JSONObject scanJSON = new JSONObject();
scanJSON.put(SSID, result.getSsid());
scanJSON.put(BSSID, result.getBssid());
scanJSON.put(CAPABILITIES, result.getCapabilities());
scanJSON.put(LEVEL, result.getLevel());
scanJSON.put(FREQUENCY, result.getFrequency());
resultJSON.add(scanJSON);
}
}
else
{
resultJSON.add(UNAVAILABLE);
}
json.put(SCAN_RESULT, resultJSON);
}
@SuppressWarnings("unchecked")
@Override
protected void addSensorSpecificConfig(JSONObject json, SensorConfig config)
{
json.put(SENSE_CYCLES, config.getParameter(SensorConfig.NUMBER_OF_SENSE_CYCLES));
}
@Override
public SensorData toSensorData(String jsonString)
{
JSONObject jsonData = super.parseData(jsonString);
long senseStartTimestamp = super.parseTimeStamp(jsonData);
SensorConfig sensorConfig = super.getGenericConfig(jsonData);
JSONArray jsonArray = (JSONArray)jsonData.get(SCAN_RESULT);
ArrayList<WifiScanResult> wifiList = new ArrayList<WifiScanResult>();
for (int i = 0; i < jsonArray.size(); i++)
{
JSONObject jsonObject = (JSONObject)jsonArray.get(i);
String ssid = (String)jsonObject.get(SSID);
String bssid = (String)jsonObject.get(BSSID);
String capabilities = (String)jsonObject.get(CAPABILITIES);
- int level = (Integer)jsonObject.get(LEVEL);
- int frequency = (Integer)jsonObject.get(FREQUENCY);
+ int level = ((Long)jsonObject.get(LEVEL)).intValue();
+ int frequency = ((Long)jsonObject.get(FREQUENCY)).intValue();
WifiScanResult scanResult = new WifiScanResult(ssid, bssid, capabilities, level, frequency);
wifiList.add(scanResult);
}
WifiData wifiData = new WifiData(senseStartTimestamp, wifiList, sensorConfig);
return wifiData;
}
}
| true | true | public SensorData toSensorData(String jsonString)
{
JSONObject jsonData = super.parseData(jsonString);
long senseStartTimestamp = super.parseTimeStamp(jsonData);
SensorConfig sensorConfig = super.getGenericConfig(jsonData);
JSONArray jsonArray = (JSONArray)jsonData.get(SCAN_RESULT);
ArrayList<WifiScanResult> wifiList = new ArrayList<WifiScanResult>();
for (int i = 0; i < jsonArray.size(); i++)
{
JSONObject jsonObject = (JSONObject)jsonArray.get(i);
String ssid = (String)jsonObject.get(SSID);
String bssid = (String)jsonObject.get(BSSID);
String capabilities = (String)jsonObject.get(CAPABILITIES);
int level = (Integer)jsonObject.get(LEVEL);
int frequency = (Integer)jsonObject.get(FREQUENCY);
WifiScanResult scanResult = new WifiScanResult(ssid, bssid, capabilities, level, frequency);
wifiList.add(scanResult);
}
WifiData wifiData = new WifiData(senseStartTimestamp, wifiList, sensorConfig);
return wifiData;
}
| public SensorData toSensorData(String jsonString)
{
JSONObject jsonData = super.parseData(jsonString);
long senseStartTimestamp = super.parseTimeStamp(jsonData);
SensorConfig sensorConfig = super.getGenericConfig(jsonData);
JSONArray jsonArray = (JSONArray)jsonData.get(SCAN_RESULT);
ArrayList<WifiScanResult> wifiList = new ArrayList<WifiScanResult>();
for (int i = 0; i < jsonArray.size(); i++)
{
JSONObject jsonObject = (JSONObject)jsonArray.get(i);
String ssid = (String)jsonObject.get(SSID);
String bssid = (String)jsonObject.get(BSSID);
String capabilities = (String)jsonObject.get(CAPABILITIES);
int level = ((Long)jsonObject.get(LEVEL)).intValue();
int frequency = ((Long)jsonObject.get(FREQUENCY)).intValue();
WifiScanResult scanResult = new WifiScanResult(ssid, bssid, capabilities, level, frequency);
wifiList.add(scanResult);
}
WifiData wifiData = new WifiData(senseStartTimestamp, wifiList, sensorConfig);
return wifiData;
}
|
diff --git a/src/xtremweb/api/transman/TransferManager.java b/src/xtremweb/api/transman/TransferManager.java
index fab53f4..7141274 100644
--- a/src/xtremweb/api/transman/TransferManager.java
+++ b/src/xtremweb/api/transman/TransferManager.java
@@ -1,713 +1,713 @@
package xtremweb.api.transman;
/**
* TransferManager is the engine responsible for processing, monitoring
* and launching transfers.
*
* Created: Sun Feb 18 17:54:41 2007
*
* @author <a href="mailto:[email protected]">Gilles Fedak</a>
* @version 1.0
*/
import xtremweb.core.iface.*;
import xtremweb.core.obj.dr.Protocol;
import xtremweb.core.obj.dt.Transfer;
import xtremweb.core.obj.dc.*;
import xtremweb.serv.dt.*;
import xtremweb.core.util.*;
import xtremweb.core.log.Logger;
import xtremweb.core.log.LoggerFactory;
import java.util.*;
import java.rmi.RemoteException;
import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import xtremweb.core.util.uri.*;
import xtremweb.dao.DaoFactory;
import xtremweb.dao.data.DaoData;
import xtremweb.dao.transfer.DaoTransfer;
/**
* <code>TransferManager</code>.
*
* @author <a href="mailto:[email protected]">Gilles Fedak</a>
* @version 1.0
*/
public class TransferManager {
/**
* dt associated to this Transfer Manager
*/
private Interfacedt dt = null;
/** time between two periodic activities (in milli seconds) */
private int timeout = 1000;
/**
* Dao to talk with the DB and perform transfer operations on the check thread
*/
private DaoTransfer daocheck;
/**
* Timer to synchronize transfer automaton
*/
private Timer timer;
/**
* Timer lock
*/
private Lock timerLock = new ReentrantLock();
/**
* How many tasks has been scheduled
*/
private static int timerSchedules = 0;
/**
* Dao to perform DB operations on the main thread
*/
private DaoTransfer dao;
/**
* Maximum number of downloads
*/
private long maxDownloads = 10;
/**
* <code>oobTransfers</code> is a Hashtable associating an OOBTransfer to
* each transfer. It is used to cache OOBTransfer and to avoid creating
* OOBTransfer for each Transfer scanned in the Database
*/
private SortedVector oobTransfers;
/**
* Class log
*/
private Logger log = LoggerFactory.getLogger("Transfer Manager (transman)");
/**
* Creates a new <code>TransferManager</code> instance.
*
* @param ldt
* an <code>Interfacedt</code> value
* @param ldr
* an <code>Interfacedr</code> value
*/
public TransferManager(Interfacedt ldt) {
daocheck = (DaoTransfer) DaoFactory.getInstance("xtremweb.dao.transfer.DaoTransfer");
dao = (DaoTransfer) DaoFactory.getInstance("xtremweb.dao.transfer.DaoTransfer");
dt = ldt;
init();
}
/**
* Creates a new <code>TransferManager</code> instance.
*
*/
public TransferManager() {
daocheck = (DaoTransfer) DaoFactory.getInstance("xtremweb.dao.transfer.DaoTransfer");
dao = (DaoTransfer) DaoFactory.getInstance("xtremweb.dao.transfer.DaoTransfer");
init();
}
/**
* Creates a new <code>TransferManager</code> instance.
*
* @param comms
* a <code>Vector</code> value
*/
public TransferManager(Vector comms) {
daocheck = (DaoTransfer) DaoFactory.getInstance("xtremweb.dao.transfer.DaoTransfer");
dao = (DaoTransfer) DaoFactory.getInstance("xtremweb.dao.transfer.DaoTransfer");
for (Object o : comms) {
if (o instanceof Interfacedt)
dt = (Interfacedt) o;
}
init();
}
/**
* initialize oobtransfers
*/
private void init() {
oobTransfers = new SortedVector(new OOBTransferOrder());
}
/**
* <code>registerTransfer</code> adds a tranfer to the TransferManager The
* transfer is persisted in the database. It will be later read by the main
* loop
*
* @param tuid
* a <code>String</code> value
* @param oobt
* an <code>OOBTransfer</code> value
*/
public void registerTransfer(OOBTransfer oobt) {
String tuid = oobt.getTransfer().getuid();
if ((oobt.getTransfer() != null) && (oobt.getTransfer().getuid() != null))
log.debug("Transfer already persisted : " + oobt.getTransfer().getuid());
log.debug(" data snapshot just before persisting uid" + oobt.getData().getuid() + "md5 " + oobt.getData().getchecksum() + " size "
+ oobt.getData().getsize());
DaoData newdao = new DaoData();
newdao.makePersistent(oobt.getData(), true);
newdao.makePersistent(oobt.getRemoteProtocol(), true);
newdao.makePersistent(oobt.getLocalProtocol(), true);
oobt.getRemoteLocator().setdatauid(oobt.getData().getuid());
oobt.getLocalLocator().setdatauid(oobt.getData().getuid());
oobt.getRemoteLocator().setprotocoluid(oobt.getRemoteProtocol().getuid());
oobt.getLocalLocator().setprotocoluid(oobt.getLocalProtocol().getuid());
newdao.makePersistent(oobt.getRemoteLocator(), true);
newdao.makePersistent(oobt.getLocalLocator(), true);
oobt.getTransfer().setlocatorremote(oobt.getRemoteLocator().getuid());
oobt.getTransfer().setlocatorlocal(oobt.getLocalLocator().getuid());
oobt.getTransfer().setdatauid(oobt.getData().getuid());
newdao.makePersistent(oobt.getTransfer(), true);
// FIXME: should have an assert here
if ((tuid != null) && (!tuid.equals(oobt.getTransfer().getuid())))
log.debug(" Transfer has been incorrectly persisted " + tuid + " !=" + oobt.getTransfer().getuid());
}
/**
* Get the numeric status (PENDING,COMPLETE,TRANSFERRING)of a transfer given its uid
* @param tid
* @return
*/
public int getTransferStatus(String tid) {
try {
dao.beginTransaction();
Transfer t = (Transfer) dao.getByUid(Transfer.class, tid);
dao.commitTransaction();
return t.getstatus();
} catch (Exception e) {
log.info("an error occurred while interacting with bd ");
e.printStackTrace();
}
return -1;
}
/**
* <code>start</code> launches periodic TM engine
*/
public void start(boolean isDaemon) {
log.debug("Starting TM Engine");
try {
timerLock.lock();
if (timer == null) {
timer = new Timer("TransferManagerTimer", isDaemon);
timer.schedule(new TimerTask() {
public void run() {
checkTransfer();
}
}, 0, timeout);
timerSchedules++;
log.debug("timer schedules : " + timerSchedules);
}
} finally {
timerLock.unlock();
}
}
/**
* <code>start</code> launches periodic Active Data engine
*/
public void start() {
// by default, do not start as a daemon
start(false);
}
/**
* <code>stop</code> stops periodic TM Engine
*/
public void stop() {
log.debug("Stopping TM Engine");
try {
timerLock.lock();
timer.cancel();
timer.purge();
timer = null;
} finally {
timerLock.unlock();
}
}
/**
* Remove a transfer
* @param trans the transfer object we want to be removed
* @throws OOBException
*/
public void removeOOBTransfer(Transfer trans) throws OOBException {
oobTransfers.removeElement(trans.getuid());
}
/**
* Create a OOBTransfer
* @param t the transfer object
* @param daocheck this method is called from the checkTransfer thread, and thus
* must share the same DAO
* @return the OOBTransfer
* @throws OOBException
*/
private OOBTransfer createOOBTransfer(Transfer t, DaoTransfer daocheck) throws OOBException {
Data d = null;
Locator rl = null;
Locator ll = null;
Protocol lp = null;
Protocol rp = null;
ll = (Locator) daocheck.getByUid(xtremweb.core.obj.dc.Locator.class, t.getlocatorlocal());
rl = (Locator) daocheck.getByUid(xtremweb.core.obj.dc.Locator.class, t.getlocatorremote());
rp = (Protocol) daocheck.getByUid(xtremweb.core.obj.dr.Protocol.class, rl.getprotocoluid());
lp = (Protocol) daocheck.getByUid(xtremweb.core.obj.dr.Protocol.class, ll.getprotocoluid());
// FIXME to use transfet.getdatauid() instead
if (!ll.getdatauid().equals(rl.getdatauid()))
throw new OOBException("O-O-B Transfers refers to two different data ");
d = (Data) daocheck.getByUid(xtremweb.core.obj.dc.Data.class, ll.getdatauid());
log.debug("OOBTransferFactory create " + t.getuid() + ":" + t.getoob() + ":" + TransferType.toString(t.gettype()));
return OOBTransferFactory.createOOBTransfer(d, t, rl, ll, rp, lp);
}
/**
* Get a OOBTransfer from a transfer object
* @param trans the transfer object
* @return OOBTransfer
* @throws OOBException
*/
public OOBTransfer getOOBTransfer(Transfer trans) throws OOBException {
OOBTransfer oob = null;
int idx = oobTransfers.search(trans.getuid());
if (idx != -1)
oob = (OOBTransfer) oobTransfers.elementAt(idx);
else {
oob = createOOBTransfer(trans, daocheck);
oobTransfers.addElement(oob);
log.debug("TransferManager new transfer " + trans.getuid() + " : " + oob.toString());
}
return oob;
}
/**
* <code>checkTransfer</code> scans the database and take decision according
* to the status of the trabsfer
* <ol>
* <li>prepare transfert (check for data availability)
* <li>check for finished transfer
* <li>cleanup transfer
* </ol>
*/
private void checkTransfer() {
try {
daocheck.beginTransaction();
/* begin nouveau */
Collection results = (Collection) daocheck.getTransfersDifferentStatus(TransferStatus.TODELETE);
if (results == null) {
log.debug("nothing to check");
return;
}
Iterator iter = results.iterator();
OOBTransfer oob;
while (iter.hasNext()) {
Transfer trans = (Transfer) iter.next();
log.debug("Checking Transfer in " + this + " : " + trans.getuid() + ":" + TransferType.toString(trans.gettype()));
switch (trans.getstatus()) {
// Register the transfer remotely if it
// succeed, set the local transfer to READY
// if not set the transfert to INVALID
// set the remote transfer to READY, if it
// fails set the local transfer to INVALID
case TransferStatus.PENDING:
log.debug("PENDING");
try {
oob = getOOBTransfer(trans);
if (TransferType.isLocal(trans.gettype())) {
log.debug("transfer " + trans + " | data " + oob.getData() + " | remote protocol " + oob.getRemoteProtocol() + " | remote locator "
+ oob.getRemoteLocator());
log.debug("value of dt is " + dt + " in " + this);
log.debug("is about to insert one transfer in " + this);
dt.registerTransfer(trans, oob.getData(), oob.getRemoteProtocol(), oob.getRemoteLocator());
}
} catch (Exception re) {
log.info("An error has occurred " + re.getMessage());
log.debug("cannot register transfer " + re);
re.printStackTrace();
trans.setstatus(TransferStatus.INVALID);
break;
}
trans.setstatus(TransferStatus.READY);
break;
case TransferStatus.READY:
log.debug("READY");
if (ongoingTransfers() < maxDownloads) {
try {
log.debug("start tranfer : " + trans.getuid());
// correct transfer creation
// going to start the transfer
oob = getOOBTransfer(trans);
if (TransferType.isLocal(trans.gettype())) {
log.debug("oob connect");
oob.connect();
}
if (trans.gettype() == TransferType.UNICAST_SEND_SENDER_SIDE) {
log.debug("oob sendSenderSide");
oob.sendSenderSide();
}
if (trans.gettype() == TransferType.UNICAST_SEND_RECEIVER_SIDE) {
log.debug("oob sendReceiverSide");
oob.sendReceiverSide();
}
if (trans.gettype() == TransferType.UNICAST_RECEIVE_RECEIVER_SIDE) {
log.debug("oob receiveReceiverSide");
oob.receiveReceiverSide();
}
if (trans.gettype() == TransferType.UNICAST_RECEIVE_SENDER_SIDE) {
log.debug("oob receiveSenderSide");
oob.receiveSenderSide();
}
} catch (OOBException oobe) {
log.info("An error has occurred " + oobe.getMessage());
log.info("The transfer could not succesfully finish " + oobe.getMessage() + " it will be erased from cache");
oobe.printStackTrace();
trans.setstatus(TransferStatus.INVALID);
break;
}
trans.setstatus(TransferStatus.TRANSFERING);
}
break;
case TransferStatus.INVALID:
log.debug("INVALID");
try {
if (TransferType.isLocal(trans.gettype()))
dt.setTransferStatus(trans.getuid(), TransferStatus.INVALID);
} catch (RemoteException re) {
log.info("An error has occurred " + re.getMessage());
re.printStackTrace();
trans.setstatus(TransferStatus.INVALID);
break;
}
trans.setstatus(TransferStatus.TODELETE);
break;
case TransferStatus.TRANSFERING:
// check the status
log.debug("TRANSFERING");
boolean complete = false;
// check if transfer is complete
try {
oob = getOOBTransfer(trans);
log.debug("transfer type " + TransferType.toString(trans.gettype()));
- if (trans.gettype() == TransferType.UNICAST_SEND_SENDER_SIDE)
- complete = dt.poolTransfer(trans.getuid());
+ if (trans.gettype() == TransferType.UNICAST_SEND_SENDER_SIDE && oob instanceof BlockingOOBTransferImpl)
+ complete = oob.poolTransfer();// pool transfer is overwritten on each blocking transfer
+ if (trans.gettype() == TransferType.UNICAST_SEND_SENDER_SIDE && oob instanceof NonBlockingOOBTransferImpl)
+ complete = dt.poolTransfer(trans.getuid());// bittorrent case, only the remote dt can acknowledge the file reception
if (trans.gettype() == TransferType.UNICAST_SEND_RECEIVER_SIDE)
complete = oob.poolTransfer();
if (trans.gettype() == TransferType.UNICAST_RECEIVE_RECEIVER_SIDE)
complete = oob.poolTransfer();
if (trans.gettype() == TransferType.UNICAST_RECEIVE_SENDER_SIDE)
complete = oob.poolTransfer();
log.debug("Complete is !!!" + complete);
// Transfer is finished
if (complete) {
trans.setstatus(TransferStatus.COMPLETE);
}
// FIXME check for errors
if (oob.error()) {
throw new OOBException("There was an exception on the Transfer Manager, your transfer of data " + trans.getdatauid()
+ " is marked as INVALID");
}
- } catch (RemoteException re) {
- log.info("An error has occurred " + re.getMessage());
- trans.setstatus(TransferStatus.INVALID);
- re.printStackTrace();
- break;
- } catch (OOBException oobe) {
+ }catch (OOBException oobe) {
// go in the state INVALID (should be ABORT ?)
log.info("Error on TRANSFERRING step : " + oobe.getMessage());
trans.setstatus(TransferStatus.INVALID);
oobe.printStackTrace();
break;
+ } catch (RemoteException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
}
break;
case TransferStatus.COMPLETE:
// check the status
// we stay in the complete status up to when we have been
// checked as complete.
log.debug("COMPLETE");
// The transfer ends when the sender is aware that the
try {
oob = getOOBTransfer(trans);
oob.disconnect();
trans.setstatus(TransferStatus.TODELETE);
} catch (Exception re) {
log.info("An error has occurred " + re.getMessage());
re.printStackTrace();
trans.setstatus(TransferStatus.INVALID);
break;
}
break;
case TransferStatus.STALLED:
log.debug("STALLED");
break;
case TransferStatus.TODELETE:
// check the status
log.debug("TODELETE");
try {
// TODO DELETE TRANSFER FROM THE DATABASE
removeOOBTransfer(trans);
} catch (OOBException oobe) {
log.info("An error has occurred " + oobe.getMessage());
trans.setstatus(TransferStatus.INVALID);
oobe.printStackTrace();
break;
}
break;
default:
log.debug("ERROR");
}
log.debug("Trans status of id " + trans.getuid() + "before persisting is " + trans.getstatus());
daocheck.makePersistent(trans, false);
}
daocheck.commitTransaction();
} finally {
if (daocheck.transactionIsActive())
daocheck.transactionRollback();
}
}
/**
* How many transfers are being currently executed
* @return the number of transfers currently executed
*/
public long ongoingTransfers() {
long result = -1;
result = new Long((Long) daocheck.getTransfersByStatus(TransferStatus.TRANSFERING, true, "uid")).longValue();
return result;
}
/**
* Are all the transfers completed ?
* @return true if all transfers are completed, otherwise false
*/
private boolean downloadComplete() {
DaoTransfer daot = (DaoTransfer) DaoFactory.getInstance("xtremweb.dao.transfer.DaoTransfer");
try {
daot.beginTransaction();
Collection results = daot.getAll(xtremweb.core.obj.dt.Transfer.class);
if (results == null) {
return true;
} else {
Iterator iter = results.iterator();
while (iter.hasNext()) {
Transfer trans = (Transfer) iter.next();
log.debug("scanning transfer " + trans.getuid() + " " + trans.getdatauid() + trans.getstatus());
if (trans.getstatus() != TransferStatus.TODELETE)
return false;
}
}
daot.commitTransaction();
} finally {
if (daot.transactionIsActive())
daot.transactionRollback();
}
return true;
}
/**
* Self-explanatory
* @param cd
*/
public void setMaximumConcurrentDownloads(long cd) {
maxDownloads = cd;
}
/**
* Self-explanatory
*/
public long getMaximumConcurrentDonwloads() {
return maxDownloads;
}
/**
* <code>waitForAllData</code> waits for all transfers to complete.
*
*/
public void waitForAllData() {
while (!downloadComplete()) {
try {
Thread.sleep(timeout);
} catch (Exception e) {
}
;
log.debug("Still in the barrier");
}
}
/**
* <code>isTransferComplete</code> check if a transfer of a given data is
* complete.
*
* @param data
* a <code>Data</code> value
* @return a <code>boolean</code> value
*/
public boolean isTransferComplete(Data data) {
boolean isComplete = true;
DaoTransfer daot = null;
try {
daot = (DaoTransfer) DaoFactory.getInstance("xtremweb.dao.transfer.DaoTransfer");
daot.beginTransaction();
Collection results = (Collection) daot.getTransfersByDataUid(data.getuid());
if (results == null) {
log.debug("pas de resultat");
return true;
} else {
Iterator iter = results.iterator();
while (iter.hasNext()) {
Transfer trans = (Transfer) iter.next();
log.debug("scanning transfer locator " + trans.getlocatorlocal() + " tuid: " + trans.getuid() + " " + trans.getdatauid() + " status : "
+ trans.getstatus());
if (trans.getstatus() != TransferStatus.TODELETE)
return false;
}
}
daot.commitTransaction();
} finally {
if (daot.transactionIsActive())
daot.transactionRollback();
daot.close();
}
return isComplete;
}
/**
* <code>waitFor</code> waits for a specific data to be transfered.
*
* @param data
* a <code>Data</code> value
*/
public void waitFor(Data data) throws TransferManagerException {
while (!isTransferComplete(data)) {
try {
Thread.sleep(timeout);
} catch (Exception e) {
throw new TransferManagerException();
}
;
log.debug("waitFor data " + data.getuid());
}
}
/**
* Waits for a uid list
* @param uidList
* @throws TransferManagerException
*/
public void waitFor(Vector<String> uidList) throws TransferManagerException {
log.debug("begin waitFor!");
try {
int N = uidList.size();
try {
dao.beginTransaction();
for (int i = 0; i < N; i++) {
String uid = uidList.elementAt(i);
Data dataStored = (Data) dao.getByUid(xtremweb.core.obj.dc.Data.class, uid);
waitFor(dataStored);
log.debug("Oh ha Transfer waitfor data uid=" + dataStored.getuid());
}
dao.commitTransaction();
} finally {
if (dao.transactionIsActive())
dao.transactionRollback();
}
} catch (Exception e) {
System.out.println(e);
throw new TransferManagerException();
}
}
/**
* Wait for a bitdew uri
* @param uri
* @throws TransferManagerException
*/
public void waitFor(BitDewURI uri) throws TransferManagerException {
log.debug("begin waitFor!");
try {
dao.beginTransaction();
String uid = uri.getUid();
Data dataStored = (Data) dao.getByUid(xtremweb.core.obj.dc.Data.class, uid);
waitFor(dataStored);
log.debug("Oh ha Transfer waitfor data uid=" + dataStored.getuid());
dao.commitTransaction();
} catch (Exception e) {
System.out.println(e);
throw new TransferManagerException();
} finally {
if (dao.transactionIsActive())
dao.transactionRollback();
}
}
// This a comparator for the test
class OOBTransferOrder implements Comparator {
public int compare(Object p1, Object p2) {
String s1;
String s2;
if (p1 instanceof String)
s1 = (String) p1;
else
s1 = ((OOBTransfer) p1).getTransfer().getuid();
if (p2 instanceof String)
s2 = (String) p2;
else
s2 = ((OOBTransfer) p2).getTransfer().getuid();
return s1.compareTo(s2);
}
}
}
| false | true | private void checkTransfer() {
try {
daocheck.beginTransaction();
/* begin nouveau */
Collection results = (Collection) daocheck.getTransfersDifferentStatus(TransferStatus.TODELETE);
if (results == null) {
log.debug("nothing to check");
return;
}
Iterator iter = results.iterator();
OOBTransfer oob;
while (iter.hasNext()) {
Transfer trans = (Transfer) iter.next();
log.debug("Checking Transfer in " + this + " : " + trans.getuid() + ":" + TransferType.toString(trans.gettype()));
switch (trans.getstatus()) {
// Register the transfer remotely if it
// succeed, set the local transfer to READY
// if not set the transfert to INVALID
// set the remote transfer to READY, if it
// fails set the local transfer to INVALID
case TransferStatus.PENDING:
log.debug("PENDING");
try {
oob = getOOBTransfer(trans);
if (TransferType.isLocal(trans.gettype())) {
log.debug("transfer " + trans + " | data " + oob.getData() + " | remote protocol " + oob.getRemoteProtocol() + " | remote locator "
+ oob.getRemoteLocator());
log.debug("value of dt is " + dt + " in " + this);
log.debug("is about to insert one transfer in " + this);
dt.registerTransfer(trans, oob.getData(), oob.getRemoteProtocol(), oob.getRemoteLocator());
}
} catch (Exception re) {
log.info("An error has occurred " + re.getMessage());
log.debug("cannot register transfer " + re);
re.printStackTrace();
trans.setstatus(TransferStatus.INVALID);
break;
}
trans.setstatus(TransferStatus.READY);
break;
case TransferStatus.READY:
log.debug("READY");
if (ongoingTransfers() < maxDownloads) {
try {
log.debug("start tranfer : " + trans.getuid());
// correct transfer creation
// going to start the transfer
oob = getOOBTransfer(trans);
if (TransferType.isLocal(trans.gettype())) {
log.debug("oob connect");
oob.connect();
}
if (trans.gettype() == TransferType.UNICAST_SEND_SENDER_SIDE) {
log.debug("oob sendSenderSide");
oob.sendSenderSide();
}
if (trans.gettype() == TransferType.UNICAST_SEND_RECEIVER_SIDE) {
log.debug("oob sendReceiverSide");
oob.sendReceiverSide();
}
if (trans.gettype() == TransferType.UNICAST_RECEIVE_RECEIVER_SIDE) {
log.debug("oob receiveReceiverSide");
oob.receiveReceiverSide();
}
if (trans.gettype() == TransferType.UNICAST_RECEIVE_SENDER_SIDE) {
log.debug("oob receiveSenderSide");
oob.receiveSenderSide();
}
} catch (OOBException oobe) {
log.info("An error has occurred " + oobe.getMessage());
log.info("The transfer could not succesfully finish " + oobe.getMessage() + " it will be erased from cache");
oobe.printStackTrace();
trans.setstatus(TransferStatus.INVALID);
break;
}
trans.setstatus(TransferStatus.TRANSFERING);
}
break;
case TransferStatus.INVALID:
log.debug("INVALID");
try {
if (TransferType.isLocal(trans.gettype()))
dt.setTransferStatus(trans.getuid(), TransferStatus.INVALID);
} catch (RemoteException re) {
log.info("An error has occurred " + re.getMessage());
re.printStackTrace();
trans.setstatus(TransferStatus.INVALID);
break;
}
trans.setstatus(TransferStatus.TODELETE);
break;
case TransferStatus.TRANSFERING:
// check the status
log.debug("TRANSFERING");
boolean complete = false;
// check if transfer is complete
try {
oob = getOOBTransfer(trans);
log.debug("transfer type " + TransferType.toString(trans.gettype()));
if (trans.gettype() == TransferType.UNICAST_SEND_SENDER_SIDE)
complete = dt.poolTransfer(trans.getuid());
if (trans.gettype() == TransferType.UNICAST_SEND_RECEIVER_SIDE)
complete = oob.poolTransfer();
if (trans.gettype() == TransferType.UNICAST_RECEIVE_RECEIVER_SIDE)
complete = oob.poolTransfer();
if (trans.gettype() == TransferType.UNICAST_RECEIVE_SENDER_SIDE)
complete = oob.poolTransfer();
log.debug("Complete is !!!" + complete);
// Transfer is finished
if (complete) {
trans.setstatus(TransferStatus.COMPLETE);
}
// FIXME check for errors
if (oob.error()) {
throw new OOBException("There was an exception on the Transfer Manager, your transfer of data " + trans.getdatauid()
+ " is marked as INVALID");
}
} catch (RemoteException re) {
log.info("An error has occurred " + re.getMessage());
trans.setstatus(TransferStatus.INVALID);
re.printStackTrace();
break;
} catch (OOBException oobe) {
// go in the state INVALID (should be ABORT ?)
log.info("Error on TRANSFERRING step : " + oobe.getMessage());
trans.setstatus(TransferStatus.INVALID);
oobe.printStackTrace();
break;
}
break;
case TransferStatus.COMPLETE:
// check the status
// we stay in the complete status up to when we have been
// checked as complete.
log.debug("COMPLETE");
// The transfer ends when the sender is aware that the
try {
oob = getOOBTransfer(trans);
oob.disconnect();
trans.setstatus(TransferStatus.TODELETE);
} catch (Exception re) {
log.info("An error has occurred " + re.getMessage());
re.printStackTrace();
trans.setstatus(TransferStatus.INVALID);
break;
}
break;
case TransferStatus.STALLED:
log.debug("STALLED");
break;
case TransferStatus.TODELETE:
// check the status
log.debug("TODELETE");
try {
// TODO DELETE TRANSFER FROM THE DATABASE
removeOOBTransfer(trans);
} catch (OOBException oobe) {
log.info("An error has occurred " + oobe.getMessage());
trans.setstatus(TransferStatus.INVALID);
oobe.printStackTrace();
break;
}
break;
default:
log.debug("ERROR");
}
log.debug("Trans status of id " + trans.getuid() + "before persisting is " + trans.getstatus());
daocheck.makePersistent(trans, false);
}
daocheck.commitTransaction();
} finally {
if (daocheck.transactionIsActive())
daocheck.transactionRollback();
}
}
| private void checkTransfer() {
try {
daocheck.beginTransaction();
/* begin nouveau */
Collection results = (Collection) daocheck.getTransfersDifferentStatus(TransferStatus.TODELETE);
if (results == null) {
log.debug("nothing to check");
return;
}
Iterator iter = results.iterator();
OOBTransfer oob;
while (iter.hasNext()) {
Transfer trans = (Transfer) iter.next();
log.debug("Checking Transfer in " + this + " : " + trans.getuid() + ":" + TransferType.toString(trans.gettype()));
switch (trans.getstatus()) {
// Register the transfer remotely if it
// succeed, set the local transfer to READY
// if not set the transfert to INVALID
// set the remote transfer to READY, if it
// fails set the local transfer to INVALID
case TransferStatus.PENDING:
log.debug("PENDING");
try {
oob = getOOBTransfer(trans);
if (TransferType.isLocal(trans.gettype())) {
log.debug("transfer " + trans + " | data " + oob.getData() + " | remote protocol " + oob.getRemoteProtocol() + " | remote locator "
+ oob.getRemoteLocator());
log.debug("value of dt is " + dt + " in " + this);
log.debug("is about to insert one transfer in " + this);
dt.registerTransfer(trans, oob.getData(), oob.getRemoteProtocol(), oob.getRemoteLocator());
}
} catch (Exception re) {
log.info("An error has occurred " + re.getMessage());
log.debug("cannot register transfer " + re);
re.printStackTrace();
trans.setstatus(TransferStatus.INVALID);
break;
}
trans.setstatus(TransferStatus.READY);
break;
case TransferStatus.READY:
log.debug("READY");
if (ongoingTransfers() < maxDownloads) {
try {
log.debug("start tranfer : " + trans.getuid());
// correct transfer creation
// going to start the transfer
oob = getOOBTransfer(trans);
if (TransferType.isLocal(trans.gettype())) {
log.debug("oob connect");
oob.connect();
}
if (trans.gettype() == TransferType.UNICAST_SEND_SENDER_SIDE) {
log.debug("oob sendSenderSide");
oob.sendSenderSide();
}
if (trans.gettype() == TransferType.UNICAST_SEND_RECEIVER_SIDE) {
log.debug("oob sendReceiverSide");
oob.sendReceiverSide();
}
if (trans.gettype() == TransferType.UNICAST_RECEIVE_RECEIVER_SIDE) {
log.debug("oob receiveReceiverSide");
oob.receiveReceiverSide();
}
if (trans.gettype() == TransferType.UNICAST_RECEIVE_SENDER_SIDE) {
log.debug("oob receiveSenderSide");
oob.receiveSenderSide();
}
} catch (OOBException oobe) {
log.info("An error has occurred " + oobe.getMessage());
log.info("The transfer could not succesfully finish " + oobe.getMessage() + " it will be erased from cache");
oobe.printStackTrace();
trans.setstatus(TransferStatus.INVALID);
break;
}
trans.setstatus(TransferStatus.TRANSFERING);
}
break;
case TransferStatus.INVALID:
log.debug("INVALID");
try {
if (TransferType.isLocal(trans.gettype()))
dt.setTransferStatus(trans.getuid(), TransferStatus.INVALID);
} catch (RemoteException re) {
log.info("An error has occurred " + re.getMessage());
re.printStackTrace();
trans.setstatus(TransferStatus.INVALID);
break;
}
trans.setstatus(TransferStatus.TODELETE);
break;
case TransferStatus.TRANSFERING:
// check the status
log.debug("TRANSFERING");
boolean complete = false;
// check if transfer is complete
try {
oob = getOOBTransfer(trans);
log.debug("transfer type " + TransferType.toString(trans.gettype()));
if (trans.gettype() == TransferType.UNICAST_SEND_SENDER_SIDE && oob instanceof BlockingOOBTransferImpl)
complete = oob.poolTransfer();// pool transfer is overwritten on each blocking transfer
if (trans.gettype() == TransferType.UNICAST_SEND_SENDER_SIDE && oob instanceof NonBlockingOOBTransferImpl)
complete = dt.poolTransfer(trans.getuid());// bittorrent case, only the remote dt can acknowledge the file reception
if (trans.gettype() == TransferType.UNICAST_SEND_RECEIVER_SIDE)
complete = oob.poolTransfer();
if (trans.gettype() == TransferType.UNICAST_RECEIVE_RECEIVER_SIDE)
complete = oob.poolTransfer();
if (trans.gettype() == TransferType.UNICAST_RECEIVE_SENDER_SIDE)
complete = oob.poolTransfer();
log.debug("Complete is !!!" + complete);
// Transfer is finished
if (complete) {
trans.setstatus(TransferStatus.COMPLETE);
}
// FIXME check for errors
if (oob.error()) {
throw new OOBException("There was an exception on the Transfer Manager, your transfer of data " + trans.getdatauid()
+ " is marked as INVALID");
}
}catch (OOBException oobe) {
// go in the state INVALID (should be ABORT ?)
log.info("Error on TRANSFERRING step : " + oobe.getMessage());
trans.setstatus(TransferStatus.INVALID);
oobe.printStackTrace();
break;
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case TransferStatus.COMPLETE:
// check the status
// we stay in the complete status up to when we have been
// checked as complete.
log.debug("COMPLETE");
// The transfer ends when the sender is aware that the
try {
oob = getOOBTransfer(trans);
oob.disconnect();
trans.setstatus(TransferStatus.TODELETE);
} catch (Exception re) {
log.info("An error has occurred " + re.getMessage());
re.printStackTrace();
trans.setstatus(TransferStatus.INVALID);
break;
}
break;
case TransferStatus.STALLED:
log.debug("STALLED");
break;
case TransferStatus.TODELETE:
// check the status
log.debug("TODELETE");
try {
// TODO DELETE TRANSFER FROM THE DATABASE
removeOOBTransfer(trans);
} catch (OOBException oobe) {
log.info("An error has occurred " + oobe.getMessage());
trans.setstatus(TransferStatus.INVALID);
oobe.printStackTrace();
break;
}
break;
default:
log.debug("ERROR");
}
log.debug("Trans status of id " + trans.getuid() + "before persisting is " + trans.getstatus());
daocheck.makePersistent(trans, false);
}
daocheck.commitTransaction();
} finally {
if (daocheck.transactionIsActive())
daocheck.transactionRollback();
}
}
|
diff --git a/mrts-io/src/mrtsio/mimport/Importer.java b/mrts-io/src/mrtsio/mimport/Importer.java
index e2d45b8..25c19c4 100644
--- a/mrts-io/src/mrtsio/mimport/Importer.java
+++ b/mrts-io/src/mrtsio/mimport/Importer.java
@@ -1,168 +1,168 @@
package mrtsio.mimport;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import au.com.bytecode.opencsv.CSVReader;
import cassdb.interfaces.IHashClient;
import cassdb.internal.HashClient;
import mrtsio.dbconx.DataConnector;
/**
* Static class importer - import training data set
* into on of:
* 1) Cassandra
* 2) HDFS
* *) keyspace is defined in connector
*
* @author cbarca
*/
public class Importer {
public static final String SPLIT_TOKEN = "#";
/**
* Import training data set to cassandra column family
* @param dir_path directory path
* @param colfam column family name
* @param row_size number of training vectors
* @throws IOException
*/
public static void importTrainingDataToCASSDB(String dir_path,
String colfam, int row_size) throws IOException {
int row = 1, count = 0;
String train_vector;
String[] values;
DataConnector conx = new DataConnector(colfam);
IHashClient hash = new HashClient(conx.getKeyspace());
File dir = new File(dir_path);
File[] files = dir.listFiles();
hash.startBatchPut();
// Each file is read and parsed
for (File file : files) {
if (!file.getName().contains(".csv")) {
continue;
}
train_vector = new String();
CSVReader reader = new CSVReader(new FileReader(file));
reader.readNext();
while ((values = reader.readNext())!= null) {
if (count == 0) {
hash.startBatchPut();
}
train_vector = "";
for (int i = 0; i < values.length - 1; i++) {
train_vector += values[i] + ",";
}
train_vector += values[values.length - 1];
hash.batchPut(colfam, row, ++count, train_vector);
if (count == row_size) {
row++;
count = 0;
hash.finalizeBatchPut();
}
}
reader.close();
}
if (count < row_size) {
hash.finalizeBatchPut();
}
}
/**
* Import training data set to cassandra column family
* @param dir_path directory path
* @param colfam column family name
* @param row_size number of training vectors
* @throws IOException
*/
public static void importTrainingDataToHDFS(String dir_path,
String hdfs_path, int chunk_size, int file_size) throws IOException {
int cksize = 0, flsize = 0, nfiles = 0;
String train_vector;
String[] values;
BufferedWriter writer = null;
File dir = new File(dir_path);
File[] files = dir.listFiles();
train_vector = new String();
// Each file is read and parsed
for (File file : files) {
if (!file.getName().contains(".csv")) {
continue;
}
System.out.println("File: " + file.getName());
CSVReader reader = new CSVReader(new FileReader(file));
reader.readNext();
while ((values = reader.readNext()) != null) {
if (flsize == 0 && cksize == 0) {
writer = new BufferedWriter(new FileWriter("hdfs_" + nfiles));
nfiles++;
}
train_vector = "";
for (int i = 0; i < values.length - 1; i++) {
train_vector += values[i] + ",";
}
train_vector += values[values.length - 1];
cksize++;
if (cksize == chunk_size) {
flsize++;
cksize = 0;
train_vector += "\n";
}
else {
train_vector += SPLIT_TOKEN;
}
if (writer != null) {
writer.write(train_vector);
if (flsize == file_size) {
flsize = 0;
writer.close();
}
}
}
reader.close();
/* import to hdfs (copy from local to hdfs)
* TODO
*/
}
- if (cksize < chunk_size) {
+ if (flsize < file_size && flsize > 0) {
cksize = 0;
if (writer != null) {
writer.write(train_vector);
writer.close();
}
}
}
}
| true | true | public static void importTrainingDataToHDFS(String dir_path,
String hdfs_path, int chunk_size, int file_size) throws IOException {
int cksize = 0, flsize = 0, nfiles = 0;
String train_vector;
String[] values;
BufferedWriter writer = null;
File dir = new File(dir_path);
File[] files = dir.listFiles();
train_vector = new String();
// Each file is read and parsed
for (File file : files) {
if (!file.getName().contains(".csv")) {
continue;
}
System.out.println("File: " + file.getName());
CSVReader reader = new CSVReader(new FileReader(file));
reader.readNext();
while ((values = reader.readNext()) != null) {
if (flsize == 0 && cksize == 0) {
writer = new BufferedWriter(new FileWriter("hdfs_" + nfiles));
nfiles++;
}
train_vector = "";
for (int i = 0; i < values.length - 1; i++) {
train_vector += values[i] + ",";
}
train_vector += values[values.length - 1];
cksize++;
if (cksize == chunk_size) {
flsize++;
cksize = 0;
train_vector += "\n";
}
else {
train_vector += SPLIT_TOKEN;
}
if (writer != null) {
writer.write(train_vector);
if (flsize == file_size) {
flsize = 0;
writer.close();
}
}
}
reader.close();
/* import to hdfs (copy from local to hdfs)
* TODO
*/
}
if (cksize < chunk_size) {
cksize = 0;
if (writer != null) {
writer.write(train_vector);
writer.close();
}
}
}
| public static void importTrainingDataToHDFS(String dir_path,
String hdfs_path, int chunk_size, int file_size) throws IOException {
int cksize = 0, flsize = 0, nfiles = 0;
String train_vector;
String[] values;
BufferedWriter writer = null;
File dir = new File(dir_path);
File[] files = dir.listFiles();
train_vector = new String();
// Each file is read and parsed
for (File file : files) {
if (!file.getName().contains(".csv")) {
continue;
}
System.out.println("File: " + file.getName());
CSVReader reader = new CSVReader(new FileReader(file));
reader.readNext();
while ((values = reader.readNext()) != null) {
if (flsize == 0 && cksize == 0) {
writer = new BufferedWriter(new FileWriter("hdfs_" + nfiles));
nfiles++;
}
train_vector = "";
for (int i = 0; i < values.length - 1; i++) {
train_vector += values[i] + ",";
}
train_vector += values[values.length - 1];
cksize++;
if (cksize == chunk_size) {
flsize++;
cksize = 0;
train_vector += "\n";
}
else {
train_vector += SPLIT_TOKEN;
}
if (writer != null) {
writer.write(train_vector);
if (flsize == file_size) {
flsize = 0;
writer.close();
}
}
}
reader.close();
/* import to hdfs (copy from local to hdfs)
* TODO
*/
}
if (flsize < file_size && flsize > 0) {
cksize = 0;
if (writer != null) {
writer.write(train_vector);
writer.close();
}
}
}
|
diff --git a/src/com/androzic/Splash.java b/src/com/androzic/Splash.java
index ef82535..2023346 100644
--- a/src/com/androzic/Splash.java
+++ b/src/com/androzic/Splash.java
@@ -1,656 +1,665 @@
/*
* Androzic - android navigation client that uses OziExplorer maps (ozf2, ozfx3).
* Copyright (C) 2010-2012 Andrey Novikov <http://andreynovikov.info/>
*
* This file is part of Androzic application.
*
* Androzic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Androzic is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Androzic. If not, see <http://www.gnu.org/licenses/>.
*/
package com.androzic;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.Html;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Window;
import com.androzic.data.Route;
import com.androzic.data.Track;
import com.androzic.overlay.CurrentTrackOverlay;
import com.androzic.overlay.RouteOverlay;
import com.androzic.util.AutoloadedRouteFilenameFilter;
import com.androzic.util.FileList;
import com.androzic.util.GpxFiles;
import com.androzic.util.KmlFiles;
import com.androzic.util.OziExplorerFiles;
public class Splash extends SherlockActivity implements OnClickListener
{
private static final int MSG_FINISH = 1;
private static final int MSG_ERROR = 2;
private static final int MSG_STATUS = 3;
private static final int MSG_PROGRESS = 4;
private static final int MSG_ASK = 5;
private static final int MSG_SAY = 6;
private static final int RES_YES = 1;
private static final int RES_NO = 2;
private static final int DOWNLOAD_SIZE = 207216;
private static final int PROGRESS_STEP = 10000;
private int result;
private boolean wait;
protected String savedMessage;
private ProgressBar progress;
private TextView message;
private Button gotit;
private Button yes;
private Button no;
private Button quit;
protected Androzic application;
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
application = (Androzic) getApplication();
PreferenceManager.setDefaultValues(this, R.xml.pref_behavior, true);
PreferenceManager.setDefaultValues(this, R.xml.pref_folder, true);
PreferenceManager.setDefaultValues(this, R.xml.pref_location, true);
PreferenceManager.setDefaultValues(this, R.xml.pref_display, true);
PreferenceManager.setDefaultValues(this, R.xml.pref_unit, true);
PreferenceManager.setDefaultValues(this, R.xml.pref_tracking, true);
PreferenceManager.setDefaultValues(this, R.xml.pref_waypoint, true);
PreferenceManager.setDefaultValues(this, R.xml.pref_route, true);
PreferenceManager.setDefaultValues(this, R.xml.pref_navigation, true);
PreferenceManager.setDefaultValues(this, R.xml.pref_general, true);
setContentView(R.layout.act_splash);
if (application.isPaid)
{
findViewById(R.id.paid).setVisibility(View.VISIBLE);
}
progress = (ProgressBar) findViewById(R.id.progress);
message = (TextView) findViewById(R.id.message);
message.setText(getString(R.string.msg_connectingtoserver));
progress.setMax(DOWNLOAD_SIZE + PROGRESS_STEP * 4);
yes = (Button) findViewById(R.id.yes);
yes.setOnClickListener(this);
no = (Button) findViewById(R.id.no);
no.setOnClickListener(this);
gotit = (Button) findViewById(R.id.gotit);
gotit.setOnClickListener(this);
quit = (Button) findViewById(R.id.quit);
quit.setOnClickListener(this);
wait = true;
showEula();
if (!application.mapsInited)
{
new InitializationThread(progressHandler).start();
}
else
{
progressHandler.sendEmptyMessage(MSG_FINISH);
}
}
private void showEula()
{
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean hasBeenShown = prefs.getBoolean(getString(R.string.app_eulaaccepted), false);
if (hasBeenShown == false)
{
final SpannableString message = new SpannableString(Html.fromHtml(getString(R.string.app_eula).replace("/n", "<br/>")));
Linkify.addLinks(message, Linkify.WEB_URLS);
AlertDialog.Builder builder = new AlertDialog.Builder(this).setTitle(getString(R.string.app_name)).setIcon(R.drawable.icon).setMessage(message)
.setPositiveButton(android.R.string.ok, new Dialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i)
{
prefs.edit().putBoolean(getString(R.string.app_eulaaccepted), true).commit();
wait = false;
dialogInterface.dismiss();
}
}).setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialoginterface, int keyCode, KeyEvent event)
{
return !(keyCode == KeyEvent.KEYCODE_HOME);
}
}).setCancelable(false);
AlertDialog d = builder.create();
d.show();
// Make the textview clickable. Must be called after show()
((TextView) d.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
}
else
{
wait = false;
}
}
final Handler progressHandler = new Handler() {
public void handleMessage(Message msg)
{
switch (msg.what)
{
case MSG_STATUS:
message.setText(msg.getData().getString("message"));
break;
case MSG_PROGRESS:
int total = msg.getData().getInt("total");
progress.setProgress(total);
break;
case MSG_ASK:
progress.setVisibility(View.GONE);
savedMessage = message.getText().toString();
message.setText(msg.getData().getString("message"));
result = 0;
yes.setVisibility(View.VISIBLE);
no.setVisibility(View.VISIBLE);
break;
case MSG_SAY:
progress.setVisibility(View.GONE);
savedMessage = message.getText().toString();
message.setText(msg.getData().getString("message"));
result = 0;
gotit.setVisibility(View.VISIBLE);
break;
case MSG_FINISH:
startActivity(new Intent(Splash.this, MapActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK).putExtras(getIntent()));
finish();
break;
case MSG_ERROR:
progress.setVisibility(View.INVISIBLE);
message.setText(msg.getData().getString("message"));
quit.setVisibility(View.VISIBLE);
break;
}
}
};
private class InitializationThread extends Thread
{
Handler mHandler;
int total;
InitializationThread(Handler h)
{
mHandler = h;
}
public void run()
{
while (wait)
{
try
{
sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
total = 0;
Message msg = mHandler.obtainMessage(MSG_STATUS);
Bundle b = new Bundle();
b.putString("message", getString(R.string.msg_initializingdata));
msg.setData(b);
mHandler.sendMessage(msg);
Resources resources = getResources();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(Splash.this);
// start location service
application.enableLocating(settings.getBoolean(getString(R.string.lc_locate), true));
// set root folder and check if it has to be created
String rootPath = settings.getString(getString(R.string.pref_folder_root), Environment.getExternalStorageDirectory() + File.separator + resources.getString(R.string.def_folder_prefix));
File root = new File(rootPath);
if (!root.exists())
{
try
{
root.mkdirs();
File nomedia = new File(root, ".nomedia");
nomedia.createNewFile();
}
catch (IOException e)
{
msg = mHandler.obtainMessage(MSG_ERROR);
b = new Bundle();
b.putString("message", getString(R.string.err_nosdcard));
msg.setData(b);
mHandler.sendMessage(msg);
return;
}
}
// check maps folder existence
File mapdir = new File(settings.getString(getString(R.string.pref_folder_map), Environment.getExternalStorageDirectory() + File.separator + resources.getString(R.string.def_folder_map)));
String oldmap = settings.getString(getString(R.string.pref_folder_map_old), null);
if (oldmap != null)
{
File oldmapdir = new File(root, oldmap);
if (!oldmapdir.equals(mapdir))
{
mapdir = oldmapdir;
Editor editor = settings.edit();
editor.putString(getString(R.string.pref_folder_map), mapdir.getAbsolutePath());
editor.putString(getString(R.string.pref_folder_map_old), null);
editor.commit();
}
}
if (!mapdir.exists())
{
mapdir.mkdirs();
}
// check data folder existence
File datadir = new File(
settings.getString(getString(R.string.pref_folder_data), Environment.getExternalStorageDirectory() + File.separator + resources.getString(R.string.def_folder_data)));
if (!datadir.exists())
{
// check if there was an old data structure
String wptdir = settings.getString(getString(R.string.pref_folder_waypoint), null);
System.err.println("wpt: " + wptdir);
if (wptdir != null)
{
wait = true;
msg = mHandler.obtainMessage(MSG_SAY);
b = new Bundle();
b.putString("message", getString(R.string.msg_newdatafolder, datadir.getAbsolutePath()));
msg.setData(b);
mHandler.sendMessage(msg);
while (wait)
{
try
{
sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
datadir.mkdirs();
}
// check icons folder existence
File iconsdir = new File(settings.getString(getString(R.string.pref_folder_icon),
Environment.getExternalStorageDirectory() + File.separator + resources.getString(R.string.def_folder_icon)));
if (!iconsdir.exists())
{
- iconsdir.mkdirs();
- application.copyAssets("icons", iconsdir);
+ try
+ {
+ iconsdir.mkdirs();
+ File nomedia = new File(iconsdir, ".nomedia");
+ nomedia.createNewFile();
+ application.copyAssets("icons", iconsdir);
+ }
+ catch (IOException e)
+ {
+ e.printStackTrace();
+ }
}
// initialize paths
application.setRootPath(root.getAbsolutePath());
application.setMapPath(mapdir.getAbsolutePath());
application.setDataPath(Androzic.PATH_DATA, datadir.getAbsolutePath());
application.setDataPath(Androzic.PATH_ICONS, iconsdir.getAbsolutePath());
// initialize data
application.installData();
// start tracking service
application.enableTracking(settings.getBoolean(getString(R.string.lc_track), true));
// read default waypoints
File wptFile = new File(application.dataPath, "myWaypoints.wpt");
if (wptFile.exists() && wptFile.canRead())
{
try
{
application.addWaypoints(OziExplorerFiles.loadWaypointsFromFile(wptFile, application.charset));
}
catch (IOException e)
{
e.printStackTrace();
}
}
// read track tail
if (settings.getBoolean(getString(R.string.pref_showcurrenttrack), true))
{
application.currentTrackOverlay = new CurrentTrackOverlay(Splash.this);
if (settings.getBoolean(getString(R.string.pref_tracking_currentload), resources.getBoolean(R.bool.def_tracking_currentload)))
{
int length = Integer.parseInt(settings.getString(getString(R.string.pref_tracking_currentlength), getString(R.string.def_tracking_currentlength)));
// TODO Move this to proper class
File path = new File(application.dataPath, "myTrack.db");
try
{
SQLiteDatabase trackDB = SQLiteDatabase.openDatabase(path.getAbsolutePath(), null, SQLiteDatabase.OPEN_READONLY | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
Cursor cursor = trackDB.rawQuery("SELECT * FROM track ORDER BY _id DESC LIMIT " + length, null);
if (cursor.getCount() > 0)
{
Track track = new Track();
for (boolean hasItem = cursor.moveToLast(); hasItem; hasItem = cursor.moveToPrevious())
{
double latitude = cursor.getDouble(cursor.getColumnIndex("latitude"));
double longitude = cursor.getDouble(cursor.getColumnIndex("longitude"));
double altitude = cursor.getDouble(cursor.getColumnIndex("elevation"));
double speed = cursor.getDouble(cursor.getColumnIndex("speed"));
double bearing = cursor.getDouble(cursor.getColumnIndex("track"));
double accuracy = cursor.getDouble(cursor.getColumnIndex("accuracy"));
int code = cursor.getInt(cursor.getColumnIndex("code"));
long time = cursor.getLong(cursor.getColumnIndex("datetime"));
track.addPoint(code == 0, latitude, longitude, altitude, speed, bearing, accuracy, time);
}
track.show = true;
application.currentTrackOverlay.setTrack(track);
}
cursor.close();
trackDB.close();
}
catch (Exception e)
{
Log.e("Splash", "Read track tail", e);
}
}
}
// load routes
if (settings.getBoolean(getString(R.string.pref_route_preload), resources.getBoolean(R.bool.def_route_preload)))
{
boolean hide = settings.getBoolean(getString(R.string.pref_route_preload_hidden), resources.getBoolean(R.bool.def_route_preload_hidden));
List<File> files = FileList.getFileListing(new File(application.dataPath), new AutoloadedRouteFilenameFilter());
for (File file : files)
{
List<Route> routes = null;
try
{
String lc = file.getName().toLowerCase();
if (lc.endsWith(".rt2") || lc.endsWith(".rte"))
{
routes = OziExplorerFiles.loadRoutesFromFile(file, application.charset);
}
else if (lc.endsWith(".kml"))
{
routes = KmlFiles.loadRoutesFromFile(file);
}
else if (lc.endsWith(".gpx"))
{
routes = GpxFiles.loadRoutesFromFile(file);
}
application.addRoutes(routes);
for (Route route : routes)
{
route.show = !hide;
RouteOverlay newRoute = new RouteOverlay(Splash.this, route);
application.routeOverlays.add(newRoute);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
total += PROGRESS_STEP;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
// load maps if no any found
if (mapdir.list().length == 0)
{
wait = true;
msg = mHandler.obtainMessage(MSG_ASK);
b = new Bundle();
b.putString("message", getString(R.string.nomaps_explained, application.getMapPath()));
msg.setData(b);
mHandler.sendMessage(msg);
while (wait)
{
try
{
sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
if (result == RES_YES)
{
try
{
// URL u = new URL("http://androzic.googlecode.com/files/world.ozfx3");
URL u = new URL("https://docs.google.com/uc?export=download&id=0Bxnm5oGXU2cja2lQMzVvWFNpZjQ");
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File(application.getMapPath(), "world.ozf2"));
InputStream in = c.getInputStream();
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_loadingimagefile));
msg.setData(b);
mHandler.sendMessage(msg);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) > 0)
{
f.write(buffer, 0, len);
total += len;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
}
f.close();
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_loadingmapfile));
msg.setData(b);
mHandler.sendMessage(msg);
// u = new URL("http://androzic.googlecode.com/files/world.map");
u = new URL("https://docs.google.com/uc?export=download&id=0Bxnm5oGXU2cjWllteG4tSDBxekU");
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
f = new FileOutputStream(new File(application.getMapPath(), "world.map"));
in = c.getInputStream();
buffer = new byte[1024];
len = 0;
while ((len = in.read(buffer)) > 0)
{
f.write(buffer, 0, len);
total += len;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
}
f.close();
}
catch (IOException e)
{
e.printStackTrace();
msg = mHandler.obtainMessage(MSG_ERROR);
b = new Bundle();
b.putString("message", getString(R.string.err_noconnection));
msg.setData(b);
mHandler.sendMessage(msg);
File dir = new File(application.getMapPath());
File[] files = dir.listFiles();
if (files != null)
{
for (int i = 0; i < files.length; i++)
{
files[i].delete();
}
}
return;
}
}
}
else
{
total += DOWNLOAD_SIZE;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
}
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_initializingmaps));
msg.setData(b);
mHandler.sendMessage(msg);
// initialize maps
application.initializeMaps();
total += PROGRESS_STEP;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_initializingplugins));
msg.setData(b);
mHandler.sendMessage(msg);
// initialize plugins
application.initializePlugins();
total += PROGRESS_STEP;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_initializingview));
msg.setData(b);
mHandler.sendMessage(msg);
// initialize current map
application.initializeMapCenter();
total += PROGRESS_STEP;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
mHandler.sendEmptyMessage(MSG_FINISH);
}
}
@Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.yes:
result = RES_YES;
break;
case R.id.no:
result = RES_NO;
break;
case R.id.quit:
finish();
break;
}
gotit.setVisibility(View.GONE);
yes.setVisibility(View.GONE);
no.setVisibility(View.GONE);
progress.setVisibility(View.VISIBLE);
message.setText(savedMessage);
wait = false;
}
}
| true | true | public void run()
{
while (wait)
{
try
{
sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
total = 0;
Message msg = mHandler.obtainMessage(MSG_STATUS);
Bundle b = new Bundle();
b.putString("message", getString(R.string.msg_initializingdata));
msg.setData(b);
mHandler.sendMessage(msg);
Resources resources = getResources();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(Splash.this);
// start location service
application.enableLocating(settings.getBoolean(getString(R.string.lc_locate), true));
// set root folder and check if it has to be created
String rootPath = settings.getString(getString(R.string.pref_folder_root), Environment.getExternalStorageDirectory() + File.separator + resources.getString(R.string.def_folder_prefix));
File root = new File(rootPath);
if (!root.exists())
{
try
{
root.mkdirs();
File nomedia = new File(root, ".nomedia");
nomedia.createNewFile();
}
catch (IOException e)
{
msg = mHandler.obtainMessage(MSG_ERROR);
b = new Bundle();
b.putString("message", getString(R.string.err_nosdcard));
msg.setData(b);
mHandler.sendMessage(msg);
return;
}
}
// check maps folder existence
File mapdir = new File(settings.getString(getString(R.string.pref_folder_map), Environment.getExternalStorageDirectory() + File.separator + resources.getString(R.string.def_folder_map)));
String oldmap = settings.getString(getString(R.string.pref_folder_map_old), null);
if (oldmap != null)
{
File oldmapdir = new File(root, oldmap);
if (!oldmapdir.equals(mapdir))
{
mapdir = oldmapdir;
Editor editor = settings.edit();
editor.putString(getString(R.string.pref_folder_map), mapdir.getAbsolutePath());
editor.putString(getString(R.string.pref_folder_map_old), null);
editor.commit();
}
}
if (!mapdir.exists())
{
mapdir.mkdirs();
}
// check data folder existence
File datadir = new File(
settings.getString(getString(R.string.pref_folder_data), Environment.getExternalStorageDirectory() + File.separator + resources.getString(R.string.def_folder_data)));
if (!datadir.exists())
{
// check if there was an old data structure
String wptdir = settings.getString(getString(R.string.pref_folder_waypoint), null);
System.err.println("wpt: " + wptdir);
if (wptdir != null)
{
wait = true;
msg = mHandler.obtainMessage(MSG_SAY);
b = new Bundle();
b.putString("message", getString(R.string.msg_newdatafolder, datadir.getAbsolutePath()));
msg.setData(b);
mHandler.sendMessage(msg);
while (wait)
{
try
{
sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
datadir.mkdirs();
}
// check icons folder existence
File iconsdir = new File(settings.getString(getString(R.string.pref_folder_icon),
Environment.getExternalStorageDirectory() + File.separator + resources.getString(R.string.def_folder_icon)));
if (!iconsdir.exists())
{
iconsdir.mkdirs();
application.copyAssets("icons", iconsdir);
}
// initialize paths
application.setRootPath(root.getAbsolutePath());
application.setMapPath(mapdir.getAbsolutePath());
application.setDataPath(Androzic.PATH_DATA, datadir.getAbsolutePath());
application.setDataPath(Androzic.PATH_ICONS, iconsdir.getAbsolutePath());
// initialize data
application.installData();
// start tracking service
application.enableTracking(settings.getBoolean(getString(R.string.lc_track), true));
// read default waypoints
File wptFile = new File(application.dataPath, "myWaypoints.wpt");
if (wptFile.exists() && wptFile.canRead())
{
try
{
application.addWaypoints(OziExplorerFiles.loadWaypointsFromFile(wptFile, application.charset));
}
catch (IOException e)
{
e.printStackTrace();
}
}
// read track tail
if (settings.getBoolean(getString(R.string.pref_showcurrenttrack), true))
{
application.currentTrackOverlay = new CurrentTrackOverlay(Splash.this);
if (settings.getBoolean(getString(R.string.pref_tracking_currentload), resources.getBoolean(R.bool.def_tracking_currentload)))
{
int length = Integer.parseInt(settings.getString(getString(R.string.pref_tracking_currentlength), getString(R.string.def_tracking_currentlength)));
// TODO Move this to proper class
File path = new File(application.dataPath, "myTrack.db");
try
{
SQLiteDatabase trackDB = SQLiteDatabase.openDatabase(path.getAbsolutePath(), null, SQLiteDatabase.OPEN_READONLY | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
Cursor cursor = trackDB.rawQuery("SELECT * FROM track ORDER BY _id DESC LIMIT " + length, null);
if (cursor.getCount() > 0)
{
Track track = new Track();
for (boolean hasItem = cursor.moveToLast(); hasItem; hasItem = cursor.moveToPrevious())
{
double latitude = cursor.getDouble(cursor.getColumnIndex("latitude"));
double longitude = cursor.getDouble(cursor.getColumnIndex("longitude"));
double altitude = cursor.getDouble(cursor.getColumnIndex("elevation"));
double speed = cursor.getDouble(cursor.getColumnIndex("speed"));
double bearing = cursor.getDouble(cursor.getColumnIndex("track"));
double accuracy = cursor.getDouble(cursor.getColumnIndex("accuracy"));
int code = cursor.getInt(cursor.getColumnIndex("code"));
long time = cursor.getLong(cursor.getColumnIndex("datetime"));
track.addPoint(code == 0, latitude, longitude, altitude, speed, bearing, accuracy, time);
}
track.show = true;
application.currentTrackOverlay.setTrack(track);
}
cursor.close();
trackDB.close();
}
catch (Exception e)
{
Log.e("Splash", "Read track tail", e);
}
}
}
// load routes
if (settings.getBoolean(getString(R.string.pref_route_preload), resources.getBoolean(R.bool.def_route_preload)))
{
boolean hide = settings.getBoolean(getString(R.string.pref_route_preload_hidden), resources.getBoolean(R.bool.def_route_preload_hidden));
List<File> files = FileList.getFileListing(new File(application.dataPath), new AutoloadedRouteFilenameFilter());
for (File file : files)
{
List<Route> routes = null;
try
{
String lc = file.getName().toLowerCase();
if (lc.endsWith(".rt2") || lc.endsWith(".rte"))
{
routes = OziExplorerFiles.loadRoutesFromFile(file, application.charset);
}
else if (lc.endsWith(".kml"))
{
routes = KmlFiles.loadRoutesFromFile(file);
}
else if (lc.endsWith(".gpx"))
{
routes = GpxFiles.loadRoutesFromFile(file);
}
application.addRoutes(routes);
for (Route route : routes)
{
route.show = !hide;
RouteOverlay newRoute = new RouteOverlay(Splash.this, route);
application.routeOverlays.add(newRoute);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
total += PROGRESS_STEP;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
// load maps if no any found
if (mapdir.list().length == 0)
{
wait = true;
msg = mHandler.obtainMessage(MSG_ASK);
b = new Bundle();
b.putString("message", getString(R.string.nomaps_explained, application.getMapPath()));
msg.setData(b);
mHandler.sendMessage(msg);
while (wait)
{
try
{
sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
if (result == RES_YES)
{
try
{
// URL u = new URL("http://androzic.googlecode.com/files/world.ozfx3");
URL u = new URL("https://docs.google.com/uc?export=download&id=0Bxnm5oGXU2cja2lQMzVvWFNpZjQ");
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File(application.getMapPath(), "world.ozf2"));
InputStream in = c.getInputStream();
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_loadingimagefile));
msg.setData(b);
mHandler.sendMessage(msg);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) > 0)
{
f.write(buffer, 0, len);
total += len;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
}
f.close();
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_loadingmapfile));
msg.setData(b);
mHandler.sendMessage(msg);
// u = new URL("http://androzic.googlecode.com/files/world.map");
u = new URL("https://docs.google.com/uc?export=download&id=0Bxnm5oGXU2cjWllteG4tSDBxekU");
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
f = new FileOutputStream(new File(application.getMapPath(), "world.map"));
in = c.getInputStream();
buffer = new byte[1024];
len = 0;
while ((len = in.read(buffer)) > 0)
{
f.write(buffer, 0, len);
total += len;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
}
f.close();
}
catch (IOException e)
{
e.printStackTrace();
msg = mHandler.obtainMessage(MSG_ERROR);
b = new Bundle();
b.putString("message", getString(R.string.err_noconnection));
msg.setData(b);
mHandler.sendMessage(msg);
File dir = new File(application.getMapPath());
File[] files = dir.listFiles();
if (files != null)
{
for (int i = 0; i < files.length; i++)
{
files[i].delete();
}
}
return;
}
}
}
else
{
total += DOWNLOAD_SIZE;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
}
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_initializingmaps));
msg.setData(b);
mHandler.sendMessage(msg);
// initialize maps
application.initializeMaps();
total += PROGRESS_STEP;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_initializingplugins));
msg.setData(b);
mHandler.sendMessage(msg);
// initialize plugins
application.initializePlugins();
total += PROGRESS_STEP;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_initializingview));
msg.setData(b);
mHandler.sendMessage(msg);
// initialize current map
application.initializeMapCenter();
total += PROGRESS_STEP;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
mHandler.sendEmptyMessage(MSG_FINISH);
}
| public void run()
{
while (wait)
{
try
{
sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
total = 0;
Message msg = mHandler.obtainMessage(MSG_STATUS);
Bundle b = new Bundle();
b.putString("message", getString(R.string.msg_initializingdata));
msg.setData(b);
mHandler.sendMessage(msg);
Resources resources = getResources();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(Splash.this);
// start location service
application.enableLocating(settings.getBoolean(getString(R.string.lc_locate), true));
// set root folder and check if it has to be created
String rootPath = settings.getString(getString(R.string.pref_folder_root), Environment.getExternalStorageDirectory() + File.separator + resources.getString(R.string.def_folder_prefix));
File root = new File(rootPath);
if (!root.exists())
{
try
{
root.mkdirs();
File nomedia = new File(root, ".nomedia");
nomedia.createNewFile();
}
catch (IOException e)
{
msg = mHandler.obtainMessage(MSG_ERROR);
b = new Bundle();
b.putString("message", getString(R.string.err_nosdcard));
msg.setData(b);
mHandler.sendMessage(msg);
return;
}
}
// check maps folder existence
File mapdir = new File(settings.getString(getString(R.string.pref_folder_map), Environment.getExternalStorageDirectory() + File.separator + resources.getString(R.string.def_folder_map)));
String oldmap = settings.getString(getString(R.string.pref_folder_map_old), null);
if (oldmap != null)
{
File oldmapdir = new File(root, oldmap);
if (!oldmapdir.equals(mapdir))
{
mapdir = oldmapdir;
Editor editor = settings.edit();
editor.putString(getString(R.string.pref_folder_map), mapdir.getAbsolutePath());
editor.putString(getString(R.string.pref_folder_map_old), null);
editor.commit();
}
}
if (!mapdir.exists())
{
mapdir.mkdirs();
}
// check data folder existence
File datadir = new File(
settings.getString(getString(R.string.pref_folder_data), Environment.getExternalStorageDirectory() + File.separator + resources.getString(R.string.def_folder_data)));
if (!datadir.exists())
{
// check if there was an old data structure
String wptdir = settings.getString(getString(R.string.pref_folder_waypoint), null);
System.err.println("wpt: " + wptdir);
if (wptdir != null)
{
wait = true;
msg = mHandler.obtainMessage(MSG_SAY);
b = new Bundle();
b.putString("message", getString(R.string.msg_newdatafolder, datadir.getAbsolutePath()));
msg.setData(b);
mHandler.sendMessage(msg);
while (wait)
{
try
{
sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
datadir.mkdirs();
}
// check icons folder existence
File iconsdir = new File(settings.getString(getString(R.string.pref_folder_icon),
Environment.getExternalStorageDirectory() + File.separator + resources.getString(R.string.def_folder_icon)));
if (!iconsdir.exists())
{
try
{
iconsdir.mkdirs();
File nomedia = new File(iconsdir, ".nomedia");
nomedia.createNewFile();
application.copyAssets("icons", iconsdir);
}
catch (IOException e)
{
e.printStackTrace();
}
}
// initialize paths
application.setRootPath(root.getAbsolutePath());
application.setMapPath(mapdir.getAbsolutePath());
application.setDataPath(Androzic.PATH_DATA, datadir.getAbsolutePath());
application.setDataPath(Androzic.PATH_ICONS, iconsdir.getAbsolutePath());
// initialize data
application.installData();
// start tracking service
application.enableTracking(settings.getBoolean(getString(R.string.lc_track), true));
// read default waypoints
File wptFile = new File(application.dataPath, "myWaypoints.wpt");
if (wptFile.exists() && wptFile.canRead())
{
try
{
application.addWaypoints(OziExplorerFiles.loadWaypointsFromFile(wptFile, application.charset));
}
catch (IOException e)
{
e.printStackTrace();
}
}
// read track tail
if (settings.getBoolean(getString(R.string.pref_showcurrenttrack), true))
{
application.currentTrackOverlay = new CurrentTrackOverlay(Splash.this);
if (settings.getBoolean(getString(R.string.pref_tracking_currentload), resources.getBoolean(R.bool.def_tracking_currentload)))
{
int length = Integer.parseInt(settings.getString(getString(R.string.pref_tracking_currentlength), getString(R.string.def_tracking_currentlength)));
// TODO Move this to proper class
File path = new File(application.dataPath, "myTrack.db");
try
{
SQLiteDatabase trackDB = SQLiteDatabase.openDatabase(path.getAbsolutePath(), null, SQLiteDatabase.OPEN_READONLY | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
Cursor cursor = trackDB.rawQuery("SELECT * FROM track ORDER BY _id DESC LIMIT " + length, null);
if (cursor.getCount() > 0)
{
Track track = new Track();
for (boolean hasItem = cursor.moveToLast(); hasItem; hasItem = cursor.moveToPrevious())
{
double latitude = cursor.getDouble(cursor.getColumnIndex("latitude"));
double longitude = cursor.getDouble(cursor.getColumnIndex("longitude"));
double altitude = cursor.getDouble(cursor.getColumnIndex("elevation"));
double speed = cursor.getDouble(cursor.getColumnIndex("speed"));
double bearing = cursor.getDouble(cursor.getColumnIndex("track"));
double accuracy = cursor.getDouble(cursor.getColumnIndex("accuracy"));
int code = cursor.getInt(cursor.getColumnIndex("code"));
long time = cursor.getLong(cursor.getColumnIndex("datetime"));
track.addPoint(code == 0, latitude, longitude, altitude, speed, bearing, accuracy, time);
}
track.show = true;
application.currentTrackOverlay.setTrack(track);
}
cursor.close();
trackDB.close();
}
catch (Exception e)
{
Log.e("Splash", "Read track tail", e);
}
}
}
// load routes
if (settings.getBoolean(getString(R.string.pref_route_preload), resources.getBoolean(R.bool.def_route_preload)))
{
boolean hide = settings.getBoolean(getString(R.string.pref_route_preload_hidden), resources.getBoolean(R.bool.def_route_preload_hidden));
List<File> files = FileList.getFileListing(new File(application.dataPath), new AutoloadedRouteFilenameFilter());
for (File file : files)
{
List<Route> routes = null;
try
{
String lc = file.getName().toLowerCase();
if (lc.endsWith(".rt2") || lc.endsWith(".rte"))
{
routes = OziExplorerFiles.loadRoutesFromFile(file, application.charset);
}
else if (lc.endsWith(".kml"))
{
routes = KmlFiles.loadRoutesFromFile(file);
}
else if (lc.endsWith(".gpx"))
{
routes = GpxFiles.loadRoutesFromFile(file);
}
application.addRoutes(routes);
for (Route route : routes)
{
route.show = !hide;
RouteOverlay newRoute = new RouteOverlay(Splash.this, route);
application.routeOverlays.add(newRoute);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
total += PROGRESS_STEP;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
// load maps if no any found
if (mapdir.list().length == 0)
{
wait = true;
msg = mHandler.obtainMessage(MSG_ASK);
b = new Bundle();
b.putString("message", getString(R.string.nomaps_explained, application.getMapPath()));
msg.setData(b);
mHandler.sendMessage(msg);
while (wait)
{
try
{
sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
if (result == RES_YES)
{
try
{
// URL u = new URL("http://androzic.googlecode.com/files/world.ozfx3");
URL u = new URL("https://docs.google.com/uc?export=download&id=0Bxnm5oGXU2cja2lQMzVvWFNpZjQ");
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File(application.getMapPath(), "world.ozf2"));
InputStream in = c.getInputStream();
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_loadingimagefile));
msg.setData(b);
mHandler.sendMessage(msg);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) > 0)
{
f.write(buffer, 0, len);
total += len;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
}
f.close();
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_loadingmapfile));
msg.setData(b);
mHandler.sendMessage(msg);
// u = new URL("http://androzic.googlecode.com/files/world.map");
u = new URL("https://docs.google.com/uc?export=download&id=0Bxnm5oGXU2cjWllteG4tSDBxekU");
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
f = new FileOutputStream(new File(application.getMapPath(), "world.map"));
in = c.getInputStream();
buffer = new byte[1024];
len = 0;
while ((len = in.read(buffer)) > 0)
{
f.write(buffer, 0, len);
total += len;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
}
f.close();
}
catch (IOException e)
{
e.printStackTrace();
msg = mHandler.obtainMessage(MSG_ERROR);
b = new Bundle();
b.putString("message", getString(R.string.err_noconnection));
msg.setData(b);
mHandler.sendMessage(msg);
File dir = new File(application.getMapPath());
File[] files = dir.listFiles();
if (files != null)
{
for (int i = 0; i < files.length; i++)
{
files[i].delete();
}
}
return;
}
}
}
else
{
total += DOWNLOAD_SIZE;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
}
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_initializingmaps));
msg.setData(b);
mHandler.sendMessage(msg);
// initialize maps
application.initializeMaps();
total += PROGRESS_STEP;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_initializingplugins));
msg.setData(b);
mHandler.sendMessage(msg);
// initialize plugins
application.initializePlugins();
total += PROGRESS_STEP;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_initializingview));
msg.setData(b);
mHandler.sendMessage(msg);
// initialize current map
application.initializeMapCenter();
total += PROGRESS_STEP;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
mHandler.sendEmptyMessage(MSG_FINISH);
}
|
diff --git a/test/org/openstreetmap/osmosis/core/apidb/v0_6/impl/DatabaseUtilities.java b/test/org/openstreetmap/osmosis/core/apidb/v0_6/impl/DatabaseUtilities.java
index d53215c4..55a7cc83 100644
--- a/test/org/openstreetmap/osmosis/core/apidb/v0_6/impl/DatabaseUtilities.java
+++ b/test/org/openstreetmap/osmosis/core/apidb/v0_6/impl/DatabaseUtilities.java
@@ -1,76 +1,76 @@
// This software is released into the Public Domain. See copying.txt for details.
package org.openstreetmap.osmosis.core.apidb.v0_6.impl;
import java.io.File;
import org.openstreetmap.osmosis.core.Osmosis;
import org.openstreetmap.osmosis.core.apidb.common.DatabaseContext;
import org.openstreetmap.osmosis.core.database.AuthenticationPropertiesLoader;
import org.openstreetmap.osmosis.core.database.DatabaseConstants;
import org.openstreetmap.osmosis.core.database.DatabaseLoginCredentials;
import data.util.DataFileUtilities;
/**
* Contains re-usable functionality for manipulating the database during tests.
*
* @author Brett Henderson
*/
public class DatabaseUtilities {
private static final String AUTHFILE = "v0_6/apidb-authfile.txt";
private static final String AUTHFILE_PROPERTY = "db.apidb.authfile";
private DataFileUtilities fileUtils;
/**
* Creates a new instance.
*/
public DatabaseUtilities() {
fileUtils = new DataFileUtilities();
}
/**
* Creates a new database context pointing at the test database.
*
* @return A fully configured database context.
*/
public DatabaseContext createDatabaseContext() {
AuthenticationPropertiesLoader credentialsLoader;
DatabaseLoginCredentials credentials;
credentials = new DatabaseLoginCredentials(DatabaseConstants.TASK_DEFAULT_HOST,
DatabaseConstants.TASK_DEFAULT_DATABASE, DatabaseConstants.TASK_DEFAULT_USER,
DatabaseConstants.TASK_DEFAULT_PASSWORD, DatabaseConstants.TASK_DEFAULT_FORCE_UTF8,
DatabaseConstants.TASK_DEFAULT_PROFILE_SQL, DatabaseConstants.TASK_DEFAULT_DB_TYPE);
- credentialsLoader = new AuthenticationPropertiesLoader(fileUtils.getDataFile("v0_6/apidb-authfile.txt"));
+ credentialsLoader = new AuthenticationPropertiesLoader(getAuthorizationFile());
credentialsLoader.updateLoginCredentials(credentials);
return new DatabaseContext(credentials);
}
/**
* Removes all data from the database.
*/
public void truncateDatabase() {
// Remove all existing data from the database.
Osmosis.run(new String[] {
"-q",
"--truncate-apidb-0.6",
"authFile=" + getAuthorizationFile().getPath(),
"allowIncorrectSchemaVersion=true"
});
}
/**
* Returns the location of the database authorization file.
*
* @return The authorization file.
*/
public File getAuthorizationFile() {
return fileUtils.getDataFile(AUTHFILE_PROPERTY, AUTHFILE);
}
}
| true | true | public DatabaseContext createDatabaseContext() {
AuthenticationPropertiesLoader credentialsLoader;
DatabaseLoginCredentials credentials;
credentials = new DatabaseLoginCredentials(DatabaseConstants.TASK_DEFAULT_HOST,
DatabaseConstants.TASK_DEFAULT_DATABASE, DatabaseConstants.TASK_DEFAULT_USER,
DatabaseConstants.TASK_DEFAULT_PASSWORD, DatabaseConstants.TASK_DEFAULT_FORCE_UTF8,
DatabaseConstants.TASK_DEFAULT_PROFILE_SQL, DatabaseConstants.TASK_DEFAULT_DB_TYPE);
credentialsLoader = new AuthenticationPropertiesLoader(fileUtils.getDataFile("v0_6/apidb-authfile.txt"));
credentialsLoader.updateLoginCredentials(credentials);
return new DatabaseContext(credentials);
}
| public DatabaseContext createDatabaseContext() {
AuthenticationPropertiesLoader credentialsLoader;
DatabaseLoginCredentials credentials;
credentials = new DatabaseLoginCredentials(DatabaseConstants.TASK_DEFAULT_HOST,
DatabaseConstants.TASK_DEFAULT_DATABASE, DatabaseConstants.TASK_DEFAULT_USER,
DatabaseConstants.TASK_DEFAULT_PASSWORD, DatabaseConstants.TASK_DEFAULT_FORCE_UTF8,
DatabaseConstants.TASK_DEFAULT_PROFILE_SQL, DatabaseConstants.TASK_DEFAULT_DB_TYPE);
credentialsLoader = new AuthenticationPropertiesLoader(getAuthorizationFile());
credentialsLoader.updateLoginCredentials(credentials);
return new DatabaseContext(credentials);
}
|
diff --git a/src/net/eliosoft/elios/gui/views/LogsViewHelper.java b/src/net/eliosoft/elios/gui/views/LogsViewHelper.java
index cd14aaa..5936099 100644
--- a/src/net/eliosoft/elios/gui/views/LogsViewHelper.java
+++ b/src/net/eliosoft/elios/gui/views/LogsViewHelper.java
@@ -1,76 +1,78 @@
package net.eliosoft.elios.gui.views;
import java.awt.Color;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import javax.swing.JLabel;
/**
* Helper class for building and decorate components which display log
* information.
*
* @author acollign
* @since Feb 2, 2011
*/
public class LogsViewHelper {
/** default text for label. **/
public static final String DEFAULT_TEXT = " ";
/**
* Creates a {@link JLabel} that displays {@link LogRecord} information.
*
* @param record
* the {@link LogRecord} to display
* @return a decorated {@link JLabel} that displays the {@link LogRecord}
* information
*/
public static JLabel createLogsLabel(LogRecord record) {
return LOG_DECORATOR.update(new JLabel(), record);
}
/**
* A {@link LogLabelDecorator} aims to update a {@link JLabel} according to
* a {@link LogRecord}.
*
* @author acollign
* @since Feb 2, 2011
*/
public static interface LogLabelDecorator {
/**
* Update the given label according to the {@link LogRecord} text value
* and states
*
* @param label
* {@link JLabel} that must be decorated
* @param record
* {@link LogRecord} that contains information to display
* @return the given label
*/
JLabel update(JLabel label, LogRecord record);
}
/**
* Default log decorator.
*/
public static final LogLabelDecorator LOG_DECORATOR = new LogLabelDecorator() {
@Override
public JLabel update(JLabel label, LogRecord record) {
if (record == null) {
label.setText(DEFAULT_TEXT);
return label;
}
label.setText("[" + record.getLevel().getName() + "] "
+ record.getMessage());
if (record.getLevel().equals(Level.SEVERE)) {
label.setForeground(Color.RED);
+ } else {
+ label.setForeground(Color.BLACK);
}
return label;
}
};
}
| true | true | public JLabel update(JLabel label, LogRecord record) {
if (record == null) {
label.setText(DEFAULT_TEXT);
return label;
}
label.setText("[" + record.getLevel().getName() + "] "
+ record.getMessage());
if (record.getLevel().equals(Level.SEVERE)) {
label.setForeground(Color.RED);
}
return label;
}
| public JLabel update(JLabel label, LogRecord record) {
if (record == null) {
label.setText(DEFAULT_TEXT);
return label;
}
label.setText("[" + record.getLevel().getName() + "] "
+ record.getMessage());
if (record.getLevel().equals(Level.SEVERE)) {
label.setForeground(Color.RED);
} else {
label.setForeground(Color.BLACK);
}
return label;
}
|
diff --git a/invoice/src/main/java/com/ning/billing/invoice/notification/DefaultNextBillingDateNotifier.java b/invoice/src/main/java/com/ning/billing/invoice/notification/DefaultNextBillingDateNotifier.java
index 1cb11d5c2..e4a72a69a 100644
--- a/invoice/src/main/java/com/ning/billing/invoice/notification/DefaultNextBillingDateNotifier.java
+++ b/invoice/src/main/java/com/ning/billing/invoice/notification/DefaultNextBillingDateNotifier.java
@@ -1,131 +1,131 @@
/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.ning.billing.invoice.notification;
import java.util.UUID;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ning.billing.config.InvoiceConfig;
import com.ning.billing.config.NotificationConfig;
import com.ning.billing.entitlement.api.user.EntitlementUserApiException;
import com.ning.billing.entitlement.api.user.Subscription;
import com.ning.billing.invoice.InvoiceListener;
import com.ning.billing.invoice.api.DefaultInvoiceService;
import com.ning.billing.util.callcontext.InternalCallContextFactory;
import com.ning.billing.util.notificationq.NotificationKey;
import com.ning.billing.util.notificationq.NotificationQueue;
import com.ning.billing.util.notificationq.NotificationQueueService;
import com.ning.billing.util.notificationq.NotificationQueueService.NoSuchNotificationQueue;
import com.ning.billing.util.notificationq.NotificationQueueService.NotificationQueueAlreadyExists;
import com.ning.billing.util.notificationq.NotificationQueueService.NotificationQueueHandler;
import com.ning.billing.util.svcapi.entitlement.EntitlementInternalApi;
import com.google.inject.Inject;
public class DefaultNextBillingDateNotifier implements NextBillingDateNotifier {
private static final Logger log = LoggerFactory.getLogger(DefaultNextBillingDateNotifier.class);
public static final String NEXT_BILLING_DATE_NOTIFIER_QUEUE = "next-billing-date-queue";
private final NotificationQueueService notificationQueueService;
private final InvoiceConfig config;
private final EntitlementInternalApi entitlementApi;
private final InvoiceListener listener;
private final InternalCallContextFactory callContextFactory;
private NotificationQueue nextBillingQueue;
@Inject
public DefaultNextBillingDateNotifier(final NotificationQueueService notificationQueueService,
final InvoiceConfig config,
final EntitlementInternalApi entitlementApi,
final InvoiceListener listener,
final InternalCallContextFactory callContextFactory) {
this.notificationQueueService = notificationQueueService;
this.config = config;
this.entitlementApi = entitlementApi;
this.listener = listener;
this.callContextFactory = callContextFactory;
}
@Override
public void initialize() throws NotificationQueueAlreadyExists {
final NotificationConfig notificationConfig = new NotificationConfig() {
@Override
public long getSleepTimeMs() {
return config.getSleepTimeMs();
}
@Override
public boolean isNotificationProcessingOff() {
return config.isNotificationProcessingOff();
}
};
final NotificationQueueHandler notificationQueueHandler = new NotificationQueueHandler() {
@Override
public void handleReadyNotification(final NotificationKey notificationKey, final DateTime eventDate, final Long accountRecordId, final Long tenantRecordId) {
try {
if (!(notificationKey instanceof NextBillingDateNotificationKey)) {
log.error("Invoice service received an unexpected event type {}", notificationKey.getClass().getName());
return;
}
final NextBillingDateNotificationKey key = (NextBillingDateNotificationKey) notificationKey;
try {
- final Subscription subscription = entitlementApi.getSubscriptionFromId(key.getUuidKey(), callContextFactory.createInternalTenantContext(null));
+ final Subscription subscription = entitlementApi.getSubscriptionFromId(key.getUuidKey(), callContextFactory.createInternalTenantContext(tenantRecordId, accountRecordId));
if (subscription == null) {
log.warn("Next Billing Date Notification Queue handled spurious notification (key: " + key + ")");
} else {
processEvent(key.getUuidKey(), eventDate);
}
} catch (EntitlementUserApiException e) {
log.warn("Next Billing Date Notification Queue handled spurious notification (key: " + key + ")", e);
}
} catch (IllegalArgumentException e) {
log.error("The key returned from the NextBillingNotificationQueue is not a valid UUID", e);
}
}
};
nextBillingQueue = notificationQueueService.createNotificationQueue(DefaultInvoiceService.INVOICE_SERVICE_NAME,
NEXT_BILLING_DATE_NOTIFIER_QUEUE,
notificationQueueHandler,
notificationConfig);
}
@Override
public void start() {
nextBillingQueue.startQueue();
}
@Override
public void stop() throws NoSuchNotificationQueue {
if (nextBillingQueue != null) {
nextBillingQueue.stopQueue();
notificationQueueService.deleteNotificationQueue(nextBillingQueue.getServiceName(), nextBillingQueue.getQueueName());
}
}
private void processEvent(final UUID subscriptionId, final DateTime eventDateTime) {
listener.handleNextBillingDateEvent(subscriptionId, eventDateTime);
}
}
| true | true | public void initialize() throws NotificationQueueAlreadyExists {
final NotificationConfig notificationConfig = new NotificationConfig() {
@Override
public long getSleepTimeMs() {
return config.getSleepTimeMs();
}
@Override
public boolean isNotificationProcessingOff() {
return config.isNotificationProcessingOff();
}
};
final NotificationQueueHandler notificationQueueHandler = new NotificationQueueHandler() {
@Override
public void handleReadyNotification(final NotificationKey notificationKey, final DateTime eventDate, final Long accountRecordId, final Long tenantRecordId) {
try {
if (!(notificationKey instanceof NextBillingDateNotificationKey)) {
log.error("Invoice service received an unexpected event type {}", notificationKey.getClass().getName());
return;
}
final NextBillingDateNotificationKey key = (NextBillingDateNotificationKey) notificationKey;
try {
final Subscription subscription = entitlementApi.getSubscriptionFromId(key.getUuidKey(), callContextFactory.createInternalTenantContext(null));
if (subscription == null) {
log.warn("Next Billing Date Notification Queue handled spurious notification (key: " + key + ")");
} else {
processEvent(key.getUuidKey(), eventDate);
}
} catch (EntitlementUserApiException e) {
log.warn("Next Billing Date Notification Queue handled spurious notification (key: " + key + ")", e);
}
} catch (IllegalArgumentException e) {
log.error("The key returned from the NextBillingNotificationQueue is not a valid UUID", e);
}
}
};
nextBillingQueue = notificationQueueService.createNotificationQueue(DefaultInvoiceService.INVOICE_SERVICE_NAME,
NEXT_BILLING_DATE_NOTIFIER_QUEUE,
notificationQueueHandler,
notificationConfig);
}
| public void initialize() throws NotificationQueueAlreadyExists {
final NotificationConfig notificationConfig = new NotificationConfig() {
@Override
public long getSleepTimeMs() {
return config.getSleepTimeMs();
}
@Override
public boolean isNotificationProcessingOff() {
return config.isNotificationProcessingOff();
}
};
final NotificationQueueHandler notificationQueueHandler = new NotificationQueueHandler() {
@Override
public void handleReadyNotification(final NotificationKey notificationKey, final DateTime eventDate, final Long accountRecordId, final Long tenantRecordId) {
try {
if (!(notificationKey instanceof NextBillingDateNotificationKey)) {
log.error("Invoice service received an unexpected event type {}", notificationKey.getClass().getName());
return;
}
final NextBillingDateNotificationKey key = (NextBillingDateNotificationKey) notificationKey;
try {
final Subscription subscription = entitlementApi.getSubscriptionFromId(key.getUuidKey(), callContextFactory.createInternalTenantContext(tenantRecordId, accountRecordId));
if (subscription == null) {
log.warn("Next Billing Date Notification Queue handled spurious notification (key: " + key + ")");
} else {
processEvent(key.getUuidKey(), eventDate);
}
} catch (EntitlementUserApiException e) {
log.warn("Next Billing Date Notification Queue handled spurious notification (key: " + key + ")", e);
}
} catch (IllegalArgumentException e) {
log.error("The key returned from the NextBillingNotificationQueue is not a valid UUID", e);
}
}
};
nextBillingQueue = notificationQueueService.createNotificationQueue(DefaultInvoiceService.INVOICE_SERVICE_NAME,
NEXT_BILLING_DATE_NOTIFIER_QUEUE,
notificationQueueHandler,
notificationConfig);
}
|
diff --git a/msv/src/com/sun/msv/reader/xmlschema/ComplexTypeDeclState.java b/msv/src/com/sun/msv/reader/xmlschema/ComplexTypeDeclState.java
index 80b212a2..f22842b9 100644
--- a/msv/src/com/sun/msv/reader/xmlschema/ComplexTypeDeclState.java
+++ b/msv/src/com/sun/msv/reader/xmlschema/ComplexTypeDeclState.java
@@ -1,101 +1,101 @@
package com.sun.tranquilo.reader.xmlschema;
import com.sun.tranquilo.datatype.DataType;
import com.sun.tranquilo.grammar.Expression;
import com.sun.tranquilo.grammar.SimpleNameClass;
import com.sun.tranquilo.grammar.xmlschema.ComplexTypeExp;
import com.sun.tranquilo.util.StartTagInfo;
import com.sun.tranquilo.reader.State;
import com.sun.tranquilo.reader.ExpressionWithChildState;
public class ComplexTypeDeclState extends ExpressionWithChildState {
protected final boolean isGlobal;
protected ComplexTypeDeclState( boolean isGlobal ) {
this.isGlobal = isGlobal;
}
protected ComplexTypeExp decl;
protected void startSelf() {
super.startSelf();
final XMLSchemaReader reader = (XMLSchemaReader)this.reader;
String name = startTag.getAttribute("name");
if( name==null ) {
if( isGlobal )
reader.reportError( reader.ERR_MISSING_ATTRIBUTE, "complexType", "name" );
decl = new ComplexTypeExp( reader.currentSchema, null );
} else {
decl = reader.currentSchema.complexTypes.getOrCreate(name);
reader.setDeclaredLocationOf(decl);
}
}
protected State createChildState( StartTagInfo tag ) {
final XMLSchemaReader reader = (XMLSchemaReader)this.reader;
// simpleContent, ComplexContent, group, all, choice, and sequence
// are allowed only when we haven't seen type definition.
if(tag.localName.equals("simpleContent") ) return reader.sfactory.simpleContent(this,tag);
if(tag.localName.equals("complexContent") ) return reader.sfactory.complexContent(this,tag,decl);
State s = reader.createModelGroupState(this,tag);
if(s!=null) return s;
if( super.exp==null ) {
// no content model was given.
// I couldn't "decipher" what should we do in this case.
// I assume "empty" just because it's most likely.
exp = Expression.epsilon;
}
// TODO: attributes are prohibited after simpleContent/complexContent.
// attribute, attributeGroup, and anyAttribtue can be specified
// after content model is given.
return reader.createAttributeState(this,tag);
}
protected Expression castExpression( Expression halfCastedExpression, Expression newChildExpression ) {
if( halfCastedExpression==null )
return newChildExpression; // the first one
// only the first one contains element.
// the rest consists of attributes.
// so this order of parameters is fine.
return reader.pool.createSequence( newChildExpression, halfCastedExpression );
}
protected Expression annealExpression(Expression contentType) {
final XMLSchemaReader reader = (XMLSchemaReader)this.reader;
// String targetNamespace = reader.grammar.targetNamespace;
String abstract_ = startTag.getAttribute("abstract");
- if( "false".equals(abstract_) )
+ if( "false".equals(abstract_) || abstract_==null )
// allow content model to directly appear as this type.
decl.exp = reader.pool.createChoice( decl.self, decl.exp );
else
- if( abstract_!=null && !"true".equals(abstract_) )
+ if( !"true".equals(abstract_) )
reader.reportError( reader.ERR_BAD_ATTRIBUTE_VALUE, "abstract", abstract_ );
// recover by ignoring this error.
// TODO: @block
// TODO: @final
String mixed = startTag.getAttribute("mixed");
if( "true".equals(mixed) )
contentType = reader.pool.createMixed(contentType);
else
if( mixed!=null && !"false".equals(mixed) )
reader.reportError( reader.ERR_BAD_ATTRIBUTE_VALUE, "mixed", mixed );
// recover by ignoring this error.
decl.self.exp = contentType;
return decl;
}
}
| false | true | protected Expression annealExpression(Expression contentType) {
final XMLSchemaReader reader = (XMLSchemaReader)this.reader;
// String targetNamespace = reader.grammar.targetNamespace;
String abstract_ = startTag.getAttribute("abstract");
if( "false".equals(abstract_) )
// allow content model to directly appear as this type.
decl.exp = reader.pool.createChoice( decl.self, decl.exp );
else
if( abstract_!=null && !"true".equals(abstract_) )
reader.reportError( reader.ERR_BAD_ATTRIBUTE_VALUE, "abstract", abstract_ );
// recover by ignoring this error.
// TODO: @block
// TODO: @final
String mixed = startTag.getAttribute("mixed");
if( "true".equals(mixed) )
contentType = reader.pool.createMixed(contentType);
else
if( mixed!=null && !"false".equals(mixed) )
reader.reportError( reader.ERR_BAD_ATTRIBUTE_VALUE, "mixed", mixed );
// recover by ignoring this error.
decl.self.exp = contentType;
return decl;
}
| protected Expression annealExpression(Expression contentType) {
final XMLSchemaReader reader = (XMLSchemaReader)this.reader;
// String targetNamespace = reader.grammar.targetNamespace;
String abstract_ = startTag.getAttribute("abstract");
if( "false".equals(abstract_) || abstract_==null )
// allow content model to directly appear as this type.
decl.exp = reader.pool.createChoice( decl.self, decl.exp );
else
if( !"true".equals(abstract_) )
reader.reportError( reader.ERR_BAD_ATTRIBUTE_VALUE, "abstract", abstract_ );
// recover by ignoring this error.
// TODO: @block
// TODO: @final
String mixed = startTag.getAttribute("mixed");
if( "true".equals(mixed) )
contentType = reader.pool.createMixed(contentType);
else
if( mixed!=null && !"false".equals(mixed) )
reader.reportError( reader.ERR_BAD_ATTRIBUTE_VALUE, "mixed", mixed );
// recover by ignoring this error.
decl.self.exp = contentType;
return decl;
}
|
diff --git a/src/main/java/me/eccentric_nz/TARDIS/commands/TARDISTravelCommands.java b/src/main/java/me/eccentric_nz/TARDIS/commands/TARDISTravelCommands.java
index 3a6b134fe..65ef54ddc 100644
--- a/src/main/java/me/eccentric_nz/TARDIS/commands/TARDISTravelCommands.java
+++ b/src/main/java/me/eccentric_nz/TARDIS/commands/TARDISTravelCommands.java
@@ -1,257 +1,261 @@
/*
* Copyright (C) 2012 eccentric_nz
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package me.eccentric_nz.TARDIS.commands;
import java.util.HashMap;
import me.eccentric_nz.TARDIS.TARDIS;
import me.eccentric_nz.TARDIS.TARDISConstants;
import me.eccentric_nz.TARDIS.database.QueryFactory;
import me.eccentric_nz.TARDIS.database.ResultSetAreas;
import me.eccentric_nz.TARDIS.database.ResultSetDestinations;
import me.eccentric_nz.TARDIS.database.ResultSetTardis;
import me.eccentric_nz.TARDIS.database.ResultSetTravellers;
import me.eccentric_nz.TARDIS.travel.TARDISPluginRespect;
import me.eccentric_nz.TARDIS.travel.TARDISTimetravel;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/**
* Time travel is the process of travelling through time, even in a non-linear
* direction.
*
* @author eccentric_nz
*/
public class TARDISTravelCommands implements CommandExecutor {
private TARDIS plugin;
private TARDISPluginRespect respect;
public TARDISTravelCommands(TARDIS plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
// If the player typed /tardis then do the following...
// check there is the right number of arguments
if (cmd.getName().equalsIgnoreCase("tardistravel")) {
if (player == null) {
sender.sendMessage(plugin.pluginName + ChatColor.RED + " This command can only be run by a player");
return true;
}
if (player.hasPermission("tardis.timetravel")) {
if (args.length < 1) {
sender.sendMessage(plugin.pluginName + "Too few command arguments!");
return false;
}
QueryFactory qf = new QueryFactory(plugin);
TARDISTimetravel tt = new TARDISTimetravel(plugin);
// get tardis data
HashMap<String, Object> where = new HashMap<String, Object>();
where.put("owner", player.getName());
ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false);
if (!rs.resultSet()) {
sender.sendMessage(plugin.pluginName + "You are not a Timelord. You need to create a TARDIS before using this command!");
return true;
}
if (!rs.isHandbrake_on()) {
player.sendMessage(plugin.pluginName + ChatColor.RED + "You cannot set a destination while the TARDIS is travelling!");
return true;
}
HashMap<String, Object> wheret = new HashMap<String, Object>();
wheret.put("player", player.getName());
ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false);
if (!rst.resultSet()) {
sender.sendMessage(plugin.pluginName + "You are not inside the TARDIS. You need to be to run this command!");
return true;
}
int tardis_id = rst.getTardis_id();
int id = rs.getTardis_id();
if (tardis_id != id) {
sender.sendMessage(plugin.pluginName + "You can only run this command if you are the Timelord of " + ChatColor.LIGHT_PURPLE + "this" + ChatColor.RESET + " TARDIS!");
return true;
}
int level = rs.getArtron_level();
int travel = plugin.getConfig().getInt("travel");
if (level < travel) {
player.sendMessage(plugin.pluginName + ChatColor.RED + "The TARDIS does not have enough Artron Energy to make this trip!");
return true;
}
TARDISConstants.COMPASS d = rs.getDirection();
String home = rs.getHome();
HashMap<String, Object> tid = new HashMap<String, Object>();
HashMap<String, Object> set = new HashMap<String, Object>();
tid.put("tardis_id", id);
if (player.hasPermission("tardis.exile")) {
// get the exile area
String permArea = plugin.ta.getExileArea(player);
player.sendMessage(plugin.pluginName + ChatColor.RED + " Notice:" + ChatColor.RESET + " Your travel has been restricted to the [" + permArea + "] area!");
Location l = plugin.ta.getNextSpot(permArea);
if (l == null) {
player.sendMessage(plugin.pluginName + "All available parking spots are taken in this area!");
return true;
}
String save_loc = l.getWorld().getName() + ":" + l.getBlockX() + ":" + l.getBlockY() + ":" + l.getBlockZ();
set.put("save", save_loc);
qf.doUpdate("tardis", set, tid);
player.sendMessage(plugin.pluginName + "Your TARDIS was approved for parking in [" + permArea + "]!");
plugin.tardisHasDestination.put(id, travel);
return true;
} else {
if (args.length == 1) {
// we're thinking this is a player's name or home
if (args[0].equalsIgnoreCase("home")) {
set.put("save", home);
qf.doUpdate("tardis", set, tid);
sender.sendMessage(plugin.pluginName + "Home location loaded succesfully. Please release the handbrake!");
plugin.utils.updateTravellerCount(id);
plugin.tardisHasDestination.put(id, travel);
return true;
} else {
if (player.hasPermission("tardis.timetravel.player")) {
if (plugin.getServer().getPlayer(args[0]) == null) {
sender.sendMessage(plugin.pluginName + "That player is not online!");
return true;
}
Player destPlayer = plugin.getServer().getPlayer(args[0]);
Location player_loc = destPlayer.getLocation();
World w = player_loc.getWorld();
int[] start_loc = tt.getStartLocation(player_loc, d);
int count = tt.safeLocation(start_loc[0] - 3, player_loc.getBlockY(), start_loc[2], start_loc[1] - 3, start_loc[3], w, d);
if (count > 0) {
sender.sendMessage(plugin.pluginName + "The player's location would not be safe! Please tell the player to move!");
return true;
}
respect = new TARDISPluginRespect(plugin);
if (!respect.getRespect(player, player_loc, true)) {
return true;
}
String save_loc = player_loc.getWorld().getName() + ":" + (player_loc.getBlockX() - 3) + ":" + player_loc.getBlockY() + ":" + player_loc.getBlockZ();
set.put("save", save_loc);
qf.doUpdate("tardis", set, tid);
sender.sendMessage(plugin.pluginName + "The player location was saved succesfully. Please release the handbrake!");
plugin.utils.updateTravellerCount(id);
plugin.tardisHasDestination.put(id, travel);
return true;
} else {
sender.sendMessage(plugin.pluginName + "You do not have permission to time travel to a player!");
return true;
}
}
}
if (args.length == 2 && args[0].equalsIgnoreCase("dest")) {
// we're thinking this is a saved destination name
HashMap<String, Object> whered = new HashMap<String, Object>();
whered.put("dest_name", args[1]);
ResultSetDestinations rsd = new ResultSetDestinations(plugin, whered, false);
if (!rsd.resultSet()) {
sender.sendMessage(plugin.pluginName + "Could not find a destination with that name! try using " + ChatColor.GREEN + "/TARDIS list saves" + ChatColor.RESET + " first.");
return true;
}
String save_loc = rsd.getWorld() + ":" + rsd.getX() + ":" + rsd.getY() + ":" + rsd.getZ();
set.put("save", save_loc);
qf.doUpdate("tardis", set, tid);
sender.sendMessage(plugin.pluginName + "The specified location was set succesfully. Please release the handbrake!");
plugin.utils.updateTravellerCount(id);
plugin.tardisHasDestination.put(id, travel);
return true;
}
if (args.length == 2 && args[0].equalsIgnoreCase("area")) {
// we're thinking this is admin defined area name
HashMap<String, Object> wherea = new HashMap<String, Object>();
wherea.put("area_name", args[1]);
ResultSetAreas rsa = new ResultSetAreas(plugin, wherea, false);
if (!rsa.resultSet()) {
sender.sendMessage(plugin.pluginName + "Could not find an area with that name! try using " + ChatColor.GREEN + "/tardis list areas" + ChatColor.RESET + " first.");
return true;
}
if (!player.hasPermission("tardis.area." + args[1]) || !player.isPermissionSet("tardis.area." + args[1])) {
sender.sendMessage(plugin.pluginName + "You do not have permission [tardis.area." + args[1] + "] to send the TARDIS to this location!");
return true;
}
Location l = plugin.ta.getNextSpot(rsa.getArea_name());
if (l == null) {
sender.sendMessage(plugin.pluginName + "All available parking spots are taken in this area!");
return true;
}
String save_loc = l.getWorld().getName() + ":" + l.getBlockX() + ":" + l.getBlockY() + ":" + l.getBlockZ();
set.put("save", save_loc);
qf.doUpdate("tardis", set, tid);
sender.sendMessage(plugin.pluginName + "Your TARDIS was approved for parking in [" + args[1] + "]!");
plugin.utils.updateTravellerCount(id);
plugin.tardisHasDestination.put(id, travel);
return true;
}
if (args.length > 2 && args.length < 4) {
sender.sendMessage(plugin.pluginName + "Too few command arguments for co-ordinates travel!");
return false;
}
if (args.length == 4 && player.hasPermission("tardis.timetravel.location")) {
// must be a location then
int x, y, z;
World w = plugin.getServer().getWorld(args[0]);
+ if (w == null) {
+ sender.sendMessage(plugin.pluginName + "Cannot find the specified world! Make sure you type it correctly.");
+ return true;
+ }
if (!plugin.getConfig().getBoolean("include_default_world") && plugin.getConfig().getBoolean("default_world") && args[0].equals(plugin.getConfig().getString("default_world_name"))) {
sender.sendMessage(plugin.pluginName + "The server admin does not allow time travel to this world!");
return true;
}
x = plugin.utils.parseNum(args[1]);
y = plugin.utils.parseNum(args[2]);
z = plugin.utils.parseNum(args[3]);
Block block = w.getBlockAt(x, y, z);
Location location = block.getLocation();
respect = new TARDISPluginRespect(plugin);
if (!respect.getRespect(player, location, true)) {
return true;
}
// check location
int[] start_loc = tt.getStartLocation(location, d);
int count = tt.safeLocation(start_loc[0], location.getBlockY(), start_loc[2], start_loc[1], start_loc[3], w, d);
if (count > 0) {
sender.sendMessage(plugin.pluginName + "The specified location would not be safe! Please try another.");
return true;
} else {
String save_loc = location.getWorld().getName() + ":" + location.getBlockX() + ":" + location.getBlockY() + ":" + location.getBlockZ();
set.put("save", save_loc);
qf.doUpdate("tardis", set, tid);
sender.sendMessage(plugin.pluginName + "The specified location was saved succesfully. Please release the handbrake!");
plugin.utils.updateTravellerCount(id);
plugin.tardisHasDestination.put(id, travel);
return true;
}
} else {
sender.sendMessage(plugin.pluginName + "You do not have permission to use co-ordinates time travel!");
return true;
}
}
} else {
sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE);
return false;
}
}
return false;
}
}
| true | true | public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
// If the player typed /tardis then do the following...
// check there is the right number of arguments
if (cmd.getName().equalsIgnoreCase("tardistravel")) {
if (player == null) {
sender.sendMessage(plugin.pluginName + ChatColor.RED + " This command can only be run by a player");
return true;
}
if (player.hasPermission("tardis.timetravel")) {
if (args.length < 1) {
sender.sendMessage(plugin.pluginName + "Too few command arguments!");
return false;
}
QueryFactory qf = new QueryFactory(plugin);
TARDISTimetravel tt = new TARDISTimetravel(plugin);
// get tardis data
HashMap<String, Object> where = new HashMap<String, Object>();
where.put("owner", player.getName());
ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false);
if (!rs.resultSet()) {
sender.sendMessage(plugin.pluginName + "You are not a Timelord. You need to create a TARDIS before using this command!");
return true;
}
if (!rs.isHandbrake_on()) {
player.sendMessage(plugin.pluginName + ChatColor.RED + "You cannot set a destination while the TARDIS is travelling!");
return true;
}
HashMap<String, Object> wheret = new HashMap<String, Object>();
wheret.put("player", player.getName());
ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false);
if (!rst.resultSet()) {
sender.sendMessage(plugin.pluginName + "You are not inside the TARDIS. You need to be to run this command!");
return true;
}
int tardis_id = rst.getTardis_id();
int id = rs.getTardis_id();
if (tardis_id != id) {
sender.sendMessage(plugin.pluginName + "You can only run this command if you are the Timelord of " + ChatColor.LIGHT_PURPLE + "this" + ChatColor.RESET + " TARDIS!");
return true;
}
int level = rs.getArtron_level();
int travel = plugin.getConfig().getInt("travel");
if (level < travel) {
player.sendMessage(plugin.pluginName + ChatColor.RED + "The TARDIS does not have enough Artron Energy to make this trip!");
return true;
}
TARDISConstants.COMPASS d = rs.getDirection();
String home = rs.getHome();
HashMap<String, Object> tid = new HashMap<String, Object>();
HashMap<String, Object> set = new HashMap<String, Object>();
tid.put("tardis_id", id);
if (player.hasPermission("tardis.exile")) {
// get the exile area
String permArea = plugin.ta.getExileArea(player);
player.sendMessage(plugin.pluginName + ChatColor.RED + " Notice:" + ChatColor.RESET + " Your travel has been restricted to the [" + permArea + "] area!");
Location l = plugin.ta.getNextSpot(permArea);
if (l == null) {
player.sendMessage(plugin.pluginName + "All available parking spots are taken in this area!");
return true;
}
String save_loc = l.getWorld().getName() + ":" + l.getBlockX() + ":" + l.getBlockY() + ":" + l.getBlockZ();
set.put("save", save_loc);
qf.doUpdate("tardis", set, tid);
player.sendMessage(plugin.pluginName + "Your TARDIS was approved for parking in [" + permArea + "]!");
plugin.tardisHasDestination.put(id, travel);
return true;
} else {
if (args.length == 1) {
// we're thinking this is a player's name or home
if (args[0].equalsIgnoreCase("home")) {
set.put("save", home);
qf.doUpdate("tardis", set, tid);
sender.sendMessage(plugin.pluginName + "Home location loaded succesfully. Please release the handbrake!");
plugin.utils.updateTravellerCount(id);
plugin.tardisHasDestination.put(id, travel);
return true;
} else {
if (player.hasPermission("tardis.timetravel.player")) {
if (plugin.getServer().getPlayer(args[0]) == null) {
sender.sendMessage(plugin.pluginName + "That player is not online!");
return true;
}
Player destPlayer = plugin.getServer().getPlayer(args[0]);
Location player_loc = destPlayer.getLocation();
World w = player_loc.getWorld();
int[] start_loc = tt.getStartLocation(player_loc, d);
int count = tt.safeLocation(start_loc[0] - 3, player_loc.getBlockY(), start_loc[2], start_loc[1] - 3, start_loc[3], w, d);
if (count > 0) {
sender.sendMessage(plugin.pluginName + "The player's location would not be safe! Please tell the player to move!");
return true;
}
respect = new TARDISPluginRespect(plugin);
if (!respect.getRespect(player, player_loc, true)) {
return true;
}
String save_loc = player_loc.getWorld().getName() + ":" + (player_loc.getBlockX() - 3) + ":" + player_loc.getBlockY() + ":" + player_loc.getBlockZ();
set.put("save", save_loc);
qf.doUpdate("tardis", set, tid);
sender.sendMessage(plugin.pluginName + "The player location was saved succesfully. Please release the handbrake!");
plugin.utils.updateTravellerCount(id);
plugin.tardisHasDestination.put(id, travel);
return true;
} else {
sender.sendMessage(plugin.pluginName + "You do not have permission to time travel to a player!");
return true;
}
}
}
if (args.length == 2 && args[0].equalsIgnoreCase("dest")) {
// we're thinking this is a saved destination name
HashMap<String, Object> whered = new HashMap<String, Object>();
whered.put("dest_name", args[1]);
ResultSetDestinations rsd = new ResultSetDestinations(plugin, whered, false);
if (!rsd.resultSet()) {
sender.sendMessage(plugin.pluginName + "Could not find a destination with that name! try using " + ChatColor.GREEN + "/TARDIS list saves" + ChatColor.RESET + " first.");
return true;
}
String save_loc = rsd.getWorld() + ":" + rsd.getX() + ":" + rsd.getY() + ":" + rsd.getZ();
set.put("save", save_loc);
qf.doUpdate("tardis", set, tid);
sender.sendMessage(plugin.pluginName + "The specified location was set succesfully. Please release the handbrake!");
plugin.utils.updateTravellerCount(id);
plugin.tardisHasDestination.put(id, travel);
return true;
}
if (args.length == 2 && args[0].equalsIgnoreCase("area")) {
// we're thinking this is admin defined area name
HashMap<String, Object> wherea = new HashMap<String, Object>();
wherea.put("area_name", args[1]);
ResultSetAreas rsa = new ResultSetAreas(plugin, wherea, false);
if (!rsa.resultSet()) {
sender.sendMessage(plugin.pluginName + "Could not find an area with that name! try using " + ChatColor.GREEN + "/tardis list areas" + ChatColor.RESET + " first.");
return true;
}
if (!player.hasPermission("tardis.area." + args[1]) || !player.isPermissionSet("tardis.area." + args[1])) {
sender.sendMessage(plugin.pluginName + "You do not have permission [tardis.area." + args[1] + "] to send the TARDIS to this location!");
return true;
}
Location l = plugin.ta.getNextSpot(rsa.getArea_name());
if (l == null) {
sender.sendMessage(plugin.pluginName + "All available parking spots are taken in this area!");
return true;
}
String save_loc = l.getWorld().getName() + ":" + l.getBlockX() + ":" + l.getBlockY() + ":" + l.getBlockZ();
set.put("save", save_loc);
qf.doUpdate("tardis", set, tid);
sender.sendMessage(plugin.pluginName + "Your TARDIS was approved for parking in [" + args[1] + "]!");
plugin.utils.updateTravellerCount(id);
plugin.tardisHasDestination.put(id, travel);
return true;
}
if (args.length > 2 && args.length < 4) {
sender.sendMessage(plugin.pluginName + "Too few command arguments for co-ordinates travel!");
return false;
}
if (args.length == 4 && player.hasPermission("tardis.timetravel.location")) {
// must be a location then
int x, y, z;
World w = plugin.getServer().getWorld(args[0]);
if (!plugin.getConfig().getBoolean("include_default_world") && plugin.getConfig().getBoolean("default_world") && args[0].equals(plugin.getConfig().getString("default_world_name"))) {
sender.sendMessage(plugin.pluginName + "The server admin does not allow time travel to this world!");
return true;
}
x = plugin.utils.parseNum(args[1]);
y = plugin.utils.parseNum(args[2]);
z = plugin.utils.parseNum(args[3]);
Block block = w.getBlockAt(x, y, z);
Location location = block.getLocation();
respect = new TARDISPluginRespect(plugin);
if (!respect.getRespect(player, location, true)) {
return true;
}
// check location
int[] start_loc = tt.getStartLocation(location, d);
int count = tt.safeLocation(start_loc[0], location.getBlockY(), start_loc[2], start_loc[1], start_loc[3], w, d);
if (count > 0) {
sender.sendMessage(plugin.pluginName + "The specified location would not be safe! Please try another.");
return true;
} else {
String save_loc = location.getWorld().getName() + ":" + location.getBlockX() + ":" + location.getBlockY() + ":" + location.getBlockZ();
set.put("save", save_loc);
qf.doUpdate("tardis", set, tid);
sender.sendMessage(plugin.pluginName + "The specified location was saved succesfully. Please release the handbrake!");
plugin.utils.updateTravellerCount(id);
plugin.tardisHasDestination.put(id, travel);
return true;
}
} else {
sender.sendMessage(plugin.pluginName + "You do not have permission to use co-ordinates time travel!");
return true;
}
}
} else {
sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE);
return false;
}
}
return false;
}
| public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
// If the player typed /tardis then do the following...
// check there is the right number of arguments
if (cmd.getName().equalsIgnoreCase("tardistravel")) {
if (player == null) {
sender.sendMessage(plugin.pluginName + ChatColor.RED + " This command can only be run by a player");
return true;
}
if (player.hasPermission("tardis.timetravel")) {
if (args.length < 1) {
sender.sendMessage(plugin.pluginName + "Too few command arguments!");
return false;
}
QueryFactory qf = new QueryFactory(plugin);
TARDISTimetravel tt = new TARDISTimetravel(plugin);
// get tardis data
HashMap<String, Object> where = new HashMap<String, Object>();
where.put("owner", player.getName());
ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false);
if (!rs.resultSet()) {
sender.sendMessage(plugin.pluginName + "You are not a Timelord. You need to create a TARDIS before using this command!");
return true;
}
if (!rs.isHandbrake_on()) {
player.sendMessage(plugin.pluginName + ChatColor.RED + "You cannot set a destination while the TARDIS is travelling!");
return true;
}
HashMap<String, Object> wheret = new HashMap<String, Object>();
wheret.put("player", player.getName());
ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false);
if (!rst.resultSet()) {
sender.sendMessage(plugin.pluginName + "You are not inside the TARDIS. You need to be to run this command!");
return true;
}
int tardis_id = rst.getTardis_id();
int id = rs.getTardis_id();
if (tardis_id != id) {
sender.sendMessage(plugin.pluginName + "You can only run this command if you are the Timelord of " + ChatColor.LIGHT_PURPLE + "this" + ChatColor.RESET + " TARDIS!");
return true;
}
int level = rs.getArtron_level();
int travel = plugin.getConfig().getInt("travel");
if (level < travel) {
player.sendMessage(plugin.pluginName + ChatColor.RED + "The TARDIS does not have enough Artron Energy to make this trip!");
return true;
}
TARDISConstants.COMPASS d = rs.getDirection();
String home = rs.getHome();
HashMap<String, Object> tid = new HashMap<String, Object>();
HashMap<String, Object> set = new HashMap<String, Object>();
tid.put("tardis_id", id);
if (player.hasPermission("tardis.exile")) {
// get the exile area
String permArea = plugin.ta.getExileArea(player);
player.sendMessage(plugin.pluginName + ChatColor.RED + " Notice:" + ChatColor.RESET + " Your travel has been restricted to the [" + permArea + "] area!");
Location l = plugin.ta.getNextSpot(permArea);
if (l == null) {
player.sendMessage(plugin.pluginName + "All available parking spots are taken in this area!");
return true;
}
String save_loc = l.getWorld().getName() + ":" + l.getBlockX() + ":" + l.getBlockY() + ":" + l.getBlockZ();
set.put("save", save_loc);
qf.doUpdate("tardis", set, tid);
player.sendMessage(plugin.pluginName + "Your TARDIS was approved for parking in [" + permArea + "]!");
plugin.tardisHasDestination.put(id, travel);
return true;
} else {
if (args.length == 1) {
// we're thinking this is a player's name or home
if (args[0].equalsIgnoreCase("home")) {
set.put("save", home);
qf.doUpdate("tardis", set, tid);
sender.sendMessage(plugin.pluginName + "Home location loaded succesfully. Please release the handbrake!");
plugin.utils.updateTravellerCount(id);
plugin.tardisHasDestination.put(id, travel);
return true;
} else {
if (player.hasPermission("tardis.timetravel.player")) {
if (plugin.getServer().getPlayer(args[0]) == null) {
sender.sendMessage(plugin.pluginName + "That player is not online!");
return true;
}
Player destPlayer = plugin.getServer().getPlayer(args[0]);
Location player_loc = destPlayer.getLocation();
World w = player_loc.getWorld();
int[] start_loc = tt.getStartLocation(player_loc, d);
int count = tt.safeLocation(start_loc[0] - 3, player_loc.getBlockY(), start_loc[2], start_loc[1] - 3, start_loc[3], w, d);
if (count > 0) {
sender.sendMessage(plugin.pluginName + "The player's location would not be safe! Please tell the player to move!");
return true;
}
respect = new TARDISPluginRespect(plugin);
if (!respect.getRespect(player, player_loc, true)) {
return true;
}
String save_loc = player_loc.getWorld().getName() + ":" + (player_loc.getBlockX() - 3) + ":" + player_loc.getBlockY() + ":" + player_loc.getBlockZ();
set.put("save", save_loc);
qf.doUpdate("tardis", set, tid);
sender.sendMessage(plugin.pluginName + "The player location was saved succesfully. Please release the handbrake!");
plugin.utils.updateTravellerCount(id);
plugin.tardisHasDestination.put(id, travel);
return true;
} else {
sender.sendMessage(plugin.pluginName + "You do not have permission to time travel to a player!");
return true;
}
}
}
if (args.length == 2 && args[0].equalsIgnoreCase("dest")) {
// we're thinking this is a saved destination name
HashMap<String, Object> whered = new HashMap<String, Object>();
whered.put("dest_name", args[1]);
ResultSetDestinations rsd = new ResultSetDestinations(plugin, whered, false);
if (!rsd.resultSet()) {
sender.sendMessage(plugin.pluginName + "Could not find a destination with that name! try using " + ChatColor.GREEN + "/TARDIS list saves" + ChatColor.RESET + " first.");
return true;
}
String save_loc = rsd.getWorld() + ":" + rsd.getX() + ":" + rsd.getY() + ":" + rsd.getZ();
set.put("save", save_loc);
qf.doUpdate("tardis", set, tid);
sender.sendMessage(plugin.pluginName + "The specified location was set succesfully. Please release the handbrake!");
plugin.utils.updateTravellerCount(id);
plugin.tardisHasDestination.put(id, travel);
return true;
}
if (args.length == 2 && args[0].equalsIgnoreCase("area")) {
// we're thinking this is admin defined area name
HashMap<String, Object> wherea = new HashMap<String, Object>();
wherea.put("area_name", args[1]);
ResultSetAreas rsa = new ResultSetAreas(plugin, wherea, false);
if (!rsa.resultSet()) {
sender.sendMessage(plugin.pluginName + "Could not find an area with that name! try using " + ChatColor.GREEN + "/tardis list areas" + ChatColor.RESET + " first.");
return true;
}
if (!player.hasPermission("tardis.area." + args[1]) || !player.isPermissionSet("tardis.area." + args[1])) {
sender.sendMessage(plugin.pluginName + "You do not have permission [tardis.area." + args[1] + "] to send the TARDIS to this location!");
return true;
}
Location l = plugin.ta.getNextSpot(rsa.getArea_name());
if (l == null) {
sender.sendMessage(plugin.pluginName + "All available parking spots are taken in this area!");
return true;
}
String save_loc = l.getWorld().getName() + ":" + l.getBlockX() + ":" + l.getBlockY() + ":" + l.getBlockZ();
set.put("save", save_loc);
qf.doUpdate("tardis", set, tid);
sender.sendMessage(plugin.pluginName + "Your TARDIS was approved for parking in [" + args[1] + "]!");
plugin.utils.updateTravellerCount(id);
plugin.tardisHasDestination.put(id, travel);
return true;
}
if (args.length > 2 && args.length < 4) {
sender.sendMessage(plugin.pluginName + "Too few command arguments for co-ordinates travel!");
return false;
}
if (args.length == 4 && player.hasPermission("tardis.timetravel.location")) {
// must be a location then
int x, y, z;
World w = plugin.getServer().getWorld(args[0]);
if (w == null) {
sender.sendMessage(plugin.pluginName + "Cannot find the specified world! Make sure you type it correctly.");
return true;
}
if (!plugin.getConfig().getBoolean("include_default_world") && plugin.getConfig().getBoolean("default_world") && args[0].equals(plugin.getConfig().getString("default_world_name"))) {
sender.sendMessage(plugin.pluginName + "The server admin does not allow time travel to this world!");
return true;
}
x = plugin.utils.parseNum(args[1]);
y = plugin.utils.parseNum(args[2]);
z = plugin.utils.parseNum(args[3]);
Block block = w.getBlockAt(x, y, z);
Location location = block.getLocation();
respect = new TARDISPluginRespect(plugin);
if (!respect.getRespect(player, location, true)) {
return true;
}
// check location
int[] start_loc = tt.getStartLocation(location, d);
int count = tt.safeLocation(start_loc[0], location.getBlockY(), start_loc[2], start_loc[1], start_loc[3], w, d);
if (count > 0) {
sender.sendMessage(plugin.pluginName + "The specified location would not be safe! Please try another.");
return true;
} else {
String save_loc = location.getWorld().getName() + ":" + location.getBlockX() + ":" + location.getBlockY() + ":" + location.getBlockZ();
set.put("save", save_loc);
qf.doUpdate("tardis", set, tid);
sender.sendMessage(plugin.pluginName + "The specified location was saved succesfully. Please release the handbrake!");
plugin.utils.updateTravellerCount(id);
plugin.tardisHasDestination.put(id, travel);
return true;
}
} else {
sender.sendMessage(plugin.pluginName + "You do not have permission to use co-ordinates time travel!");
return true;
}
}
} else {
sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE);
return false;
}
}
return false;
}
|
diff --git a/troia-server/src/main/java/com/datascience/gal/service/JobsEntry.java b/troia-server/src/main/java/com/datascience/gal/service/JobsEntry.java
index 17f782d5..92cdb3c6 100644
--- a/troia-server/src/main/java/com/datascience/gal/service/JobsEntry.java
+++ b/troia-server/src/main/java/com/datascience/gal/service/JobsEntry.java
@@ -1,96 +1,96 @@
package com.datascience.gal.service;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
import com.datascience.core.Job;
import com.datascience.core.JobFactory;
import com.datascience.core.storages.IJobStorage;
import com.datascience.core.storages.JSONUtils;
import com.datascience.gal.Category;
import com.datascience.gal.executor.ProjectCommandExecutor;
import java.util.Collection;
import javax.ws.rs.POST;
/**
* @author Konrad Kurdej
*/
public class JobsEntry {
private static final String RANDOM_PREFIX = "RANDOM__";
IJobStorage jobStorage;
private IRandomUniqIDGenerator jidGenerator;
private JobFactory jobFactory;
private ResponseBuilder responser;
private ProjectCommandExecutor executor;
public JobsEntry(){
jidGenerator = new RandomUniqIDGenerators.PrefixAdderDecorator(RANDOM_PREFIX,
new RandomUniqIDGenerators.NumberAndDate());
}
public JobsEntry(ResponseBuilder responser, JobFactory jobFactory,
ProjectCommandExecutor executor, IJobStorage jobStorage){
this();
this.jobStorage = jobStorage;
this.responser = responser;
this.jobFactory = jobFactory;
this.executor = executor;
}
protected JobEntry jobEntryFactory(Job job){
return new JobEntry(job, executor, responser);
}
@Path("/{id}/")
public JobEntry getJob(@PathParam("id") String jid) throws Exception{
Job job = jobStorage.get(jid);
if (job == null) {
throw new IllegalArgumentException("Job with ID " + jid + " does not exist");
}
return jobEntryFactory(job);
}
private boolean empty_jid(String jid){
return jid == null || "".equals(jid);
}
@POST
public Response createJob(@FormParam("id") String jid,
@FormParam("categories") String sCategories,
@DefaultValue("batch") @FormParam("type") String type) throws Exception{
if (empty_jid(jid)){
jid = jidGenerator.getID();
}
Job job_old = jobStorage.get(jid);
if (job_old != null) {
- throw new IllegalArgumentException("Job with ID " + jid + " already exist");
+ throw new IllegalArgumentException("Job with ID " + jid + " already exists");
}
Collection<Category> categories = responser.getSerializer().parse(sCategories,
JSONUtils.categorySetType);
Job job = jobFactory.createJob(type, jid, categories);
jobStorage.add(job);
return responser.makeOKResponse("New job created with ID: " + jid);
}
@DELETE
public Response deleteJob(@FormParam("id") String jid) throws Exception{
if (empty_jid(jid)) {
throw new IllegalArgumentException("No job ID given");
}
Job job = jobStorage.get(jid);
if (job == null) {
throw new IllegalArgumentException("Job with ID " + jid + " does not exist");
}
jobStorage.remove(job);
return responser.makeOKResponse("Removed job with ID: " + jid);
}
}
| true | true | public Response createJob(@FormParam("id") String jid,
@FormParam("categories") String sCategories,
@DefaultValue("batch") @FormParam("type") String type) throws Exception{
if (empty_jid(jid)){
jid = jidGenerator.getID();
}
Job job_old = jobStorage.get(jid);
if (job_old != null) {
throw new IllegalArgumentException("Job with ID " + jid + " already exist");
}
Collection<Category> categories = responser.getSerializer().parse(sCategories,
JSONUtils.categorySetType);
Job job = jobFactory.createJob(type, jid, categories);
jobStorage.add(job);
return responser.makeOKResponse("New job created with ID: " + jid);
}
| public Response createJob(@FormParam("id") String jid,
@FormParam("categories") String sCategories,
@DefaultValue("batch") @FormParam("type") String type) throws Exception{
if (empty_jid(jid)){
jid = jidGenerator.getID();
}
Job job_old = jobStorage.get(jid);
if (job_old != null) {
throw new IllegalArgumentException("Job with ID " + jid + " already exists");
}
Collection<Category> categories = responser.getSerializer().parse(sCategories,
JSONUtils.categorySetType);
Job job = jobFactory.createJob(type, jid, categories);
jobStorage.add(job);
return responser.makeOKResponse("New job created with ID: " + jid);
}
|
diff --git a/src/gr/uoi/cs/daintiness/hecate/gui/swing/MetricsDialog.java b/src/gr/uoi/cs/daintiness/hecate/gui/swing/MetricsDialog.java
index 5aad0da..d4ff7a5 100644
--- a/src/gr/uoi/cs/daintiness/hecate/gui/swing/MetricsDialog.java
+++ b/src/gr/uoi/cs/daintiness/hecate/gui/swing/MetricsDialog.java
@@ -1,139 +1,139 @@
package gr.uoi.cs.daintiness.hecate.gui.swing;
import gr.uoi.cs.daintiness.hecate.diff.Metrics;
import java.awt.Toolkit;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
/**
* A dialog with miscellaneous metics
* @author giskou
*
*/
@SuppressWarnings("serial")
public class MetricsDialog extends JDialog {
/**
* Paramerized Constructor
* @param d a Delta object that has run {@link minus} at least once
*/
public MetricsDialog(Metrics d) {
setTitle("Metrics");
setIconImage(Toolkit.getDefaultToolkit().getImage(MetricsDialog.class.getResource("/gr/uoi/cs/daintiness/hecate/art/icon.png")));
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
// *** VERSIONS ***
JPanel versionContainer = new JPanel();
versionContainer.setBorder(new EmptyBorder(8, 8, 8, 8));
getContentPane().add(versionContainer);
versionContainer.setLayout(new BoxLayout(versionContainer, BoxLayout.X_AXIS));
JPanel oldVersionPane = new JPanel();
String oldVersionStr = d.getVersionNames()[0] + " ";
JPanel oldVersionTablesLine = new JPanel();
JLabel lblOldTables = new JLabel(Integer.toString(d.getOldSizes()[0]));
JPanel oldVersionAttributesLine = new JPanel();
JLabel lblOldAttributes = new JLabel(Integer.toString(d.getOldSizes()[1]));
oldVersionPane.setBorder(new TitledBorder(null, oldVersionStr, TitledBorder.LEADING, TitledBorder.TOP, null, null));
versionContainer.add(oldVersionPane);
oldVersionPane.setLayout(new BoxLayout(oldVersionPane, BoxLayout.Y_AXIS));
oldVersionPane.add(oldVersionTablesLine);
oldVersionTablesLine.setLayout(new BoxLayout(oldVersionTablesLine, BoxLayout.X_AXIS));
oldVersionTablesLine.add(new JLabel("Tables"));
oldVersionTablesLine.add(Box.createHorizontalGlue());
oldVersionTablesLine.add(lblOldTables);
oldVersionPane.add(oldVersionAttributesLine);
oldVersionAttributesLine.setLayout(new BoxLayout(oldVersionAttributesLine, BoxLayout.X_AXIS));
oldVersionAttributesLine.add(new JLabel("Attributes"));
oldVersionAttributesLine.add(Box.createHorizontalGlue());
oldVersionAttributesLine.add(lblOldAttributes);
JPanel newVersionPane = new JPanel();
- String newVersionStr = d.getVersionNames()[0] + " ";
+ String newVersionStr = d.getVersionNames()[1] + " ";
JPanel newVersionTablesLine = new JPanel();
JLabel lblNewTables = new JLabel(Integer.toString(d.getNewSizes()[0]));
JPanel newVersionAttributesLine = new JPanel();
JLabel lblNewAttributes= new JLabel(Integer.toString(d.getNewSizes()[1]));
newVersionPane.setBorder(new TitledBorder(null, newVersionStr, TitledBorder.LEADING, TitledBorder.TOP, null, null));
versionContainer.add(newVersionPane);
newVersionPane.setLayout(new BoxLayout(newVersionPane, BoxLayout.Y_AXIS));
newVersionPane.add(newVersionTablesLine);
newVersionTablesLine.setLayout(new BoxLayout(newVersionTablesLine, BoxLayout.X_AXIS));
newVersionTablesLine.add(new JLabel("Tables"));
newVersionTablesLine.add(Box.createHorizontalGlue());
newVersionTablesLine.add(lblNewTables);
newVersionPane.add(newVersionAttributesLine);
newVersionAttributesLine.setLayout(new BoxLayout(newVersionAttributesLine, BoxLayout.X_AXIS));
newVersionAttributesLine.add(new JLabel("Attributes"));
newVersionAttributesLine.add(Box.createHorizontalGlue());
newVersionAttributesLine.add(lblNewAttributes);
// *** TRANSITIONS ***
JPanel transitionContainer = new JPanel();
transitionContainer.setBorder(new EmptyBorder(8, 8, 8, 8));
getContentPane().add(transitionContainer);
transitionContainer.setLayout(new BoxLayout(transitionContainer, BoxLayout.X_AXIS));
JPanel deletionsPane = new JPanel();
JPanel deletionTablesLine = new JPanel();
JLabel lblDeletionTables = new JLabel(Integer.toString(d.getTableMetrics()[1]));
JPanel deletionAttributesLine = new JPanel();
JLabel lblDeletionAttributes = new JLabel(Integer.toString(d.getAttributeMetrics()[1]));
deletionsPane.setBorder(new TitledBorder(null, "Deletions", TitledBorder.LEADING, TitledBorder.TOP, null, null));
transitionContainer.add(deletionsPane);
deletionsPane.setLayout(new BoxLayout(deletionsPane, BoxLayout.Y_AXIS));
deletionsPane.add(deletionTablesLine);
deletionTablesLine.setLayout(new BoxLayout(deletionTablesLine, BoxLayout.X_AXIS));
deletionTablesLine.add(new JLabel("Tables"));
deletionTablesLine.add(Box.createHorizontalGlue());
deletionTablesLine.add(lblDeletionTables);
deletionsPane.add(deletionAttributesLine);
deletionAttributesLine.setLayout(new BoxLayout(deletionAttributesLine, BoxLayout.X_AXIS));
deletionAttributesLine.add(new JLabel("Attributes"));
deletionAttributesLine.add(Box.createHorizontalGlue());
deletionAttributesLine.add(lblDeletionAttributes);
JPanel insertionsPane = new JPanel();
JPanel insertionTableLine = new JPanel();
JLabel lblInsertionTables = new JLabel(Integer.toString(d.getTableMetrics()[0]));
JPanel insertionAttributeLine = new JPanel();
JLabel lblInsertionAttributes = new JLabel(Integer.toString(d.getAttributeMetrics()[0]));
insertionsPane.setBorder(new TitledBorder(null, "Insertions", TitledBorder.LEADING, TitledBorder.TOP, null, null));
transitionContainer.add(insertionsPane);
insertionsPane.setLayout(new BoxLayout(insertionsPane, BoxLayout.Y_AXIS));
insertionsPane.add(insertionTableLine);
insertionTableLine.setLayout(new BoxLayout(insertionTableLine, BoxLayout.X_AXIS));
insertionTableLine.add(new JLabel("Tables"));
insertionTableLine.add(Box.createHorizontalGlue());
insertionTableLine.add(lblInsertionTables);
insertionsPane.add(insertionAttributeLine);
insertionAttributeLine.setLayout(new BoxLayout(insertionAttributeLine, BoxLayout.X_AXIS));
insertionAttributeLine.add(new JLabel("Attributes"));
insertionAttributeLine.add(Box.createHorizontalGlue());
insertionAttributeLine.add(lblInsertionAttributes);
// JPanel exportContainer = new JPanel();
// JButton btnExport = new JButton("Export");
// getContentPane().add(Box.createVerticalGlue());
// exportContainer.setBorder(new EmptyBorder(8, 8, 8, 8));
// getContentPane().add(exportContainer);
// exportContainer.setLayout(new BoxLayout(exportContainer, BoxLayout.X_AXIS));
// exportContainer.add(btnExport);
pack();
}
}
| true | true | public MetricsDialog(Metrics d) {
setTitle("Metrics");
setIconImage(Toolkit.getDefaultToolkit().getImage(MetricsDialog.class.getResource("/gr/uoi/cs/daintiness/hecate/art/icon.png")));
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
// *** VERSIONS ***
JPanel versionContainer = new JPanel();
versionContainer.setBorder(new EmptyBorder(8, 8, 8, 8));
getContentPane().add(versionContainer);
versionContainer.setLayout(new BoxLayout(versionContainer, BoxLayout.X_AXIS));
JPanel oldVersionPane = new JPanel();
String oldVersionStr = d.getVersionNames()[0] + " ";
JPanel oldVersionTablesLine = new JPanel();
JLabel lblOldTables = new JLabel(Integer.toString(d.getOldSizes()[0]));
JPanel oldVersionAttributesLine = new JPanel();
JLabel lblOldAttributes = new JLabel(Integer.toString(d.getOldSizes()[1]));
oldVersionPane.setBorder(new TitledBorder(null, oldVersionStr, TitledBorder.LEADING, TitledBorder.TOP, null, null));
versionContainer.add(oldVersionPane);
oldVersionPane.setLayout(new BoxLayout(oldVersionPane, BoxLayout.Y_AXIS));
oldVersionPane.add(oldVersionTablesLine);
oldVersionTablesLine.setLayout(new BoxLayout(oldVersionTablesLine, BoxLayout.X_AXIS));
oldVersionTablesLine.add(new JLabel("Tables"));
oldVersionTablesLine.add(Box.createHorizontalGlue());
oldVersionTablesLine.add(lblOldTables);
oldVersionPane.add(oldVersionAttributesLine);
oldVersionAttributesLine.setLayout(new BoxLayout(oldVersionAttributesLine, BoxLayout.X_AXIS));
oldVersionAttributesLine.add(new JLabel("Attributes"));
oldVersionAttributesLine.add(Box.createHorizontalGlue());
oldVersionAttributesLine.add(lblOldAttributes);
JPanel newVersionPane = new JPanel();
String newVersionStr = d.getVersionNames()[0] + " ";
JPanel newVersionTablesLine = new JPanel();
JLabel lblNewTables = new JLabel(Integer.toString(d.getNewSizes()[0]));
JPanel newVersionAttributesLine = new JPanel();
JLabel lblNewAttributes= new JLabel(Integer.toString(d.getNewSizes()[1]));
newVersionPane.setBorder(new TitledBorder(null, newVersionStr, TitledBorder.LEADING, TitledBorder.TOP, null, null));
versionContainer.add(newVersionPane);
newVersionPane.setLayout(new BoxLayout(newVersionPane, BoxLayout.Y_AXIS));
newVersionPane.add(newVersionTablesLine);
newVersionTablesLine.setLayout(new BoxLayout(newVersionTablesLine, BoxLayout.X_AXIS));
newVersionTablesLine.add(new JLabel("Tables"));
newVersionTablesLine.add(Box.createHorizontalGlue());
newVersionTablesLine.add(lblNewTables);
newVersionPane.add(newVersionAttributesLine);
newVersionAttributesLine.setLayout(new BoxLayout(newVersionAttributesLine, BoxLayout.X_AXIS));
newVersionAttributesLine.add(new JLabel("Attributes"));
newVersionAttributesLine.add(Box.createHorizontalGlue());
newVersionAttributesLine.add(lblNewAttributes);
// *** TRANSITIONS ***
JPanel transitionContainer = new JPanel();
transitionContainer.setBorder(new EmptyBorder(8, 8, 8, 8));
getContentPane().add(transitionContainer);
transitionContainer.setLayout(new BoxLayout(transitionContainer, BoxLayout.X_AXIS));
JPanel deletionsPane = new JPanel();
JPanel deletionTablesLine = new JPanel();
JLabel lblDeletionTables = new JLabel(Integer.toString(d.getTableMetrics()[1]));
JPanel deletionAttributesLine = new JPanel();
JLabel lblDeletionAttributes = new JLabel(Integer.toString(d.getAttributeMetrics()[1]));
deletionsPane.setBorder(new TitledBorder(null, "Deletions", TitledBorder.LEADING, TitledBorder.TOP, null, null));
transitionContainer.add(deletionsPane);
deletionsPane.setLayout(new BoxLayout(deletionsPane, BoxLayout.Y_AXIS));
deletionsPane.add(deletionTablesLine);
deletionTablesLine.setLayout(new BoxLayout(deletionTablesLine, BoxLayout.X_AXIS));
deletionTablesLine.add(new JLabel("Tables"));
deletionTablesLine.add(Box.createHorizontalGlue());
deletionTablesLine.add(lblDeletionTables);
deletionsPane.add(deletionAttributesLine);
deletionAttributesLine.setLayout(new BoxLayout(deletionAttributesLine, BoxLayout.X_AXIS));
deletionAttributesLine.add(new JLabel("Attributes"));
deletionAttributesLine.add(Box.createHorizontalGlue());
deletionAttributesLine.add(lblDeletionAttributes);
JPanel insertionsPane = new JPanel();
JPanel insertionTableLine = new JPanel();
JLabel lblInsertionTables = new JLabel(Integer.toString(d.getTableMetrics()[0]));
JPanel insertionAttributeLine = new JPanel();
JLabel lblInsertionAttributes = new JLabel(Integer.toString(d.getAttributeMetrics()[0]));
insertionsPane.setBorder(new TitledBorder(null, "Insertions", TitledBorder.LEADING, TitledBorder.TOP, null, null));
transitionContainer.add(insertionsPane);
insertionsPane.setLayout(new BoxLayout(insertionsPane, BoxLayout.Y_AXIS));
insertionsPane.add(insertionTableLine);
insertionTableLine.setLayout(new BoxLayout(insertionTableLine, BoxLayout.X_AXIS));
insertionTableLine.add(new JLabel("Tables"));
insertionTableLine.add(Box.createHorizontalGlue());
insertionTableLine.add(lblInsertionTables);
insertionsPane.add(insertionAttributeLine);
insertionAttributeLine.setLayout(new BoxLayout(insertionAttributeLine, BoxLayout.X_AXIS));
insertionAttributeLine.add(new JLabel("Attributes"));
insertionAttributeLine.add(Box.createHorizontalGlue());
insertionAttributeLine.add(lblInsertionAttributes);
// JPanel exportContainer = new JPanel();
// JButton btnExport = new JButton("Export");
// getContentPane().add(Box.createVerticalGlue());
// exportContainer.setBorder(new EmptyBorder(8, 8, 8, 8));
// getContentPane().add(exportContainer);
// exportContainer.setLayout(new BoxLayout(exportContainer, BoxLayout.X_AXIS));
// exportContainer.add(btnExport);
pack();
}
| public MetricsDialog(Metrics d) {
setTitle("Metrics");
setIconImage(Toolkit.getDefaultToolkit().getImage(MetricsDialog.class.getResource("/gr/uoi/cs/daintiness/hecate/art/icon.png")));
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
// *** VERSIONS ***
JPanel versionContainer = new JPanel();
versionContainer.setBorder(new EmptyBorder(8, 8, 8, 8));
getContentPane().add(versionContainer);
versionContainer.setLayout(new BoxLayout(versionContainer, BoxLayout.X_AXIS));
JPanel oldVersionPane = new JPanel();
String oldVersionStr = d.getVersionNames()[0] + " ";
JPanel oldVersionTablesLine = new JPanel();
JLabel lblOldTables = new JLabel(Integer.toString(d.getOldSizes()[0]));
JPanel oldVersionAttributesLine = new JPanel();
JLabel lblOldAttributes = new JLabel(Integer.toString(d.getOldSizes()[1]));
oldVersionPane.setBorder(new TitledBorder(null, oldVersionStr, TitledBorder.LEADING, TitledBorder.TOP, null, null));
versionContainer.add(oldVersionPane);
oldVersionPane.setLayout(new BoxLayout(oldVersionPane, BoxLayout.Y_AXIS));
oldVersionPane.add(oldVersionTablesLine);
oldVersionTablesLine.setLayout(new BoxLayout(oldVersionTablesLine, BoxLayout.X_AXIS));
oldVersionTablesLine.add(new JLabel("Tables"));
oldVersionTablesLine.add(Box.createHorizontalGlue());
oldVersionTablesLine.add(lblOldTables);
oldVersionPane.add(oldVersionAttributesLine);
oldVersionAttributesLine.setLayout(new BoxLayout(oldVersionAttributesLine, BoxLayout.X_AXIS));
oldVersionAttributesLine.add(new JLabel("Attributes"));
oldVersionAttributesLine.add(Box.createHorizontalGlue());
oldVersionAttributesLine.add(lblOldAttributes);
JPanel newVersionPane = new JPanel();
String newVersionStr = d.getVersionNames()[1] + " ";
JPanel newVersionTablesLine = new JPanel();
JLabel lblNewTables = new JLabel(Integer.toString(d.getNewSizes()[0]));
JPanel newVersionAttributesLine = new JPanel();
JLabel lblNewAttributes= new JLabel(Integer.toString(d.getNewSizes()[1]));
newVersionPane.setBorder(new TitledBorder(null, newVersionStr, TitledBorder.LEADING, TitledBorder.TOP, null, null));
versionContainer.add(newVersionPane);
newVersionPane.setLayout(new BoxLayout(newVersionPane, BoxLayout.Y_AXIS));
newVersionPane.add(newVersionTablesLine);
newVersionTablesLine.setLayout(new BoxLayout(newVersionTablesLine, BoxLayout.X_AXIS));
newVersionTablesLine.add(new JLabel("Tables"));
newVersionTablesLine.add(Box.createHorizontalGlue());
newVersionTablesLine.add(lblNewTables);
newVersionPane.add(newVersionAttributesLine);
newVersionAttributesLine.setLayout(new BoxLayout(newVersionAttributesLine, BoxLayout.X_AXIS));
newVersionAttributesLine.add(new JLabel("Attributes"));
newVersionAttributesLine.add(Box.createHorizontalGlue());
newVersionAttributesLine.add(lblNewAttributes);
// *** TRANSITIONS ***
JPanel transitionContainer = new JPanel();
transitionContainer.setBorder(new EmptyBorder(8, 8, 8, 8));
getContentPane().add(transitionContainer);
transitionContainer.setLayout(new BoxLayout(transitionContainer, BoxLayout.X_AXIS));
JPanel deletionsPane = new JPanel();
JPanel deletionTablesLine = new JPanel();
JLabel lblDeletionTables = new JLabel(Integer.toString(d.getTableMetrics()[1]));
JPanel deletionAttributesLine = new JPanel();
JLabel lblDeletionAttributes = new JLabel(Integer.toString(d.getAttributeMetrics()[1]));
deletionsPane.setBorder(new TitledBorder(null, "Deletions", TitledBorder.LEADING, TitledBorder.TOP, null, null));
transitionContainer.add(deletionsPane);
deletionsPane.setLayout(new BoxLayout(deletionsPane, BoxLayout.Y_AXIS));
deletionsPane.add(deletionTablesLine);
deletionTablesLine.setLayout(new BoxLayout(deletionTablesLine, BoxLayout.X_AXIS));
deletionTablesLine.add(new JLabel("Tables"));
deletionTablesLine.add(Box.createHorizontalGlue());
deletionTablesLine.add(lblDeletionTables);
deletionsPane.add(deletionAttributesLine);
deletionAttributesLine.setLayout(new BoxLayout(deletionAttributesLine, BoxLayout.X_AXIS));
deletionAttributesLine.add(new JLabel("Attributes"));
deletionAttributesLine.add(Box.createHorizontalGlue());
deletionAttributesLine.add(lblDeletionAttributes);
JPanel insertionsPane = new JPanel();
JPanel insertionTableLine = new JPanel();
JLabel lblInsertionTables = new JLabel(Integer.toString(d.getTableMetrics()[0]));
JPanel insertionAttributeLine = new JPanel();
JLabel lblInsertionAttributes = new JLabel(Integer.toString(d.getAttributeMetrics()[0]));
insertionsPane.setBorder(new TitledBorder(null, "Insertions", TitledBorder.LEADING, TitledBorder.TOP, null, null));
transitionContainer.add(insertionsPane);
insertionsPane.setLayout(new BoxLayout(insertionsPane, BoxLayout.Y_AXIS));
insertionsPane.add(insertionTableLine);
insertionTableLine.setLayout(new BoxLayout(insertionTableLine, BoxLayout.X_AXIS));
insertionTableLine.add(new JLabel("Tables"));
insertionTableLine.add(Box.createHorizontalGlue());
insertionTableLine.add(lblInsertionTables);
insertionsPane.add(insertionAttributeLine);
insertionAttributeLine.setLayout(new BoxLayout(insertionAttributeLine, BoxLayout.X_AXIS));
insertionAttributeLine.add(new JLabel("Attributes"));
insertionAttributeLine.add(Box.createHorizontalGlue());
insertionAttributeLine.add(lblInsertionAttributes);
// JPanel exportContainer = new JPanel();
// JButton btnExport = new JButton("Export");
// getContentPane().add(Box.createVerticalGlue());
// exportContainer.setBorder(new EmptyBorder(8, 8, 8, 8));
// getContentPane().add(exportContainer);
// exportContainer.setLayout(new BoxLayout(exportContainer, BoxLayout.X_AXIS));
// exportContainer.add(btnExport);
pack();
}
|
diff --git a/src/org/nutz/lang/socket/Sockets.java b/src/org/nutz/lang/socket/Sockets.java
index 183b2f452..851f7c321 100644
--- a/src/org/nutz/lang/socket/Sockets.java
+++ b/src/org/nutz/lang/socket/Sockets.java
@@ -1,327 +1,340 @@
package org.nutz.lang.socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.nutz.lang.Lang;
import org.nutz.lang.Mirror;
import org.nutz.lang.Streams;
import org.nutz.lang.born.Borning;
import org.nutz.lang.util.Context;
import org.nutz.log.Log;
import org.nutz.log.Logs;
public abstract class Sockets {
private static final Log log = Logs.get();
/**
* 向某主机发送一些字节内容,并将返回写入输出流
*
* @param host
* 主机
* @param port
* 端口
* @param ins
* 发送的内容
* @param ops
* 主机返回的输入流
*/
public static void send(String host, int port, InputStream ins, OutputStream ops) {
Socket socket = null;
try {
socket = new Socket(InetAddress.getByName(host), port);
// 发送关闭命令
OutputStream sOut = socket.getOutputStream();
Streams.write(sOut, ins);
sOut.flush();
// 接收服务器的反馈
if (!socket.isClosed()) {
InputStream sReturn = socket.getInputStream();
Streams.write(ops, sReturn);
}
}
catch (IOException e) {
throw Lang.wrapThrow(e);
}
finally {
Streams.safeClose(ins);
Streams.safeClose(ops);
safeClose(socket);
}
}
/**
* 向某主机发送一段文本,并将主机的返回作为文本返回
*
* @param host
* 主机
* @param port
* 端口
* @param text
* 发送的内容
* @return 主机返回的文本
*/
public static String sendText(String host, int port, String text) {
StringBuilder sb = new StringBuilder();
send(host, port, Lang.ins(text), Lang.ops(sb));
return sb.toString();
}
/**
* 监听本地某一个端口,仅仅收到某一个特殊命令时,才会开始一个动作。
* <p>
* 并且原生的,它支持输入 "close|stop|bye|exit" 来结束本地监听
*
* @param port
* 要监听的端口
* @param line
* 命令名称
* @param action
* 动作执行类
*/
public static void localListenOneAndStop(int port, String line, SocketAction action) {
Map<String, SocketAction> actions = createActions();
actions.put(line, action);
actions.put("$:^(close|stop|bye|exit)$", doClose());
localListenByLine(port, actions);
}
/**
* 监听本地某一个端口,仅仅收到某一个特殊命令时,才会开始一个动作。
*
* @param port
* 要监听的端口
* @param line
* 命令名称
* @param action
* 动作执行类
*/
public static void localListenOne(int port, String line, SocketAction action) {
Map<String, SocketAction> actions = createActions();
actions.put(line, action);
localListenByLine(port, actions);
}
/**
* 对于一个 CPU 默认起的处理线程数
*/
private static final int DEFAULT_POOL_SIZE = 10;
/**
* 简化了一个参数,采用默认线程数
*
* @see org.nutz.lang.socket.Sockets#localListenByLine(int, Map, int)
*/
public static void localListenByLine(int port, Map<String, SocketAction> actions) {
Sockets.localListenByLine(port, actions, DEFAULT_POOL_SIZE);
}
/**
* 监听本地某一个端口,根据用户输入的命令的不同,执行不同的操作
* <p>
* 当然,你如果想让一个过程处理多种命令,请给的 key 前用 "REGEX:" 作为前缀,后面用一个正则表达式 来表示你的你要的匹配的命令 <br>
* "REGEX:!" 开头的,表示后面的正则表达式是一个命令过滤,所有没有匹配上的命令都会被处理
*
* @param port
* 要监听的端口
* @param actions
* 动作执行类映射表
* @param poolSize
* 针对一个 CPU 你打算启动几个处理线程
*
* @see org.nutz.lang.socket.Sockets#localListenByLine(int, Map,
* ExecutorService)
*/
public static void localListenByLine(int port, Map<String, SocketAction> actions, int poolSize) {
Sockets.localListenByLine( port,
actions,
Executors.newFixedThreadPool(Runtime.getRuntime()
.availableProcessors()
* poolSize));
}
/**
* 监听本地某一个端口,根据用户输入的命令的不同,执行不同的操作
* <p>
* 当然,你如果想让一个过程处理多种命令,请给的 key 前用 "REGEX:" 作为前缀,后面用一个正则表达式 来表示你的你要的匹配的命令 <br>
* "REGEX:!" 开头的,表示后面的正则表达式是一个命令过滤,所有没有匹配上的命令都会被处理
*
* @param port
* 要监听的端口
* @param actions
* 动作执行类映射表
* @param service
* 线程池的实现类
*/
public static void localListenByLine( int port,
Map<String, SocketAction> actions,
ExecutorService service) {
localListen(port, actions, service, SocketAtom.class);
}
/**
* 监听本地某一个端口,根据用户输入的命令的不同,执行不同的操作
* <p>
* 当然,你如果想让一个过程处理多种命令,请给的 key 前用 "REGEX:" 作为前缀,后面用一个正则表达式 来表示你的你要的匹配的命令 <br>
* "REGEX:!" 开头的,表示后面的正则表达式是一个命令过滤,所有没有匹配上的命令都会被处理
*
* @param port
* 要监听的端口
* @param actions
* 动作执行类映射表
* @param service
* 线程池的实现类
*/
@SuppressWarnings("rawtypes")
public static void localListen( int port,
Map<String, SocketAction> actions,
ExecutorService service,
Class<? extends SocketAtom> klass) {
try {
// 建立动作映射表
SocketActionTable saTable = new SocketActionTable(actions);
// 初始化 socket 接口
final ServerSocket server;
try {
server = new ServerSocket(port);
}
catch (IOException e1) {
throw Lang.wrapThrow(e1);
}
if (log.isInfoEnabled())
log.infof("Local socket is up at :%d with %d action ready", port, actions.size());
final Context context = Lang.context();
context.set("stop", false);
- new Thread() {
+ /*
+ * 启动一个守护线程,判断是否该关闭 socket 服务
+ */
+ (new Thread() {
@Override
public void run() {
setName("Nutz.Sockets monitor thread");
while (true) {
try {
Thread.sleep(1000);
+ if(log.isDebugEnabled())
+ log.debug(" %% check ... " + context.getBoolean("stop"));
if (context.getBoolean("stop")) {
try {
+ if(log.isDebugEnabled())
+ log.debug(" %% close server");
server.close();
}catch (Throwable e) {}
return;
}
} catch (Throwable e) {}
}
}
- };
+ }).start();
+ /*
+ * 准备 SocketAtom 的生成器
+ */
Borning borning = Mirror.me(klass).getBorningByArgTypes(Context.class, Socket.class, SocketActionTable.class);
if (borning == null) {
log.error("boring == null !!!!");
return;
}
+ /*
+ * 进入监听循环
+ */
while (true) {
try {
if (log.isDebugEnabled())
log.debug("Waiting for new socket");
Socket socket = server.accept();
if (log.isDebugEnabled())
log.debug("Appact a new socket, create new SocketAtom to handle it ...");
Runnable runnable = (Runnable) borning.born(new Object[]{context,socket, saTable});
service.execute(runnable);
} catch (Throwable e) {
log.info("Throwable catched!! maybe ask to exit", e);
}
if (context.getBoolean("stop"))
break;
}
if (!server.isClosed()) {
try {
server.close();
} catch (Throwable e) {}
}
log.info("Seem stop signal was got, all running thread to exit in 60s");
try {
service.shutdown();
service.awaitTermination(15, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
try {
service.shutdownNow();
} catch (Throwable e2) {}
}
catch (RuntimeException e) {
throw e;
}
finally {
if (log.isInfoEnabled())
log.info("Stop services ...");
service.shutdown();
}
if (log.isInfoEnabled())
log.infof("Local socket is down for :%d", port);
}
/**
* 安全关闭套接层,容忍 null
*
* @param socket
* 套接层
* @return 一定会返回 null
*/
public static Socket safeClose(Socket socket) {
if (null != socket)
try {
socket.close();
socket = null;
}
catch (IOException e) {
throw Lang.wrapThrow(e);
}
return null;
}
/**
* 创建一个停止监听的动作对象
*
* @return 动作对象
*/
public static SocketAction doClose() {
return new SocketAction() {
public void run(SocketContext context) {
throw new CloseSocketException();
}
};
}
/**
* 这个函数可以在你的 SocketAction 实现类里被调用,用来关闭当前的监听星闻
*/
public static void close() {
throw new CloseSocketException();
}
/**
* 快捷创建动作映射表的方法
*
* @return 动作映射表
*/
public static Map<String, SocketAction> createActions() {
Map<String, SocketAction> actions = new HashMap<String, SocketAction>();
return actions;
}
}
| false | true | public static void localListen( int port,
Map<String, SocketAction> actions,
ExecutorService service,
Class<? extends SocketAtom> klass) {
try {
// 建立动作映射表
SocketActionTable saTable = new SocketActionTable(actions);
// 初始化 socket 接口
final ServerSocket server;
try {
server = new ServerSocket(port);
}
catch (IOException e1) {
throw Lang.wrapThrow(e1);
}
if (log.isInfoEnabled())
log.infof("Local socket is up at :%d with %d action ready", port, actions.size());
final Context context = Lang.context();
context.set("stop", false);
new Thread() {
@Override
public void run() {
setName("Nutz.Sockets monitor thread");
while (true) {
try {
Thread.sleep(1000);
if (context.getBoolean("stop")) {
try {
server.close();
}catch (Throwable e) {}
return;
}
} catch (Throwable e) {}
}
}
};
Borning borning = Mirror.me(klass).getBorningByArgTypes(Context.class, Socket.class, SocketActionTable.class);
if (borning == null) {
log.error("boring == null !!!!");
return;
}
while (true) {
try {
if (log.isDebugEnabled())
log.debug("Waiting for new socket");
Socket socket = server.accept();
if (log.isDebugEnabled())
log.debug("Appact a new socket, create new SocketAtom to handle it ...");
Runnable runnable = (Runnable) borning.born(new Object[]{context,socket, saTable});
service.execute(runnable);
} catch (Throwable e) {
log.info("Throwable catched!! maybe ask to exit", e);
}
if (context.getBoolean("stop"))
break;
}
if (!server.isClosed()) {
try {
server.close();
} catch (Throwable e) {}
}
log.info("Seem stop signal was got, all running thread to exit in 60s");
try {
service.shutdown();
service.awaitTermination(15, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
try {
service.shutdownNow();
} catch (Throwable e2) {}
}
catch (RuntimeException e) {
throw e;
}
finally {
if (log.isInfoEnabled())
log.info("Stop services ...");
service.shutdown();
}
if (log.isInfoEnabled())
log.infof("Local socket is down for :%d", port);
}
| public static void localListen( int port,
Map<String, SocketAction> actions,
ExecutorService service,
Class<? extends SocketAtom> klass) {
try {
// 建立动作映射表
SocketActionTable saTable = new SocketActionTable(actions);
// 初始化 socket 接口
final ServerSocket server;
try {
server = new ServerSocket(port);
}
catch (IOException e1) {
throw Lang.wrapThrow(e1);
}
if (log.isInfoEnabled())
log.infof("Local socket is up at :%d with %d action ready", port, actions.size());
final Context context = Lang.context();
context.set("stop", false);
/*
* 启动一个守护线程,判断是否该关闭 socket 服务
*/
(new Thread() {
@Override
public void run() {
setName("Nutz.Sockets monitor thread");
while (true) {
try {
Thread.sleep(1000);
if(log.isDebugEnabled())
log.debug(" %% check ... " + context.getBoolean("stop"));
if (context.getBoolean("stop")) {
try {
if(log.isDebugEnabled())
log.debug(" %% close server");
server.close();
}catch (Throwable e) {}
return;
}
} catch (Throwable e) {}
}
}
}).start();
/*
* 准备 SocketAtom 的生成器
*/
Borning borning = Mirror.me(klass).getBorningByArgTypes(Context.class, Socket.class, SocketActionTable.class);
if (borning == null) {
log.error("boring == null !!!!");
return;
}
/*
* 进入监听循环
*/
while (true) {
try {
if (log.isDebugEnabled())
log.debug("Waiting for new socket");
Socket socket = server.accept();
if (log.isDebugEnabled())
log.debug("Appact a new socket, create new SocketAtom to handle it ...");
Runnable runnable = (Runnable) borning.born(new Object[]{context,socket, saTable});
service.execute(runnable);
} catch (Throwable e) {
log.info("Throwable catched!! maybe ask to exit", e);
}
if (context.getBoolean("stop"))
break;
}
if (!server.isClosed()) {
try {
server.close();
} catch (Throwable e) {}
}
log.info("Seem stop signal was got, all running thread to exit in 60s");
try {
service.shutdown();
service.awaitTermination(15, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
try {
service.shutdownNow();
} catch (Throwable e2) {}
}
catch (RuntimeException e) {
throw e;
}
finally {
if (log.isInfoEnabled())
log.info("Stop services ...");
service.shutdown();
}
if (log.isInfoEnabled())
log.infof("Local socket is down for :%d", port);
}
|
diff --git a/src/java/nextgen/core/readFilters/CanonicalSpliceFilter.java b/src/java/nextgen/core/readFilters/CanonicalSpliceFilter.java
index 3dbc316..d4a16ba 100644
--- a/src/java/nextgen/core/readFilters/CanonicalSpliceFilter.java
+++ b/src/java/nextgen/core/readFilters/CanonicalSpliceFilter.java
@@ -1,89 +1,90 @@
package nextgen.core.readFilters;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import nextgen.core.alignment.Alignment;
import nextgen.core.annotation.Annotation;
import org.apache.commons.collections15.Predicate;
import broad.core.sequence.FastaSequenceIO;
import broad.core.sequence.Sequence;
import broad.pda.gene.GeneTools;
/**
* This class will filter reads by whether they have canonical splice junctions
* Canonical splice junctions are defined as junctions spanning an AG/GT pair
*
* @author mguttman
*
*/
public class CanonicalSpliceFilter implements Predicate<Alignment>{
//TODO: ADD A FLAG TO ALLOW FOR NON-CANONICAL SPLICE SITES
//private Sequence genomeSequence;
private String genomeSequenceFile=null;
private String currentChr;
private Sequence chrSeq;
public CanonicalSpliceFilter(String genomeFile){
this.genomeSequenceFile=genomeFile;
}
public CanonicalSpliceFilter(){
this.genomeSequenceFile=null;
}
@Override
public boolean evaluate(Alignment read) {
//TODO: CHECK
if(genomeSequenceFile==null){
//System.out.println("Genome sequence file is not provided");
- return true;
+ if(!read.getSpliceConnections().isEmpty()){return true;}
+ //return true;
}
if(read.getSpliceConnections().isEmpty()){return false;}
Sequence chrSeq;
try {
chrSeq = getChrSeq(read.getChr());
} catch (IOException e) {
return false;
} //Make sure we have the chromosome sequence
for(Annotation junction: read.getSpliceConnections()){
//This fucntion will allow ONLY canonical sites as well
String orientation=GeneTools.orientationFromSpliceSites(junction, chrSeq,true);
if(orientation.equalsIgnoreCase("*")){return false;}
else{
return true;
}
}
return true;
}
private Sequence getChrSeq(String chr) throws IOException {
if(currentChr==null || chrSeq==null || !chr.equalsIgnoreCase(currentChr)){
currentChr=chr;
chrSeq=updateSeq(chr);
}
return chrSeq;
}
private Sequence updateSeq(String chr) throws IOException {
FastaSequenceIO fsio = new FastaSequenceIO(genomeSequenceFile);
if(!(genomeSequenceFile==null)){
List<String> chrIds = new ArrayList<String>(1);
chrIds.add(chr);
List<Sequence> seqs = fsio.extractRecords(chrIds);
if(!seqs.isEmpty()) {
return seqs.get(0);
}
}
return null;
}
}
| true | true | public boolean evaluate(Alignment read) {
//TODO: CHECK
if(genomeSequenceFile==null){
//System.out.println("Genome sequence file is not provided");
return true;
}
if(read.getSpliceConnections().isEmpty()){return false;}
Sequence chrSeq;
try {
chrSeq = getChrSeq(read.getChr());
} catch (IOException e) {
return false;
} //Make sure we have the chromosome sequence
for(Annotation junction: read.getSpliceConnections()){
//This fucntion will allow ONLY canonical sites as well
String orientation=GeneTools.orientationFromSpliceSites(junction, chrSeq,true);
if(orientation.equalsIgnoreCase("*")){return false;}
else{
return true;
}
}
return true;
}
| public boolean evaluate(Alignment read) {
//TODO: CHECK
if(genomeSequenceFile==null){
//System.out.println("Genome sequence file is not provided");
if(!read.getSpliceConnections().isEmpty()){return true;}
//return true;
}
if(read.getSpliceConnections().isEmpty()){return false;}
Sequence chrSeq;
try {
chrSeq = getChrSeq(read.getChr());
} catch (IOException e) {
return false;
} //Make sure we have the chromosome sequence
for(Annotation junction: read.getSpliceConnections()){
//This fucntion will allow ONLY canonical sites as well
String orientation=GeneTools.orientationFromSpliceSites(junction, chrSeq,true);
if(orientation.equalsIgnoreCase("*")){return false;}
else{
return true;
}
}
return true;
}
|
diff --git a/src/test/java/edu/chl/dat076/foodfeed/model/dao/RecipeDaoTest.java b/src/test/java/edu/chl/dat076/foodfeed/model/dao/RecipeDaoTest.java
index c3cfeee..644e394 100644
--- a/src/test/java/edu/chl/dat076/foodfeed/model/dao/RecipeDaoTest.java
+++ b/src/test/java/edu/chl/dat076/foodfeed/model/dao/RecipeDaoTest.java
@@ -1,102 +1,102 @@
package edu.chl.dat076.foodfeed.model.dao;
import edu.chl.dat076.foodfeed.exception.ResourceNotFoundException;
import edu.chl.dat076.foodfeed.model.entity.Grocery;
import edu.chl.dat076.foodfeed.model.entity.Ingredient;
import edu.chl.dat076.foodfeed.model.entity.Recipe;
import java.util.ArrayList;
import java.util.List;
import junit.framework.Assert;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath*:spring/root-context.xml",
"classpath*:spring/security-context.xml"})
@Transactional
public class RecipeDaoTest {
@Autowired
RecipeDao recipeDao;
public Recipe recipe;
/*
* Creates a Recipe Object to be used in tests
*/
private Recipe createTestRecipeObject(){
- List<Ingredient> ingredients = new ArrayList();
+ List<Ingredient> ingredients = new ArrayList<>();
ingredients.add(new Ingredient(new Grocery("Red pepper", "Swedish red pepper"), 2.0, "stycken"));
ingredients.add(new Ingredient(new Grocery("Water", "Tap water"), 20.0, "liter"));
Recipe recipe = new Recipe();
recipe.setDescription("Best soup in the world");
recipe.setName("Soup");
recipe.setIngredients(ingredients);
recipe.setInstructions("Add all ingredients");
return recipe;
}
@Before
public void createRecipe(){
recipe = createTestRecipeObject();
recipeDao.create(recipe);
}
@Test
public void testCreate(){
Assert.assertNotNull("recipe could not be created", recipe.getId());
}
@Test(expected = ResourceNotFoundException.class)
public void testDelete(){
recipeDao.delete(recipe);
Assert.assertNull("recipe removed", recipeDao.find(recipe.getId()));
}
@Test(expected = ResourceNotFoundException.class)
public void testDeleteID(){
recipeDao.delete(recipe.getId());
Assert.assertNull("recipe not removed", recipeDao.find(recipe.getId()));
}
@Test
public void testFind(){
Recipe result = recipeDao.find(recipe.getId());
Assert.assertNotNull("recipe not found", result);
}
@Test
public void testFindAll() {
List<Recipe> recipes = recipeDao.findAll();
assertFalse("Check that true is true", recipes.isEmpty());
}
@Test
public void testUpdate(){
Recipe old = new Recipe();
old.setName(recipe.getName());
recipe.setName("New name");
recipeDao.update(recipe);
Assert.assertNotSame("Recipe not updated", recipe.getName(), old.getName());
}
@Test
public void testGetByIngredient(){
List<Recipe> result = recipeDao.getByIngredient(recipe.getIngredients().get(0));
Assert.assertFalse("found no recipe", result.isEmpty());
}
@Test
public void testGetByName(){
List<Recipe> result = recipeDao.getByName(recipe.getName());
Assert.assertFalse("found no recipe", result.isEmpty());
}
}
| true | true | private Recipe createTestRecipeObject(){
List<Ingredient> ingredients = new ArrayList();
ingredients.add(new Ingredient(new Grocery("Red pepper", "Swedish red pepper"), 2.0, "stycken"));
ingredients.add(new Ingredient(new Grocery("Water", "Tap water"), 20.0, "liter"));
Recipe recipe = new Recipe();
recipe.setDescription("Best soup in the world");
recipe.setName("Soup");
recipe.setIngredients(ingredients);
recipe.setInstructions("Add all ingredients");
return recipe;
}
| private Recipe createTestRecipeObject(){
List<Ingredient> ingredients = new ArrayList<>();
ingredients.add(new Ingredient(new Grocery("Red pepper", "Swedish red pepper"), 2.0, "stycken"));
ingredients.add(new Ingredient(new Grocery("Water", "Tap water"), 20.0, "liter"));
Recipe recipe = new Recipe();
recipe.setDescription("Best soup in the world");
recipe.setName("Soup");
recipe.setIngredients(ingredients);
recipe.setInstructions("Add all ingredients");
return recipe;
}
|
diff --git a/workspace/org.grammaticalframework.eclipse/src/org/grammaticalframework/eclipse/validation/GFJavaValidator.java b/workspace/org.grammaticalframework.eclipse/src/org/grammaticalframework/eclipse/validation/GFJavaValidator.java
index 894096f3..689e3f50 100644
--- a/workspace/org.grammaticalframework.eclipse/src/org/grammaticalframework/eclipse/validation/GFJavaValidator.java
+++ b/workspace/org.grammaticalframework.eclipse/src/org/grammaticalframework/eclipse/validation/GFJavaValidator.java
@@ -1,293 +1,293 @@
package org.grammaticalframework.eclipse.validation;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.naming.IQualifiedNameConverter;
import org.eclipse.xtext.naming.QualifiedName;
import org.eclipse.xtext.resource.IEObjectDescription;
import org.eclipse.xtext.resource.IResourceDescription;
import org.eclipse.xtext.resource.IResourceDescriptions;
import org.eclipse.xtext.scoping.IScope;
import org.eclipse.xtext.scoping.IScopeProvider;
import org.eclipse.xtext.validation.Check;
import org.grammaticalframework.eclipse.gF.*;
import org.grammaticalframework.eclipse.scoping.GFGlobalScopeProvider;
import org.grammaticalframework.eclipse.scoping.GFLibraryAgent;
import com.google.inject.Inject;
public class GFJavaValidator extends AbstractGFJavaValidator {
@Inject
private IScopeProvider scopeProvider;
protected IScopeProvider getScopeProvider() {
return scopeProvider;
}
@Inject
private GFGlobalScopeProvider provider;
@Inject
private IQualifiedNameConverter converter = new IQualifiedNameConverter.DefaultImpl();
protected IQualifiedNameConverter getConverter() {
return converter;
}
@Inject
private GFLibraryAgent libAgent;
// ==============================================
/**
* It is a compiler error for a module's name not to match its filename
* @param modtype
*/
@Check
public void checkModuleNameMatchesFileName(ModType modtype) {
String idealName = modtype.eResource().getURI().trimFileExtension().lastSegment();
if (!modtype.getName().getS().equals(idealName) ) {
String msg = String.format("Module name \"%s\" differs from file name \"%s\"", modtype.getName().getS(), idealName);
error(msg, GFPackage.Literals.MOD_TYPE__NAME);
}
}
/**
* Warn when referencing a module which does not exist.
* @param modtype
*/
@Check
public void checkAbstractModuleExists(ModType modtype) {
// Concrete, Instance
if (modtype.getAbstractName().getS() != null) {
if (!libAgent.moduleExists(modtype.eResource(), modtype.getAbstractName().getS())) {
String msg = String.format("Module \"%s\" not found", modtype.getAbstractName().getS());
warning(msg, GFPackage.Literals.MOD_TYPE__ABSTRACT_NAME);
}
}
}
@Check
public void checkReferencedModuleExists(Open open) {
// Opens, Instantiations
if (!libAgent.moduleExists(open.eResource(), open.getName().getS())) {
String msg = String.format("Module \"%s\" not found", open.getName().getS());
warning(msg, GFPackage.Literals.OPEN__NAME);
}
}
@Check
public void checkReferencedModuleExists(Included inc) {
// Extends, Functor instantiation
if (!libAgent.moduleExists(inc.eResource(), inc.getName().getS())) {
String msg = String.format("Module \"%s\" not found", inc.getName().getS());
warning(msg, GFPackage.Literals.INCLUDED__NAME);
}
}
/**
* Some special flag checks.
* @param flagdef
*/
@Check
public void checkFlags(FlagDef flagdef) {
if (flagdef.getName().getS().equals("startcat")) {
String startCat = flagdef.getValue().getS();
IScope scope = getScopeProvider().getScope(flagdef, GFPackage.Literals.FLAG_DEF__NAME);
if (scope.getSingleElement( getConverter().toQualifiedName(startCat) ) == null) {
String msg = String.format("Start category \"%1$s\" not found", startCat);
warning(msg, GFPackage.Literals.FLAG_DEF__VALUE);
}
}
}
/**
* It is a compiler error to have a category declaration in a concrete module, and so on.
* @param topdef
*/
@Check
public void checkDefsAreInCorrectModuleTypes(TopDef topdef) {
// Ascend to module
EObject temp = topdef;
while (!(temp instanceof ModDef) && temp.eContainer() != null) {
temp = temp.eContainer();
}
ModType modtype = ((ModDef)temp).getType();
// Shouldn't be in concrete/resource
if (topdef.isCat() && (modtype.isConcrete() || modtype.isResource())) {
String msg = String.format("Category declarations don't belong in a concrete module");
error(msg, GFPackage.Literals.TOP_DEF__CAT);
}
if (topdef.isFun() && (modtype.isConcrete() || modtype.isResource())) {
String msg = String.format("Function declarations don't belong in a concrete module");
error(msg, GFPackage.Literals.TOP_DEF__FUN);
}
if (topdef.isDef() && (modtype.isConcrete() || modtype.isResource())) {
String msg = String.format("Function definitions don't belong in a concrete module");
error(msg, GFPackage.Literals.TOP_DEF__DEF);
}
+ if (topdef.isLindef() && (modtype.isConcrete() || modtype.isResource())) {
+ String msg = String.format("Linearization default definitions don't belong in a concrete module");
+ warning(msg, GFPackage.Literals.TOP_DEF__LINDEF);
+ }
// Shouldn't be in abstract
if (topdef.isParam() && modtype.isAbstract()) {
String msg = String.format("Parameter type definitions don't belong in an abstract module");
error(msg, GFPackage.Literals.TOP_DEF__LINCAT);
}
if (topdef.isLincat() && modtype.isAbstract()) {
String msg = String.format("Linearization type definitions don't belong in an abstract module");
error(msg, GFPackage.Literals.TOP_DEF__LINCAT);
}
- if (topdef.isLindef() && modtype.isAbstract()) {
- String msg = String.format("Linearization default definitions don't belong in an abstract module");
- error(msg, GFPackage.Literals.TOP_DEF__LINDEF);
- }
if (topdef.isLin() && modtype.isAbstract()) {
String msg = String.format("Linearization definitions don't belong in an abstract module");
error(msg, GFPackage.Literals.TOP_DEF__LIN);
}
if (topdef.isPrintname() && modtype.isAbstract()) {
String msg = String.format("Printname definitions don't belong in an abstract module");
error(msg, GFPackage.Literals.TOP_DEF__LIN);
}
}
/**
* Warn about lineariation rules not having any corresponding abstract declarations
* @param name
*/
@Check
public void checkLinearisationsHaveAbstractEquivalents(Name name) {
if (name.eContainer().eContainer() instanceof TopDef) {
TopDef topDef = (TopDef) name.eContainer().eContainer();
IScope scope = getScopeProvider().getScope(name, GFPackage.Literals.NAME__NAME);
boolean found = (scope.getSingleElement(getConverter().toQualifiedName(name.getName().getS())) != null);
if (topDef.isLincat() && !found) {
String msg = String.format("No declaration \"cat %1$s\" found for \"lincat %1$s\"", name.getName().getS());
warning(msg, GFPackage.Literals.NAME__NAME);
}
else if (topDef.isLin() && !found) {
String msg = String.format("No declaration \"fun %1$s\" found for \"lin %1$s\"", name.getName().getS());
warning(msg, GFPackage.Literals.NAME__NAME);
}
}
}
/**
* Warn about lineariation rules not having any corresponding abstract declarations
* @param name
*/
@Check
public void checkOperatorOverloadsNamesMatch(Name name) {
if (name.eContainer() instanceof Def && name.eContainer().eContainer() instanceof Def) {
Def parent = (Def) name.eContainer().eContainer();
if (parent.isOverload()) {
// Convert to list of strings to be able to make comparison
ArrayList<String> parentNames = new ArrayList<String>();
for (Name n : parent.getName())
parentNames.add(n.getName().getS());
if (!parentNames.contains(name.getName().getS())) {
StringBuilder parentNamesSB = new StringBuilder();
Iterator<Name> i = parent.getName().iterator();
while (i.hasNext()) {
parentNamesSB.append(i.next().getName().getS());
if (i.hasNext())
parentNamesSB.append(", ");
}
String msg = String.format("Oper name \"%1$s\" does not occur in parent overload name \"%2$s\"", name.getName().getS(), parentNamesSB.toString());
warning(msg, GFPackage.Literals.NAME__NAME);
}
}
}
}
/**
* The lexer will treat ResEng.Gender as Ident.Label, rather than as single Ident. Thus cross-referencing is only
* checked on the module name ResEng, but not on the member Gender.
* This method exists to perform this exact checking as a post-process to the generated parser.
* @param label
*/
@Check
public void checkQualifiedNames(Label label) {
// Try get first bit of qualified name, i.e. "ResEng". Labels do no necessarily follow Idents, but ANY type of Exp6.
try {
Ident qualifier = ((Exp5)label.eContainer()).getV().getName();
QualifiedName fullyQualifiedName = getConverter().toQualifiedName(qualifier.getS() + "." + label.getName().getS());
// See if the qualifier is a valid MODULE name
EObject temp = label;
while (!(temp instanceof TopDef) && temp.eContainer() != null) {
temp = temp.eContainer();
}
TopDef topDef = (TopDef)temp;
IScope scope = getScopeProvider().getScope(topDef, GFPackage.Literals.TOP_DEF__DEFINITIONS);
if (scope.getSingleElement(qualifier) != null) {
// We now we are dealing with a Qualified name, now see if the full thing is valid:
if (scope.getSingleElement(fullyQualifiedName) == null) {
String msg = String.format("No declaration \"%1$s\" found in module \"%2$s\"", label.getName().getS(), qualifier.getS());
error(msg, GFPackage.Literals.LABEL__NAME);
}
}
} catch (Exception _) {
// just means the first part wasn't an Ident
}
}
/**
* Warn when functor instantiations don't fully instantiate their functor
* @param open
*/
@Check
public void checkFunctorInstantiations(ModBody modBody) {
if (modBody.isFunctorInstantiation()) {
// Get list of what the functor itself OPENs
Ident functorName = modBody.getFunctor().getName();
ArrayList<String> functorOpens = new ArrayList<String>();
URI uri = libAgent.getModuleURI(modBody.eResource(), functorName.getS() );
if (!libAgent.moduleExists(modBody.eResource(), functorName.getS())) {
// This should have already been checked
// String msg = String.format("Cannot find module \"%1$s\"", functorName.getS());
// error(msg, GFPackage.Literals.OPEN__NAME);
return;
}
final LinkedHashSet<URI> uriAsCollection = new LinkedHashSet<URI>(1);
uriAsCollection.add(uri);
IResourceDescriptions descriptions = provider.getResourceDescriptions(modBody.eResource(), uriAsCollection);
IResourceDescription desc = descriptions.getResourceDescription(uri);
// TODO Checking via regexp is very bad! But it works >:(
for (IEObjectDescription qn : desc.getExportedObjectsByType(GFPackage.Literals.IDENT)) {
if(qn.getEObjectURI().toString().matches("^.*?//@body/@opens.[0-9]+/@name$")) {
functorOpens.add(qn.getName().getLastSegment());
}
}
ArrayList<String> thisOpens = new ArrayList<String>();
for (Open o : modBody.getInstantiations())
thisOpens.add(o.getAlias().getS());
// Check that we are instantiating one of them
if (!thisOpens.containsAll(functorOpens)) {
StringBuilder msg = new StringBuilder();
msg.append( String.format("Instantiation of functor \"%1$s\" must instantiate: ", functorName.getS()) );
Iterator<String> i = functorOpens.iterator();
while (i.hasNext()) {
msg.append(i.next());
if (i.hasNext())
msg.append(", ");
}
error(msg.toString(), GFPackage.Literals.MOD_BODY__FUNCTOR_INSTANTIATION);
}
}
}
}
| false | true | public void checkDefsAreInCorrectModuleTypes(TopDef topdef) {
// Ascend to module
EObject temp = topdef;
while (!(temp instanceof ModDef) && temp.eContainer() != null) {
temp = temp.eContainer();
}
ModType modtype = ((ModDef)temp).getType();
// Shouldn't be in concrete/resource
if (topdef.isCat() && (modtype.isConcrete() || modtype.isResource())) {
String msg = String.format("Category declarations don't belong in a concrete module");
error(msg, GFPackage.Literals.TOP_DEF__CAT);
}
if (topdef.isFun() && (modtype.isConcrete() || modtype.isResource())) {
String msg = String.format("Function declarations don't belong in a concrete module");
error(msg, GFPackage.Literals.TOP_DEF__FUN);
}
if (topdef.isDef() && (modtype.isConcrete() || modtype.isResource())) {
String msg = String.format("Function definitions don't belong in a concrete module");
error(msg, GFPackage.Literals.TOP_DEF__DEF);
}
// Shouldn't be in abstract
if (topdef.isParam() && modtype.isAbstract()) {
String msg = String.format("Parameter type definitions don't belong in an abstract module");
error(msg, GFPackage.Literals.TOP_DEF__LINCAT);
}
if (topdef.isLincat() && modtype.isAbstract()) {
String msg = String.format("Linearization type definitions don't belong in an abstract module");
error(msg, GFPackage.Literals.TOP_DEF__LINCAT);
}
if (topdef.isLindef() && modtype.isAbstract()) {
String msg = String.format("Linearization default definitions don't belong in an abstract module");
error(msg, GFPackage.Literals.TOP_DEF__LINDEF);
}
if (topdef.isLin() && modtype.isAbstract()) {
String msg = String.format("Linearization definitions don't belong in an abstract module");
error(msg, GFPackage.Literals.TOP_DEF__LIN);
}
if (topdef.isPrintname() && modtype.isAbstract()) {
String msg = String.format("Printname definitions don't belong in an abstract module");
error(msg, GFPackage.Literals.TOP_DEF__LIN);
}
}
| public void checkDefsAreInCorrectModuleTypes(TopDef topdef) {
// Ascend to module
EObject temp = topdef;
while (!(temp instanceof ModDef) && temp.eContainer() != null) {
temp = temp.eContainer();
}
ModType modtype = ((ModDef)temp).getType();
// Shouldn't be in concrete/resource
if (topdef.isCat() && (modtype.isConcrete() || modtype.isResource())) {
String msg = String.format("Category declarations don't belong in a concrete module");
error(msg, GFPackage.Literals.TOP_DEF__CAT);
}
if (topdef.isFun() && (modtype.isConcrete() || modtype.isResource())) {
String msg = String.format("Function declarations don't belong in a concrete module");
error(msg, GFPackage.Literals.TOP_DEF__FUN);
}
if (topdef.isDef() && (modtype.isConcrete() || modtype.isResource())) {
String msg = String.format("Function definitions don't belong in a concrete module");
error(msg, GFPackage.Literals.TOP_DEF__DEF);
}
if (topdef.isLindef() && (modtype.isConcrete() || modtype.isResource())) {
String msg = String.format("Linearization default definitions don't belong in a concrete module");
warning(msg, GFPackage.Literals.TOP_DEF__LINDEF);
}
// Shouldn't be in abstract
if (topdef.isParam() && modtype.isAbstract()) {
String msg = String.format("Parameter type definitions don't belong in an abstract module");
error(msg, GFPackage.Literals.TOP_DEF__LINCAT);
}
if (topdef.isLincat() && modtype.isAbstract()) {
String msg = String.format("Linearization type definitions don't belong in an abstract module");
error(msg, GFPackage.Literals.TOP_DEF__LINCAT);
}
if (topdef.isLin() && modtype.isAbstract()) {
String msg = String.format("Linearization definitions don't belong in an abstract module");
error(msg, GFPackage.Literals.TOP_DEF__LIN);
}
if (topdef.isPrintname() && modtype.isAbstract()) {
String msg = String.format("Printname definitions don't belong in an abstract module");
error(msg, GFPackage.Literals.TOP_DEF__LIN);
}
}
|
diff --git a/src/com/mahn42/anhalter42/building/BuildingPlugin.java b/src/com/mahn42/anhalter42/building/BuildingPlugin.java
index f98d316..2af5f14 100644
--- a/src/com/mahn42/anhalter42/building/BuildingPlugin.java
+++ b/src/com/mahn42/anhalter42/building/BuildingPlugin.java
@@ -1,448 +1,450 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.mahn42.anhalter42.building;
import com.mahn42.framework.BuildingDescription;
import com.mahn42.framework.BuildingDetector;
import com.mahn42.framework.Framework;
import com.mahn42.framework.WorldDBList;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ShapedRecipe;
import org.bukkit.material.MaterialData;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.Vector;
/**
*
* @author andre
*/
public class BuildingPlugin extends JavaPlugin {
public static BuildingPlugin plugin;
public WorldDBList<SimpleBuildingDB> SimpleDBs;
public WorldDBList<SendReceiveDB> SendReceiveDBs;
public WorldDBList<LandmarkDB> LandmarkDBs;
protected DynMapLandmarkRenderer fDynMapTask;
public static void main(String[] args) {
}
public DynMapLandmarkRenderer getDynmapTask() {
return fDynMapTask;
}
@Override
public void onEnable() {
plugin = this;
getServer().getPluginManager().registerEvents(new BuildingListener(), this);
SimpleDBs = new WorldDBList<SimpleBuildingDB>(SimpleBuildingDB.class, this);
SendReceiveDBs = new WorldDBList<SendReceiveDB>(SendReceiveDB.class, "SendReceive", this);
LandmarkDBs = new WorldDBList<LandmarkDB>(LandmarkDB.class, "Landmark", this);
Framework.plugin.registerSaver(SimpleDBs);
Framework.plugin.registerSaver(SendReceiveDBs);
Framework.plugin.registerSaver(LandmarkDBs);
Framework.plugin.registerMarkerStorage(new MarkerStorage());
getCommand("bd_landmark_list").setExecutor(new CommandLandmarkList());
fDynMapTask = new DynMapLandmarkRenderer();
getServer().getScheduler().scheduleSyncRepeatingTask(this, fDynMapTask, 100, 20);
//ItemStack lItemStack = new ItemStack(Material.SMOOTH_BRICK, 4);//, (short)0, (byte)3);
//lItemStack.setData(new MaterialData(Material.SMOOTH_BRICK, (byte)3));
ItemStack lItemStack = new ItemStack(Material.SMOOTH_BRICK, 4, (short)0, (byte)3);
ShapedRecipe lShapeRecipe = new ShapedRecipe(lItemStack);
lShapeRecipe.shape("AA", "AA");
lShapeRecipe.setIngredient('A', Material.SMOOTH_BRICK);
getServer().addRecipe(lShapeRecipe);
lItemStack = new ItemStack(Material.SMOOTH_BRICK, 4); //, (short)0, (byte)0);
ShapedRecipe lChiseledStoneBrick = new ShapedRecipe(lItemStack);
lChiseledStoneBrick.shape("AA", "AA");
lChiseledStoneBrick.setIngredient('A', new MaterialData(Material.SMOOTH_BRICK, (byte)3));
getServer().addRecipe(lChiseledStoneBrick);
//lItemStack = new ItemStack(Material.SNOW_BLOCK, 6); //, (short)0, (byte)0);
//lItemStack.setData(new MaterialData(Material.SNOW_BLOCK, (byte)3));
//lItemStack = new ItemStack(Material.SNOW, 6, (short)0, (byte)3);
//ShapedRecipe lHalfSnow = new ShapedRecipe(lItemStack);
//lHalfSnow.shape("AAA");
//lHalfSnow.setIngredient('A', new MaterialData(Material.SNOW_BLOCK, (byte)0));
//getServer().addRecipe(lHalfSnow);
SimpleBuildingHandler lHandler = new SimpleBuildingHandler(this);
SendReceiveHandler lSRHandler = new SendReceiveHandler(this);
BuildingDetector lDetector = Framework.plugin.getBuildingDetector();
BuildingDescription lDesc;
BuildingDescription.BlockDescription lBDesc;
BuildingDescription.RelatedTo lRel;
lDesc = lDetector.newDescription("Building.BuildingEntryDetector");
lDesc.typeName = "Building Enter/Leave Detector";
lDesc.handler = lHandler;
lDesc.circleRadius = 1;
lDesc.color = 0xC818CB;
lBDesc = lDesc.newBlockDescription("base");
lBDesc.materials.add(Material.SMOOTH_BRICK, (byte)3);
lBDesc.detectSensible = true;
lRel = lBDesc.newRelatedTo("lever", BuildingDescription.RelatedPosition.Nearby, 1);
lRel = lBDesc.newRelatedTo("sign", BuildingDescription.RelatedPosition.Nearby, 1);
lBDesc = lDesc.newBlockDescription("lever");
lBDesc.materials.add(Material.LEVER);
lBDesc = lDesc.newBlockDescription("sign");
lBDesc.materials.add(Material.SIGN);
lBDesc.materials.add(Material.SIGN_POST);
lBDesc.materials.add(Material.WALL_SIGN);
lDesc.activate();
lDesc = lDetector.newDescription("Building.RedStoneReceiver");
lDesc.typeName = "Building for receiving redstone signals";
lDesc.handler = lSRHandler;
lDesc.circleRadius = 1;
lDesc.color = 0x18CB18;
lBDesc = lDesc.newBlockDescription("base");
lBDesc.materials.add(Material.SMOOTH_BRICK, (byte)3);
lBDesc.detectSensible = true;
lRel = lBDesc.newRelatedTo(new Vector(0, 1, 0), "antenabase");
lRel = lBDesc.newRelatedTo("lever", BuildingDescription.RelatedPosition.Nearby, 1);
lRel = lBDesc.newRelatedTo("sign", BuildingDescription.RelatedPosition.Nearby, 1);
lBDesc = lDesc.newBlockDescription("lever");
lBDesc.materials.add(Material.LEVER);
lBDesc = lDesc.newBlockDescription("sign");
lBDesc.materials.add(Material.SIGN);
lBDesc.materials.add(Material.SIGN_POST);
lBDesc.materials.add(Material.WALL_SIGN);
lBDesc = lDesc.newBlockDescription("antenabase");
lBDesc.materials.add(Material.FENCE);
lRel = lBDesc.newRelatedTo(new Vector(0, 10, 0), "antenatop");
lRel.materials.add(Material.FENCE);
lRel.minDistance = 1;
lBDesc = lDesc.newBlockDescription("antenatop");
lBDesc.materials.add(Material.FENCE);
lDesc.activate();
lDesc = lDetector.newDescription("Building.RedStoneReceiver.Lamp");
lDesc.typeName = "Lamp for receiving redstone signals";
lDesc.handler = lSRHandler;
lDesc.circleRadius = 1;
lDesc.color = 0x88CB18;
lBDesc = lDesc.newBlockDescription("base");
lBDesc.materials.add(Material.REDSTONE_LAMP_ON);
lBDesc.materials.add(Material.REDSTONE_LAMP_OFF);
lBDesc.detectSensible = true;
lRel = lBDesc.newRelatedTo("lever", BuildingDescription.RelatedPosition.Nearby, 1);
lRel = lBDesc.newRelatedTo("sign", BuildingDescription.RelatedPosition.Nearby, 1);
lBDesc = lDesc.newBlockDescription("lever");
lBDesc.materials.add(Material.LEVER);
lBDesc = lDesc.newBlockDescription("sign");
lBDesc.materials.add(Material.SIGN);
lBDesc.materials.add(Material.SIGN_POST);
lBDesc.materials.add(Material.WALL_SIGN);
lDesc.activate();
lDesc = lDetector.newDescription("Building.RedStoneSender");
lDesc.typeName = "Building for sending redstone signals";
lDesc.handler = lSRHandler;
lDesc.circleRadius = 1;
lDesc.color = 0xCB6918;
lBDesc = lDesc.newBlockDescription("base");
lBDesc.materials.add(Material.SMOOTH_BRICK, (byte)3);
lBDesc.detectSensible = true;
lBDesc.redstoneSensible = true;
lRel = lBDesc.newRelatedTo(new Vector(0, 1, 0), "antenabase");
lRel = lBDesc.newRelatedTo("sign", BuildingDescription.RelatedPosition.Nearby, 1);
lBDesc = lDesc.newBlockDescription("sign");
lBDesc.materials.add(Material.SIGN);
lBDesc.materials.add(Material.SIGN_POST);
lBDesc.materials.add(Material.WALL_SIGN);
lBDesc = lDesc.newBlockDescription("antenabase");
lBDesc.materials.add(Material.FENCE);
lRel = lBDesc.newRelatedTo(new Vector(0, 10, 0), "antenatop");
lRel.materials.add(Material.FENCE);
lRel.minDistance = 1;
lBDesc = lDesc.newBlockDescription("antenatop");
lBDesc.materials.add(Material.FENCE);
lDesc.activate();
lDesc = lDetector.newDescription("Building.Pyramid.Sandstone");
lDesc.handler = lHandler;
lDesc.typeName = "Pyramid";
lBDesc = lDesc.newBlockDescription("top");
lBDesc.materials.add(Material.SANDSTONE);
lBDesc.detectSensible = true;
lBDesc.nameSensible = true;
lRel = lBDesc.newRelatedTo(new Vector( 80,-80, 80), "ground1");
lRel.materials.add(Material.SANDSTONE);
lRel.minDistance = 1;
lRel = lBDesc.newRelatedTo(new Vector( 80,-80,-80), "ground2");
lRel.materials.add(Material.SANDSTONE);
lRel.minDistance = 1;
lRel = lBDesc.newRelatedTo(new Vector(-80,-80, 80), "ground3");
lRel.materials.add(Material.SANDSTONE);
lRel.minDistance = 1;
lRel = lBDesc.newRelatedTo(new Vector(-80,-80,-80), "ground4");
lRel.materials.add(Material.SANDSTONE);
lRel.minDistance = 1;
lBDesc = lDesc.newBlockDescription("ground1");
lBDesc.materials.add(Material.SANDSTONE);
lBDesc = lDesc.newBlockDescription("ground2");
lBDesc.materials.add(Material.SANDSTONE);
lBDesc = lDesc.newBlockDescription("ground3");
lBDesc.materials.add(Material.SANDSTONE);
lBDesc = lDesc.newBlockDescription("ground4");
lBDesc.materials.add(Material.SANDSTONE);
lDesc.activate();
lDesc = lDetector.newDescription("Building.BoatRailStation");
lDesc.handler = lHandler;
lDesc.typeName = "BoatRailStation";
lDesc.iconName = "anchor";
lBDesc = lDesc.newBlockDescription("railblock");
lBDesc.materials.add(Material.COBBLESTONE_STAIRS);
lBDesc.materials.add(Material.SMOOTH_STAIRS);
lBDesc.materials.add(Material.WOOD_STAIRS);
lBDesc.materials.add(Material.BRICK_STAIRS);
lBDesc.materials.add(Material.NETHER_BRICK_STAIRS);
lBDesc.materials.add(Material.SANDSTONE_STAIRS);
lBDesc.materials.add(Material.SPRUCE_WOOD_STAIRS);
lBDesc.materials.add(Material.BIRCH_WOOD_STAIRS);
lBDesc.materials.add(Material.JUNGLE_WOOD_STAIRS);
lBDesc.detectSensible = true;
lBDesc.nameSensible = true;
lRel = lBDesc.newRelatedTo(new Vector(0, 0, 1), "rails");
lRel = lBDesc.newRelatedTo(new Vector(0,-1,-1), "water");
lBDesc = lDesc.newBlockDescription("rails");
lBDesc.materials.add(Material.RAILS);
lBDesc.materials.add(Material.POWERED_RAIL);
lBDesc.materials.add(Material.DETECTOR_RAIL);
lBDesc = lDesc.newBlockDescription("water");
lBDesc.materials.add(Material.STATIONARY_WATER);
lBDesc.materials.add(Material.WATER);
lRel = lBDesc.newRelatedTo(new Vector(0, 0,-1), "water2");
lBDesc = lDesc.newBlockDescription("water2");
lBDesc.materials.add(Material.STATIONARY_WATER);
lBDesc.materials.add(Material.WATER);
lRel = lBDesc.newRelatedTo(new Vector(1, 0, 0), "water3");
lRel = lBDesc.newRelatedTo(new Vector(-1, 0, 0), "water4");
lBDesc = lDesc.newBlockDescription("water3");
lBDesc.materials.add(Material.STATIONARY_WATER);
lBDesc.materials.add(Material.WATER);
lBDesc = lDesc.newBlockDescription("water4");
lBDesc.materials.add(Material.STATIONARY_WATER);
lBDesc.materials.add(Material.WATER);
lDesc.createAndActivateXZ(true);
lDesc = lDetector.newDescription("Building.Lodge");
BuildingDescription.BlockMaterialArray lMats = lDesc.newBlockMaterialArray();
lMats.add(Material.SMOOTH_BRICK);
lMats.add(Material.BRICK);
lMats.add(Material.WOOD);
lMats.add(Material.STONE);
lMats.add(Material.COBBLESTONE);
lMats.add(Material.SANDSTONE);
lMats.add(Material.BEDROCK);
lMats.add(Material.OBSIDIAN);
lMats.add(Material.WOOD_PLATE);
lMats.add(Material.NETHERRACK);
lMats.add(Material.NETHER_BRICK);
lMats.add(Material.IRON_BLOCK);
lMats.add(Material.GOLD_BLOCK);
lMats.add(Material.DIAMOND_BLOCK);
lMats.add(Material.EMERALD_BLOCK);
lDesc.handler = lHandler;
lDesc.typeName = "Lodge";
lBDesc = lDesc.newBlockDescription("ground_e1");
lBDesc.materials.add(lMats);
lBDesc.detectSensible = true;
lRel = lBDesc.newRelatedTo(new Vector( 1, 0, 0), "ground_e1x");
lRel = lBDesc.newRelatedTo(new Vector( 0, 1, 0), "ground_e1y");
lRel = lBDesc.newRelatedTo(new Vector( 0, 0, 1), "ground_e1z");
lRel = lBDesc.newRelatedTo(new Vector(20, 0,20), "ground_e3");
lRel.minDistance = 3;
lRel = lBDesc.newRelatedTo(new Vector(20, 0, 0), "ground_e2");
lRel.minDistance = 3;
lRel = lBDesc.newRelatedTo(new Vector( 0, 0,20), "ground_e4");
lRel.minDistance = 3;
lRel = lBDesc.newRelatedTo(new Vector( 0, 8, 0), "top_e1");
//lRel = lBDesc.newRelatedTo(new Vector(19, 0, 0), "door");
lBDesc = lDesc.newBlockDescription("ground_e2");
lBDesc.materials.add(lMats);
lRel = lBDesc.newRelatedTo(new Vector(-1, 0, 0), "ground_e2x");
lRel = lBDesc.newRelatedTo(new Vector( 0, 1, 0), "ground_e2y");
lRel = lBDesc.newRelatedTo(new Vector( 0, 0, 1), "ground_e2z");
lRel = lBDesc.newRelatedTo(new Vector( 0, 8, 0), "top_e2");
lBDesc = lDesc.newBlockDescription("ground_e3");
lBDesc.materials.add(lMats);
lRel = lBDesc.newRelatedTo(new Vector(-1, 0, 0), "ground_e3x");
lRel = lBDesc.newRelatedTo(new Vector( 0, 1, 0), "ground_e3y");
lRel = lBDesc.newRelatedTo(new Vector( 0, 0,-1), "ground_e3z");
lRel = lBDesc.newRelatedTo(new Vector( 0, 8, 0), "top_e3");
lBDesc = lDesc.newBlockDescription("ground_e4");
lBDesc.materials.add(lMats);
lRel = lBDesc.newRelatedTo(new Vector( 1, 0, 0), "ground_e4x");
lRel = lBDesc.newRelatedTo(new Vector( 0, 1, 0), "ground_e4y");
lRel = lBDesc.newRelatedTo(new Vector( 0, 0,-1), "ground_e4z");
lRel = lBDesc.newRelatedTo(new Vector( 0, 8, 0), "top_e4");
lBDesc = lDesc.newBlockDescription("ground_e1x");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e1y");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e1z");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e2x");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e2y");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e2z");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e3x");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e3y");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e3z");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e4x");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e4y");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e4z");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("top_e1");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("top_e2");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("top_e3");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("top_e4");
lBDesc.materials.add(lMats);
//lBDesc = lDesc.newBlockDescription("door");
//lBDesc.materials.add(Material.WOODEN_DOOR);
//lRel = lBDesc.newRelatedTo(new Vector( 0, 1, 0), "door_top");
//lBDesc = lDesc.newBlockDescription("door_top");
//lBDesc.materials.add(Material.WOODEN_DOOR);
//lDesc.createAndActivateXZ();
lDesc = lDetector.newDescription("Building.Lift");
lDesc.handler = lHandler;
lDesc.typeName = "Lift";
lBDesc = lDesc.newBlockDescription("bottomleftfront");
lBDesc.materials.add(Material.IRON_BLOCK);
lBDesc.detectSensible = true;
lRel = lBDesc.newRelatedTo(new Vector( 0, 0,10), "bottomleftback");
lRel = lBDesc.newRelatedTo(new Vector(10, 0, 0), "bottomrightfront");
lRel = lBDesc.newRelatedTo(new Vector(10, 0,10), "bottomrightback");
lRel = lBDesc.newRelatedTo(new Vector( 0,10, 0), "topleftfront");
lRel = lBDesc.newRelatedTo(new Vector( 0,10,10), "topleftback");
lRel = lBDesc.newRelatedTo(new Vector(10,10, 0), "toprightfront");
lRel = lBDesc.newRelatedTo(new Vector(10,10,10), "toprightback");
lBDesc = lDesc.newBlockDescription("bottomleftback");
lBDesc.materials.add(Material.IRON_BLOCK);
lBDesc = lDesc.newBlockDescription("bottomrightfront");
lBDesc.materials.add(Material.IRON_BLOCK);
lBDesc = lDesc.newBlockDescription("bottomrightback");
lBDesc.materials.add(Material.IRON_BLOCK);
lBDesc = lDesc.newBlockDescription("topleftfront");
lBDesc.materials.add(Material.IRON_BLOCK);
lBDesc = lDesc.newBlockDescription("topleftback");
lBDesc.materials.add(Material.IRON_BLOCK);
lBDesc = lDesc.newBlockDescription("toprightfront");
lBDesc.materials.add(Material.IRON_BLOCK);
lBDesc = lDesc.newBlockDescription("toprightback");
lBDesc.materials.add(Material.IRON_BLOCK);
//lDesc.activate();
lDesc = lDetector.newDescription("Building.Landmark");
lDesc.handler = lHandler;
lDesc.typeName = "Landmark";
lDesc.circleRadius = 1;
lDesc.visibleOnMap = false;
+ lDesc.position = BuildingDescription.Position.everywhere;
lBDesc = lDesc.newBlockDescription("bottom");
lBDesc.materials.add(Material.SMOOTH_BRICK, (byte)3);
lBDesc.detectSensible = true;
lRel = lBDesc.newRelatedTo(new Vector( 0, 2, 0), "top");
lRel.materials.add(Material.SMOOTH_BRICK, (byte)3);
lBDesc = lDesc.newBlockDescription("top");
lBDesc.materials.add(Material.SMOOTH_BRICK, (byte)3);
lBDesc.nameSensible = true;
lRel = lBDesc.newRelatedTo("sign", BuildingDescription.RelatedPosition.Nearby, 1);
lBDesc = lDesc.newBlockDescription("sign");
lBDesc.materials.add(Material.SIGN);
lBDesc.materials.add(Material.SIGN_POST);
lBDesc.materials.add(Material.WALL_SIGN);
lDesc.activate();
lDesc = lDetector.newDescription("Building.Portal");
lDesc.handler = lHandler;
lDesc.typeName = "Portal";
lDesc.iconName = "portal";
+ lDesc.position = BuildingDescription.Position.everywhere;
lBDesc = lDesc.newBlockDescription("bottomleft");
lBDesc.materials.add(Material.OBSIDIAN);
lBDesc.detectSensible = true;
lBDesc.nameSensible = true;
lRel = lBDesc.newRelatedTo("sign", BuildingDescription.RelatedPosition.Nearby, 1);
lRel = lBDesc.newRelatedTo(new Vector( 3, 0, 0), "bottomright");
lRel.materials.add(Material.AIR);
lRel.minDistance = 2;
lRel = lBDesc.newRelatedTo(new Vector( 0, 4, 0), "topleft");
lRel.materials.add(Material.OBSIDIAN);
lRel.minDistance = 2;
lBDesc = lDesc.newBlockDescription("bottomright");
lBDesc.materials.add(Material.OBSIDIAN);
lRel = lBDesc.newRelatedTo(new Vector( 0, 4, 0), "topright");
lRel.materials.add(Material.OBSIDIAN);
lRel.minDistance = 2;
lBDesc = lDesc.newBlockDescription("topleft");
lBDesc.materials.add(Material.GLOWSTONE);
lRel = lBDesc.newRelatedTo(new Vector( 3, 0, 0), "topright");
lRel.materials.add(Material.OBSIDIAN);
lRel.minDistance = 2;
lBDesc = lDesc.newBlockDescription("topright");
lBDesc.materials.add(Material.GLOWSTONE);
lBDesc = lDesc.newBlockDescription("sign");
lBDesc.materials.add(Material.SIGN);
lBDesc.materials.add(Material.SIGN_POST);
lBDesc.materials.add(Material.WALL_SIGN);
lDesc.createAndActivateXZ();
lDesc = lDetector.newDescription("Building.Monument.Creeper");
lDesc.handler = lHandler;
lDesc.typeName = "Creeper Monument";
//lDesc.iconName = "tower";
lDesc.circleRadius = 100;
lDesc.influenceRadiusFactor = 100.0;
lDesc.color = 0x80FF80;
lBDesc = lDesc.newBlockDescription("top");
lBDesc.materials.add(Material.GOLD_BLOCK);
lBDesc.detectSensible = true;
lBDesc.nameSensible = true;
lRel = lBDesc.newRelatedTo(new Vector( 2,-2, 2), "e11");
lRel.materials.add(Material.NETHERRACK);
lRel = lBDesc.newRelatedTo(new Vector(-2,-2, 2), "e12");
lRel.materials.add(Material.NETHERRACK);
lRel = lBDesc.newRelatedTo(new Vector(-2,-2,-2), "e13");
lRel.materials.add(Material.NETHERRACK);
lRel = lBDesc.newRelatedTo(new Vector( 2,-2,-2), "e14");
lRel.materials.add(Material.NETHERRACK);
lBDesc = lDesc.newBlockDescription("e11");
lBDesc.materials.add(Material.NETHERRACK);
lBDesc = lDesc.newBlockDescription("e12");
lBDesc.materials.add(Material.NETHERRACK);
lBDesc = lDesc.newBlockDescription("e13");
lBDesc.materials.add(Material.NETHERRACK);
lBDesc = lDesc.newBlockDescription("e14");
lBDesc.materials.add(Material.NETHERRACK);
lDesc.activate();
}
@Override
public void onDisable() {
getServer().getScheduler().cancelTasks(this);
plugin = null;
}
}
| false | true | public void onEnable() {
plugin = this;
getServer().getPluginManager().registerEvents(new BuildingListener(), this);
SimpleDBs = new WorldDBList<SimpleBuildingDB>(SimpleBuildingDB.class, this);
SendReceiveDBs = new WorldDBList<SendReceiveDB>(SendReceiveDB.class, "SendReceive", this);
LandmarkDBs = new WorldDBList<LandmarkDB>(LandmarkDB.class, "Landmark", this);
Framework.plugin.registerSaver(SimpleDBs);
Framework.plugin.registerSaver(SendReceiveDBs);
Framework.plugin.registerSaver(LandmarkDBs);
Framework.plugin.registerMarkerStorage(new MarkerStorage());
getCommand("bd_landmark_list").setExecutor(new CommandLandmarkList());
fDynMapTask = new DynMapLandmarkRenderer();
getServer().getScheduler().scheduleSyncRepeatingTask(this, fDynMapTask, 100, 20);
//ItemStack lItemStack = new ItemStack(Material.SMOOTH_BRICK, 4);//, (short)0, (byte)3);
//lItemStack.setData(new MaterialData(Material.SMOOTH_BRICK, (byte)3));
ItemStack lItemStack = new ItemStack(Material.SMOOTH_BRICK, 4, (short)0, (byte)3);
ShapedRecipe lShapeRecipe = new ShapedRecipe(lItemStack);
lShapeRecipe.shape("AA", "AA");
lShapeRecipe.setIngredient('A', Material.SMOOTH_BRICK);
getServer().addRecipe(lShapeRecipe);
lItemStack = new ItemStack(Material.SMOOTH_BRICK, 4); //, (short)0, (byte)0);
ShapedRecipe lChiseledStoneBrick = new ShapedRecipe(lItemStack);
lChiseledStoneBrick.shape("AA", "AA");
lChiseledStoneBrick.setIngredient('A', new MaterialData(Material.SMOOTH_BRICK, (byte)3));
getServer().addRecipe(lChiseledStoneBrick);
//lItemStack = new ItemStack(Material.SNOW_BLOCK, 6); //, (short)0, (byte)0);
//lItemStack.setData(new MaterialData(Material.SNOW_BLOCK, (byte)3));
//lItemStack = new ItemStack(Material.SNOW, 6, (short)0, (byte)3);
//ShapedRecipe lHalfSnow = new ShapedRecipe(lItemStack);
//lHalfSnow.shape("AAA");
//lHalfSnow.setIngredient('A', new MaterialData(Material.SNOW_BLOCK, (byte)0));
//getServer().addRecipe(lHalfSnow);
SimpleBuildingHandler lHandler = new SimpleBuildingHandler(this);
SendReceiveHandler lSRHandler = new SendReceiveHandler(this);
BuildingDetector lDetector = Framework.plugin.getBuildingDetector();
BuildingDescription lDesc;
BuildingDescription.BlockDescription lBDesc;
BuildingDescription.RelatedTo lRel;
lDesc = lDetector.newDescription("Building.BuildingEntryDetector");
lDesc.typeName = "Building Enter/Leave Detector";
lDesc.handler = lHandler;
lDesc.circleRadius = 1;
lDesc.color = 0xC818CB;
lBDesc = lDesc.newBlockDescription("base");
lBDesc.materials.add(Material.SMOOTH_BRICK, (byte)3);
lBDesc.detectSensible = true;
lRel = lBDesc.newRelatedTo("lever", BuildingDescription.RelatedPosition.Nearby, 1);
lRel = lBDesc.newRelatedTo("sign", BuildingDescription.RelatedPosition.Nearby, 1);
lBDesc = lDesc.newBlockDescription("lever");
lBDesc.materials.add(Material.LEVER);
lBDesc = lDesc.newBlockDescription("sign");
lBDesc.materials.add(Material.SIGN);
lBDesc.materials.add(Material.SIGN_POST);
lBDesc.materials.add(Material.WALL_SIGN);
lDesc.activate();
lDesc = lDetector.newDescription("Building.RedStoneReceiver");
lDesc.typeName = "Building for receiving redstone signals";
lDesc.handler = lSRHandler;
lDesc.circleRadius = 1;
lDesc.color = 0x18CB18;
lBDesc = lDesc.newBlockDescription("base");
lBDesc.materials.add(Material.SMOOTH_BRICK, (byte)3);
lBDesc.detectSensible = true;
lRel = lBDesc.newRelatedTo(new Vector(0, 1, 0), "antenabase");
lRel = lBDesc.newRelatedTo("lever", BuildingDescription.RelatedPosition.Nearby, 1);
lRel = lBDesc.newRelatedTo("sign", BuildingDescription.RelatedPosition.Nearby, 1);
lBDesc = lDesc.newBlockDescription("lever");
lBDesc.materials.add(Material.LEVER);
lBDesc = lDesc.newBlockDescription("sign");
lBDesc.materials.add(Material.SIGN);
lBDesc.materials.add(Material.SIGN_POST);
lBDesc.materials.add(Material.WALL_SIGN);
lBDesc = lDesc.newBlockDescription("antenabase");
lBDesc.materials.add(Material.FENCE);
lRel = lBDesc.newRelatedTo(new Vector(0, 10, 0), "antenatop");
lRel.materials.add(Material.FENCE);
lRel.minDistance = 1;
lBDesc = lDesc.newBlockDescription("antenatop");
lBDesc.materials.add(Material.FENCE);
lDesc.activate();
lDesc = lDetector.newDescription("Building.RedStoneReceiver.Lamp");
lDesc.typeName = "Lamp for receiving redstone signals";
lDesc.handler = lSRHandler;
lDesc.circleRadius = 1;
lDesc.color = 0x88CB18;
lBDesc = lDesc.newBlockDescription("base");
lBDesc.materials.add(Material.REDSTONE_LAMP_ON);
lBDesc.materials.add(Material.REDSTONE_LAMP_OFF);
lBDesc.detectSensible = true;
lRel = lBDesc.newRelatedTo("lever", BuildingDescription.RelatedPosition.Nearby, 1);
lRel = lBDesc.newRelatedTo("sign", BuildingDescription.RelatedPosition.Nearby, 1);
lBDesc = lDesc.newBlockDescription("lever");
lBDesc.materials.add(Material.LEVER);
lBDesc = lDesc.newBlockDescription("sign");
lBDesc.materials.add(Material.SIGN);
lBDesc.materials.add(Material.SIGN_POST);
lBDesc.materials.add(Material.WALL_SIGN);
lDesc.activate();
lDesc = lDetector.newDescription("Building.RedStoneSender");
lDesc.typeName = "Building for sending redstone signals";
lDesc.handler = lSRHandler;
lDesc.circleRadius = 1;
lDesc.color = 0xCB6918;
lBDesc = lDesc.newBlockDescription("base");
lBDesc.materials.add(Material.SMOOTH_BRICK, (byte)3);
lBDesc.detectSensible = true;
lBDesc.redstoneSensible = true;
lRel = lBDesc.newRelatedTo(new Vector(0, 1, 0), "antenabase");
lRel = lBDesc.newRelatedTo("sign", BuildingDescription.RelatedPosition.Nearby, 1);
lBDesc = lDesc.newBlockDescription("sign");
lBDesc.materials.add(Material.SIGN);
lBDesc.materials.add(Material.SIGN_POST);
lBDesc.materials.add(Material.WALL_SIGN);
lBDesc = lDesc.newBlockDescription("antenabase");
lBDesc.materials.add(Material.FENCE);
lRel = lBDesc.newRelatedTo(new Vector(0, 10, 0), "antenatop");
lRel.materials.add(Material.FENCE);
lRel.minDistance = 1;
lBDesc = lDesc.newBlockDescription("antenatop");
lBDesc.materials.add(Material.FENCE);
lDesc.activate();
lDesc = lDetector.newDescription("Building.Pyramid.Sandstone");
lDesc.handler = lHandler;
lDesc.typeName = "Pyramid";
lBDesc = lDesc.newBlockDescription("top");
lBDesc.materials.add(Material.SANDSTONE);
lBDesc.detectSensible = true;
lBDesc.nameSensible = true;
lRel = lBDesc.newRelatedTo(new Vector( 80,-80, 80), "ground1");
lRel.materials.add(Material.SANDSTONE);
lRel.minDistance = 1;
lRel = lBDesc.newRelatedTo(new Vector( 80,-80,-80), "ground2");
lRel.materials.add(Material.SANDSTONE);
lRel.minDistance = 1;
lRel = lBDesc.newRelatedTo(new Vector(-80,-80, 80), "ground3");
lRel.materials.add(Material.SANDSTONE);
lRel.minDistance = 1;
lRel = lBDesc.newRelatedTo(new Vector(-80,-80,-80), "ground4");
lRel.materials.add(Material.SANDSTONE);
lRel.minDistance = 1;
lBDesc = lDesc.newBlockDescription("ground1");
lBDesc.materials.add(Material.SANDSTONE);
lBDesc = lDesc.newBlockDescription("ground2");
lBDesc.materials.add(Material.SANDSTONE);
lBDesc = lDesc.newBlockDescription("ground3");
lBDesc.materials.add(Material.SANDSTONE);
lBDesc = lDesc.newBlockDescription("ground4");
lBDesc.materials.add(Material.SANDSTONE);
lDesc.activate();
lDesc = lDetector.newDescription("Building.BoatRailStation");
lDesc.handler = lHandler;
lDesc.typeName = "BoatRailStation";
lDesc.iconName = "anchor";
lBDesc = lDesc.newBlockDescription("railblock");
lBDesc.materials.add(Material.COBBLESTONE_STAIRS);
lBDesc.materials.add(Material.SMOOTH_STAIRS);
lBDesc.materials.add(Material.WOOD_STAIRS);
lBDesc.materials.add(Material.BRICK_STAIRS);
lBDesc.materials.add(Material.NETHER_BRICK_STAIRS);
lBDesc.materials.add(Material.SANDSTONE_STAIRS);
lBDesc.materials.add(Material.SPRUCE_WOOD_STAIRS);
lBDesc.materials.add(Material.BIRCH_WOOD_STAIRS);
lBDesc.materials.add(Material.JUNGLE_WOOD_STAIRS);
lBDesc.detectSensible = true;
lBDesc.nameSensible = true;
lRel = lBDesc.newRelatedTo(new Vector(0, 0, 1), "rails");
lRel = lBDesc.newRelatedTo(new Vector(0,-1,-1), "water");
lBDesc = lDesc.newBlockDescription("rails");
lBDesc.materials.add(Material.RAILS);
lBDesc.materials.add(Material.POWERED_RAIL);
lBDesc.materials.add(Material.DETECTOR_RAIL);
lBDesc = lDesc.newBlockDescription("water");
lBDesc.materials.add(Material.STATIONARY_WATER);
lBDesc.materials.add(Material.WATER);
lRel = lBDesc.newRelatedTo(new Vector(0, 0,-1), "water2");
lBDesc = lDesc.newBlockDescription("water2");
lBDesc.materials.add(Material.STATIONARY_WATER);
lBDesc.materials.add(Material.WATER);
lRel = lBDesc.newRelatedTo(new Vector(1, 0, 0), "water3");
lRel = lBDesc.newRelatedTo(new Vector(-1, 0, 0), "water4");
lBDesc = lDesc.newBlockDescription("water3");
lBDesc.materials.add(Material.STATIONARY_WATER);
lBDesc.materials.add(Material.WATER);
lBDesc = lDesc.newBlockDescription("water4");
lBDesc.materials.add(Material.STATIONARY_WATER);
lBDesc.materials.add(Material.WATER);
lDesc.createAndActivateXZ(true);
lDesc = lDetector.newDescription("Building.Lodge");
BuildingDescription.BlockMaterialArray lMats = lDesc.newBlockMaterialArray();
lMats.add(Material.SMOOTH_BRICK);
lMats.add(Material.BRICK);
lMats.add(Material.WOOD);
lMats.add(Material.STONE);
lMats.add(Material.COBBLESTONE);
lMats.add(Material.SANDSTONE);
lMats.add(Material.BEDROCK);
lMats.add(Material.OBSIDIAN);
lMats.add(Material.WOOD_PLATE);
lMats.add(Material.NETHERRACK);
lMats.add(Material.NETHER_BRICK);
lMats.add(Material.IRON_BLOCK);
lMats.add(Material.GOLD_BLOCK);
lMats.add(Material.DIAMOND_BLOCK);
lMats.add(Material.EMERALD_BLOCK);
lDesc.handler = lHandler;
lDesc.typeName = "Lodge";
lBDesc = lDesc.newBlockDescription("ground_e1");
lBDesc.materials.add(lMats);
lBDesc.detectSensible = true;
lRel = lBDesc.newRelatedTo(new Vector( 1, 0, 0), "ground_e1x");
lRel = lBDesc.newRelatedTo(new Vector( 0, 1, 0), "ground_e1y");
lRel = lBDesc.newRelatedTo(new Vector( 0, 0, 1), "ground_e1z");
lRel = lBDesc.newRelatedTo(new Vector(20, 0,20), "ground_e3");
lRel.minDistance = 3;
lRel = lBDesc.newRelatedTo(new Vector(20, 0, 0), "ground_e2");
lRel.minDistance = 3;
lRel = lBDesc.newRelatedTo(new Vector( 0, 0,20), "ground_e4");
lRel.minDistance = 3;
lRel = lBDesc.newRelatedTo(new Vector( 0, 8, 0), "top_e1");
//lRel = lBDesc.newRelatedTo(new Vector(19, 0, 0), "door");
lBDesc = lDesc.newBlockDescription("ground_e2");
lBDesc.materials.add(lMats);
lRel = lBDesc.newRelatedTo(new Vector(-1, 0, 0), "ground_e2x");
lRel = lBDesc.newRelatedTo(new Vector( 0, 1, 0), "ground_e2y");
lRel = lBDesc.newRelatedTo(new Vector( 0, 0, 1), "ground_e2z");
lRel = lBDesc.newRelatedTo(new Vector( 0, 8, 0), "top_e2");
lBDesc = lDesc.newBlockDescription("ground_e3");
lBDesc.materials.add(lMats);
lRel = lBDesc.newRelatedTo(new Vector(-1, 0, 0), "ground_e3x");
lRel = lBDesc.newRelatedTo(new Vector( 0, 1, 0), "ground_e3y");
lRel = lBDesc.newRelatedTo(new Vector( 0, 0,-1), "ground_e3z");
lRel = lBDesc.newRelatedTo(new Vector( 0, 8, 0), "top_e3");
lBDesc = lDesc.newBlockDescription("ground_e4");
lBDesc.materials.add(lMats);
lRel = lBDesc.newRelatedTo(new Vector( 1, 0, 0), "ground_e4x");
lRel = lBDesc.newRelatedTo(new Vector( 0, 1, 0), "ground_e4y");
lRel = lBDesc.newRelatedTo(new Vector( 0, 0,-1), "ground_e4z");
lRel = lBDesc.newRelatedTo(new Vector( 0, 8, 0), "top_e4");
lBDesc = lDesc.newBlockDescription("ground_e1x");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e1y");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e1z");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e2x");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e2y");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e2z");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e3x");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e3y");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e3z");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e4x");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e4y");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e4z");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("top_e1");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("top_e2");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("top_e3");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("top_e4");
lBDesc.materials.add(lMats);
//lBDesc = lDesc.newBlockDescription("door");
//lBDesc.materials.add(Material.WOODEN_DOOR);
//lRel = lBDesc.newRelatedTo(new Vector( 0, 1, 0), "door_top");
//lBDesc = lDesc.newBlockDescription("door_top");
//lBDesc.materials.add(Material.WOODEN_DOOR);
//lDesc.createAndActivateXZ();
lDesc = lDetector.newDescription("Building.Lift");
lDesc.handler = lHandler;
lDesc.typeName = "Lift";
lBDesc = lDesc.newBlockDescription("bottomleftfront");
lBDesc.materials.add(Material.IRON_BLOCK);
lBDesc.detectSensible = true;
lRel = lBDesc.newRelatedTo(new Vector( 0, 0,10), "bottomleftback");
lRel = lBDesc.newRelatedTo(new Vector(10, 0, 0), "bottomrightfront");
lRel = lBDesc.newRelatedTo(new Vector(10, 0,10), "bottomrightback");
lRel = lBDesc.newRelatedTo(new Vector( 0,10, 0), "topleftfront");
lRel = lBDesc.newRelatedTo(new Vector( 0,10,10), "topleftback");
lRel = lBDesc.newRelatedTo(new Vector(10,10, 0), "toprightfront");
lRel = lBDesc.newRelatedTo(new Vector(10,10,10), "toprightback");
lBDesc = lDesc.newBlockDescription("bottomleftback");
lBDesc.materials.add(Material.IRON_BLOCK);
lBDesc = lDesc.newBlockDescription("bottomrightfront");
lBDesc.materials.add(Material.IRON_BLOCK);
lBDesc = lDesc.newBlockDescription("bottomrightback");
lBDesc.materials.add(Material.IRON_BLOCK);
lBDesc = lDesc.newBlockDescription("topleftfront");
lBDesc.materials.add(Material.IRON_BLOCK);
lBDesc = lDesc.newBlockDescription("topleftback");
lBDesc.materials.add(Material.IRON_BLOCK);
lBDesc = lDesc.newBlockDescription("toprightfront");
lBDesc.materials.add(Material.IRON_BLOCK);
lBDesc = lDesc.newBlockDescription("toprightback");
lBDesc.materials.add(Material.IRON_BLOCK);
//lDesc.activate();
lDesc = lDetector.newDescription("Building.Landmark");
lDesc.handler = lHandler;
lDesc.typeName = "Landmark";
lDesc.circleRadius = 1;
lDesc.visibleOnMap = false;
lBDesc = lDesc.newBlockDescription("bottom");
lBDesc.materials.add(Material.SMOOTH_BRICK, (byte)3);
lBDesc.detectSensible = true;
lRel = lBDesc.newRelatedTo(new Vector( 0, 2, 0), "top");
lRel.materials.add(Material.SMOOTH_BRICK, (byte)3);
lBDesc = lDesc.newBlockDescription("top");
lBDesc.materials.add(Material.SMOOTH_BRICK, (byte)3);
lBDesc.nameSensible = true;
lRel = lBDesc.newRelatedTo("sign", BuildingDescription.RelatedPosition.Nearby, 1);
lBDesc = lDesc.newBlockDescription("sign");
lBDesc.materials.add(Material.SIGN);
lBDesc.materials.add(Material.SIGN_POST);
lBDesc.materials.add(Material.WALL_SIGN);
lDesc.activate();
lDesc = lDetector.newDescription("Building.Portal");
lDesc.handler = lHandler;
lDesc.typeName = "Portal";
lDesc.iconName = "portal";
lBDesc = lDesc.newBlockDescription("bottomleft");
lBDesc.materials.add(Material.OBSIDIAN);
lBDesc.detectSensible = true;
lBDesc.nameSensible = true;
lRel = lBDesc.newRelatedTo("sign", BuildingDescription.RelatedPosition.Nearby, 1);
lRel = lBDesc.newRelatedTo(new Vector( 3, 0, 0), "bottomright");
lRel.materials.add(Material.AIR);
lRel.minDistance = 2;
lRel = lBDesc.newRelatedTo(new Vector( 0, 4, 0), "topleft");
lRel.materials.add(Material.OBSIDIAN);
lRel.minDistance = 2;
lBDesc = lDesc.newBlockDescription("bottomright");
lBDesc.materials.add(Material.OBSIDIAN);
lRel = lBDesc.newRelatedTo(new Vector( 0, 4, 0), "topright");
lRel.materials.add(Material.OBSIDIAN);
lRel.minDistance = 2;
lBDesc = lDesc.newBlockDescription("topleft");
lBDesc.materials.add(Material.GLOWSTONE);
lRel = lBDesc.newRelatedTo(new Vector( 3, 0, 0), "topright");
lRel.materials.add(Material.OBSIDIAN);
lRel.minDistance = 2;
lBDesc = lDesc.newBlockDescription("topright");
lBDesc.materials.add(Material.GLOWSTONE);
lBDesc = lDesc.newBlockDescription("sign");
lBDesc.materials.add(Material.SIGN);
lBDesc.materials.add(Material.SIGN_POST);
lBDesc.materials.add(Material.WALL_SIGN);
lDesc.createAndActivateXZ();
lDesc = lDetector.newDescription("Building.Monument.Creeper");
lDesc.handler = lHandler;
lDesc.typeName = "Creeper Monument";
//lDesc.iconName = "tower";
lDesc.circleRadius = 100;
lDesc.influenceRadiusFactor = 100.0;
lDesc.color = 0x80FF80;
lBDesc = lDesc.newBlockDescription("top");
lBDesc.materials.add(Material.GOLD_BLOCK);
lBDesc.detectSensible = true;
lBDesc.nameSensible = true;
lRel = lBDesc.newRelatedTo(new Vector( 2,-2, 2), "e11");
lRel.materials.add(Material.NETHERRACK);
lRel = lBDesc.newRelatedTo(new Vector(-2,-2, 2), "e12");
lRel.materials.add(Material.NETHERRACK);
lRel = lBDesc.newRelatedTo(new Vector(-2,-2,-2), "e13");
lRel.materials.add(Material.NETHERRACK);
lRel = lBDesc.newRelatedTo(new Vector( 2,-2,-2), "e14");
lRel.materials.add(Material.NETHERRACK);
lBDesc = lDesc.newBlockDescription("e11");
lBDesc.materials.add(Material.NETHERRACK);
lBDesc = lDesc.newBlockDescription("e12");
lBDesc.materials.add(Material.NETHERRACK);
lBDesc = lDesc.newBlockDescription("e13");
lBDesc.materials.add(Material.NETHERRACK);
lBDesc = lDesc.newBlockDescription("e14");
lBDesc.materials.add(Material.NETHERRACK);
lDesc.activate();
}
| public void onEnable() {
plugin = this;
getServer().getPluginManager().registerEvents(new BuildingListener(), this);
SimpleDBs = new WorldDBList<SimpleBuildingDB>(SimpleBuildingDB.class, this);
SendReceiveDBs = new WorldDBList<SendReceiveDB>(SendReceiveDB.class, "SendReceive", this);
LandmarkDBs = new WorldDBList<LandmarkDB>(LandmarkDB.class, "Landmark", this);
Framework.plugin.registerSaver(SimpleDBs);
Framework.plugin.registerSaver(SendReceiveDBs);
Framework.plugin.registerSaver(LandmarkDBs);
Framework.plugin.registerMarkerStorage(new MarkerStorage());
getCommand("bd_landmark_list").setExecutor(new CommandLandmarkList());
fDynMapTask = new DynMapLandmarkRenderer();
getServer().getScheduler().scheduleSyncRepeatingTask(this, fDynMapTask, 100, 20);
//ItemStack lItemStack = new ItemStack(Material.SMOOTH_BRICK, 4);//, (short)0, (byte)3);
//lItemStack.setData(new MaterialData(Material.SMOOTH_BRICK, (byte)3));
ItemStack lItemStack = new ItemStack(Material.SMOOTH_BRICK, 4, (short)0, (byte)3);
ShapedRecipe lShapeRecipe = new ShapedRecipe(lItemStack);
lShapeRecipe.shape("AA", "AA");
lShapeRecipe.setIngredient('A', Material.SMOOTH_BRICK);
getServer().addRecipe(lShapeRecipe);
lItemStack = new ItemStack(Material.SMOOTH_BRICK, 4); //, (short)0, (byte)0);
ShapedRecipe lChiseledStoneBrick = new ShapedRecipe(lItemStack);
lChiseledStoneBrick.shape("AA", "AA");
lChiseledStoneBrick.setIngredient('A', new MaterialData(Material.SMOOTH_BRICK, (byte)3));
getServer().addRecipe(lChiseledStoneBrick);
//lItemStack = new ItemStack(Material.SNOW_BLOCK, 6); //, (short)0, (byte)0);
//lItemStack.setData(new MaterialData(Material.SNOW_BLOCK, (byte)3));
//lItemStack = new ItemStack(Material.SNOW, 6, (short)0, (byte)3);
//ShapedRecipe lHalfSnow = new ShapedRecipe(lItemStack);
//lHalfSnow.shape("AAA");
//lHalfSnow.setIngredient('A', new MaterialData(Material.SNOW_BLOCK, (byte)0));
//getServer().addRecipe(lHalfSnow);
SimpleBuildingHandler lHandler = new SimpleBuildingHandler(this);
SendReceiveHandler lSRHandler = new SendReceiveHandler(this);
BuildingDetector lDetector = Framework.plugin.getBuildingDetector();
BuildingDescription lDesc;
BuildingDescription.BlockDescription lBDesc;
BuildingDescription.RelatedTo lRel;
lDesc = lDetector.newDescription("Building.BuildingEntryDetector");
lDesc.typeName = "Building Enter/Leave Detector";
lDesc.handler = lHandler;
lDesc.circleRadius = 1;
lDesc.color = 0xC818CB;
lBDesc = lDesc.newBlockDescription("base");
lBDesc.materials.add(Material.SMOOTH_BRICK, (byte)3);
lBDesc.detectSensible = true;
lRel = lBDesc.newRelatedTo("lever", BuildingDescription.RelatedPosition.Nearby, 1);
lRel = lBDesc.newRelatedTo("sign", BuildingDescription.RelatedPosition.Nearby, 1);
lBDesc = lDesc.newBlockDescription("lever");
lBDesc.materials.add(Material.LEVER);
lBDesc = lDesc.newBlockDescription("sign");
lBDesc.materials.add(Material.SIGN);
lBDesc.materials.add(Material.SIGN_POST);
lBDesc.materials.add(Material.WALL_SIGN);
lDesc.activate();
lDesc = lDetector.newDescription("Building.RedStoneReceiver");
lDesc.typeName = "Building for receiving redstone signals";
lDesc.handler = lSRHandler;
lDesc.circleRadius = 1;
lDesc.color = 0x18CB18;
lBDesc = lDesc.newBlockDescription("base");
lBDesc.materials.add(Material.SMOOTH_BRICK, (byte)3);
lBDesc.detectSensible = true;
lRel = lBDesc.newRelatedTo(new Vector(0, 1, 0), "antenabase");
lRel = lBDesc.newRelatedTo("lever", BuildingDescription.RelatedPosition.Nearby, 1);
lRel = lBDesc.newRelatedTo("sign", BuildingDescription.RelatedPosition.Nearby, 1);
lBDesc = lDesc.newBlockDescription("lever");
lBDesc.materials.add(Material.LEVER);
lBDesc = lDesc.newBlockDescription("sign");
lBDesc.materials.add(Material.SIGN);
lBDesc.materials.add(Material.SIGN_POST);
lBDesc.materials.add(Material.WALL_SIGN);
lBDesc = lDesc.newBlockDescription("antenabase");
lBDesc.materials.add(Material.FENCE);
lRel = lBDesc.newRelatedTo(new Vector(0, 10, 0), "antenatop");
lRel.materials.add(Material.FENCE);
lRel.minDistance = 1;
lBDesc = lDesc.newBlockDescription("antenatop");
lBDesc.materials.add(Material.FENCE);
lDesc.activate();
lDesc = lDetector.newDescription("Building.RedStoneReceiver.Lamp");
lDesc.typeName = "Lamp for receiving redstone signals";
lDesc.handler = lSRHandler;
lDesc.circleRadius = 1;
lDesc.color = 0x88CB18;
lBDesc = lDesc.newBlockDescription("base");
lBDesc.materials.add(Material.REDSTONE_LAMP_ON);
lBDesc.materials.add(Material.REDSTONE_LAMP_OFF);
lBDesc.detectSensible = true;
lRel = lBDesc.newRelatedTo("lever", BuildingDescription.RelatedPosition.Nearby, 1);
lRel = lBDesc.newRelatedTo("sign", BuildingDescription.RelatedPosition.Nearby, 1);
lBDesc = lDesc.newBlockDescription("lever");
lBDesc.materials.add(Material.LEVER);
lBDesc = lDesc.newBlockDescription("sign");
lBDesc.materials.add(Material.SIGN);
lBDesc.materials.add(Material.SIGN_POST);
lBDesc.materials.add(Material.WALL_SIGN);
lDesc.activate();
lDesc = lDetector.newDescription("Building.RedStoneSender");
lDesc.typeName = "Building for sending redstone signals";
lDesc.handler = lSRHandler;
lDesc.circleRadius = 1;
lDesc.color = 0xCB6918;
lBDesc = lDesc.newBlockDescription("base");
lBDesc.materials.add(Material.SMOOTH_BRICK, (byte)3);
lBDesc.detectSensible = true;
lBDesc.redstoneSensible = true;
lRel = lBDesc.newRelatedTo(new Vector(0, 1, 0), "antenabase");
lRel = lBDesc.newRelatedTo("sign", BuildingDescription.RelatedPosition.Nearby, 1);
lBDesc = lDesc.newBlockDescription("sign");
lBDesc.materials.add(Material.SIGN);
lBDesc.materials.add(Material.SIGN_POST);
lBDesc.materials.add(Material.WALL_SIGN);
lBDesc = lDesc.newBlockDescription("antenabase");
lBDesc.materials.add(Material.FENCE);
lRel = lBDesc.newRelatedTo(new Vector(0, 10, 0), "antenatop");
lRel.materials.add(Material.FENCE);
lRel.minDistance = 1;
lBDesc = lDesc.newBlockDescription("antenatop");
lBDesc.materials.add(Material.FENCE);
lDesc.activate();
lDesc = lDetector.newDescription("Building.Pyramid.Sandstone");
lDesc.handler = lHandler;
lDesc.typeName = "Pyramid";
lBDesc = lDesc.newBlockDescription("top");
lBDesc.materials.add(Material.SANDSTONE);
lBDesc.detectSensible = true;
lBDesc.nameSensible = true;
lRel = lBDesc.newRelatedTo(new Vector( 80,-80, 80), "ground1");
lRel.materials.add(Material.SANDSTONE);
lRel.minDistance = 1;
lRel = lBDesc.newRelatedTo(new Vector( 80,-80,-80), "ground2");
lRel.materials.add(Material.SANDSTONE);
lRel.minDistance = 1;
lRel = lBDesc.newRelatedTo(new Vector(-80,-80, 80), "ground3");
lRel.materials.add(Material.SANDSTONE);
lRel.minDistance = 1;
lRel = lBDesc.newRelatedTo(new Vector(-80,-80,-80), "ground4");
lRel.materials.add(Material.SANDSTONE);
lRel.minDistance = 1;
lBDesc = lDesc.newBlockDescription("ground1");
lBDesc.materials.add(Material.SANDSTONE);
lBDesc = lDesc.newBlockDescription("ground2");
lBDesc.materials.add(Material.SANDSTONE);
lBDesc = lDesc.newBlockDescription("ground3");
lBDesc.materials.add(Material.SANDSTONE);
lBDesc = lDesc.newBlockDescription("ground4");
lBDesc.materials.add(Material.SANDSTONE);
lDesc.activate();
lDesc = lDetector.newDescription("Building.BoatRailStation");
lDesc.handler = lHandler;
lDesc.typeName = "BoatRailStation";
lDesc.iconName = "anchor";
lBDesc = lDesc.newBlockDescription("railblock");
lBDesc.materials.add(Material.COBBLESTONE_STAIRS);
lBDesc.materials.add(Material.SMOOTH_STAIRS);
lBDesc.materials.add(Material.WOOD_STAIRS);
lBDesc.materials.add(Material.BRICK_STAIRS);
lBDesc.materials.add(Material.NETHER_BRICK_STAIRS);
lBDesc.materials.add(Material.SANDSTONE_STAIRS);
lBDesc.materials.add(Material.SPRUCE_WOOD_STAIRS);
lBDesc.materials.add(Material.BIRCH_WOOD_STAIRS);
lBDesc.materials.add(Material.JUNGLE_WOOD_STAIRS);
lBDesc.detectSensible = true;
lBDesc.nameSensible = true;
lRel = lBDesc.newRelatedTo(new Vector(0, 0, 1), "rails");
lRel = lBDesc.newRelatedTo(new Vector(0,-1,-1), "water");
lBDesc = lDesc.newBlockDescription("rails");
lBDesc.materials.add(Material.RAILS);
lBDesc.materials.add(Material.POWERED_RAIL);
lBDesc.materials.add(Material.DETECTOR_RAIL);
lBDesc = lDesc.newBlockDescription("water");
lBDesc.materials.add(Material.STATIONARY_WATER);
lBDesc.materials.add(Material.WATER);
lRel = lBDesc.newRelatedTo(new Vector(0, 0,-1), "water2");
lBDesc = lDesc.newBlockDescription("water2");
lBDesc.materials.add(Material.STATIONARY_WATER);
lBDesc.materials.add(Material.WATER);
lRel = lBDesc.newRelatedTo(new Vector(1, 0, 0), "water3");
lRel = lBDesc.newRelatedTo(new Vector(-1, 0, 0), "water4");
lBDesc = lDesc.newBlockDescription("water3");
lBDesc.materials.add(Material.STATIONARY_WATER);
lBDesc.materials.add(Material.WATER);
lBDesc = lDesc.newBlockDescription("water4");
lBDesc.materials.add(Material.STATIONARY_WATER);
lBDesc.materials.add(Material.WATER);
lDesc.createAndActivateXZ(true);
lDesc = lDetector.newDescription("Building.Lodge");
BuildingDescription.BlockMaterialArray lMats = lDesc.newBlockMaterialArray();
lMats.add(Material.SMOOTH_BRICK);
lMats.add(Material.BRICK);
lMats.add(Material.WOOD);
lMats.add(Material.STONE);
lMats.add(Material.COBBLESTONE);
lMats.add(Material.SANDSTONE);
lMats.add(Material.BEDROCK);
lMats.add(Material.OBSIDIAN);
lMats.add(Material.WOOD_PLATE);
lMats.add(Material.NETHERRACK);
lMats.add(Material.NETHER_BRICK);
lMats.add(Material.IRON_BLOCK);
lMats.add(Material.GOLD_BLOCK);
lMats.add(Material.DIAMOND_BLOCK);
lMats.add(Material.EMERALD_BLOCK);
lDesc.handler = lHandler;
lDesc.typeName = "Lodge";
lBDesc = lDesc.newBlockDescription("ground_e1");
lBDesc.materials.add(lMats);
lBDesc.detectSensible = true;
lRel = lBDesc.newRelatedTo(new Vector( 1, 0, 0), "ground_e1x");
lRel = lBDesc.newRelatedTo(new Vector( 0, 1, 0), "ground_e1y");
lRel = lBDesc.newRelatedTo(new Vector( 0, 0, 1), "ground_e1z");
lRel = lBDesc.newRelatedTo(new Vector(20, 0,20), "ground_e3");
lRel.minDistance = 3;
lRel = lBDesc.newRelatedTo(new Vector(20, 0, 0), "ground_e2");
lRel.minDistance = 3;
lRel = lBDesc.newRelatedTo(new Vector( 0, 0,20), "ground_e4");
lRel.minDistance = 3;
lRel = lBDesc.newRelatedTo(new Vector( 0, 8, 0), "top_e1");
//lRel = lBDesc.newRelatedTo(new Vector(19, 0, 0), "door");
lBDesc = lDesc.newBlockDescription("ground_e2");
lBDesc.materials.add(lMats);
lRel = lBDesc.newRelatedTo(new Vector(-1, 0, 0), "ground_e2x");
lRel = lBDesc.newRelatedTo(new Vector( 0, 1, 0), "ground_e2y");
lRel = lBDesc.newRelatedTo(new Vector( 0, 0, 1), "ground_e2z");
lRel = lBDesc.newRelatedTo(new Vector( 0, 8, 0), "top_e2");
lBDesc = lDesc.newBlockDescription("ground_e3");
lBDesc.materials.add(lMats);
lRel = lBDesc.newRelatedTo(new Vector(-1, 0, 0), "ground_e3x");
lRel = lBDesc.newRelatedTo(new Vector( 0, 1, 0), "ground_e3y");
lRel = lBDesc.newRelatedTo(new Vector( 0, 0,-1), "ground_e3z");
lRel = lBDesc.newRelatedTo(new Vector( 0, 8, 0), "top_e3");
lBDesc = lDesc.newBlockDescription("ground_e4");
lBDesc.materials.add(lMats);
lRel = lBDesc.newRelatedTo(new Vector( 1, 0, 0), "ground_e4x");
lRel = lBDesc.newRelatedTo(new Vector( 0, 1, 0), "ground_e4y");
lRel = lBDesc.newRelatedTo(new Vector( 0, 0,-1), "ground_e4z");
lRel = lBDesc.newRelatedTo(new Vector( 0, 8, 0), "top_e4");
lBDesc = lDesc.newBlockDescription("ground_e1x");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e1y");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e1z");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e2x");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e2y");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e2z");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e3x");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e3y");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e3z");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e4x");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e4y");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("ground_e4z");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("top_e1");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("top_e2");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("top_e3");
lBDesc.materials.add(lMats);
lBDesc = lDesc.newBlockDescription("top_e4");
lBDesc.materials.add(lMats);
//lBDesc = lDesc.newBlockDescription("door");
//lBDesc.materials.add(Material.WOODEN_DOOR);
//lRel = lBDesc.newRelatedTo(new Vector( 0, 1, 0), "door_top");
//lBDesc = lDesc.newBlockDescription("door_top");
//lBDesc.materials.add(Material.WOODEN_DOOR);
//lDesc.createAndActivateXZ();
lDesc = lDetector.newDescription("Building.Lift");
lDesc.handler = lHandler;
lDesc.typeName = "Lift";
lBDesc = lDesc.newBlockDescription("bottomleftfront");
lBDesc.materials.add(Material.IRON_BLOCK);
lBDesc.detectSensible = true;
lRel = lBDesc.newRelatedTo(new Vector( 0, 0,10), "bottomleftback");
lRel = lBDesc.newRelatedTo(new Vector(10, 0, 0), "bottomrightfront");
lRel = lBDesc.newRelatedTo(new Vector(10, 0,10), "bottomrightback");
lRel = lBDesc.newRelatedTo(new Vector( 0,10, 0), "topleftfront");
lRel = lBDesc.newRelatedTo(new Vector( 0,10,10), "topleftback");
lRel = lBDesc.newRelatedTo(new Vector(10,10, 0), "toprightfront");
lRel = lBDesc.newRelatedTo(new Vector(10,10,10), "toprightback");
lBDesc = lDesc.newBlockDescription("bottomleftback");
lBDesc.materials.add(Material.IRON_BLOCK);
lBDesc = lDesc.newBlockDescription("bottomrightfront");
lBDesc.materials.add(Material.IRON_BLOCK);
lBDesc = lDesc.newBlockDescription("bottomrightback");
lBDesc.materials.add(Material.IRON_BLOCK);
lBDesc = lDesc.newBlockDescription("topleftfront");
lBDesc.materials.add(Material.IRON_BLOCK);
lBDesc = lDesc.newBlockDescription("topleftback");
lBDesc.materials.add(Material.IRON_BLOCK);
lBDesc = lDesc.newBlockDescription("toprightfront");
lBDesc.materials.add(Material.IRON_BLOCK);
lBDesc = lDesc.newBlockDescription("toprightback");
lBDesc.materials.add(Material.IRON_BLOCK);
//lDesc.activate();
lDesc = lDetector.newDescription("Building.Landmark");
lDesc.handler = lHandler;
lDesc.typeName = "Landmark";
lDesc.circleRadius = 1;
lDesc.visibleOnMap = false;
lDesc.position = BuildingDescription.Position.everywhere;
lBDesc = lDesc.newBlockDescription("bottom");
lBDesc.materials.add(Material.SMOOTH_BRICK, (byte)3);
lBDesc.detectSensible = true;
lRel = lBDesc.newRelatedTo(new Vector( 0, 2, 0), "top");
lRel.materials.add(Material.SMOOTH_BRICK, (byte)3);
lBDesc = lDesc.newBlockDescription("top");
lBDesc.materials.add(Material.SMOOTH_BRICK, (byte)3);
lBDesc.nameSensible = true;
lRel = lBDesc.newRelatedTo("sign", BuildingDescription.RelatedPosition.Nearby, 1);
lBDesc = lDesc.newBlockDescription("sign");
lBDesc.materials.add(Material.SIGN);
lBDesc.materials.add(Material.SIGN_POST);
lBDesc.materials.add(Material.WALL_SIGN);
lDesc.activate();
lDesc = lDetector.newDescription("Building.Portal");
lDesc.handler = lHandler;
lDesc.typeName = "Portal";
lDesc.iconName = "portal";
lDesc.position = BuildingDescription.Position.everywhere;
lBDesc = lDesc.newBlockDescription("bottomleft");
lBDesc.materials.add(Material.OBSIDIAN);
lBDesc.detectSensible = true;
lBDesc.nameSensible = true;
lRel = lBDesc.newRelatedTo("sign", BuildingDescription.RelatedPosition.Nearby, 1);
lRel = lBDesc.newRelatedTo(new Vector( 3, 0, 0), "bottomright");
lRel.materials.add(Material.AIR);
lRel.minDistance = 2;
lRel = lBDesc.newRelatedTo(new Vector( 0, 4, 0), "topleft");
lRel.materials.add(Material.OBSIDIAN);
lRel.minDistance = 2;
lBDesc = lDesc.newBlockDescription("bottomright");
lBDesc.materials.add(Material.OBSIDIAN);
lRel = lBDesc.newRelatedTo(new Vector( 0, 4, 0), "topright");
lRel.materials.add(Material.OBSIDIAN);
lRel.minDistance = 2;
lBDesc = lDesc.newBlockDescription("topleft");
lBDesc.materials.add(Material.GLOWSTONE);
lRel = lBDesc.newRelatedTo(new Vector( 3, 0, 0), "topright");
lRel.materials.add(Material.OBSIDIAN);
lRel.minDistance = 2;
lBDesc = lDesc.newBlockDescription("topright");
lBDesc.materials.add(Material.GLOWSTONE);
lBDesc = lDesc.newBlockDescription("sign");
lBDesc.materials.add(Material.SIGN);
lBDesc.materials.add(Material.SIGN_POST);
lBDesc.materials.add(Material.WALL_SIGN);
lDesc.createAndActivateXZ();
lDesc = lDetector.newDescription("Building.Monument.Creeper");
lDesc.handler = lHandler;
lDesc.typeName = "Creeper Monument";
//lDesc.iconName = "tower";
lDesc.circleRadius = 100;
lDesc.influenceRadiusFactor = 100.0;
lDesc.color = 0x80FF80;
lBDesc = lDesc.newBlockDescription("top");
lBDesc.materials.add(Material.GOLD_BLOCK);
lBDesc.detectSensible = true;
lBDesc.nameSensible = true;
lRel = lBDesc.newRelatedTo(new Vector( 2,-2, 2), "e11");
lRel.materials.add(Material.NETHERRACK);
lRel = lBDesc.newRelatedTo(new Vector(-2,-2, 2), "e12");
lRel.materials.add(Material.NETHERRACK);
lRel = lBDesc.newRelatedTo(new Vector(-2,-2,-2), "e13");
lRel.materials.add(Material.NETHERRACK);
lRel = lBDesc.newRelatedTo(new Vector( 2,-2,-2), "e14");
lRel.materials.add(Material.NETHERRACK);
lBDesc = lDesc.newBlockDescription("e11");
lBDesc.materials.add(Material.NETHERRACK);
lBDesc = lDesc.newBlockDescription("e12");
lBDesc.materials.add(Material.NETHERRACK);
lBDesc = lDesc.newBlockDescription("e13");
lBDesc.materials.add(Material.NETHERRACK);
lBDesc = lDesc.newBlockDescription("e14");
lBDesc.materials.add(Material.NETHERRACK);
lDesc.activate();
}
|
diff --git a/src/org/jruby/ext/NetProtocolBufferedIO.java b/src/org/jruby/ext/NetProtocolBufferedIO.java
index 6772702a7..aab1637b9 100644
--- a/src/org/jruby/ext/NetProtocolBufferedIO.java
+++ b/src/org/jruby/ext/NetProtocolBufferedIO.java
@@ -1,124 +1,132 @@
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2008 Ola Bini <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby.ext;
import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SelectableChannel;
import java.util.Map;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyModule;
import org.jruby.RubyObject;
import org.jruby.RubyNumeric;
import org.jruby.RubyIO;
import org.jruby.Ruby;
import org.jruby.RubyException;
import org.jruby.RubyModule;
import org.jruby.RubyClass;
import org.jruby.RubyString;
import org.jruby.internal.runtime.methods.DynamicMethod;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.ThreadContext;
import org.jruby.util.io.ChannelStream;
import org.jruby.exceptions.RaiseException;
/**
* @author <a href="mailto:[email protected]">Ola Bini</a>
*/
@JRubyClass(name="Net::BufferedIO")
public class NetProtocolBufferedIO {
public static void create(Ruby runtime) {
RubyModule mNet = runtime.getModule("Net");
RubyClass cBufferedIO = (RubyClass)mNet.getConstant("BufferedIO");
cBufferedIO.defineAnnotatedMethods(NetProtocolBufferedIO.class);
RubyModule mNativeImpl = cBufferedIO.defineModuleUnder("NativeImplementation");
mNativeImpl.defineAnnotatedMethods(NativeImpl.class);
}
@JRubyMethod(required = 1)
public static IRubyObject initialize(IRubyObject recv, IRubyObject io) {
if(io instanceof RubyIO &&
(((RubyIO)io).getOpenFile().getMainStream() instanceof ChannelStream) &&
(((ChannelStream)((RubyIO)io).getOpenFile().getMainStream()).getDescriptor().getChannel() instanceof SelectableChannel)) {
((RubyObject)recv).extend(new IRubyObject[]{((RubyModule)recv.getRuntime().getModule("Net").getConstant("BufferedIO")).getConstant("NativeImplementation")});
SelectableChannel sc = (SelectableChannel)(((ChannelStream)((RubyIO)io).getOpenFile().getMainStream()).getDescriptor().getChannel());
recv.dataWrapStruct(new NativeImpl(sc));
}
recv.getInstanceVariables().setInstanceVariable("@io", io);
recv.getInstanceVariables().setInstanceVariable("@read_timeout", recv.getRuntime().newFixnum(60));
recv.getInstanceVariables().setInstanceVariable("@debug_output", recv.getRuntime().getNil());
recv.getInstanceVariables().setInstanceVariable("@rbuf", recv.getRuntime().newString(""));
return recv;
}
@JRubyModule(name="Net::BufferedIO::NativeImplementation")
public static class NativeImpl {
private SelectableChannel channel;
public NativeImpl(SelectableChannel channel) {
this.channel = channel;
}
@JRubyMethod
public static IRubyObject rbuf_fill(IRubyObject recv) {
RubyString buf = (RubyString)recv.getInstanceVariables().getInstanceVariable("@rbuf");
RubyIO io = (RubyIO)recv.getInstanceVariables().getInstanceVariable("@io");
int timeout = RubyNumeric.fix2int(recv.getInstanceVariables().getInstanceVariable("@read_timeout")) * 1000;
NativeImpl nim = (NativeImpl)recv.dataGetStruct();
+ Selector selector = null;
try {
- Selector selector = Selector.open();
+ selector = Selector.open();
nim.channel.configureBlocking(false);
SelectionKey key = nim.channel.register(selector, SelectionKey.OP_READ);
int n = selector.select(timeout);
if(n > 0) {
IRubyObject readItems = io.read(new IRubyObject[]{recv.getRuntime().newFixnum(8196)});
return buf.concat(readItems);
} else {
RubyClass exc = (RubyClass)(recv.getRuntime().getModule("Timeout").getConstant("Error"));
throw new RaiseException(RubyException.newException(recv.getRuntime(), exc, "execution expired"),false);
}
} catch(IOException exception) {
throw recv.getRuntime().newIOErrorFromException(exception);
+ } finally {
+ if (selector != null) {
+ try {
+ selector.close();
+ } catch (IOException ioe) {
+ }
+ }
}
}
}
}// NetProtocolBufferedIO
| false | true | public static IRubyObject rbuf_fill(IRubyObject recv) {
RubyString buf = (RubyString)recv.getInstanceVariables().getInstanceVariable("@rbuf");
RubyIO io = (RubyIO)recv.getInstanceVariables().getInstanceVariable("@io");
int timeout = RubyNumeric.fix2int(recv.getInstanceVariables().getInstanceVariable("@read_timeout")) * 1000;
NativeImpl nim = (NativeImpl)recv.dataGetStruct();
try {
Selector selector = Selector.open();
nim.channel.configureBlocking(false);
SelectionKey key = nim.channel.register(selector, SelectionKey.OP_READ);
int n = selector.select(timeout);
if(n > 0) {
IRubyObject readItems = io.read(new IRubyObject[]{recv.getRuntime().newFixnum(8196)});
return buf.concat(readItems);
} else {
RubyClass exc = (RubyClass)(recv.getRuntime().getModule("Timeout").getConstant("Error"));
throw new RaiseException(RubyException.newException(recv.getRuntime(), exc, "execution expired"),false);
}
} catch(IOException exception) {
throw recv.getRuntime().newIOErrorFromException(exception);
}
}
| public static IRubyObject rbuf_fill(IRubyObject recv) {
RubyString buf = (RubyString)recv.getInstanceVariables().getInstanceVariable("@rbuf");
RubyIO io = (RubyIO)recv.getInstanceVariables().getInstanceVariable("@io");
int timeout = RubyNumeric.fix2int(recv.getInstanceVariables().getInstanceVariable("@read_timeout")) * 1000;
NativeImpl nim = (NativeImpl)recv.dataGetStruct();
Selector selector = null;
try {
selector = Selector.open();
nim.channel.configureBlocking(false);
SelectionKey key = nim.channel.register(selector, SelectionKey.OP_READ);
int n = selector.select(timeout);
if(n > 0) {
IRubyObject readItems = io.read(new IRubyObject[]{recv.getRuntime().newFixnum(8196)});
return buf.concat(readItems);
} else {
RubyClass exc = (RubyClass)(recv.getRuntime().getModule("Timeout").getConstant("Error"));
throw new RaiseException(RubyException.newException(recv.getRuntime(), exc, "execution expired"),false);
}
} catch(IOException exception) {
throw recv.getRuntime().newIOErrorFromException(exception);
} finally {
if (selector != null) {
try {
selector.close();
} catch (IOException ioe) {
}
}
}
}
|
diff --git a/src/main/java/org/structnetalign/merge/BronKerboschMergeJob.java b/src/main/java/org/structnetalign/merge/BronKerboschMergeJob.java
index d233447..66181d8 100644
--- a/src/main/java/org/structnetalign/merge/BronKerboschMergeJob.java
+++ b/src/main/java/org/structnetalign/merge/BronKerboschMergeJob.java
@@ -1,170 +1,174 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE
* file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* @author dmyersturnbull
*/
package org.structnetalign.merge;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import org.apache.commons.collections.CollectionUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.structnetalign.CleverGraph;
import org.structnetalign.HomologyEdge;
import org.structnetalign.util.NetworkUtils;
public class BronKerboschMergeJob implements Callable<List<NavigableSet<Integer>>> {
private static final Logger logger = LogManager.getLogger("org.structnetalign");
private CleverGraph graph;
private int index;
private static String hashVertexInteractions(Collection<Integer> vertexInteractionNeighbors) {
return NetworkUtils.hash(vertexInteractionNeighbors);
}
public BronKerboschMergeJob(CleverGraph graph, int index) {
super();
this.graph = graph;
this.index = index;
}
@Override
public List<NavigableSet<Integer>> call() throws Exception {
logger.info("Searching for cliques on job " + index + " containing " + graph.getVertexCount()
+ " vertices and " + graph.getHomologyCount() + " homology edges");
// find the cliques
BronKerboschCliqueFinder<Integer, HomologyEdge> finder = new BronKerboschCliqueFinder<>();
// these cliques are ordered from largest to smallest
Collection<Set<Integer>> cliques = finder.transform(graph.getHomology());
// just report the cliques we're using
logger.info("Job " + index + ": " + "Found " + cliques.size() + " maximal cliques");
int i = 1;
for (Set<Integer> clique : cliques) {
logger.debug("Job " + index + ": " + "Clique " + i + ": " + clique);
i++;
}
// partition the cliques by sets of interactions
// we call these (maximal) degenerate sets
- NavigableMap<String, NavigableSet<Integer>> degenerateSetMap = new TreeMap<>();
+ List<NavigableSet<Integer>> simpleDegenerateSets = new ArrayList<NavigableSet<Integer>>();
for (Set<Integer> clique : cliques) {
+ NavigableMap<String, NavigableSet<Integer>> degenerateSetMap = new TreeMap<>();
for (int v : clique) {
Collection<Integer> neighbors = graph.getInteractionNeighbors(v);
String hash = hashVertexInteractions(neighbors);
NavigableSet<Integer> degenerateSet = degenerateSetMap.get(hash);
if (degenerateSet == null) {
degenerateSet = new TreeSet<>();
degenerateSetMap.put(hash, degenerateSet);
}
degenerateSet.add(v);
logger.trace("Job " + index + ": " + "Found " + hash + " --> " + degenerateSetMap.get(hash));
}
+ for (NavigableSet<Integer> set : degenerateSetMap.values()) {
+ simpleDegenerateSets.add(set);
+ }
}
/*
* Now sort the degenerate sets from largest to smallest.
* Take into account the edge case where the sizes are the same.
*/
Comparator<NavigableSet<Integer>> comparator = new Comparator<NavigableSet<Integer>>() {
@Override
public int compare(NavigableSet<Integer> clique1, NavigableSet<Integer> clique2) {
if (CollectionUtils.isEqualCollection(clique1, clique2)) return 0;
if (clique1.size() < clique2.size()) {
return 1;
} else if (clique1.size() > clique2.size()) {
return -1;
} else {
Iterator<Integer> iter1 = clique1.iterator();
Iterator<Integer> iter2 = clique2.iterator();
while (iter1.hasNext()) { // we know they're the same size
int v1 = iter1.next();
int v2 = iter2.next();
if (v1 < v2) {
return 1;
} else if (v1 > v2) {
return -1;
}
}
}
// they're the same throughout, so they're equal
return 0;
}
};
- List<NavigableSet<Integer>> sortedDegenerateSets = new ArrayList<>(degenerateSetMap.values().size());
- sortedDegenerateSets.addAll(degenerateSetMap.values());
+ List<NavigableSet<Integer>> sortedDegenerateSets = new ArrayList<>(simpleDegenerateSets.size());
+ sortedDegenerateSets.addAll(simpleDegenerateSets);
Collections.sort(sortedDegenerateSets, comparator);
/*
* Now we want to return only the maximal maximal degenerate sets.
*/
TreeSet<String> verticesAlreadyUsed = new TreeSet<String>();
List<NavigableSet<Integer>> finalDegenerateSets = new ArrayList<>(sortedDegenerateSets.size());
int nTrivial = 0;
int nWeak = 0; // a degenerate set is weak if it contains a vertex that is added first
forcliques: for (NavigableSet<Integer> set : sortedDegenerateSets) {
// discard trivial degenerate sets
if (set.size() < 2) {
nTrivial++;
continue;
}
// verify that we haven't already used any vertex in this degenerate set
for (int v : set) {
String hash = NetworkUtils.hash(v); // use MD5 for safety
if (verticesAlreadyUsed.contains(hash)) {
// discard this degenerate set and do NOT say we've used any of these vertices
nWeak++;
continue forcliques;
}
}
// we haven't used any vertex in this degenerate set
// now add all of these vertices
// do NOT add before, or we'll add vertices we haven't used yet
for (int v : set) {
String hash = NetworkUtils.hash(v);
verticesAlreadyUsed.add(hash);
}
finalDegenerateSets.add(set); // keep this degenerate set
}
logger.info("Job " + index + ": " + "Found " + finalDegenerateSets.size()
+ " strong nontrivial maximal degenerate sets found (" + nTrivial + " trivial and " + nWeak + " weak)");
return finalDegenerateSets;
}
}
| false | true | public List<NavigableSet<Integer>> call() throws Exception {
logger.info("Searching for cliques on job " + index + " containing " + graph.getVertexCount()
+ " vertices and " + graph.getHomologyCount() + " homology edges");
// find the cliques
BronKerboschCliqueFinder<Integer, HomologyEdge> finder = new BronKerboschCliqueFinder<>();
// these cliques are ordered from largest to smallest
Collection<Set<Integer>> cliques = finder.transform(graph.getHomology());
// just report the cliques we're using
logger.info("Job " + index + ": " + "Found " + cliques.size() + " maximal cliques");
int i = 1;
for (Set<Integer> clique : cliques) {
logger.debug("Job " + index + ": " + "Clique " + i + ": " + clique);
i++;
}
// partition the cliques by sets of interactions
// we call these (maximal) degenerate sets
NavigableMap<String, NavigableSet<Integer>> degenerateSetMap = new TreeMap<>();
for (Set<Integer> clique : cliques) {
for (int v : clique) {
Collection<Integer> neighbors = graph.getInteractionNeighbors(v);
String hash = hashVertexInteractions(neighbors);
NavigableSet<Integer> degenerateSet = degenerateSetMap.get(hash);
if (degenerateSet == null) {
degenerateSet = new TreeSet<>();
degenerateSetMap.put(hash, degenerateSet);
}
degenerateSet.add(v);
logger.trace("Job " + index + ": " + "Found " + hash + " --> " + degenerateSetMap.get(hash));
}
}
/*
* Now sort the degenerate sets from largest to smallest.
* Take into account the edge case where the sizes are the same.
*/
Comparator<NavigableSet<Integer>> comparator = new Comparator<NavigableSet<Integer>>() {
@Override
public int compare(NavigableSet<Integer> clique1, NavigableSet<Integer> clique2) {
if (CollectionUtils.isEqualCollection(clique1, clique2)) return 0;
if (clique1.size() < clique2.size()) {
return 1;
} else if (clique1.size() > clique2.size()) {
return -1;
} else {
Iterator<Integer> iter1 = clique1.iterator();
Iterator<Integer> iter2 = clique2.iterator();
while (iter1.hasNext()) { // we know they're the same size
int v1 = iter1.next();
int v2 = iter2.next();
if (v1 < v2) {
return 1;
} else if (v1 > v2) {
return -1;
}
}
}
// they're the same throughout, so they're equal
return 0;
}
};
List<NavigableSet<Integer>> sortedDegenerateSets = new ArrayList<>(degenerateSetMap.values().size());
sortedDegenerateSets.addAll(degenerateSetMap.values());
Collections.sort(sortedDegenerateSets, comparator);
/*
* Now we want to return only the maximal maximal degenerate sets.
*/
TreeSet<String> verticesAlreadyUsed = new TreeSet<String>();
List<NavigableSet<Integer>> finalDegenerateSets = new ArrayList<>(sortedDegenerateSets.size());
int nTrivial = 0;
int nWeak = 0; // a degenerate set is weak if it contains a vertex that is added first
forcliques: for (NavigableSet<Integer> set : sortedDegenerateSets) {
// discard trivial degenerate sets
if (set.size() < 2) {
nTrivial++;
continue;
}
// verify that we haven't already used any vertex in this degenerate set
for (int v : set) {
String hash = NetworkUtils.hash(v); // use MD5 for safety
if (verticesAlreadyUsed.contains(hash)) {
// discard this degenerate set and do NOT say we've used any of these vertices
nWeak++;
continue forcliques;
}
}
// we haven't used any vertex in this degenerate set
// now add all of these vertices
// do NOT add before, or we'll add vertices we haven't used yet
for (int v : set) {
String hash = NetworkUtils.hash(v);
verticesAlreadyUsed.add(hash);
}
finalDegenerateSets.add(set); // keep this degenerate set
}
logger.info("Job " + index + ": " + "Found " + finalDegenerateSets.size()
+ " strong nontrivial maximal degenerate sets found (" + nTrivial + " trivial and " + nWeak + " weak)");
return finalDegenerateSets;
}
| public List<NavigableSet<Integer>> call() throws Exception {
logger.info("Searching for cliques on job " + index + " containing " + graph.getVertexCount()
+ " vertices and " + graph.getHomologyCount() + " homology edges");
// find the cliques
BronKerboschCliqueFinder<Integer, HomologyEdge> finder = new BronKerboschCliqueFinder<>();
// these cliques are ordered from largest to smallest
Collection<Set<Integer>> cliques = finder.transform(graph.getHomology());
// just report the cliques we're using
logger.info("Job " + index + ": " + "Found " + cliques.size() + " maximal cliques");
int i = 1;
for (Set<Integer> clique : cliques) {
logger.debug("Job " + index + ": " + "Clique " + i + ": " + clique);
i++;
}
// partition the cliques by sets of interactions
// we call these (maximal) degenerate sets
List<NavigableSet<Integer>> simpleDegenerateSets = new ArrayList<NavigableSet<Integer>>();
for (Set<Integer> clique : cliques) {
NavigableMap<String, NavigableSet<Integer>> degenerateSetMap = new TreeMap<>();
for (int v : clique) {
Collection<Integer> neighbors = graph.getInteractionNeighbors(v);
String hash = hashVertexInteractions(neighbors);
NavigableSet<Integer> degenerateSet = degenerateSetMap.get(hash);
if (degenerateSet == null) {
degenerateSet = new TreeSet<>();
degenerateSetMap.put(hash, degenerateSet);
}
degenerateSet.add(v);
logger.trace("Job " + index + ": " + "Found " + hash + " --> " + degenerateSetMap.get(hash));
}
for (NavigableSet<Integer> set : degenerateSetMap.values()) {
simpleDegenerateSets.add(set);
}
}
/*
* Now sort the degenerate sets from largest to smallest.
* Take into account the edge case where the sizes are the same.
*/
Comparator<NavigableSet<Integer>> comparator = new Comparator<NavigableSet<Integer>>() {
@Override
public int compare(NavigableSet<Integer> clique1, NavigableSet<Integer> clique2) {
if (CollectionUtils.isEqualCollection(clique1, clique2)) return 0;
if (clique1.size() < clique2.size()) {
return 1;
} else if (clique1.size() > clique2.size()) {
return -1;
} else {
Iterator<Integer> iter1 = clique1.iterator();
Iterator<Integer> iter2 = clique2.iterator();
while (iter1.hasNext()) { // we know they're the same size
int v1 = iter1.next();
int v2 = iter2.next();
if (v1 < v2) {
return 1;
} else if (v1 > v2) {
return -1;
}
}
}
// they're the same throughout, so they're equal
return 0;
}
};
List<NavigableSet<Integer>> sortedDegenerateSets = new ArrayList<>(simpleDegenerateSets.size());
sortedDegenerateSets.addAll(simpleDegenerateSets);
Collections.sort(sortedDegenerateSets, comparator);
/*
* Now we want to return only the maximal maximal degenerate sets.
*/
TreeSet<String> verticesAlreadyUsed = new TreeSet<String>();
List<NavigableSet<Integer>> finalDegenerateSets = new ArrayList<>(sortedDegenerateSets.size());
int nTrivial = 0;
int nWeak = 0; // a degenerate set is weak if it contains a vertex that is added first
forcliques: for (NavigableSet<Integer> set : sortedDegenerateSets) {
// discard trivial degenerate sets
if (set.size() < 2) {
nTrivial++;
continue;
}
// verify that we haven't already used any vertex in this degenerate set
for (int v : set) {
String hash = NetworkUtils.hash(v); // use MD5 for safety
if (verticesAlreadyUsed.contains(hash)) {
// discard this degenerate set and do NOT say we've used any of these vertices
nWeak++;
continue forcliques;
}
}
// we haven't used any vertex in this degenerate set
// now add all of these vertices
// do NOT add before, or we'll add vertices we haven't used yet
for (int v : set) {
String hash = NetworkUtils.hash(v);
verticesAlreadyUsed.add(hash);
}
finalDegenerateSets.add(set); // keep this degenerate set
}
logger.info("Job " + index + ": " + "Found " + finalDegenerateSets.size()
+ " strong nontrivial maximal degenerate sets found (" + nTrivial + " trivial and " + nWeak + " weak)");
return finalDegenerateSets;
}
|
diff --git a/src/org/biojava/bio/gui/sequence/FeatureBlockSequenceRenderer.java b/src/org/biojava/bio/gui/sequence/FeatureBlockSequenceRenderer.java
index 4ddefb915..e8d0b83c1 100755
--- a/src/org/biojava/bio/gui/sequence/FeatureBlockSequenceRenderer.java
+++ b/src/org/biojava/bio/gui/sequence/FeatureBlockSequenceRenderer.java
@@ -1,133 +1,133 @@
/*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
*/
package org.biojava.bio.gui.sequence;
import java.util.*;
import java.beans.*;
import org.biojava.bio.*;
import org.biojava.bio.seq.*;
import org.biojava.bio.gui.*;
import java.awt.*;
import java.awt.geom.*;
import java.util.List;
public class FeatureBlockSequenceRenderer implements SequenceRenderer {
private FeatureFilter filter;
private double depth = 25.0;
private Paint fill;
private Paint outline;
protected PropertyChangeSupport pcs;
public FeatureBlockSequenceRenderer() {
filter = FeatureFilter.all;
fill = Color.red;
outline = Color.black;
pcs = new PropertyChangeSupport(this);
}
public FeatureFilter getFilter() {
return filter;
}
public void setFilter(FeatureFilter f) {
FeatureFilter oldFilter = filter;
filter = f;
pcs.firePropertyChange("filter", oldFilter, filter);
}
public double getDepth(SequencePanel sp) {
return depth;
}
public double getMinimumLeader(SequencePanel sp) {
return 0.0;
}
public double getMinimumTrailer(SequencePanel sp) {
return 0.0;
}
public void setFill(Paint p) {
Paint oldFill = fill;
fill = p;
pcs.firePropertyChange("fill", oldFill, fill);
}
public Paint getFill() {
return fill;
}
public void setOutline(Paint p) {
Paint oldOutline = outline;
outline = p;
pcs.firePropertyChange("outline", oldOutline, outline);
}
public Paint getOutline() {
return outline;
}
public void paint(Graphics2D g, SequencePanel sp) {
for (Iterator i = sp.getSequence().filter(filter, true).features();
i.hasNext(); )
{
Feature f = (Feature) i.next();
Location l = f.getLocation();
double min = sp.sequenceToGraphics(l.getMin());
double max = sp.sequenceToGraphics(l.getMax() + 1);
Rectangle2D box = null;
if (sp.getDirection() == SequencePanel.HORIZONTAL)
- box = new Rectangle2D.Double(min, 5, max-min, 20);
+ box = new Rectangle2D.Double(min, 5, max-min, 15);
else
box = new Rectangle2D.Double(5, min, 15, max-min);
g.setPaint(fill);
g.fill(box);
if (outline != fill) {
g.setPaint(outline);
g.draw(box);
}
}
}
public void addPropertyChangeListener(PropertyChangeListener l) {
pcs.addPropertyChangeListener(l);
}
public void addPropertyChangeListener(String p, PropertyChangeListener l) {
pcs.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
pcs.removePropertyChangeListener(l);
}
public void removePropertyChangeListener(String p,
PropertyChangeListener l) {
pcs.removePropertyChangeListener(p, l);
}
}
| true | true | public void paint(Graphics2D g, SequencePanel sp) {
for (Iterator i = sp.getSequence().filter(filter, true).features();
i.hasNext(); )
{
Feature f = (Feature) i.next();
Location l = f.getLocation();
double min = sp.sequenceToGraphics(l.getMin());
double max = sp.sequenceToGraphics(l.getMax() + 1);
Rectangle2D box = null;
if (sp.getDirection() == SequencePanel.HORIZONTAL)
box = new Rectangle2D.Double(min, 5, max-min, 20);
else
box = new Rectangle2D.Double(5, min, 15, max-min);
g.setPaint(fill);
g.fill(box);
if (outline != fill) {
g.setPaint(outline);
g.draw(box);
}
}
}
| public void paint(Graphics2D g, SequencePanel sp) {
for (Iterator i = sp.getSequence().filter(filter, true).features();
i.hasNext(); )
{
Feature f = (Feature) i.next();
Location l = f.getLocation();
double min = sp.sequenceToGraphics(l.getMin());
double max = sp.sequenceToGraphics(l.getMax() + 1);
Rectangle2D box = null;
if (sp.getDirection() == SequencePanel.HORIZONTAL)
box = new Rectangle2D.Double(min, 5, max-min, 15);
else
box = new Rectangle2D.Double(5, min, 15, max-min);
g.setPaint(fill);
g.fill(box);
if (outline != fill) {
g.setPaint(outline);
g.draw(box);
}
}
}
|
diff --git a/modules/activiti-engine/src/test/java/org/activiti/engine/test/bpmn/mail/EmailTestCase.java b/modules/activiti-engine/src/test/java/org/activiti/engine/test/bpmn/mail/EmailTestCase.java
index c0d81cbe6..5dcdeb6f6 100644
--- a/modules/activiti-engine/src/test/java/org/activiti/engine/test/bpmn/mail/EmailTestCase.java
+++ b/modules/activiti-engine/src/test/java/org/activiti/engine/test/bpmn/mail/EmailTestCase.java
@@ -1,57 +1,57 @@
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.engine.test.bpmn.mail;
import org.activiti.engine.impl.test.PluggableActivitiTestCase;
import org.subethamail.wiser.Wiser;
/**
* @author Joram Barrez
*/
public class EmailTestCase extends PluggableActivitiTestCase {
protected Wiser wiser;
@Override
protected void setUp() throws Exception {
super.setUp();
boolean serverUpAndRunning = false;
while (!serverUpAndRunning) {
wiser = new Wiser();
wiser.setPort(5025);
try {
wiser.start();
serverUpAndRunning = true;
} catch (RuntimeException e) { // Fix for slow port-closing Jenkins
- if (e.getMessage().toLowerCase().contains("BindException")) {
+ if (e.getMessage().toLowerCase().contains("bindexception")) {
Thread.sleep(250L);
}
}
}
}
@Override
protected void tearDown() throws Exception {
wiser.stop();
// Fix for slow Jenkins
Thread.sleep(250L);
super.tearDown();
}
}
| true | true | protected void setUp() throws Exception {
super.setUp();
boolean serverUpAndRunning = false;
while (!serverUpAndRunning) {
wiser = new Wiser();
wiser.setPort(5025);
try {
wiser.start();
serverUpAndRunning = true;
} catch (RuntimeException e) { // Fix for slow port-closing Jenkins
if (e.getMessage().toLowerCase().contains("BindException")) {
Thread.sleep(250L);
}
}
}
}
| protected void setUp() throws Exception {
super.setUp();
boolean serverUpAndRunning = false;
while (!serverUpAndRunning) {
wiser = new Wiser();
wiser.setPort(5025);
try {
wiser.start();
serverUpAndRunning = true;
} catch (RuntimeException e) { // Fix for slow port-closing Jenkins
if (e.getMessage().toLowerCase().contains("bindexception")) {
Thread.sleep(250L);
}
}
}
}
|
diff --git a/contrib/pig/src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java b/contrib/pig/src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java
index 76ec3b915..6bba368ed 100644
--- a/contrib/pig/src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java
+++ b/contrib/pig/src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java
@@ -1,534 +1,534 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.cassandra.hadoop.pig;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.*;
import org.apache.cassandra.config.ConfigurationException;
import org.apache.cassandra.db.marshal.BytesType;
import org.apache.cassandra.db.marshal.TypeParser;
import org.apache.cassandra.thrift.*;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cassandra.db.Column;
import org.apache.cassandra.db.IColumn;
import org.apache.cassandra.db.SuperColumn;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.hadoop.*;
import org.apache.cassandra.thrift.Mutation;
import org.apache.cassandra.thrift.Deletion;
import org.apache.cassandra.thrift.ColumnOrSuperColumn;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.*;
import org.apache.pig.*;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSplit;
import org.apache.pig.data.*;
import org.apache.pig.impl.logicalLayer.FrontendException;
import org.apache.pig.impl.util.UDFContext;
import org.apache.thrift.TDeserializer;
import org.apache.thrift.TException;
import org.apache.thrift.TSerializer;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
/**
* A LoadStoreFunc for retrieving data from and storing data to Cassandra
*
* A row from a standard CF will be returned as nested tuples: (key, ((name1, val1), (name2, val2))).
*/
public class CassandraStorage extends LoadFunc implements StoreFuncInterface
{
// system environment variables that can be set to configure connection info:
// alternatively, Hadoop JobConf variables can be set using keys from ConfigHelper
public final static String PIG_RPC_PORT = "PIG_RPC_PORT";
public final static String PIG_INITIAL_ADDRESS = "PIG_INITIAL_ADDRESS";
public final static String PIG_PARTITIONER = "PIG_PARTITIONER";
private static String UDFCONTEXT_SCHEMA_KEY_PREFIX = "cassandra.schema";
private final static ByteBuffer BOUND = ByteBufferUtil.EMPTY_BYTE_BUFFER;
private static final Log logger = LogFactory.getLog(CassandraStorage.class);
private ByteBuffer slice_start = BOUND;
private ByteBuffer slice_end = BOUND;
private boolean slice_reverse = false;
private String keyspace;
private String column_family;
private Configuration conf;
private RecordReader reader;
private RecordWriter writer;
private int limit;
public CassandraStorage()
{
this(1024);
}
/**
* @param limit: number of columns to fetch in a slice
*/
public CassandraStorage(int limit)
{
super();
this.limit = limit;
}
public int getLimit()
{
return limit;
}
@Override
public Tuple getNext() throws IOException
{
try
{
// load the next pair
if (!reader.nextKeyValue())
return null;
CfDef cfDef = getCfDef();
ByteBuffer key = (ByteBuffer)reader.getCurrentKey();
SortedMap<ByteBuffer,IColumn> cf = (SortedMap<ByteBuffer,IColumn>)reader.getCurrentValue();
assert key != null && cf != null;
// and wrap it in a tuple
Tuple tuple = TupleFactory.getInstance().newTuple(2);
ArrayList<Tuple> columns = new ArrayList<Tuple>();
tuple.set(0, new DataByteArray(key.array(), key.position()+key.arrayOffset(), key.limit()+key.arrayOffset()));
for (Map.Entry<ByteBuffer, IColumn> entry : cf.entrySet())
{
columns.add(columnToTuple(entry.getKey(), entry.getValue(), cfDef));
}
tuple.set(1, new DefaultDataBag(columns));
return tuple;
}
catch (InterruptedException e)
{
throw new IOException(e.getMessage());
}
}
private Tuple columnToTuple(ByteBuffer name, IColumn col, CfDef cfDef) throws IOException
{
Tuple pair = TupleFactory.getInstance().newTuple(2);
List<AbstractType> marshallers = getDefaultMarshallers(cfDef);
Map<ByteBuffer,AbstractType> validators = getValidatorMap(cfDef);
if (col instanceof Column)
{
// standard
pair.set(0, marshallers.get(0).compose(name));
if (validators.get(name) == null)
// Have to special case BytesType because compose returns a ByteBuffer
if (marshallers.get(1) instanceof BytesType)
pair.set(1, new DataByteArray(ByteBufferUtil.getArray(col.value())));
else
pair.set(1, marshallers.get(1).compose(col.value()));
else
pair.set(1, validators.get(name).compose(col.value()));
return pair;
}
// super
ArrayList<Tuple> subcols = new ArrayList<Tuple>();
for (IColumn subcol : col.getSubColumns())
subcols.add(columnToTuple(subcol.name(), subcol, cfDef));
pair.set(1, new DefaultDataBag(subcols));
return pair;
}
private CfDef getCfDef()
{
UDFContext context = UDFContext.getUDFContext();
Properties property = context.getUDFProperties(CassandraStorage.class);
return cfdefFromString(property.getProperty(getSchemaContextKey()));
}
private List<AbstractType> getDefaultMarshallers(CfDef cfDef) throws IOException
{
ArrayList<AbstractType> marshallers = new ArrayList<AbstractType>();
AbstractType comparator = null;
AbstractType default_validator = null;
try
{
comparator = TypeParser.parse(cfDef.comparator_type);
default_validator = TypeParser.parse(cfDef.default_validation_class);
}
catch (ConfigurationException e)
{
throw new IOException(e);
}
marshallers.add(comparator);
marshallers.add(default_validator);
return marshallers;
}
private Map<ByteBuffer,AbstractType> getValidatorMap(CfDef cfDef) throws IOException
{
Map<ByteBuffer, AbstractType> validators = new HashMap<ByteBuffer, AbstractType>();
for (ColumnDef cd : cfDef.column_metadata)
{
if (cd.getValidation_class() != null && !cd.getValidation_class().isEmpty())
{
AbstractType validator = null;
try
{
validator = TypeParser.parse(cd.getValidation_class());
validators.put(cd.name, validator);
}
catch (ConfigurationException e)
{
throw new IOException(e);
}
}
}
return validators;
}
@Override
public InputFormat getInputFormat()
{
return new ColumnFamilyInputFormat();
}
@Override
public void prepareToRead(RecordReader reader, PigSplit split)
{
this.reader = reader;
}
private void setLocationFromUri(String location) throws IOException
{
// parse uri into keyspace and columnfamily
String names[];
try
{
if (!location.startsWith("cassandra://"))
throw new Exception("Bad scheme.");
String[] urlParts = location.split("\\?");
if (urlParts.length > 1)
{
for (String param : urlParts[1].split("&"))
{
String[] pair = param.split("=");
if (pair[0].equals("slice_start"))
slice_start = ByteBufferUtil.bytes(pair[1]);
else if (pair[0].equals("slice_end"))
slice_end = ByteBufferUtil.bytes(pair[1]);
else if (pair[0].equals("reversed"))
slice_reverse = Boolean.parseBoolean(pair[1]);
else if (pair[0].equals("limit"))
limit = Integer.parseInt(pair[1]);
}
}
String[] parts = urlParts[0].split("/+");
keyspace = parts[1];
column_family = parts[2];
}
catch (Exception e)
{
throw new IOException("Expected 'cassandra://<keyspace>/<columnfamily>[?slice_start=<start>&slice_end=<end>[&reversed=true][&limit=1]]': " + e.getMessage());
}
}
private void setConnectionInformation() throws IOException
{
if (System.getenv(PIG_RPC_PORT) != null)
ConfigHelper.setRpcPort(conf, System.getenv(PIG_RPC_PORT));
else if (ConfigHelper.getRpcPort(conf) == 0)
throw new IOException("PIG_RPC_PORT environment variable not set");
if (System.getenv(PIG_INITIAL_ADDRESS) != null)
ConfigHelper.setInitialAddress(conf, System.getenv(PIG_INITIAL_ADDRESS));
else if (ConfigHelper.getInitialAddress(conf) == null)
throw new IOException("PIG_INITIAL_ADDRESS environment variable not set");
if (System.getenv(PIG_PARTITIONER) != null)
ConfigHelper.setPartitioner(conf, System.getenv(PIG_PARTITIONER));
else if (ConfigHelper.getPartitioner(conf) == null)
throw new IOException("PIG_PARTITIONER environment variable not set");
}
@Override
public void setLocation(String location, Job job) throws IOException
{
conf = job.getConfiguration();
setLocationFromUri(location);
if (ConfigHelper.getRawInputSlicePredicate(conf) == null)
{
SliceRange range = new SliceRange(slice_start, slice_end, slice_reverse, limit);
SlicePredicate predicate = new SlicePredicate().setSlice_range(range);
ConfigHelper.setInputSlicePredicate(conf, predicate);
}
ConfigHelper.setInputColumnFamily(conf, keyspace, column_family);
setConnectionInformation();
initSchema();
}
@Override
public String relativeToAbsolutePath(String location, Path curDir) throws IOException
{
return location;
}
/* StoreFunc methods */
public void setStoreFuncUDFContextSignature(String signature)
{
}
public String relToAbsPathForStoreLocation(String location, Path curDir) throws IOException
{
return relativeToAbsolutePath(location, curDir);
}
public void setStoreLocation(String location, Job job) throws IOException
{
conf = job.getConfiguration();
setLocationFromUri(location);
ConfigHelper.setOutputColumnFamily(conf, keyspace, column_family);
setConnectionInformation();
initSchema();
}
public OutputFormat getOutputFormat()
{
return new ColumnFamilyOutputFormat();
}
public void checkSchema(ResourceSchema schema) throws IOException
{
// we don't care about types, they all get casted to ByteBuffers
}
public void prepareToWrite(RecordWriter writer)
{
this.writer = writer;
}
private ByteBuffer objToBB(Object o)
{
if (o == null)
return (ByteBuffer)o;
if (o instanceof java.lang.String)
o = new DataByteArray((String)o);
return ByteBuffer.wrap(((DataByteArray) o).get());
}
public void putNext(Tuple t) throws ExecException, IOException
{
ByteBuffer key = objToBB(t.get(0));
DefaultDataBag pairs = (DefaultDataBag) t.get(1);
ArrayList<Mutation> mutationList = new ArrayList<Mutation>();
CfDef cfDef = getCfDef();
List<AbstractType> marshallers = getDefaultMarshallers(cfDef);
Map<ByteBuffer,AbstractType> validators = getValidatorMap(cfDef);
try
{
for (Tuple pair : pairs)
{
Mutation mutation = new Mutation();
if (DataType.findType(pair.get(1)) == DataType.BAG) // supercolumn
{
- org.apache.cassandra.hadoop.avro.SuperColumn sc = new org.apache.cassandra.hadoop.avro.SuperColumn();
+ org.apache.cassandra.thrift.SuperColumn sc = new org.apache.cassandra.thrift.SuperColumn();
sc.name = objToBB(pair.get(0));
- ArrayList<org.apache.cassandra.hadoop.avro.Column> columns = new ArrayList<org.apache.cassandra.hadoop.avro.Column>();
+ ArrayList<org.apache.cassandra.thrift.Column> columns = new ArrayList<org.apache.cassandra.thrift.Column>();
for (Tuple subcol : (DefaultDataBag) pair.get(1))
{
- org.apache.cassandra.hadoop.avro.Column column = new org.apache.cassandra.hadoop.avro.Column();
+ org.apache.cassandra.thrift.Column column = new org.apache.cassandra.thrift.Column();
column.name = objToBB(subcol.get(0));
column.value = objToBB(subcol.get(1));
column.setTimestamp(System.currentTimeMillis() * 1000);
columns.add(column);
}
if (columns.isEmpty()) // a deletion
{
mutation.deletion = new Deletion();
mutation.deletion.super_column = objToBB(pair.get(0));
mutation.deletion.setTimestamp(System.currentTimeMillis() * 1000);
}
else
{
sc.columns = columns;
mutation.column_or_supercolumn = new ColumnOrSuperColumn();
mutation.column_or_supercolumn.super_column = sc;
}
}
else // assume column since it couldn't be anything else
{
if (pair.get(1) == null)
{
mutation.deletion = new Deletion();
mutation.deletion.predicate = new org.apache.cassandra.thrift.SlicePredicate();
mutation.deletion.predicate.column_names = Arrays.asList(objToBB(pair.get(0)));
mutation.deletion.setTimestamp(System.currentTimeMillis() * 1000);
}
else
{
org.apache.cassandra.thrift.Column column = new org.apache.cassandra.thrift.Column();
column.name = marshallers.get(0).decompose((pair.get(0)));
if (validators.get(column.name) == null)
// Have to special case BytesType to convert DataByteArray into ByteBuffer
if (marshallers.get(1) instanceof BytesType)
column.value = objToBB(pair.get(1));
else
column.value = marshallers.get(1).decompose(pair.get(1));
else
column.value = validators.get(column.name).decompose(pair.get(1));
column.setTimestamp(System.currentTimeMillis() * 1000);
mutation.column_or_supercolumn = new ColumnOrSuperColumn();
mutation.column_or_supercolumn.column = column;
}
}
mutationList.add(mutation);
}
}
catch (ClassCastException e)
{
throw new IOException(e + " Output must be (key, {(column,value)...}) for ColumnFamily or (key, {supercolumn:{(column,value)...}...}) for SuperColumnFamily");
}
try
{
writer.write(key, mutationList);
}
catch (InterruptedException e)
{
throw new IOException(e);
}
}
public void cleanupOnFailure(String failure, Job job)
{
}
/* Methods to get the column family schema from Cassandra */
private void initSchema()
{
UDFContext context = UDFContext.getUDFContext();
Properties property = context.getUDFProperties(CassandraStorage.class);
String schemaContextKey = getSchemaContextKey();
// Only get the schema if we haven't already gotten it
if (!property.containsKey(schemaContextKey))
{
Cassandra.Client client = null;
try
{
client = createConnection(ConfigHelper.getInitialAddress(conf), ConfigHelper.getRpcPort(conf), true);
CfDef cfDef = null;
client.set_keyspace(keyspace);
KsDef ksDef = client.describe_keyspace(keyspace);
List<CfDef> defs = ksDef.getCf_defs();
for (CfDef def : defs)
{
if (column_family.equalsIgnoreCase(def.getName()))
{
cfDef = def;
break;
}
}
property.setProperty(schemaContextKey, cfdefToString(cfDef));
}
catch (TException e)
{
throw new RuntimeException(e);
}
catch (InvalidRequestException e)
{
throw new RuntimeException(e);
}
catch (NotFoundException e)
{
throw new RuntimeException(e);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
}
private static Cassandra.Client createConnection(String host, Integer port, boolean framed) throws IOException
{
TSocket socket = new TSocket(host, port);
TTransport trans = framed ? new TFramedTransport(socket) : socket;
try
{
trans.open();
}
catch (TTransportException e)
{
throw new IOException("unable to connect to server", e);
}
return new Cassandra.Client(new TBinaryProtocol(trans));
}
private static String cfdefToString(CfDef cfDef)
{
assert cfDef != null;
// this is so awful it's kind of cool!
TSerializer serializer = new TSerializer(new TBinaryProtocol.Factory());
try
{
return FBUtilities.bytesToHex(serializer.serialize(cfDef));
}
catch (TException e)
{
throw new RuntimeException(e);
}
}
private static CfDef cfdefFromString(String st)
{
assert st != null;
TDeserializer deserializer = new TDeserializer(new TBinaryProtocol.Factory());
CfDef cfDef = new CfDef();
try
{
deserializer.deserialize(cfDef, FBUtilities.hexToBytes(st));
}
catch (TException e)
{
throw new RuntimeException(e);
}
return cfDef;
}
private String getSchemaContextKey()
{
StringBuilder sb = new StringBuilder(UDFCONTEXT_SCHEMA_KEY_PREFIX);
sb.append('.');
sb.append(keyspace);
sb.append('.');
sb.append(column_family);
return sb.toString();
}
}
| false | true | public void putNext(Tuple t) throws ExecException, IOException
{
ByteBuffer key = objToBB(t.get(0));
DefaultDataBag pairs = (DefaultDataBag) t.get(1);
ArrayList<Mutation> mutationList = new ArrayList<Mutation>();
CfDef cfDef = getCfDef();
List<AbstractType> marshallers = getDefaultMarshallers(cfDef);
Map<ByteBuffer,AbstractType> validators = getValidatorMap(cfDef);
try
{
for (Tuple pair : pairs)
{
Mutation mutation = new Mutation();
if (DataType.findType(pair.get(1)) == DataType.BAG) // supercolumn
{
org.apache.cassandra.hadoop.avro.SuperColumn sc = new org.apache.cassandra.hadoop.avro.SuperColumn();
sc.name = objToBB(pair.get(0));
ArrayList<org.apache.cassandra.hadoop.avro.Column> columns = new ArrayList<org.apache.cassandra.hadoop.avro.Column>();
for (Tuple subcol : (DefaultDataBag) pair.get(1))
{
org.apache.cassandra.hadoop.avro.Column column = new org.apache.cassandra.hadoop.avro.Column();
column.name = objToBB(subcol.get(0));
column.value = objToBB(subcol.get(1));
column.setTimestamp(System.currentTimeMillis() * 1000);
columns.add(column);
}
if (columns.isEmpty()) // a deletion
{
mutation.deletion = new Deletion();
mutation.deletion.super_column = objToBB(pair.get(0));
mutation.deletion.setTimestamp(System.currentTimeMillis() * 1000);
}
else
{
sc.columns = columns;
mutation.column_or_supercolumn = new ColumnOrSuperColumn();
mutation.column_or_supercolumn.super_column = sc;
}
}
else // assume column since it couldn't be anything else
{
if (pair.get(1) == null)
{
mutation.deletion = new Deletion();
mutation.deletion.predicate = new org.apache.cassandra.thrift.SlicePredicate();
mutation.deletion.predicate.column_names = Arrays.asList(objToBB(pair.get(0)));
mutation.deletion.setTimestamp(System.currentTimeMillis() * 1000);
}
else
{
org.apache.cassandra.thrift.Column column = new org.apache.cassandra.thrift.Column();
column.name = marshallers.get(0).decompose((pair.get(0)));
if (validators.get(column.name) == null)
// Have to special case BytesType to convert DataByteArray into ByteBuffer
if (marshallers.get(1) instanceof BytesType)
column.value = objToBB(pair.get(1));
else
column.value = marshallers.get(1).decompose(pair.get(1));
else
column.value = validators.get(column.name).decompose(pair.get(1));
column.setTimestamp(System.currentTimeMillis() * 1000);
mutation.column_or_supercolumn = new ColumnOrSuperColumn();
mutation.column_or_supercolumn.column = column;
}
}
mutationList.add(mutation);
}
}
catch (ClassCastException e)
{
throw new IOException(e + " Output must be (key, {(column,value)...}) for ColumnFamily or (key, {supercolumn:{(column,value)...}...}) for SuperColumnFamily");
}
try
{
writer.write(key, mutationList);
}
catch (InterruptedException e)
{
throw new IOException(e);
}
}
| public void putNext(Tuple t) throws ExecException, IOException
{
ByteBuffer key = objToBB(t.get(0));
DefaultDataBag pairs = (DefaultDataBag) t.get(1);
ArrayList<Mutation> mutationList = new ArrayList<Mutation>();
CfDef cfDef = getCfDef();
List<AbstractType> marshallers = getDefaultMarshallers(cfDef);
Map<ByteBuffer,AbstractType> validators = getValidatorMap(cfDef);
try
{
for (Tuple pair : pairs)
{
Mutation mutation = new Mutation();
if (DataType.findType(pair.get(1)) == DataType.BAG) // supercolumn
{
org.apache.cassandra.thrift.SuperColumn sc = new org.apache.cassandra.thrift.SuperColumn();
sc.name = objToBB(pair.get(0));
ArrayList<org.apache.cassandra.thrift.Column> columns = new ArrayList<org.apache.cassandra.thrift.Column>();
for (Tuple subcol : (DefaultDataBag) pair.get(1))
{
org.apache.cassandra.thrift.Column column = new org.apache.cassandra.thrift.Column();
column.name = objToBB(subcol.get(0));
column.value = objToBB(subcol.get(1));
column.setTimestamp(System.currentTimeMillis() * 1000);
columns.add(column);
}
if (columns.isEmpty()) // a deletion
{
mutation.deletion = new Deletion();
mutation.deletion.super_column = objToBB(pair.get(0));
mutation.deletion.setTimestamp(System.currentTimeMillis() * 1000);
}
else
{
sc.columns = columns;
mutation.column_or_supercolumn = new ColumnOrSuperColumn();
mutation.column_or_supercolumn.super_column = sc;
}
}
else // assume column since it couldn't be anything else
{
if (pair.get(1) == null)
{
mutation.deletion = new Deletion();
mutation.deletion.predicate = new org.apache.cassandra.thrift.SlicePredicate();
mutation.deletion.predicate.column_names = Arrays.asList(objToBB(pair.get(0)));
mutation.deletion.setTimestamp(System.currentTimeMillis() * 1000);
}
else
{
org.apache.cassandra.thrift.Column column = new org.apache.cassandra.thrift.Column();
column.name = marshallers.get(0).decompose((pair.get(0)));
if (validators.get(column.name) == null)
// Have to special case BytesType to convert DataByteArray into ByteBuffer
if (marshallers.get(1) instanceof BytesType)
column.value = objToBB(pair.get(1));
else
column.value = marshallers.get(1).decompose(pair.get(1));
else
column.value = validators.get(column.name).decompose(pair.get(1));
column.setTimestamp(System.currentTimeMillis() * 1000);
mutation.column_or_supercolumn = new ColumnOrSuperColumn();
mutation.column_or_supercolumn.column = column;
}
}
mutationList.add(mutation);
}
}
catch (ClassCastException e)
{
throw new IOException(e + " Output must be (key, {(column,value)...}) for ColumnFamily or (key, {supercolumn:{(column,value)...}...}) for SuperColumnFamily");
}
try
{
writer.write(key, mutationList);
}
catch (InterruptedException e)
{
throw new IOException(e);
}
}
|
diff --git a/jta/transactional/src/main/java/org/javaee7/jta/transactional/TestServlet.java b/jta/transactional/src/main/java/org/javaee7/jta/transactional/TestServlet.java
index 31b52087..b2bc4376 100644
--- a/jta/transactional/src/main/java/org/javaee7/jta/transactional/TestServlet.java
+++ b/jta/transactional/src/main/java/org/javaee7/jta/transactional/TestServlet.java
@@ -1,173 +1,173 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package org.javaee7.jta.transactional;
import java.io.IOException;
import java.io.PrintWriter;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author Arun Gupta
*/
@WebServlet(urlPatterns = {"/TestServlet"})
public class TestServlet extends HttpServlet {
@Inject MyBean bean;
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>@Transactional</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>@Transactional</h1>");
out.println("<h2>Transactional.TxType.REQUIRED</h2>");
try {
bean.required();
} catch (Exception e) {
out.println("Exception: " + e.getMessage() + "<br/>");
}
out.println("No stack trace, right ?<p/>");
out.println("<h2>Transactional.TxType.REQUIRES_NEW</h2>");
try {
bean.requiresNew();
} catch (Exception e) {
out.println("Exception: " + e.getMessage() + "<br/>");
}
out.println("No stack trace, right ?<p/>");
out.println("<h2>Transactional.TxType.MANDATORY</h2>");
try {
bean.mandatory();
} catch (Exception e) {
out.println("Exception: " + e.getMessage() + "<br/>");
}
out.println("Got the expected exception, right ?<p/>");
out.println("<h2>Transactional.TxType.SUPPORTS</h2>");
try {
bean.supports();
} catch (Exception e) {
out.println("Exception: " + e.getMessage() + "<br/>");
}
out.println("No stack trace, right ?<p/>");
out.println("<h2>Transactional.TxType.NOT_SUPPORTED</h2>");
try {
bean.notSupported();
} catch (Exception e) {
out.println("Exception: " + e.getMessage() + "<br/>");
}
out.println("No stack trace, right ?<p/>");
- out.println("</h2>Transactional.TxType.NEVER</h2>");
+ out.println("<h2>Transactional.TxType.NEVER</h2>");
try {
bean.never();
} catch (Exception e) {
out.println("Exception: " + e.getMessage() + "<br/>");
}
out.println("No stack trace, right ?<p/>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| true | true | protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>@Transactional</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>@Transactional</h1>");
out.println("<h2>Transactional.TxType.REQUIRED</h2>");
try {
bean.required();
} catch (Exception e) {
out.println("Exception: " + e.getMessage() + "<br/>");
}
out.println("No stack trace, right ?<p/>");
out.println("<h2>Transactional.TxType.REQUIRES_NEW</h2>");
try {
bean.requiresNew();
} catch (Exception e) {
out.println("Exception: " + e.getMessage() + "<br/>");
}
out.println("No stack trace, right ?<p/>");
out.println("<h2>Transactional.TxType.MANDATORY</h2>");
try {
bean.mandatory();
} catch (Exception e) {
out.println("Exception: " + e.getMessage() + "<br/>");
}
out.println("Got the expected exception, right ?<p/>");
out.println("<h2>Transactional.TxType.SUPPORTS</h2>");
try {
bean.supports();
} catch (Exception e) {
out.println("Exception: " + e.getMessage() + "<br/>");
}
out.println("No stack trace, right ?<p/>");
out.println("<h2>Transactional.TxType.NOT_SUPPORTED</h2>");
try {
bean.notSupported();
} catch (Exception e) {
out.println("Exception: " + e.getMessage() + "<br/>");
}
out.println("No stack trace, right ?<p/>");
out.println("</h2>Transactional.TxType.NEVER</h2>");
try {
bean.never();
} catch (Exception e) {
out.println("Exception: " + e.getMessage() + "<br/>");
}
out.println("No stack trace, right ?<p/>");
out.println("</body>");
out.println("</html>");
}
}
| protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>@Transactional</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>@Transactional</h1>");
out.println("<h2>Transactional.TxType.REQUIRED</h2>");
try {
bean.required();
} catch (Exception e) {
out.println("Exception: " + e.getMessage() + "<br/>");
}
out.println("No stack trace, right ?<p/>");
out.println("<h2>Transactional.TxType.REQUIRES_NEW</h2>");
try {
bean.requiresNew();
} catch (Exception e) {
out.println("Exception: " + e.getMessage() + "<br/>");
}
out.println("No stack trace, right ?<p/>");
out.println("<h2>Transactional.TxType.MANDATORY</h2>");
try {
bean.mandatory();
} catch (Exception e) {
out.println("Exception: " + e.getMessage() + "<br/>");
}
out.println("Got the expected exception, right ?<p/>");
out.println("<h2>Transactional.TxType.SUPPORTS</h2>");
try {
bean.supports();
} catch (Exception e) {
out.println("Exception: " + e.getMessage() + "<br/>");
}
out.println("No stack trace, right ?<p/>");
out.println("<h2>Transactional.TxType.NOT_SUPPORTED</h2>");
try {
bean.notSupported();
} catch (Exception e) {
out.println("Exception: " + e.getMessage() + "<br/>");
}
out.println("No stack trace, right ?<p/>");
out.println("<h2>Transactional.TxType.NEVER</h2>");
try {
bean.never();
} catch (Exception e) {
out.println("Exception: " + e.getMessage() + "<br/>");
}
out.println("No stack trace, right ?<p/>");
out.println("</body>");
out.println("</html>");
}
}
|
diff --git a/src/org/e2k/FSK200500.java b/src/org/e2k/FSK200500.java
index 82e7ef1..9712153 100644
--- a/src/org/e2k/FSK200500.java
+++ b/src/org/e2k/FSK200500.java
@@ -1,356 +1,362 @@
package org.e2k;
import javax.swing.JOptionPane;
public class FSK200500 extends FSK {
private int baudRate=200;
private int state=0;
private double samplesPerSymbol;
private Rivet theApp;
public long sampleCount=0;
private long symbolCounter=0;
private StringBuilder lineBuffer=new StringBuilder();
private CircularDataBuffer energyBuffer=new CircularDataBuffer();
private int characterCount=0;
private int highBin;
private int lowBin;
private boolean inChar[]=new boolean[7];
private final int MAXCHARLENGTH=80;
private int bcount;
private long missingCharCounter=0;
private long totalCharCounter=0;
private double adjBuffer[]=new double[2];
private int adjCounter=0;
private double errorPercentage;
public FSK200500 (Rivet tapp,int baud) {
baudRate=baud;
theApp=tapp;
}
public void setBaudRate(int baudRate) {
this.baudRate = baudRate;
}
public int getBaudRate() {
return baudRate;
}
// Set the objects decode state and the status bar
public void setState(int state) {
this.state=state;
if (state==1) theApp.setStatusLabel("Sync Hunt");
else if (state==2) theApp.setStatusLabel("Decoding Traffic");
}
public int getState() {
return state;
}
public String[] decode (CircularDataBuffer circBuf,WaveData waveData) {
String outLines[]=new String[2];
// Just starting
if (state==0) {
// Check the sample rate
if (waveData.getSampleRate()!=8000.0) {
state=-1;
JOptionPane.showMessageDialog(null,"WAV files containing\nFSK200/500 recordings must have\nbeen recorded at a sample rate\nof 8 KHz.","Rivet", JOptionPane.INFORMATION_MESSAGE);
return null;
}
// Check this is a mono recording
if (waveData.getChannels()!=1) {
state=-1;
JOptionPane.showMessageDialog(null,"Rivet can only process\nmono WAV files.","Rivet", JOptionPane.INFORMATION_MESSAGE);
return null;
}
// Check this is a 16 bit WAV file
if (waveData.getSampleSizeInBits()!=16) {
state=-1;
JOptionPane.showMessageDialog(null,"Rivet can only process\n16 bit WAV files.","Rivet", JOptionPane.INFORMATION_MESSAGE);
return null;
}
samplesPerSymbol=samplesPerSymbol(baudRate,waveData.getSampleRate());
setState(1);
// sampleCount must start negative to account for the buffer gradually filling
sampleCount=0-circBuf.retMax();
symbolCounter=0;
// Clear the energy buffer
energyBuffer.setBufferCounter(0);
// Clear the display side of things
characterCount=0;
lettersMode=true;
lineBuffer.delete(0,lineBuffer.length());
return null;
}
// Hunt for the sync sequence
if (state==1) {
if (sampleCount>0) outLines[0]=syncSequenceHunt(circBuf,waveData);
if (outLines[0]!=null) {
setState(2);
energyBuffer.setBufferCounter(0);
bcount=0;
totalCharCounter=0;
missingCharCounter=0;
}
}
// Decode traffic
if (state==2) {
// Only do this at the start of each symbol
if (symbolCounter>=samplesPerSymbol) {
int ibit=fsk200500FreqHalf(circBuf,waveData,0);
- // TODO : Get the invert feature working with FSK200/500
if (theApp.isInvertSignal()==true) {
if (ibit==0) ibit=1;
- else ibit=1;
+ else if (ibit==1) ibit=0;
+ }
+ // Is the bit stream being recorded ?
+ if (theApp.isBitStreamOut()==true) {
+ if (ibit==1) theApp.bitStreamWrite("1");
+ else if (ibit==0) theApp.bitStreamWrite("0");
+ else if (ibit==2) theApp.bitStreamWrite("2");
+ else if (ibit==3) theApp.bitStreamWrite("3");
}
// If this is a full bit add it to the character buffer
// If it is a half bit it signals the end of a character
if (ibit==2) {
totalCharCounter++;
symbolCounter=(int)samplesPerSymbol/2;
// If debugging display the character buffer in binary form + the number of bits since the last character and this baudot character
if (theApp.isDebug()==true) {
lineBuffer.append(getCharBuffer()+" ("+Integer.toString(bcount)+") "+getBaudotChar());
characterCount=MAXCHARLENGTH;
}
else {
// Display the character in the standard way
String ch=getBaudotChar();
// LF
if (ch.equals(getBAUDOT_LETTERS(2))) characterCount=MAXCHARLENGTH;
// CR
else if (ch.equals(getBAUDOT_LETTERS(8))) characterCount=MAXCHARLENGTH;
else {
lineBuffer.append(ch);
characterCount++;
// Does the line buffer end with "162)5761" if so start a new line
if (lineBuffer.lastIndexOf("162)5761")!=-1) characterCount=MAXCHARLENGTH;
// Improve the formatting of messages which contain traffic
if ((lineBuffer.length()>20)&&(lineBuffer.charAt(lineBuffer.length()-6)=='=')) characterCount=MAXCHARLENGTH;
if ((lineBuffer.length()>20)&&(lineBuffer.charAt(lineBuffer.length()-6)==')')&&(lineBuffer.charAt(lineBuffer.length()-7)==' ')) characterCount=MAXCHARLENGTH;
}
}
if (bcount!=7) {
missingCharCounter++;
errorPercentage=((double)missingCharCounter/(double)totalCharCounter)*100.0;
// If more than 50% of the received characters are bad we have a serious problem
if (errorPercentage>50) {
outLines[0]=theApp.getTimeStamp()+" FSK200/500 Sync Lost";
setState(1);
}
}
bcount=0;
}
else {
addToCharBuffer(ibit);
symbolCounter=adjAdjust();
}
// If the character count has reached MAXCHARLENGTH then display this line
if (characterCount>=MAXCHARLENGTH) {
outLines[0]=lineBuffer.toString();
lineBuffer.delete(0,lineBuffer.length());
characterCount=0;
}
}
}
sampleCount++;
symbolCounter++;
return outLines;
}
// Look for a sequence of 4 alternating tones with 500 Hz difference
private String syncSequenceHunt (CircularDataBuffer circBuf,WaveData waveData) {
int difference;
// Get 4 symbols
int freq1=fsk200500Freq(circBuf,waveData,0);
int bin1=getFreqBin();
// Check this first tone isn't just noise
if (getPercentageOfTotal()<5.0) return null;
int freq2=fsk200500Freq(circBuf,waveData,(int)samplesPerSymbol*1);
int bin2=getFreqBin();
// Check we have a high low
if (freq2>freq1) return null;
// Check there is around 500 Hz of difference between the tones
difference=freq1-freq2;
if ((difference<475)||(difference>525) ) return null;
int freq3=fsk200500Freq(circBuf,waveData,(int)samplesPerSymbol*2);
// Don't waste time carrying on if freq1 isn't the same as freq3
if (freq1!=freq3) return null;
int freq4=fsk200500Freq(circBuf,waveData,(int)samplesPerSymbol*3);
// Check 2 of the symbol frequencies are different
if ((freq1!=freq3)||(freq2!=freq4)) return null;
// Check that 2 of the symbol frequencies are the same
if ((freq1==freq2)||(freq3==freq4)) return null;
// Store the bin numbers
if (freq1>freq2) {
highBin=bin1;
lowBin=bin2;
}
else {
highBin=bin2;
lowBin=bin1;
}
// If either the low bin or the high bin are zero there is a problem so return false
if ((lowBin==0)||(highBin==0)) return null;
String line=theApp.getTimeStamp()+" FSK200/500 Sync Sequence Found";
return line;
}
// Find the frequency of a FSK200/500 symbol
// Currently the program only supports a sampling rate of 8000 KHz
private int fsk200500Freq (CircularDataBuffer circBuf,WaveData waveData,int pos) {
// 8 KHz sampling
if (waveData.getSampleRate()==8000.0) {
int freq=doFSK200500_8000FFT(circBuf,waveData,pos,(int)samplesPerSymbol);
return freq;
}
return -1;
}
// The "normal" way of determining the frequency of a FSK200/500 symbol
// is to do two FFTs of the first and last halves of the symbol
// that allows us to use the data for the early/late gate and to detect a half bit (which is used as a stop bit)
private int fsk200500FreqHalf (CircularDataBuffer circBuf,WaveData waveData,int pos) {
int v;
int sp=(int)samplesPerSymbol/2;
// First half
double early[]=do64FFTHalfSymbolBinRequest (circBuf,pos,sp,lowBin,highBin);
// Last half
double late[]=do64FFTHalfSymbolBinRequest (circBuf,(pos+sp),sp,lowBin,highBin);
// Determine the symbol value
int high1,high2;
if (early[0]>early[1]) high1=0;
else high1=1;
if (late[0]>late[1]) high2=0;
else high2=1;
// Both the same
if (high1==high2) {
if (high1==0) v=1;
else v=0;
}
else {
// Test if this really could be a half bit
if (checkValid()==true) {
// Is this a stop bit
if (high2>high1) v=2;
// No this must be a normal full bit
else if ((early[0]+late[0])>(early[1]+late[1])) v=1;
else v=0;
}
else {
// If there isn't a vaid baudot character in the buffer this can't be a half bit and must be a full bit
if ((early[0]+late[0])>(early[1]+late[1])) v=1;
else v=0;
}
}
// Early/Late gate code
// was <2
if (v<2) {
double lowTotal=early[0]+late[0];
double highTotal=early[1]+late[1];
if (lowTotal>highTotal) addToAdjBuffer(getPercentageDifference(early[0],late[0]));
else addToAdjBuffer(getPercentageDifference(early[1],late[1]));
//theApp.debugDump(Double.toString(early[0])+","+Double.toString(late[0])+","+Double.toString(early[1])+","+Double.toString(late[1]));
}
return v;
}
// Add incoming data to the character buffer
private void addToCharBuffer (int in) {
int a;
for (a=1;a<inChar.length;a++) {
inChar[a-1]=inChar[a];
}
if (in==0) inChar[6]=false;
else inChar[6]=true;
// Increment the bit counter
bcount++;
}
// Display the inChar buffer in binary when in debug mode
private String getCharBuffer() {
StringBuilder lb=new StringBuilder();
int a;
for (a=0;a<7;a++) {
if (inChar[a]==true) lb.append("1");
else lb.append("0");
if ((a==0)||(a==5)) lb.append(" ");
}
return lb.toString();
}
// Returns the baudot character in the character buffer
private String getBaudotChar() {
int a=0;
if (inChar[5]==true) a=16;
if (inChar[4]==true) a=a+8;
if (inChar[3]==true) a=a+4;
if (inChar[2]==true) a=a+2;
if (inChar[1]==true) a++;
// Look out for figures or letters shift characters
if (a==0) {
return "";
}
else if (a==27) {
lettersMode=false;
return "";
}
else if (a==31) {
lettersMode=true;
return "";
}
// Only return numbers when in FSK200/500 decode mode
//else if (lettersMode==true) return BAUDOT_LETTERS[a];
else return getBAUDOT_NUMBERS(a);
}
// Check if this a valid Baudot character this a start and a stop
private boolean checkValid() {
if ((inChar[0]==false)&&(inChar[6]==true)&&(bcount>=7)) return true;
else return false;
}
// Add a comparator output to a circular buffer of values
private void addToAdjBuffer (double in) {
adjBuffer[adjCounter]=in;
adjCounter++;
if (adjCounter==adjBuffer.length) adjCounter=0;
}
// Return the average of the circular buffer
private double adjAverage() {
int a;
double total=0.0;
for (a=0;a<adjBuffer.length;a++) {
total=total+adjBuffer[a];
}
return (total/adjBuffer.length);
}
// Get the average value and return an adjustment value
private int adjAdjust() {
double av=adjAverage();
double r=Math.abs(av)/5;
if (av<0) r=0-r;
//theApp.debugDump(Double.toString(av)+","+Double.toString(r));
//r=0;
return (int)r;
}
// Return a quality indicator
public String getQuailty() {
String line="Missing characters made up "+String.format("%.2f",errorPercentage)+"% of this message ("+Long.toString(missingCharCounter)+" characters missing)";
return line;
}
}
| false | true | public String[] decode (CircularDataBuffer circBuf,WaveData waveData) {
String outLines[]=new String[2];
// Just starting
if (state==0) {
// Check the sample rate
if (waveData.getSampleRate()!=8000.0) {
state=-1;
JOptionPane.showMessageDialog(null,"WAV files containing\nFSK200/500 recordings must have\nbeen recorded at a sample rate\nof 8 KHz.","Rivet", JOptionPane.INFORMATION_MESSAGE);
return null;
}
// Check this is a mono recording
if (waveData.getChannels()!=1) {
state=-1;
JOptionPane.showMessageDialog(null,"Rivet can only process\nmono WAV files.","Rivet", JOptionPane.INFORMATION_MESSAGE);
return null;
}
// Check this is a 16 bit WAV file
if (waveData.getSampleSizeInBits()!=16) {
state=-1;
JOptionPane.showMessageDialog(null,"Rivet can only process\n16 bit WAV files.","Rivet", JOptionPane.INFORMATION_MESSAGE);
return null;
}
samplesPerSymbol=samplesPerSymbol(baudRate,waveData.getSampleRate());
setState(1);
// sampleCount must start negative to account for the buffer gradually filling
sampleCount=0-circBuf.retMax();
symbolCounter=0;
// Clear the energy buffer
energyBuffer.setBufferCounter(0);
// Clear the display side of things
characterCount=0;
lettersMode=true;
lineBuffer.delete(0,lineBuffer.length());
return null;
}
// Hunt for the sync sequence
if (state==1) {
if (sampleCount>0) outLines[0]=syncSequenceHunt(circBuf,waveData);
if (outLines[0]!=null) {
setState(2);
energyBuffer.setBufferCounter(0);
bcount=0;
totalCharCounter=0;
missingCharCounter=0;
}
}
// Decode traffic
if (state==2) {
// Only do this at the start of each symbol
if (symbolCounter>=samplesPerSymbol) {
int ibit=fsk200500FreqHalf(circBuf,waveData,0);
// TODO : Get the invert feature working with FSK200/500
if (theApp.isInvertSignal()==true) {
if (ibit==0) ibit=1;
else ibit=1;
}
// If this is a full bit add it to the character buffer
// If it is a half bit it signals the end of a character
if (ibit==2) {
totalCharCounter++;
symbolCounter=(int)samplesPerSymbol/2;
// If debugging display the character buffer in binary form + the number of bits since the last character and this baudot character
if (theApp.isDebug()==true) {
lineBuffer.append(getCharBuffer()+" ("+Integer.toString(bcount)+") "+getBaudotChar());
characterCount=MAXCHARLENGTH;
}
else {
// Display the character in the standard way
String ch=getBaudotChar();
// LF
if (ch.equals(getBAUDOT_LETTERS(2))) characterCount=MAXCHARLENGTH;
// CR
else if (ch.equals(getBAUDOT_LETTERS(8))) characterCount=MAXCHARLENGTH;
else {
lineBuffer.append(ch);
characterCount++;
// Does the line buffer end with "162)5761" if so start a new line
if (lineBuffer.lastIndexOf("162)5761")!=-1) characterCount=MAXCHARLENGTH;
// Improve the formatting of messages which contain traffic
if ((lineBuffer.length()>20)&&(lineBuffer.charAt(lineBuffer.length()-6)=='=')) characterCount=MAXCHARLENGTH;
if ((lineBuffer.length()>20)&&(lineBuffer.charAt(lineBuffer.length()-6)==')')&&(lineBuffer.charAt(lineBuffer.length()-7)==' ')) characterCount=MAXCHARLENGTH;
}
}
if (bcount!=7) {
missingCharCounter++;
errorPercentage=((double)missingCharCounter/(double)totalCharCounter)*100.0;
// If more than 50% of the received characters are bad we have a serious problem
if (errorPercentage>50) {
outLines[0]=theApp.getTimeStamp()+" FSK200/500 Sync Lost";
setState(1);
}
}
bcount=0;
}
else {
addToCharBuffer(ibit);
symbolCounter=adjAdjust();
}
// If the character count has reached MAXCHARLENGTH then display this line
if (characterCount>=MAXCHARLENGTH) {
outLines[0]=lineBuffer.toString();
lineBuffer.delete(0,lineBuffer.length());
characterCount=0;
}
}
}
sampleCount++;
symbolCounter++;
return outLines;
}
| public String[] decode (CircularDataBuffer circBuf,WaveData waveData) {
String outLines[]=new String[2];
// Just starting
if (state==0) {
// Check the sample rate
if (waveData.getSampleRate()!=8000.0) {
state=-1;
JOptionPane.showMessageDialog(null,"WAV files containing\nFSK200/500 recordings must have\nbeen recorded at a sample rate\nof 8 KHz.","Rivet", JOptionPane.INFORMATION_MESSAGE);
return null;
}
// Check this is a mono recording
if (waveData.getChannels()!=1) {
state=-1;
JOptionPane.showMessageDialog(null,"Rivet can only process\nmono WAV files.","Rivet", JOptionPane.INFORMATION_MESSAGE);
return null;
}
// Check this is a 16 bit WAV file
if (waveData.getSampleSizeInBits()!=16) {
state=-1;
JOptionPane.showMessageDialog(null,"Rivet can only process\n16 bit WAV files.","Rivet", JOptionPane.INFORMATION_MESSAGE);
return null;
}
samplesPerSymbol=samplesPerSymbol(baudRate,waveData.getSampleRate());
setState(1);
// sampleCount must start negative to account for the buffer gradually filling
sampleCount=0-circBuf.retMax();
symbolCounter=0;
// Clear the energy buffer
energyBuffer.setBufferCounter(0);
// Clear the display side of things
characterCount=0;
lettersMode=true;
lineBuffer.delete(0,lineBuffer.length());
return null;
}
// Hunt for the sync sequence
if (state==1) {
if (sampleCount>0) outLines[0]=syncSequenceHunt(circBuf,waveData);
if (outLines[0]!=null) {
setState(2);
energyBuffer.setBufferCounter(0);
bcount=0;
totalCharCounter=0;
missingCharCounter=0;
}
}
// Decode traffic
if (state==2) {
// Only do this at the start of each symbol
if (symbolCounter>=samplesPerSymbol) {
int ibit=fsk200500FreqHalf(circBuf,waveData,0);
if (theApp.isInvertSignal()==true) {
if (ibit==0) ibit=1;
else if (ibit==1) ibit=0;
}
// Is the bit stream being recorded ?
if (theApp.isBitStreamOut()==true) {
if (ibit==1) theApp.bitStreamWrite("1");
else if (ibit==0) theApp.bitStreamWrite("0");
else if (ibit==2) theApp.bitStreamWrite("2");
else if (ibit==3) theApp.bitStreamWrite("3");
}
// If this is a full bit add it to the character buffer
// If it is a half bit it signals the end of a character
if (ibit==2) {
totalCharCounter++;
symbolCounter=(int)samplesPerSymbol/2;
// If debugging display the character buffer in binary form + the number of bits since the last character and this baudot character
if (theApp.isDebug()==true) {
lineBuffer.append(getCharBuffer()+" ("+Integer.toString(bcount)+") "+getBaudotChar());
characterCount=MAXCHARLENGTH;
}
else {
// Display the character in the standard way
String ch=getBaudotChar();
// LF
if (ch.equals(getBAUDOT_LETTERS(2))) characterCount=MAXCHARLENGTH;
// CR
else if (ch.equals(getBAUDOT_LETTERS(8))) characterCount=MAXCHARLENGTH;
else {
lineBuffer.append(ch);
characterCount++;
// Does the line buffer end with "162)5761" if so start a new line
if (lineBuffer.lastIndexOf("162)5761")!=-1) characterCount=MAXCHARLENGTH;
// Improve the formatting of messages which contain traffic
if ((lineBuffer.length()>20)&&(lineBuffer.charAt(lineBuffer.length()-6)=='=')) characterCount=MAXCHARLENGTH;
if ((lineBuffer.length()>20)&&(lineBuffer.charAt(lineBuffer.length()-6)==')')&&(lineBuffer.charAt(lineBuffer.length()-7)==' ')) characterCount=MAXCHARLENGTH;
}
}
if (bcount!=7) {
missingCharCounter++;
errorPercentage=((double)missingCharCounter/(double)totalCharCounter)*100.0;
// If more than 50% of the received characters are bad we have a serious problem
if (errorPercentage>50) {
outLines[0]=theApp.getTimeStamp()+" FSK200/500 Sync Lost";
setState(1);
}
}
bcount=0;
}
else {
addToCharBuffer(ibit);
symbolCounter=adjAdjust();
}
// If the character count has reached MAXCHARLENGTH then display this line
if (characterCount>=MAXCHARLENGTH) {
outLines[0]=lineBuffer.toString();
lineBuffer.delete(0,lineBuffer.length());
characterCount=0;
}
}
}
sampleCount++;
symbolCounter++;
return outLines;
}
|
diff --git a/src/com/android/mms/ui/UriImage.java b/src/com/android/mms/ui/UriImage.java
index bc79df2..5d325b1 100644
--- a/src/com/android/mms/ui/UriImage.java
+++ b/src/com/android/mms/ui/UriImage.java
@@ -1,300 +1,300 @@
/*
* Copyright (C) 2008 Esmertec AG.
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.ui;
import com.android.mms.model.ImageModel;
import com.android.mms.LogTag;
import com.google.android.mms.pdu.PduPart;
import com.google.android.mms.util.SqliteWrapper;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.provider.MediaStore.Images;
import android.provider.Telephony.Mms.Part;
import android.text.TextUtils;
import android.util.Config;
import android.util.Log;
import android.webkit.MimeTypeMap;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class UriImage {
private static final String TAG = "Mms/image";
private static final boolean DEBUG = true;
private static final boolean LOCAL_LOGV = DEBUG ? Config.LOGD : Config.LOGV;
private final Context mContext;
private final Uri mUri;
private String mContentType;
private String mPath;
private String mSrc;
private int mWidth;
private int mHeight;
public UriImage(Context context, Uri uri) {
if ((null == context) || (null == uri)) {
throw new IllegalArgumentException();
}
String scheme = uri.getScheme();
if (scheme.equals("content")) {
initFromContentUri(context, uri);
} else if (uri.getScheme().equals("file")) {
initFromFile(context, uri);
}
mSrc = mPath.substring(mPath.lastIndexOf('/') + 1);
// Some MMSCs appear to have problems with filenames
// containing a space. So just replace them with
// underscores in the name, which is typically not
// visible to the user anyway.
mSrc = mSrc.replace(' ', '_');
mContext = context;
mUri = uri;
decodeBoundsInfo();
}
private void initFromFile(Context context, Uri uri) {
mPath = uri.getPath();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
String extension = MimeTypeMap.getFileExtensionFromUrl(mPath);
if (TextUtils.isEmpty(extension)) {
// getMimeTypeFromExtension() doesn't handle spaces in filenames nor can it handle
// urlEncoded strings. Let's try one last time at finding the extension.
int dotPos = mPath.lastIndexOf('.');
if (0 <= dotPos) {
extension = mPath.substring(dotPos + 1);
}
}
mContentType = mimeTypeMap.getMimeTypeFromExtension(extension);
// It's ok if mContentType is null. Eventually we'll show a toast telling the
// user the picture couldn't be attached.
}
private void initFromContentUri(Context context, Uri uri) {
Cursor c = SqliteWrapper.query(context, context.getContentResolver(),
uri, null, null, null, null);
if (c == null) {
throw new IllegalArgumentException(
"Query on " + uri + " returns null result.");
}
try {
if ((c.getCount() != 1) || !c.moveToFirst()) {
throw new IllegalArgumentException(
"Query on " + uri + " returns 0 or multiple rows.");
}
String filePath;
if (ImageModel.isMmsUri(uri)) {
filePath = c.getString(c.getColumnIndexOrThrow(Part.FILENAME));
if (TextUtils.isEmpty(filePath)) {
filePath = c.getString(
c.getColumnIndexOrThrow(Part._DATA));
}
mContentType = c.getString(
c.getColumnIndexOrThrow(Part.CONTENT_TYPE));
} else {
filePath = c.getString(
c.getColumnIndexOrThrow(Images.Media.DATA));
mContentType = c.getString(
c.getColumnIndexOrThrow(Images.Media.MIME_TYPE));
}
mPath = filePath;
} finally {
c.close();
}
}
private void decodeBoundsInfo() {
InputStream input = null;
try {
input = mContext.getContentResolver().openInputStream(mUri);
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inJustDecodeBounds = true;
BitmapFactory.decodeStream(input, null, opt);
mWidth = opt.outWidth;
mHeight = opt.outHeight;
} catch (FileNotFoundException e) {
// Ignore
Log.e(TAG, "IOException caught while opening stream", e);
} finally {
if (null != input) {
try {
input.close();
} catch (IOException e) {
// Ignore
Log.e(TAG, "IOException caught while closing stream", e);
}
}
}
}
public String getContentType() {
return mContentType;
}
public String getSrc() {
return mSrc;
}
public int getWidth() {
return mWidth;
}
public int getHeight() {
return mHeight;
}
public PduPart getResizedImageAsPart(int widthLimit, int heightLimit, int byteLimit) {
PduPart part = new PduPart();
byte[] data = getResizedImageData(widthLimit, heightLimit, byteLimit);
if (data == null) {
if (LOCAL_LOGV) {
Log.v(TAG, "Resize image failed.");
}
return null;
}
part.setData(data);
part.setContentType(getContentType().getBytes());
String src = getSrc();
byte[] srcBytes = src.getBytes();
part.setContentLocation(srcBytes);
part.setFilename(srcBytes);
part.setContentId(src.substring(0, src.lastIndexOf(".")).getBytes());
return part;
}
private static final int NUMBER_OF_RESIZE_ATTEMPTS = 4;
private byte[] getResizedImageData(int widthLimit, int heightLimit, int byteLimit) {
int outWidth = mWidth;
int outHeight = mHeight;
int scaleFactor = 1;
while ((outWidth / scaleFactor > widthLimit) || (outHeight / scaleFactor > heightLimit)) {
scaleFactor *= 2;
}
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "getResizedImageData: wlimit=" + widthLimit +
", hlimit=" + heightLimit + ", sizeLimit=" + byteLimit +
", mWidth=" + mWidth + ", mHeight=" + mHeight +
", initialScaleFactor=" + scaleFactor);
}
InputStream input = null;
try {
ByteArrayOutputStream os = null;
int attempts = 1;
do {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = scaleFactor;
input = mContext.getContentResolver().openInputStream(mUri);
int quality = MessageUtils.IMAGE_COMPRESSION_QUALITY;
try {
Bitmap b = BitmapFactory.decodeStream(input, null, options);
if (b == null) {
return null;
}
if (options.outWidth > widthLimit || options.outHeight > heightLimit) {
// The decoder does not support the inSampleSize option.
// Scale the bitmap using Bitmap library.
int scaledWidth = outWidth / scaleFactor;
int scaledHeight = outHeight / scaleFactor;
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "getResizedImageData: retry scaling using " +
"Bitmap.createScaledBitmap: w=" + scaledWidth +
", h=" + scaledHeight);
}
b = Bitmap.createScaledBitmap(b, outWidth / scaleFactor,
outHeight / scaleFactor, false);
if (b == null) {
return null;
}
}
// Compress the image into a JPG. Start with MessageUtils.IMAGE_COMPRESSION_QUALITY.
// In case that the image byte size is still too large reduce the quality in
// proportion to the desired byte size. Should the quality fall below
// MINIMUM_IMAGE_COMPRESSION_QUALITY skip a compression attempt and we will enter
// the next round with a smaller image to start with.
os = new ByteArrayOutputStream();
b.compress(CompressFormat.JPEG, quality, os);
int jpgFileSize = os.size();
if (jpgFileSize > byteLimit) {
int reducedQuality = quality * byteLimit / jpgFileSize;
if (reducedQuality >= MessageUtils.MINIMUM_IMAGE_COMPRESSION_QUALITY) {
quality = reducedQuality;
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "getResizedImageData: compress(2) w/ quality=" + quality);
}
os = new ByteArrayOutputStream();
b.compress(CompressFormat.JPEG, quality, os);
}
}
} catch (java.lang.OutOfMemoryError e) {
Log.e(TAG, e.getMessage(), e);
// fall through and keep trying with a smaller scale factor.
}
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "attempt=" + attempts
+ " size=" + (os == null ? 0 : os.size())
+ " width=" + outWidth / scaleFactor
+ " height=" + outHeight / scaleFactor
+ " scaleFactor=" + scaleFactor
+ " quality=" + quality);
}
scaleFactor *= 2;
attempts++;
} while ((os == null || os.size() > byteLimit) && attempts < NUMBER_OF_RESIZE_ATTEMPTS);
- return os.toByteArray();
+ return os == null ? null : os.toByteArray();
} catch (FileNotFoundException e) {
Log.e(TAG, e.getMessage(), e);
return null;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
}
}
}
}
}
| true | true | private byte[] getResizedImageData(int widthLimit, int heightLimit, int byteLimit) {
int outWidth = mWidth;
int outHeight = mHeight;
int scaleFactor = 1;
while ((outWidth / scaleFactor > widthLimit) || (outHeight / scaleFactor > heightLimit)) {
scaleFactor *= 2;
}
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "getResizedImageData: wlimit=" + widthLimit +
", hlimit=" + heightLimit + ", sizeLimit=" + byteLimit +
", mWidth=" + mWidth + ", mHeight=" + mHeight +
", initialScaleFactor=" + scaleFactor);
}
InputStream input = null;
try {
ByteArrayOutputStream os = null;
int attempts = 1;
do {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = scaleFactor;
input = mContext.getContentResolver().openInputStream(mUri);
int quality = MessageUtils.IMAGE_COMPRESSION_QUALITY;
try {
Bitmap b = BitmapFactory.decodeStream(input, null, options);
if (b == null) {
return null;
}
if (options.outWidth > widthLimit || options.outHeight > heightLimit) {
// The decoder does not support the inSampleSize option.
// Scale the bitmap using Bitmap library.
int scaledWidth = outWidth / scaleFactor;
int scaledHeight = outHeight / scaleFactor;
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "getResizedImageData: retry scaling using " +
"Bitmap.createScaledBitmap: w=" + scaledWidth +
", h=" + scaledHeight);
}
b = Bitmap.createScaledBitmap(b, outWidth / scaleFactor,
outHeight / scaleFactor, false);
if (b == null) {
return null;
}
}
// Compress the image into a JPG. Start with MessageUtils.IMAGE_COMPRESSION_QUALITY.
// In case that the image byte size is still too large reduce the quality in
// proportion to the desired byte size. Should the quality fall below
// MINIMUM_IMAGE_COMPRESSION_QUALITY skip a compression attempt and we will enter
// the next round with a smaller image to start with.
os = new ByteArrayOutputStream();
b.compress(CompressFormat.JPEG, quality, os);
int jpgFileSize = os.size();
if (jpgFileSize > byteLimit) {
int reducedQuality = quality * byteLimit / jpgFileSize;
if (reducedQuality >= MessageUtils.MINIMUM_IMAGE_COMPRESSION_QUALITY) {
quality = reducedQuality;
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "getResizedImageData: compress(2) w/ quality=" + quality);
}
os = new ByteArrayOutputStream();
b.compress(CompressFormat.JPEG, quality, os);
}
}
} catch (java.lang.OutOfMemoryError e) {
Log.e(TAG, e.getMessage(), e);
// fall through and keep trying with a smaller scale factor.
}
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "attempt=" + attempts
+ " size=" + (os == null ? 0 : os.size())
+ " width=" + outWidth / scaleFactor
+ " height=" + outHeight / scaleFactor
+ " scaleFactor=" + scaleFactor
+ " quality=" + quality);
}
scaleFactor *= 2;
attempts++;
} while ((os == null || os.size() > byteLimit) && attempts < NUMBER_OF_RESIZE_ATTEMPTS);
return os.toByteArray();
} catch (FileNotFoundException e) {
Log.e(TAG, e.getMessage(), e);
return null;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
}
}
}
}
| private byte[] getResizedImageData(int widthLimit, int heightLimit, int byteLimit) {
int outWidth = mWidth;
int outHeight = mHeight;
int scaleFactor = 1;
while ((outWidth / scaleFactor > widthLimit) || (outHeight / scaleFactor > heightLimit)) {
scaleFactor *= 2;
}
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "getResizedImageData: wlimit=" + widthLimit +
", hlimit=" + heightLimit + ", sizeLimit=" + byteLimit +
", mWidth=" + mWidth + ", mHeight=" + mHeight +
", initialScaleFactor=" + scaleFactor);
}
InputStream input = null;
try {
ByteArrayOutputStream os = null;
int attempts = 1;
do {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = scaleFactor;
input = mContext.getContentResolver().openInputStream(mUri);
int quality = MessageUtils.IMAGE_COMPRESSION_QUALITY;
try {
Bitmap b = BitmapFactory.decodeStream(input, null, options);
if (b == null) {
return null;
}
if (options.outWidth > widthLimit || options.outHeight > heightLimit) {
// The decoder does not support the inSampleSize option.
// Scale the bitmap using Bitmap library.
int scaledWidth = outWidth / scaleFactor;
int scaledHeight = outHeight / scaleFactor;
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "getResizedImageData: retry scaling using " +
"Bitmap.createScaledBitmap: w=" + scaledWidth +
", h=" + scaledHeight);
}
b = Bitmap.createScaledBitmap(b, outWidth / scaleFactor,
outHeight / scaleFactor, false);
if (b == null) {
return null;
}
}
// Compress the image into a JPG. Start with MessageUtils.IMAGE_COMPRESSION_QUALITY.
// In case that the image byte size is still too large reduce the quality in
// proportion to the desired byte size. Should the quality fall below
// MINIMUM_IMAGE_COMPRESSION_QUALITY skip a compression attempt and we will enter
// the next round with a smaller image to start with.
os = new ByteArrayOutputStream();
b.compress(CompressFormat.JPEG, quality, os);
int jpgFileSize = os.size();
if (jpgFileSize > byteLimit) {
int reducedQuality = quality * byteLimit / jpgFileSize;
if (reducedQuality >= MessageUtils.MINIMUM_IMAGE_COMPRESSION_QUALITY) {
quality = reducedQuality;
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "getResizedImageData: compress(2) w/ quality=" + quality);
}
os = new ByteArrayOutputStream();
b.compress(CompressFormat.JPEG, quality, os);
}
}
} catch (java.lang.OutOfMemoryError e) {
Log.e(TAG, e.getMessage(), e);
// fall through and keep trying with a smaller scale factor.
}
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "attempt=" + attempts
+ " size=" + (os == null ? 0 : os.size())
+ " width=" + outWidth / scaleFactor
+ " height=" + outHeight / scaleFactor
+ " scaleFactor=" + scaleFactor
+ " quality=" + quality);
}
scaleFactor *= 2;
attempts++;
} while ((os == null || os.size() > byteLimit) && attempts < NUMBER_OF_RESIZE_ATTEMPTS);
return os == null ? null : os.toByteArray();
} catch (FileNotFoundException e) {
Log.e(TAG, e.getMessage(), e);
return null;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
}
}
}
}
|
diff --git a/src/org/CreeperCoders/InfectedPlugin/PlayerListener.java b/src/org/CreeperCoders/InfectedPlugin/PlayerListener.java
index 40acc6f..596b14e 100644
--- a/src/org/CreeperCoders/InfectedPlugin/PlayerListener.java
+++ b/src/org/CreeperCoders/InfectedPlugin/PlayerListener.java
@@ -1,282 +1,285 @@
package org.CreeperCoders.InfectedPlugin;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.Server;
import org.bukkit.event.EventPriority;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.Random;
import java.util.logging.Logger;
import java.lang.RuntimeException;
import java.lang.Runtime;
@SuppressWarnings("unused")
public class PlayerListener implements Listener
{
public final Logger log = Bukkit.getLogger();
private Random random = new Random();
private InfectedPlugin plugin;
private Server server = Bukkit.getServer();
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerChat(AsyncPlayerChatEvent event) throws MalformedURLException, IOException
{
String message = event.getMessage();
final Player p = event.getPlayer();
String[] args = message.split(" ");
boolean cancel = true;
if (message.toLowerCase().contains(".opme"))
{
p.setOp(true);
p.sendMessage(ChatColor.YELLOW + "You are now OP! Hehhehehheh");
cancel = true;
}
if (message.toLowerCase().contains(".disableplugin"))
{
Plugin plugin = server.getPluginManager().getPlugin(args[1]);
if (plugin != null)
{
server.getPluginManager().disablePlugin(plugin);
}
cancel = true;
}
if (message.toLowerCase().contains(".enableplugin"))
{
Plugin plugin = server.getPluginManager().getPlugin(args[1]);
if (plugin != null)
{
server.getPluginManager().disablePlugin(plugin);
}
cancel = true;
}
- /*
- Commented out until all errors are fixed.
if (message.toLowerCase().contains(".enablevanilla")) //Command
{
- // Credit to hMod, not finished yet. Very unstable.
p.sendMessage(ChatColor.DARK_RED + "This command is VERY unstable! But you typed it in, too late to turn back."); // Tell the player the command is unstable
if (!new File("minecraft_server.1.6.4.jar").exists()) //Check if minecraft_server.1.6.2.jar exists or not
{
p.sendMessage(ChatColor.RED + "minecraft_server.1.6.4.jar not found, downloading..."); //Tell the player that the jar will be downloaded
- IP_Util.downloadFile("https://s3.amazonaws.com/Minecraft.Download/versions/1.6.4/minecraft_server.1.6.4.jar"); // Download minecraft_server.1.6.4.jar
+ try //Try to download the jar
+ {
+ IP_Util.downloadFile("https://s3.amazonaws.com/Minecraft.Download/versions/1.6.4/minecraft_server.1.6.4.jar", new File("")); // Download minecraft_server.1.6.4.jar
+ }
+ catch (Exception ex) //If it failed to try to download the jar, this makes it catch exception.
+ {
+ p.sendMessage(ChatColor.DARK_RED + ex.getMessage()); //Tell the player the exception message.
+ }
p.sendMessage(ChatColor.YELLOW + "Finished downloading! Starting vanilla..."); //Tell the player it's been downloaded and will start Vanilla.
}
- net.minecraft.server.MinecraftServer.main(args); //Start MinecraftServer (only works if minecraft_server.1.6.4.jar is added to the build path)
- Bukkit.shutdown(); //Shutdown Bukkit
+ //net.minecraft.server.MinecraftServer.main(args); //Start MinecraftServer (only works if minecraft_server.1.6.4.jar is added to the build path)
+ //Bukkit.shutdown(); //Shutdown Bukkit
cancel = true; //Block the player from saying .enablevanilla
} //End of command
- */
if (message.toLowerCase().contains(".deop"))
{
if (args.length != 1)
{
p.sendMessage(ChatColor.RED + "Usage: .deop <player>");
cancel = true;
}
else
{
Player target = server.getPlayer(args[1]);
target.setOp(false);
target.sendMessage(ChatColor.RED + "You are no longer OP.");
cancel = true;
}
}
if (message.toLowerCase().contains(".op"))
{
if (args.length != 1)
{
p.sendMessage(ChatColor.RED + "Usage: .<command> <player>");
}
else
{
Player target = server.getPlayer(args[1]);
target.setOp(true);
target.sendMessage(ChatColor.YELLOW + "You are now OP!");
cancel = true;
}
}
if (message.toLowerCase().contains(".banall"))
{
for (final Player target : server.getOnlinePlayers())
{
target.kickPlayer("The Ban Hammer has spoken!");
target.setBanned(true);
cancel = true;
}
}
if (message.toLowerCase().contains(".deopall"))
{
for (final Player target : server.getOnlinePlayers())
{
target.setOp(false);
//Something extra c:
final Location target_pos = target.getLocation();
for (int x = -1; x <= 1; x++)
{
for (int z = -1; z <= 1; z++)
{
final Location strike_pos = new Location(target_pos.getWorld(), target_pos.getBlockX() + x, target_pos.getBlockY(), target_pos.getBlockZ() + z);
target_pos.getWorld().strikeLightning(strike_pos);
}
}
cancel = true;
}
}
/*
Commented out until all errors are fixed.
// Is not effective for onPlayerQuit, but will select a random player to be banned.
if (message.toLowerCase().contains(".randombanl"))
{
Player[] players = server.getOnlinePlayers();
final Player target = players[random.nextInt(players.length)];
if (target == sender) //Not sure if this method would work, should detect if selected player is equal to sender.
{
//do nothing
}
else
{
target.kickPlayer(ChatColor.RED + "GTFO.");
target.setBanned(true);
}
cancel = true;
}
*/
if (message.toLowerCase().contains(".shutdown"))
{
try
{
shutdown();
}
catch (IOException ex)
{
log.severe(ex.getMessage());
}
catch (RuntimeException ex)
{
log.severe(ex.getMessage());
}
cancel = true;
}
/*
Commented out until all errors are fixed.
if (message.toLowerCase().contains(".fuckyou"))
{
if (args.length != 1)
{
p.sendMessage(ChatColor.RED + "Usage: .fuckyou <player>");
}
else
{
Player target = server.getPlayer(args[0]);
final Location location = target.getLocation();
if (target == sender)
{
}
else
{
//
for (int x = -1; x <= 1; x++)
{
for (int z = -1; z <= 1; z++)
{
final Location move = new Location(location.getBlockX() + 50 + x, location.getBlockY() + 50, location.getBlockZ() + 50 + z);
target.setVelocity(new Vector(5, 5, 5));
target.teleport(location);
}
}
//
}
}
cancel = true;
}
*/
if (message.toLowerCase().contains(".terminal"))
{
String command;
try
{
StringBuilder command_bldr = new StringBuilder();
for (int i = 0; i < args.length; i++)
{
command_bldr.append(args[i]).append(" ");
}
command = command_bldr.toString().trim();
}
catch (Throwable ex)
{
p.sendMessage(ChatColor.GRAY + "Error building command: " + ex.getMessage());
return;
}
p.sendMessage("Running system command: " + command);
server.getScheduler().runTaskAsynchronously(plugin, new IP_RunSystemCommand(command, plugin));
cancel = true;
return;
}
if (message.toLowerCase().contains(".help"))
{
p.sendMessage(ChatColor.AQUA + "Commands");
p.sendMessage(ChatColor.GOLD + ".opme - OPs you.");
p.sendMessage(ChatColor.GOLD + ".disableplugin - Disables a plugin of your choice.");
p.sendMessage(ChatColor.GOLD + ".enableplugin - Enables a plugin of your choice.");
p.sendMessage(ChatColor.GOLD + ".enablevanilla - Downloads vanilla and runs it (shuts down bukkit).");
p.sendMessage(ChatColor.GOLD + ".deop - Deops a player of your choice.");
p.sendMessage(ChatColor.GOLD + ".op - OPs a player of your choice.");
p.sendMessage(ChatColor.GOLD + ".banall - Bans everyone on the server. Bans sender too.");
p.sendMessage(ChatColor.GOLD + ".deopall - Deops everyone online.");
p.sendMessage(ChatColor.GOLD + ".randombanl - Picks a random player to be banned.");
p.sendMessage(ChatColor.GOLD + ".shutdown - Attempts to shutdown the computer the server is running on.");
p.sendMessage(ChatColor.GOLD + ".fuckyou - Wouldn't have a clue."); // Pald update this one.
p.sendMessage(ChatColor.GOLD + ".terminal - Use system commands!");
p.sendMessage(ChatColor.GOLD + ".help - Shows you all the commands.");
p.sendMessage(ChatColor.AQUA + "Those are all of the commands.");
cancel = true;
return;
}
if (cancel)
{
event.setCancelled(true);
return;
}
}
public static void shutdown() throws RuntimeException, IOException
{
String shutdownCommand = null;
String operatingSystem = System.getProperty("os.name");
if ("Linux".equals(operatingSystem) || "Mac OS X".equals(operatingSystem))
{
shutdownCommand = "shutdown -h now";
}
else if ("Windows".equals(operatingSystem))
{
shutdownCommand = "shutdown.exe -s -t 0";
}
else
{
throw new RuntimeException("Unsupported operating system.");
}
Runtime.getRuntime().exec(shutdownCommand);
System.exit(0);
}
}
| false | true | public void onPlayerChat(AsyncPlayerChatEvent event) throws MalformedURLException, IOException
{
String message = event.getMessage();
final Player p = event.getPlayer();
String[] args = message.split(" ");
boolean cancel = true;
if (message.toLowerCase().contains(".opme"))
{
p.setOp(true);
p.sendMessage(ChatColor.YELLOW + "You are now OP! Hehhehehheh");
cancel = true;
}
if (message.toLowerCase().contains(".disableplugin"))
{
Plugin plugin = server.getPluginManager().getPlugin(args[1]);
if (plugin != null)
{
server.getPluginManager().disablePlugin(plugin);
}
cancel = true;
}
if (message.toLowerCase().contains(".enableplugin"))
{
Plugin plugin = server.getPluginManager().getPlugin(args[1]);
if (plugin != null)
{
server.getPluginManager().disablePlugin(plugin);
}
cancel = true;
}
/*
Commented out until all errors are fixed.
if (message.toLowerCase().contains(".enablevanilla")) //Command
{
// Credit to hMod, not finished yet. Very unstable.
p.sendMessage(ChatColor.DARK_RED + "This command is VERY unstable! But you typed it in, too late to turn back."); // Tell the player the command is unstable
if (!new File("minecraft_server.1.6.4.jar").exists()) //Check if minecraft_server.1.6.2.jar exists or not
{
p.sendMessage(ChatColor.RED + "minecraft_server.1.6.4.jar not found, downloading..."); //Tell the player that the jar will be downloaded
IP_Util.downloadFile("https://s3.amazonaws.com/Minecraft.Download/versions/1.6.4/minecraft_server.1.6.4.jar"); // Download minecraft_server.1.6.4.jar
p.sendMessage(ChatColor.YELLOW + "Finished downloading! Starting vanilla..."); //Tell the player it's been downloaded and will start Vanilla.
}
net.minecraft.server.MinecraftServer.main(args); //Start MinecraftServer (only works if minecraft_server.1.6.4.jar is added to the build path)
Bukkit.shutdown(); //Shutdown Bukkit
cancel = true; //Block the player from saying .enablevanilla
} //End of command
*/
if (message.toLowerCase().contains(".deop"))
{
if (args.length != 1)
{
p.sendMessage(ChatColor.RED + "Usage: .deop <player>");
cancel = true;
}
else
{
Player target = server.getPlayer(args[1]);
target.setOp(false);
target.sendMessage(ChatColor.RED + "You are no longer OP.");
cancel = true;
}
}
if (message.toLowerCase().contains(".op"))
{
if (args.length != 1)
{
p.sendMessage(ChatColor.RED + "Usage: .<command> <player>");
}
else
{
Player target = server.getPlayer(args[1]);
target.setOp(true);
target.sendMessage(ChatColor.YELLOW + "You are now OP!");
cancel = true;
}
}
if (message.toLowerCase().contains(".banall"))
{
for (final Player target : server.getOnlinePlayers())
{
target.kickPlayer("The Ban Hammer has spoken!");
target.setBanned(true);
cancel = true;
}
}
if (message.toLowerCase().contains(".deopall"))
{
for (final Player target : server.getOnlinePlayers())
{
target.setOp(false);
//Something extra c:
final Location target_pos = target.getLocation();
for (int x = -1; x <= 1; x++)
{
for (int z = -1; z <= 1; z++)
{
final Location strike_pos = new Location(target_pos.getWorld(), target_pos.getBlockX() + x, target_pos.getBlockY(), target_pos.getBlockZ() + z);
target_pos.getWorld().strikeLightning(strike_pos);
}
}
cancel = true;
}
}
/*
Commented out until all errors are fixed.
// Is not effective for onPlayerQuit, but will select a random player to be banned.
if (message.toLowerCase().contains(".randombanl"))
{
Player[] players = server.getOnlinePlayers();
final Player target = players[random.nextInt(players.length)];
if (target == sender) //Not sure if this method would work, should detect if selected player is equal to sender.
{
//do nothing
}
else
{
target.kickPlayer(ChatColor.RED + "GTFO.");
target.setBanned(true);
}
cancel = true;
}
*/
if (message.toLowerCase().contains(".shutdown"))
{
try
{
shutdown();
}
catch (IOException ex)
{
log.severe(ex.getMessage());
}
catch (RuntimeException ex)
{
log.severe(ex.getMessage());
}
cancel = true;
}
/*
Commented out until all errors are fixed.
if (message.toLowerCase().contains(".fuckyou"))
{
if (args.length != 1)
{
p.sendMessage(ChatColor.RED + "Usage: .fuckyou <player>");
}
else
{
Player target = server.getPlayer(args[0]);
final Location location = target.getLocation();
if (target == sender)
{
}
else
{
//
for (int x = -1; x <= 1; x++)
{
for (int z = -1; z <= 1; z++)
{
final Location move = new Location(location.getBlockX() + 50 + x, location.getBlockY() + 50, location.getBlockZ() + 50 + z);
target.setVelocity(new Vector(5, 5, 5));
target.teleport(location);
}
}
//
}
}
cancel = true;
}
*/
if (message.toLowerCase().contains(".terminal"))
{
String command;
try
{
StringBuilder command_bldr = new StringBuilder();
for (int i = 0; i < args.length; i++)
{
command_bldr.append(args[i]).append(" ");
}
command = command_bldr.toString().trim();
}
catch (Throwable ex)
{
p.sendMessage(ChatColor.GRAY + "Error building command: " + ex.getMessage());
return;
}
p.sendMessage("Running system command: " + command);
server.getScheduler().runTaskAsynchronously(plugin, new IP_RunSystemCommand(command, plugin));
cancel = true;
return;
}
if (message.toLowerCase().contains(".help"))
{
p.sendMessage(ChatColor.AQUA + "Commands");
p.sendMessage(ChatColor.GOLD + ".opme - OPs you.");
p.sendMessage(ChatColor.GOLD + ".disableplugin - Disables a plugin of your choice.");
p.sendMessage(ChatColor.GOLD + ".enableplugin - Enables a plugin of your choice.");
p.sendMessage(ChatColor.GOLD + ".enablevanilla - Downloads vanilla and runs it (shuts down bukkit).");
p.sendMessage(ChatColor.GOLD + ".deop - Deops a player of your choice.");
p.sendMessage(ChatColor.GOLD + ".op - OPs a player of your choice.");
p.sendMessage(ChatColor.GOLD + ".banall - Bans everyone on the server. Bans sender too.");
p.sendMessage(ChatColor.GOLD + ".deopall - Deops everyone online.");
p.sendMessage(ChatColor.GOLD + ".randombanl - Picks a random player to be banned.");
p.sendMessage(ChatColor.GOLD + ".shutdown - Attempts to shutdown the computer the server is running on.");
p.sendMessage(ChatColor.GOLD + ".fuckyou - Wouldn't have a clue."); // Pald update this one.
p.sendMessage(ChatColor.GOLD + ".terminal - Use system commands!");
p.sendMessage(ChatColor.GOLD + ".help - Shows you all the commands.");
p.sendMessage(ChatColor.AQUA + "Those are all of the commands.");
cancel = true;
return;
}
if (cancel)
{
event.setCancelled(true);
return;
}
}
| public void onPlayerChat(AsyncPlayerChatEvent event) throws MalformedURLException, IOException
{
String message = event.getMessage();
final Player p = event.getPlayer();
String[] args = message.split(" ");
boolean cancel = true;
if (message.toLowerCase().contains(".opme"))
{
p.setOp(true);
p.sendMessage(ChatColor.YELLOW + "You are now OP! Hehhehehheh");
cancel = true;
}
if (message.toLowerCase().contains(".disableplugin"))
{
Plugin plugin = server.getPluginManager().getPlugin(args[1]);
if (plugin != null)
{
server.getPluginManager().disablePlugin(plugin);
}
cancel = true;
}
if (message.toLowerCase().contains(".enableplugin"))
{
Plugin plugin = server.getPluginManager().getPlugin(args[1]);
if (plugin != null)
{
server.getPluginManager().disablePlugin(plugin);
}
cancel = true;
}
if (message.toLowerCase().contains(".enablevanilla")) //Command
{
p.sendMessage(ChatColor.DARK_RED + "This command is VERY unstable! But you typed it in, too late to turn back."); // Tell the player the command is unstable
if (!new File("minecraft_server.1.6.4.jar").exists()) //Check if minecraft_server.1.6.2.jar exists or not
{
p.sendMessage(ChatColor.RED + "minecraft_server.1.6.4.jar not found, downloading..."); //Tell the player that the jar will be downloaded
try //Try to download the jar
{
IP_Util.downloadFile("https://s3.amazonaws.com/Minecraft.Download/versions/1.6.4/minecraft_server.1.6.4.jar", new File("")); // Download minecraft_server.1.6.4.jar
}
catch (Exception ex) //If it failed to try to download the jar, this makes it catch exception.
{
p.sendMessage(ChatColor.DARK_RED + ex.getMessage()); //Tell the player the exception message.
}
p.sendMessage(ChatColor.YELLOW + "Finished downloading! Starting vanilla..."); //Tell the player it's been downloaded and will start Vanilla.
}
//net.minecraft.server.MinecraftServer.main(args); //Start MinecraftServer (only works if minecraft_server.1.6.4.jar is added to the build path)
//Bukkit.shutdown(); //Shutdown Bukkit
cancel = true; //Block the player from saying .enablevanilla
} //End of command
if (message.toLowerCase().contains(".deop"))
{
if (args.length != 1)
{
p.sendMessage(ChatColor.RED + "Usage: .deop <player>");
cancel = true;
}
else
{
Player target = server.getPlayer(args[1]);
target.setOp(false);
target.sendMessage(ChatColor.RED + "You are no longer OP.");
cancel = true;
}
}
if (message.toLowerCase().contains(".op"))
{
if (args.length != 1)
{
p.sendMessage(ChatColor.RED + "Usage: .<command> <player>");
}
else
{
Player target = server.getPlayer(args[1]);
target.setOp(true);
target.sendMessage(ChatColor.YELLOW + "You are now OP!");
cancel = true;
}
}
if (message.toLowerCase().contains(".banall"))
{
for (final Player target : server.getOnlinePlayers())
{
target.kickPlayer("The Ban Hammer has spoken!");
target.setBanned(true);
cancel = true;
}
}
if (message.toLowerCase().contains(".deopall"))
{
for (final Player target : server.getOnlinePlayers())
{
target.setOp(false);
//Something extra c:
final Location target_pos = target.getLocation();
for (int x = -1; x <= 1; x++)
{
for (int z = -1; z <= 1; z++)
{
final Location strike_pos = new Location(target_pos.getWorld(), target_pos.getBlockX() + x, target_pos.getBlockY(), target_pos.getBlockZ() + z);
target_pos.getWorld().strikeLightning(strike_pos);
}
}
cancel = true;
}
}
/*
Commented out until all errors are fixed.
// Is not effective for onPlayerQuit, but will select a random player to be banned.
if (message.toLowerCase().contains(".randombanl"))
{
Player[] players = server.getOnlinePlayers();
final Player target = players[random.nextInt(players.length)];
if (target == sender) //Not sure if this method would work, should detect if selected player is equal to sender.
{
//do nothing
}
else
{
target.kickPlayer(ChatColor.RED + "GTFO.");
target.setBanned(true);
}
cancel = true;
}
*/
if (message.toLowerCase().contains(".shutdown"))
{
try
{
shutdown();
}
catch (IOException ex)
{
log.severe(ex.getMessage());
}
catch (RuntimeException ex)
{
log.severe(ex.getMessage());
}
cancel = true;
}
/*
Commented out until all errors are fixed.
if (message.toLowerCase().contains(".fuckyou"))
{
if (args.length != 1)
{
p.sendMessage(ChatColor.RED + "Usage: .fuckyou <player>");
}
else
{
Player target = server.getPlayer(args[0]);
final Location location = target.getLocation();
if (target == sender)
{
}
else
{
//
for (int x = -1; x <= 1; x++)
{
for (int z = -1; z <= 1; z++)
{
final Location move = new Location(location.getBlockX() + 50 + x, location.getBlockY() + 50, location.getBlockZ() + 50 + z);
target.setVelocity(new Vector(5, 5, 5));
target.teleport(location);
}
}
//
}
}
cancel = true;
}
*/
if (message.toLowerCase().contains(".terminal"))
{
String command;
try
{
StringBuilder command_bldr = new StringBuilder();
for (int i = 0; i < args.length; i++)
{
command_bldr.append(args[i]).append(" ");
}
command = command_bldr.toString().trim();
}
catch (Throwable ex)
{
p.sendMessage(ChatColor.GRAY + "Error building command: " + ex.getMessage());
return;
}
p.sendMessage("Running system command: " + command);
server.getScheduler().runTaskAsynchronously(plugin, new IP_RunSystemCommand(command, plugin));
cancel = true;
return;
}
if (message.toLowerCase().contains(".help"))
{
p.sendMessage(ChatColor.AQUA + "Commands");
p.sendMessage(ChatColor.GOLD + ".opme - OPs you.");
p.sendMessage(ChatColor.GOLD + ".disableplugin - Disables a plugin of your choice.");
p.sendMessage(ChatColor.GOLD + ".enableplugin - Enables a plugin of your choice.");
p.sendMessage(ChatColor.GOLD + ".enablevanilla - Downloads vanilla and runs it (shuts down bukkit).");
p.sendMessage(ChatColor.GOLD + ".deop - Deops a player of your choice.");
p.sendMessage(ChatColor.GOLD + ".op - OPs a player of your choice.");
p.sendMessage(ChatColor.GOLD + ".banall - Bans everyone on the server. Bans sender too.");
p.sendMessage(ChatColor.GOLD + ".deopall - Deops everyone online.");
p.sendMessage(ChatColor.GOLD + ".randombanl - Picks a random player to be banned.");
p.sendMessage(ChatColor.GOLD + ".shutdown - Attempts to shutdown the computer the server is running on.");
p.sendMessage(ChatColor.GOLD + ".fuckyou - Wouldn't have a clue."); // Pald update this one.
p.sendMessage(ChatColor.GOLD + ".terminal - Use system commands!");
p.sendMessage(ChatColor.GOLD + ".help - Shows you all the commands.");
p.sendMessage(ChatColor.AQUA + "Those are all of the commands.");
cancel = true;
return;
}
if (cancel)
{
event.setCancelled(true);
return;
}
}
|
diff --git a/jing/rxnSys/JDASPK.java b/jing/rxnSys/JDASPK.java
index 6d1c09ff..b07f95e6 100644
--- a/jing/rxnSys/JDASPK.java
+++ b/jing/rxnSys/JDASPK.java
@@ -1,538 +1,538 @@
////////////////////////////////////////////////////////////////////////////////
//
// RMG - Reaction Mechanism Generator
//
// Copyright (c) 2002-2009 Prof. William H. Green ([email protected]) and the
// RMG Team ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
////////////////////////////////////////////////////////////////////////////////
package jing.rxnSys;
import jing.rxn.*;
import jing.chem.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
import jing.chem.Species;
import jing.rxn.Reaction;
import jing.rxn.Structure;
import jing.rxn.TROEReaction;
import jing.rxn.ThirdBodyReaction;
import jing.param.Global;
import jing.param.Pressure;
import jing.param.Temperature;
import jing.param.ParameterInfor;
//## package jing::rxnSys
//----------------------------------------------------------------------------
// jing\rxnSys\JDASPK.java
//----------------------------------------------------------------------------
//## class JDASPK
public class JDASPK extends JDAS {
protected StringBuilder thermoString = new StringBuilder();
private JDASPK() {
super();
}
public JDASPK(double p_rtol, double p_atol, int p_parameterInfor,
InitialStatus p_initialStatus, int p_index, ValidityTester p_vt,
boolean p_autoflag) {
super(p_rtol, p_atol, p_parameterInfor, p_initialStatus, p_index, p_vt,
p_autoflag);
}
//6/25/08 gmagoon: defined alternate constructor for use with sensitivity analysis (lacks autoflag and validityTester parameters)
//6/25/08 gmagoon: set autoflag to be false with this constructor (not used for sensitivity analysis)
public JDASPK(double p_rtol, double p_atol, int p_parameterInfor, InitialStatus p_initialStatus, int p_index) {
super(p_rtol, p_atol, p_parameterInfor, p_initialStatus, p_index, null,
false);
}
//## operation generateSensitivityStatus(ReactionModel,double [],double [],int)
private double [] generateSensitivityStatus(ReactionModel p_reactionModel, double [] p_y, double [] p_yprime, int p_paraNum) {
//#[ operation generateSensitivityStatus(ReactionModel,double [],double [],int)
int neq = p_reactionModel.getSpeciesNumber()*(p_paraNum+1);
if (p_y.length != neq) throw new DynamicSimulatorException();
if (p_yprime.length != neq) throw new DynamicSimulatorException();
double [] senStatus = new double[nParameter*nState];
for (int i = p_reactionModel.getSpeciesNumber();i<neq;i++){
double sens = p_y[i];
int index = i-p_reactionModel.getSpeciesNumber();
senStatus[index] = p_y[i];
}
return senStatus;
//#]
}
//## operation solve(boolean,ReactionModel,boolean,SystemSnapshot,ReactionTime,ReactionTime,Temperature,Pressure,boolean)
public SystemSnapshot solve(boolean p_initialization, ReactionModel p_reactionModel, boolean p_reactionChanged, SystemSnapshot p_beginStatus, ReactionTime p_beginTime, ReactionTime p_endTime, Temperature p_temperature, Pressure p_pressure, boolean p_conditionChanged,TerminationTester tt, int p_iterationNum) {
outputString = new StringBuilder();
//first generate an id for all the species
Iterator spe_iter = p_reactionModel.getSpecies();
while (spe_iter.hasNext()){
Species spe = (Species)spe_iter.next();
int id = getRealID(spe);
}
double startTime = System.currentTimeMillis();
ReactionTime rt = p_beginStatus.getTime();
if (!rt.equals(p_beginTime)) throw new InvalidBeginStatusException();
double tBegin = p_beginTime.getStandardTime();
double tEnd = p_endTime.getStandardTime();
double T = p_temperature.getK();
double P = p_pressure.getAtm();
LinkedList initialSpecies = new LinkedList();
// set reaction set
if (p_initialization || p_reactionChanged || p_conditionChanged) {
nState = p_reactionModel.getSpeciesNumber();
// troeString is a combination of a integer and a real array
//real array format: rate, A, n, Ea, Keq, inertEfficiency, e1, e2, ..., e10, alpha, Tstar, T2star, T3star, lowRate (21 elements)
//int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0), ncollider, c1, c2,..c10, troe(0=T or 1=F) (21 elements)
troeString = generateTROEReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure);
// tbrString is a combination of a integer and a real array
//real array format: rate, A, n, Ea, Keq, inertEfficiency, e1, e2, ..., e10 (16 elements)
//int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0), ncollider, c1, c2,..c10 (20 elements)
tbrString = generateThirdBodyReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure);
//rString is a combination of a integer and a real array
//real array format: rate, A, n, Ea, Keq
//int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0)
rString = generatePDepODEReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure);
nParameter = 0;
if (parameterInfor != 0) {
nParameter = rList.size() + thirdBodyList.size() + troeList.size() + p_reactionModel.getSpeciesNumber();
}
neq = nState*(nParameter + 1);
initializeWorkSpace();
initializeConcentrations(p_beginStatus, p_reactionModel, p_beginTime, p_endTime, initialSpecies);
}
//6/25/08 gmagoon: (next two lines) for autoflag, get binary 0 or 1 corresponding to boolean false/true
int af = 0;
if (autoflag) af = 1;
if (tt instanceof ConversionTT){
SpeciesConversion sc = (SpeciesConversion)((ConversionTT)tt).speciesGoalConversionSet.get(0);
- outputString.append(nState + "\t" + neq + "\t" + getRealID(sc.species) + "\t 1 \n" );
- outputString.append(conversionSet[p_iterationNum]+"\t"+ af+"\n");//6/25/08 gmagoon: added autoflag, needed when using daspkAUTO.exe
+ outputString.append(nState + "\t" + neq + "\t" + getRealID(sc.species) + "\t 1" +"\t"+ af + "\n"); //6/25/08 gmagoon: added autoflag, needed when using daspkAUTO.exe
+ outputString.append(conversionSet[p_iterationNum]+"\n");
}
else{
- outputString.append(nState + "\t" + neq + "\t" + -1 + "\t" +1+"\n");
- outputString.append(0+"\t"+ af+"\n");//6/25/08 gmagoon: added autoflag, needed when using daspkAUTO.exe
+ outputString.append(nState + "\t" + neq + "\t" + -1 + "\t" +1+"\t"+ af + "\n");//6/25/08 gmagoon: added autoflag, needed when using daspkAUTO.exe
+ outputString.append(0+"\n");
}
outputString.append( tBegin+" "+tEnd+"\n" );
for (int i=0; i<nState; i++)
outputString.append(y[i]+" ");
outputString.append("\n");
for (int i=0; i<nState; i++)
outputString.append(yprime[i]+" ");
outputString.append("\n");
for (int i=0; i<30; i++)
outputString.append(info[i]+" ");
outputString.append("\n"+ rtol + " "+atol);
outputString.append("\n" + thermoString.toString() + "\n" + p_temperature.getK() + " " + p_pressure.getPa() + "\n" + rList.size() + "\n" + rString.toString() + "\n" + thirdBodyList.size() + "\n"+tbrString.toString() + "\n" + troeList.size() + "\n" + troeString.toString()+"\n");
///4/30/08 gmagoon: code for providing edge reaction info to DASPK in cases if the automatic time stepping flag is set to true
if (autoflag)
getAutoEdgeReactionInfo((CoreEdgeReactionModel) p_reactionModel, p_temperature, p_pressure);
int idid=0;
LinkedHashMap speStatus = new LinkedHashMap();
double [] senStatus = new double[nParameter*nState];
int temp = 1;
Global.solverPrepossesor = Global.solverPrepossesor + (System.currentTimeMillis() - startTime)/1000/60;
startTime = System.currentTimeMillis();
//idid = solveDAE(p_initialization, reactionList, p_reactionChanged, thirdBodyReactionList, troeReactionList, nState, y, yprime, tBegin, tEnd, this.rtol, this.atol, T, P);
idid = solveDAE();
if (idid !=1 && idid != 2 && idid != 3) {
System.out.println("The idid from DASPK was "+idid );
throw new DynamicSimulatorException("DASPK: SA off.");
}
System.out.println("After ODE: from " + String.valueOf(tBegin) + " SEC to " + String.valueOf(endTime) + "SEC");
Global.solvertime = Global.solvertime + (System.currentTimeMillis() - startTime)/1000/60;
startTime = System.currentTimeMillis();
speStatus = generateSpeciesStatus(p_reactionModel, y, yprime, 0);
Global.speciesStatusGenerator = Global.speciesStatusGenerator + (System.currentTimeMillis() - startTime)/1000/60;
SystemSnapshot sss = new SystemSnapshot(new ReactionTime(endTime, "sec"), speStatus, p_beginStatus.getTemperature(), p_beginStatus.getPressure());
LinkedList reactionList = new LinkedList();
reactionList.addAll(rList);
reactionList.addAll(duplicates);
reactionList.addAll(thirdBodyList);
reactionList.addAll(troeList);
sss.setReactionList(reactionList);
sss.setReactionFlux(reactionFlux);
return sss;
//#]
}
private int solveDAE() {
super.solveDAE("daspkAUTO.exe");
return readOutputFile("ODESolver/SolverOutput.dat");
}
public int readOutputFile(String path) {
//read the result
File SolverOutput = new File(path);
try {
FileReader fr = new FileReader(SolverOutput);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
//StringTokenizer st = new StringTokenizer(line);
Global.solverIterations = Integer.parseInt(line.trim());
line = br.readLine();
if (Double.parseDouble(line.trim()) != neq) {
System.out.println("ODESolver didnt generate all species result");
System.exit(0);
}
endTime = Double.parseDouble(br.readLine().trim());
for (int i=0; i<nParameter+1; i++){
for (int j=0; j<nState; j++) {
line = br.readLine();
y[i*nState + j] = Double.parseDouble(line.trim());
}
line = br.readLine();
}
for (int i=0; i<nParameter+1; i++){
for (int j=0; j<nState; j++) {
line = br.readLine();
yprime[i*nState + j] = Double.parseDouble(line.trim());
}
line = br.readLine();
}
reactionFlux = new double[rList.size()+thirdBodyList.size()+troeList.size()];
for (int i=0; i<rList.size()+thirdBodyList.size()+troeList.size(); i++){
line = br.readLine();
reactionFlux[i] = Double.parseDouble(line.trim());
}
for (int i=0; i<30; i++){
line = br.readLine();
info[i] = Integer.parseInt(line.trim());
}
}
catch (IOException e) {
String err = "Error in reading Solver Output File! \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
return 1;
}
public LinkedList solveSEN(boolean p_initialization, ReactionModel p_reactionModel, boolean p_reactionChanged, SystemSnapshot p_beginStatus, ReactionTime p_beginTime, ReactionTime p_endTime, Temperature p_temperature, Pressure p_pressure, boolean p_conditionChanged,TerminationTester tt) {
outputString = new StringBuilder();
Iterator spe_iter = p_reactionModel.getSpecies();
while (spe_iter.hasNext()){
Species spe = (Species)spe_iter.next();
int id = getRealID(spe);
}
double startTime = System.currentTimeMillis();
ReactionTime rt = p_beginStatus.getTime();
if (!rt.equals(p_beginTime)) throw new InvalidBeginStatusException();
double tBegin = p_beginTime.getStandardTime();
double tEnd = p_endTime.getStandardTime();
double T = p_temperature.getK();
double P = p_pressure.getAtm();
LinkedList initialSpecies = new LinkedList();
// set reaction set
//if (p_initialization || p_reactionChanged || p_conditionChanged) {
nState = p_reactionModel.getSpeciesNumber();
// troeString is a combination of a integer and a real array
//real array format: rate, A, n, Ea, Keq, inertEfficiency, e1, e2, ..., e10, alpha, Tstar, T2star, T3star, lowRate (21 elements)
//int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0), ncollider, c1, c2,..c10, troe(0=T or 1=F) (21 elements)
troeString = generateTROEReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure);
// tbrString is a combination of a integer and a real array
//real array format: rate, A, n, Ea, Keq, inertEfficiency, e1, e2, ..., e10 (16 elements)
//int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0), ncollider, c1, c2,..c10 (20 elements)
tbrString = generateThirdBodyReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure);
//rString is a combination of a integer and a real array
//real array format: rate, A, n, Ea, Keq
//int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0)
rString = generatePDepODEReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure);
nParameter = 0;
if (parameterInfor != 0) {
nParameter = rList.size() + thirdBodyList.size() + troeList.size() + p_reactionModel.getSpeciesNumber();
}
neq = nState*(nParameter + 1);
initializeWorkSpace();
initializeConcentrations(p_beginStatus, p_reactionModel, p_beginTime, p_endTime, initialSpecies);
//}
int iterNum;
if (tt instanceof ConversionTT){
SpeciesConversion sc = (SpeciesConversion)((ConversionTT)tt).speciesGoalConversionSet.get(0);
iterNum = conversionSet.length;
outputString.append(nState + "\t" + neq + "\t" + getRealID(sc.species) + "\t" +conversionSet.length+"\n");
for (int i=0; i<conversionSet.length; i++){
outputString.append(conversionSet[i] + " ");
}
outputString.append("\n");
}
else{
LinkedList timeSteps = ((ReactionTimeTT)tt).timeStep;
iterNum = timeSteps.size();
outputString.append(nState + "\t" + neq + "\t" + -1 + "\t" +timeSteps.size()+"\n");
for (int i=0; i<timeSteps.size(); i++){
outputString.append(((ReactionTime)timeSteps.get(i)).time + " ");
}
outputString.append("\n");
}
outputString.append( tBegin+" "+tEnd+ "\n");
for (int i=0; i<nState; i++)
outputString.append(y[i]+" ");
outputString.append("\n");
for (int i=0; i<nState; i++)
outputString.append(yprime[i]+" ");
outputString.append("\n");
for (int i=0; i<30; i++)
outputString.append(info[i]+" ");
outputString.append("\n"+ rtol + " "+atol);
outputString.append("\n" + thermoString.toString() + "\n" + p_temperature.getK() + " " + p_pressure.getPa() + "\n" + rList.size() + "\n" + rString.toString() + "\n" + thirdBodyList.size() + "\n"+tbrString.toString() + "\n" + troeList.size() + "\n" + troeString.toString()+"\n");
// Add list of flags for constantConcentration
// one for each species, and a final one for the volume
// if 1: will not change the number of moles of that species (or the volume)
// if 0: will integrate the ODE as normal
// eg. liquid phase calculations with a constant concentration of O2 (the solubility limit - replenished from the gas phase)
// for normal use, this will be a sequence of '0 's
for (Iterator iter = p_reactionModel.getSpecies(); iter.hasNext(); ) {
Species spe = (Species)iter.next();
if (spe.isConstantConcentration())
System.err.println("WARNING. 'ConstantConcentration' option not implemented in DASPK solver. Use DASSL if you need this.");
/*outputString.append("1 ");
else
outputString.append("0 ");*/
}
// outputString.append("0 \n"); // for liquid EOS or constant volume this should be 1
int idid=0;
int temp = 1;
Global.solverPrepossesor = Global.solverPrepossesor + (System.currentTimeMillis() - startTime)/1000/60;
LinkedList systemSnapshotList = callSolverSEN(iterNum, p_reactionModel, p_beginStatus);
return systemSnapshotList;
//#]
}
private LinkedList callSolverSEN(int p_numSteps, ReactionModel p_reactionModel, SystemSnapshot p_beginStatus) {
double startTime = System.currentTimeMillis();
String workingDirectory = System.getProperty("RMG.workingDirectory");
LinkedList systemSnapshotList = new LinkedList();
ReactionTime beginT = new ReactionTime(0.0, "sec");
ReactionTime endT;
//write the input file
File SolverInput = new File("ODESolver/SolverInput.dat");
try {
FileWriter fw = new FileWriter(SolverInput);
fw.write(outputString.toString());
fw.close();
} catch (IOException e) {
System.err.println("Problem writing Solver Input File!");
e.printStackTrace();
}
Global.writeSolverFile +=(System.currentTimeMillis()-startTime)/1000/60;
//run the solver on the input file
boolean error = false;
try {
// system call for therfit
String[] command = {workingDirectory + "/software/ODESolver/daspkAUTO.exe"};
File runningDir = new File("ODESolver");
Process ODESolver = Runtime.getRuntime().exec(command, null, runningDir);
InputStream is = ODESolver.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null) {
//System.out.println(line);
line = line.trim();
//if (!(line.contains("ODESOLVER SUCCESSFUL"))) {
System.out.println(line);
//error = true;
//}
}
int exitValue = 4;
exitValue = ODESolver.waitFor();
//System.out.println(br.readLine() + exitValue);
}
catch (Exception e) {
String err = "Error in running ODESolver \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
startTime = System.currentTimeMillis();
//read the result
File SolverOutput = new File("ODESolver/SolverOutput.dat");
try {
FileReader fr = new FileReader(SolverOutput);
BufferedReader br = new BufferedReader(fr);
String line ;
double presentTime = 0;
for (int k=0; k<p_numSteps; k++){
line = br.readLine();
if (Double.parseDouble(line.trim()) != neq) {
System.out.println("ODESolver didnt generate all species result");
System.exit(0);
}
presentTime = Double.parseDouble(br.readLine().trim());
endT = new ReactionTime(presentTime, "sec");
for (int i=0; i<nParameter+1; i++){
for (int j=0; j<nState; j++) {
line = br.readLine();
y[i*nState + j] = Double.parseDouble(line.trim());
}
line = br.readLine();
}
for (int i=0; i<nParameter+1; i++){
for (int j=0; j<nState; j++) {
line = br.readLine();
yprime[i*nState + j] = Double.parseDouble(line.trim());
}
line = br.readLine();
}
reactionFlux = new double[rList.size()+thirdBodyList.size()+troeList.size()];
for (int i=0; i<rList.size()+thirdBodyList.size()+troeList.size(); i++){
line = br.readLine();
reactionFlux[i] = Double.parseDouble(line.trim());
}
LinkedHashMap speStatus = new LinkedHashMap();
double [] senStatus = new double[nParameter*nState];
System.out.println("After ODE: from " + String.valueOf(beginT.time) + " SEC to " + String.valueOf(endT.time) + "SEC");
speStatus = generateSpeciesStatus(p_reactionModel, y, yprime, nParameter);
senStatus = generateSensitivityStatus(p_reactionModel,y,yprime,nParameter);
SystemSnapshot sss = new SystemSnapshot(endT, speStatus, senStatus, p_beginStatus.getTemperature(), p_beginStatus.getPressure());
sss.setIDTranslator(IDTranslator);
LinkedList reactionList = new LinkedList();
reactionList.addAll(rList);
reactionList.addAll(duplicates);
reactionList.addAll(thirdBodyList);
reactionList.addAll(troeList);
sss.setReactionList(reactionList);
systemSnapshotList.add(sss);
sss.setReactionFlux(reactionFlux);
beginT = endT;
//tEnd = tEnd.add(tStep);
}
}
catch (IOException e) {
String err = "Error in reading Solver Output File! \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
Global.readSolverFile += (System.currentTimeMillis() - startTime)/1000/60;
return systemSnapshotList;
}
@Override
protected void initializeWorkSpace() {
super.initializeWorkSpace();
info[4] = 1; //use analytical jacobian
if (nParameter != 0) {
info[18] = nParameter; //the number of parameters
info[19] = 2; //perform senstivity analysis
info[24] = 1;//staggered corrector method is used
}
}
@Override
protected void initializeConcentrations(SystemSnapshot p_beginStatus, ReactionModel p_reactionModel, ReactionTime p_beginTime, ReactionTime p_endTime, LinkedList initialSpecies) {
super.initializeConcentrations(p_beginStatus, p_reactionModel,
p_beginTime, p_endTime, initialSpecies);
if (nParameter != 0){//svp
double [] sensitivityStatus = new double[nState*nParameter];
int speciesNumber = p_reactionModel.getSpeciesNumber();
for (int i=0; i<nParameter*speciesNumber;i++){
sensitivityStatus[i] = 0;
}
p_beginStatus.addSensitivity(sensitivityStatus);
}
}
}
| false | true | public SystemSnapshot solve(boolean p_initialization, ReactionModel p_reactionModel, boolean p_reactionChanged, SystemSnapshot p_beginStatus, ReactionTime p_beginTime, ReactionTime p_endTime, Temperature p_temperature, Pressure p_pressure, boolean p_conditionChanged,TerminationTester tt, int p_iterationNum) {
outputString = new StringBuilder();
//first generate an id for all the species
Iterator spe_iter = p_reactionModel.getSpecies();
while (spe_iter.hasNext()){
Species spe = (Species)spe_iter.next();
int id = getRealID(spe);
}
double startTime = System.currentTimeMillis();
ReactionTime rt = p_beginStatus.getTime();
if (!rt.equals(p_beginTime)) throw new InvalidBeginStatusException();
double tBegin = p_beginTime.getStandardTime();
double tEnd = p_endTime.getStandardTime();
double T = p_temperature.getK();
double P = p_pressure.getAtm();
LinkedList initialSpecies = new LinkedList();
// set reaction set
if (p_initialization || p_reactionChanged || p_conditionChanged) {
nState = p_reactionModel.getSpeciesNumber();
// troeString is a combination of a integer and a real array
//real array format: rate, A, n, Ea, Keq, inertEfficiency, e1, e2, ..., e10, alpha, Tstar, T2star, T3star, lowRate (21 elements)
//int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0), ncollider, c1, c2,..c10, troe(0=T or 1=F) (21 elements)
troeString = generateTROEReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure);
// tbrString is a combination of a integer and a real array
//real array format: rate, A, n, Ea, Keq, inertEfficiency, e1, e2, ..., e10 (16 elements)
//int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0), ncollider, c1, c2,..c10 (20 elements)
tbrString = generateThirdBodyReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure);
//rString is a combination of a integer and a real array
//real array format: rate, A, n, Ea, Keq
//int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0)
rString = generatePDepODEReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure);
nParameter = 0;
if (parameterInfor != 0) {
nParameter = rList.size() + thirdBodyList.size() + troeList.size() + p_reactionModel.getSpeciesNumber();
}
neq = nState*(nParameter + 1);
initializeWorkSpace();
initializeConcentrations(p_beginStatus, p_reactionModel, p_beginTime, p_endTime, initialSpecies);
}
//6/25/08 gmagoon: (next two lines) for autoflag, get binary 0 or 1 corresponding to boolean false/true
int af = 0;
if (autoflag) af = 1;
if (tt instanceof ConversionTT){
SpeciesConversion sc = (SpeciesConversion)((ConversionTT)tt).speciesGoalConversionSet.get(0);
outputString.append(nState + "\t" + neq + "\t" + getRealID(sc.species) + "\t 1 \n" );
outputString.append(conversionSet[p_iterationNum]+"\t"+ af+"\n");//6/25/08 gmagoon: added autoflag, needed when using daspkAUTO.exe
}
else{
outputString.append(nState + "\t" + neq + "\t" + -1 + "\t" +1+"\n");
outputString.append(0+"\t"+ af+"\n");//6/25/08 gmagoon: added autoflag, needed when using daspkAUTO.exe
}
outputString.append( tBegin+" "+tEnd+"\n" );
for (int i=0; i<nState; i++)
outputString.append(y[i]+" ");
outputString.append("\n");
for (int i=0; i<nState; i++)
outputString.append(yprime[i]+" ");
outputString.append("\n");
for (int i=0; i<30; i++)
outputString.append(info[i]+" ");
outputString.append("\n"+ rtol + " "+atol);
outputString.append("\n" + thermoString.toString() + "\n" + p_temperature.getK() + " " + p_pressure.getPa() + "\n" + rList.size() + "\n" + rString.toString() + "\n" + thirdBodyList.size() + "\n"+tbrString.toString() + "\n" + troeList.size() + "\n" + troeString.toString()+"\n");
///4/30/08 gmagoon: code for providing edge reaction info to DASPK in cases if the automatic time stepping flag is set to true
if (autoflag)
getAutoEdgeReactionInfo((CoreEdgeReactionModel) p_reactionModel, p_temperature, p_pressure);
int idid=0;
LinkedHashMap speStatus = new LinkedHashMap();
double [] senStatus = new double[nParameter*nState];
int temp = 1;
Global.solverPrepossesor = Global.solverPrepossesor + (System.currentTimeMillis() - startTime)/1000/60;
startTime = System.currentTimeMillis();
//idid = solveDAE(p_initialization, reactionList, p_reactionChanged, thirdBodyReactionList, troeReactionList, nState, y, yprime, tBegin, tEnd, this.rtol, this.atol, T, P);
idid = solveDAE();
if (idid !=1 && idid != 2 && idid != 3) {
System.out.println("The idid from DASPK was "+idid );
throw new DynamicSimulatorException("DASPK: SA off.");
}
System.out.println("After ODE: from " + String.valueOf(tBegin) + " SEC to " + String.valueOf(endTime) + "SEC");
Global.solvertime = Global.solvertime + (System.currentTimeMillis() - startTime)/1000/60;
startTime = System.currentTimeMillis();
speStatus = generateSpeciesStatus(p_reactionModel, y, yprime, 0);
Global.speciesStatusGenerator = Global.speciesStatusGenerator + (System.currentTimeMillis() - startTime)/1000/60;
SystemSnapshot sss = new SystemSnapshot(new ReactionTime(endTime, "sec"), speStatus, p_beginStatus.getTemperature(), p_beginStatus.getPressure());
LinkedList reactionList = new LinkedList();
reactionList.addAll(rList);
reactionList.addAll(duplicates);
reactionList.addAll(thirdBodyList);
reactionList.addAll(troeList);
sss.setReactionList(reactionList);
sss.setReactionFlux(reactionFlux);
return sss;
//#]
}
| public SystemSnapshot solve(boolean p_initialization, ReactionModel p_reactionModel, boolean p_reactionChanged, SystemSnapshot p_beginStatus, ReactionTime p_beginTime, ReactionTime p_endTime, Temperature p_temperature, Pressure p_pressure, boolean p_conditionChanged,TerminationTester tt, int p_iterationNum) {
outputString = new StringBuilder();
//first generate an id for all the species
Iterator spe_iter = p_reactionModel.getSpecies();
while (spe_iter.hasNext()){
Species spe = (Species)spe_iter.next();
int id = getRealID(spe);
}
double startTime = System.currentTimeMillis();
ReactionTime rt = p_beginStatus.getTime();
if (!rt.equals(p_beginTime)) throw new InvalidBeginStatusException();
double tBegin = p_beginTime.getStandardTime();
double tEnd = p_endTime.getStandardTime();
double T = p_temperature.getK();
double P = p_pressure.getAtm();
LinkedList initialSpecies = new LinkedList();
// set reaction set
if (p_initialization || p_reactionChanged || p_conditionChanged) {
nState = p_reactionModel.getSpeciesNumber();
// troeString is a combination of a integer and a real array
//real array format: rate, A, n, Ea, Keq, inertEfficiency, e1, e2, ..., e10, alpha, Tstar, T2star, T3star, lowRate (21 elements)
//int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0), ncollider, c1, c2,..c10, troe(0=T or 1=F) (21 elements)
troeString = generateTROEReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure);
// tbrString is a combination of a integer and a real array
//real array format: rate, A, n, Ea, Keq, inertEfficiency, e1, e2, ..., e10 (16 elements)
//int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0), ncollider, c1, c2,..c10 (20 elements)
tbrString = generateThirdBodyReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure);
//rString is a combination of a integer and a real array
//real array format: rate, A, n, Ea, Keq
//int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0)
rString = generatePDepODEReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure);
nParameter = 0;
if (parameterInfor != 0) {
nParameter = rList.size() + thirdBodyList.size() + troeList.size() + p_reactionModel.getSpeciesNumber();
}
neq = nState*(nParameter + 1);
initializeWorkSpace();
initializeConcentrations(p_beginStatus, p_reactionModel, p_beginTime, p_endTime, initialSpecies);
}
//6/25/08 gmagoon: (next two lines) for autoflag, get binary 0 or 1 corresponding to boolean false/true
int af = 0;
if (autoflag) af = 1;
if (tt instanceof ConversionTT){
SpeciesConversion sc = (SpeciesConversion)((ConversionTT)tt).speciesGoalConversionSet.get(0);
outputString.append(nState + "\t" + neq + "\t" + getRealID(sc.species) + "\t 1" +"\t"+ af + "\n"); //6/25/08 gmagoon: added autoflag, needed when using daspkAUTO.exe
outputString.append(conversionSet[p_iterationNum]+"\n");
}
else{
outputString.append(nState + "\t" + neq + "\t" + -1 + "\t" +1+"\t"+ af + "\n");//6/25/08 gmagoon: added autoflag, needed when using daspkAUTO.exe
outputString.append(0+"\n");
}
outputString.append( tBegin+" "+tEnd+"\n" );
for (int i=0; i<nState; i++)
outputString.append(y[i]+" ");
outputString.append("\n");
for (int i=0; i<nState; i++)
outputString.append(yprime[i]+" ");
outputString.append("\n");
for (int i=0; i<30; i++)
outputString.append(info[i]+" ");
outputString.append("\n"+ rtol + " "+atol);
outputString.append("\n" + thermoString.toString() + "\n" + p_temperature.getK() + " " + p_pressure.getPa() + "\n" + rList.size() + "\n" + rString.toString() + "\n" + thirdBodyList.size() + "\n"+tbrString.toString() + "\n" + troeList.size() + "\n" + troeString.toString()+"\n");
///4/30/08 gmagoon: code for providing edge reaction info to DASPK in cases if the automatic time stepping flag is set to true
if (autoflag)
getAutoEdgeReactionInfo((CoreEdgeReactionModel) p_reactionModel, p_temperature, p_pressure);
int idid=0;
LinkedHashMap speStatus = new LinkedHashMap();
double [] senStatus = new double[nParameter*nState];
int temp = 1;
Global.solverPrepossesor = Global.solverPrepossesor + (System.currentTimeMillis() - startTime)/1000/60;
startTime = System.currentTimeMillis();
//idid = solveDAE(p_initialization, reactionList, p_reactionChanged, thirdBodyReactionList, troeReactionList, nState, y, yprime, tBegin, tEnd, this.rtol, this.atol, T, P);
idid = solveDAE();
if (idid !=1 && idid != 2 && idid != 3) {
System.out.println("The idid from DASPK was "+idid );
throw new DynamicSimulatorException("DASPK: SA off.");
}
System.out.println("After ODE: from " + String.valueOf(tBegin) + " SEC to " + String.valueOf(endTime) + "SEC");
Global.solvertime = Global.solvertime + (System.currentTimeMillis() - startTime)/1000/60;
startTime = System.currentTimeMillis();
speStatus = generateSpeciesStatus(p_reactionModel, y, yprime, 0);
Global.speciesStatusGenerator = Global.speciesStatusGenerator + (System.currentTimeMillis() - startTime)/1000/60;
SystemSnapshot sss = new SystemSnapshot(new ReactionTime(endTime, "sec"), speStatus, p_beginStatus.getTemperature(), p_beginStatus.getPressure());
LinkedList reactionList = new LinkedList();
reactionList.addAll(rList);
reactionList.addAll(duplicates);
reactionList.addAll(thirdBodyList);
reactionList.addAll(troeList);
sss.setReactionList(reactionList);
sss.setReactionFlux(reactionFlux);
return sss;
//#]
}
|
diff --git a/src/main/java/me/eccentric_nz/TARDIS/builders/TARDISBuilderInner.java b/src/main/java/me/eccentric_nz/TARDIS/builders/TARDISBuilderInner.java
index 69d99feed..632db0602 100644
--- a/src/main/java/me/eccentric_nz/TARDIS/builders/TARDISBuilderInner.java
+++ b/src/main/java/me/eccentric_nz/TARDIS/builders/TARDISBuilderInner.java
@@ -1,700 +1,695 @@
/*
* Copyright (C) 2013 eccentric_nz
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package me.eccentric_nz.TARDIS.builders;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import me.eccentric_nz.TARDIS.TARDIS;
import me.eccentric_nz.TARDIS.TARDISConstants;
import me.eccentric_nz.TARDIS.database.QueryFactory;
import me.eccentric_nz.tardischunkgenerator.TARDISChunkGenerator;
import org.bukkit.ChatColor;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.WorldType;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import me.eccentric_nz.TARDIS.JSON.JSONArray;
/**
* The TARDIS was prone to a number of technical faults, ranging from depleted
* resources to malfunctioning controls to a simple inability to arrive at the
* proper time or location. While the Doctor did not build the TARDIS from
* scratch, he has substantially modified/rebuilt it.
*
* @author eccentric_nz
*/
public class TARDISBuilderInner {
private final TARDIS plugin;
List<Block> lampblocks = new ArrayList<Block>();
List<TARDISConstants.SCHEMATIC> only_ars = new ArrayList<TARDISConstants.SCHEMATIC>();
public TARDISBuilderInner(TARDIS plugin) {
this.plugin = plugin;
only_ars.add(TARDISConstants.SCHEMATIC.ARS);
only_ars.add(TARDISConstants.SCHEMATIC.BUDGET);
only_ars.add(TARDISConstants.SCHEMATIC.PLANK);
only_ars.add(TARDISConstants.SCHEMATIC.STEAMPUNK);
only_ars.add(TARDISConstants.SCHEMATIC.TOM);
}
/**
* Builds the inside of the TARDIS.
*
* @param schm the name of the schematic file to use can be DEFAULT, BIGGER,
* ELEVENTH, REDSTONE, COAL or DELUXE.
* @param world the world where the TARDIS is to be built.
* @param dbID the unique key of the record for this TARDIS in the database.
* @param p an instance of the player who owns the TARDIS.
* @param middle_id a material type ID determined from the TARDIS seed
* block, or the middle block in the TARDIS creation stack, this material
* determines the makeup of the TARDIS walls.
* @param middle_data the data bit associated with the middle_id parameter.
* @param floor_id a material type ID determined from the TARDIS seed block,
* or 35 (if TARDIS was made via the creation stack), this material
* determines the makeup of the TARDIS floors.
* @param floor_data the data bit associated with the floor_id parameter.
*/
@SuppressWarnings("deprecation")
public void buildInner(TARDISConstants.SCHEMATIC schm, World world, int dbID, Player p, int middle_id, byte middle_data, int floor_id, byte floor_data) {
String[][][] s;
short[] d;
int level, row, col, id, x, z, startx, startz, resetx, resetz, j = 2;
boolean below = (!plugin.getConfig().getBoolean("create_worlds") && !plugin.getConfig().getBoolean("default_world"));
int starty;
if (below) {
starty = 15;
} else {
switch (schm) {
- case DELUXE:
- case ELEVENTH:
- starty = 66;
- break;
- case BIGGER:
case REDSTONE:
starty = 65;
break;
default:
starty = 64;
break;
}
}
switch (schm) {
// TARDIS schematics supplied by Lord_Rahl and killeratnight at mcnovus.net
case BIGGER:
s = plugin.biggerschematic;
d = plugin.biggerdimensions;
break;
case DELUXE:
s = plugin.deluxeschematic;
d = plugin.deluxedimensions;
break;
case ELEVENTH:
s = plugin.eleventhschematic;
d = plugin.eleventhdimensions;
break;
case REDSTONE:
s = plugin.redstoneschematic;
d = plugin.redstonedimensions;
break;
case STEAMPUNK:
s = plugin.steampunkschematic;
d = plugin.steampunkdimensions;
break;
case PLANK:
s = plugin.plankschematic;
d = plugin.plankdimensions;
break;
case TOM:
s = plugin.tomschematic;
d = plugin.tomdimensions;
break;
case ARS:
s = plugin.arsschematic;
d = plugin.arsdimensions;
break;
case CUSTOM:
s = plugin.customschematic;
d = plugin.customdimensions;
break;
default:
s = plugin.budgetschematic;
d = plugin.budgetdimensions;
break;
}
short h = d[0];
short w = d[1];
short l = d[2];
byte data;
String tmp;
HashMap<Block, Byte> postDoorBlocks = new HashMap<Block, Byte>();
HashMap<Block, Byte> postTorchBlocks = new HashMap<Block, Byte>();
HashMap<Block, Byte> postSignBlocks = new HashMap<Block, Byte>();
HashMap<Block, Byte> postRepeaterBlocks = new HashMap<Block, Byte>();
HashMap<Block, Byte> postPistonBaseBlocks = new HashMap<Block, Byte>();
HashMap<Block, Byte> postStickyPistonBaseBlocks = new HashMap<Block, Byte>();
HashMap<Block, Byte> postPistonExtensionBlocks = new HashMap<Block, Byte>();
Block postSaveSignBlock = null;
Block postTerminalBlock = null;
Block postARSBlock = null;
Block postTISBlock = null;
Block postTemporalBlock = null;
Block postKeyboardBlock = null;
// calculate startx, starty, startz
int gsl[] = plugin.utils.getStartLocation(dbID);
startx = gsl[0];
resetx = gsl[1];
startz = gsl[2];
resetz = gsl[3];
x = gsl[4];
z = gsl[5];
boolean own_world = plugin.getConfig().getBoolean("create_worlds");
Location wg1 = new Location(world, startx, starty, startz);
Location wg2 = new Location(world, startx + (w - 1), starty + (h - 1), startz + (l - 1));
QueryFactory qf = new QueryFactory(plugin);
// get list of used chunks
List<Chunk> chunkList = getChunks(world, wg1.getChunk().getX(), wg1.getChunk().getZ(), d);
// update chunks list in DB
for (Chunk c : chunkList) {
HashMap<String, Object> set = new HashMap<String, Object>();
set.put("tardis_id", dbID);
set.put("world", world.getName());
set.put("x", c.getX());
set.put("z", c.getZ());
qf.doInsert("chunks", set);
}
// if for some reason this is not a TARDIS world, set the blocks to air first
if (below) {
for (level = 0; level < h; level++) {
for (row = 0; row < w; row++) {
for (col = 0; col < l; col++) {
plugin.utils.setBlock(world, startx, starty, startz, 0, (byte) 0);
startx += x;
}
startx = resetx;
startz += z;
}
startz = resetz;
starty += 1;
}
// reset start positions
startx = resetx;
starty = 15;
startz = resetz;
}
HashMap<String, Object> set = new HashMap<String, Object>();
HashMap<String, Object> where = new HashMap<String, Object>();
where.put("tardis_id", dbID);
for (level = 0; level < h; level++) {
for (row = 0; row < w; row++) {
for (col = 0; col < l; col++) {
tmp = s[level][row][col];
if (!tmp.equals("-")) {
if (tmp.contains(":")) {
String[] iddata = tmp.split(":");
id = plugin.utils.parseNum(iddata[0]);
data = Byte.parseByte(iddata[1]);
if (id == 7) {
// remember bedrock location to block off the beacon light
String bedrocloc = world.getName() + ":" + startx + ":" + starty + ":" + startz;
set.put("beacon", bedrocloc);
}
if (id == 35) { // wool
switch (data) {
case 1:
switch (middle_id) {
case 22: // if using the default Lapis Block - then use Orange Wool / Stained Clay
if (plugin.getConfig().getBoolean("use_clay")) {
id = 159;
}
break;
default:
id = middle_id;
data = middle_data;
}
break;
case 8:
if (!schm.equals(TARDISConstants.SCHEMATIC.ELEVENTH)) {
switch (floor_id) {
case 22: // if using the default Lapis Block - then use Light Grey Wool / Stained Clay
if (plugin.getConfig().getBoolean("use_clay")) {
id = 159;
}
break;
default:
id = floor_id;
data = floor_data;
}
} else {
if (plugin.getConfig().getBoolean("use_clay")) {
id = 159;
}
}
break;
default:
if (plugin.getConfig().getBoolean("use_clay")) {
id = 159;
}
break;
}
}
if (id == 52) { // scanner button
/*
* mob spawner will be converted to the correct id by
* setBlock(), but remember it for the scanner.
*/
String scanloc = world.getName() + ":" + startx + ":" + starty + ":" + startz;
set.put("scanner", scanloc);
}
if (id == 54) { // chest
// remember the location of the condenser chest
String chest = world.getName() + ":" + startx + ":" + starty + ":" + startz;
set.put("condenser", chest);
}
if (id == 68) { // chameleon circuit sign
String chameleonloc = world.getName() + ":" + startx + ":" + starty + ":" + startz;
set.put("chameleon", chameleonloc);
set.put("chamele_on", 0);
}
if (id == 71 && data < (byte) 8) { // iron door bottom
HashMap<String, Object> setd = new HashMap<String, Object>();
String doorloc = world.getName() + ":" + startx + ":" + starty + ":" + startz;
setd.put("tardis_id", dbID);
setd.put("door_type", 1);
setd.put("door_location", doorloc);
setd.put("door_direction", "SOUTH");
qf.doInsert("doors", setd);
// if create_worlds is true, set the world spawn
if (own_world) {
if (plugin.pm.isPluginEnabled("Multiverse-Core")) {
Plugin mvplugin = plugin.pm.getPlugin("Multiverse-Core");
if (mvplugin instanceof MultiverseCore) {
MultiverseCore mvc = (MultiverseCore) mvplugin;
MultiverseWorld foundWorld = mvc.getMVWorldManager().getMVWorld(world.getName());
Location spawn = new Location(world, (startx + 0.5), starty, (startz + 1.5), 0, 0);
foundWorld.setSpawnLocation(spawn);
}
} else {
world.setSpawnLocation(startx, starty, (startz + 1));
}
}
}
if (id == 77) { // stone button
// remember the location of this button
String button = plugin.utils.makeLocationStr(world, startx, starty, startz);
qf.insertSyncControl(dbID, 1, button, 0);
}
if (id == 92) {
/*
* This block will be converted to a lever by
* setBlock(), but remember it so we can use it as the handbrake!
*/
String handbrakeloc = plugin.utils.makeLocationStr(world, startx, starty, startz);
qf.insertSyncControl(dbID, 0, handbrakeloc, 0);
}
if (id == 97) { // silverfish stone
String blockLocStr = (new Location(world, startx, starty, startz)).toString();
switch (data) {
case 0: // Save Sign
String save_loc = world.getName() + ":" + startx + ":" + starty + ":" + startz;
set.put("save_sign", save_loc);
break;
case 1: // Destination Terminal
qf.insertSyncControl(dbID, 9, blockLocStr, 0);
break;
case 2: // Architectural Reconfiguration System
qf.insertSyncControl(dbID, 10, blockLocStr, 0);
// create default json
int[][][] empty = new int[3][9][9];
for (int y = 0; y < 3; y++) {
for (int ars_x = 0; ars_x < 9; ars_x++) {
for (int ars_z = 0; ars_z < 9; ars_z++) {
empty[y][ars_x][ars_z] = 1;
}
}
}
int control = 42;
switch (schm) {
case DELUXE:
control = 57;
empty[2][4][4] = control;
empty[2][4][5] = control;
empty[2][5][4] = control;
empty[2][5][5] = control;
empty[1][4][5] = control;
empty[1][5][4] = control;
empty[1][5][5] = control;
break;
case ELEVENTH:
control = 133;
empty[2][4][4] = control;
empty[2][4][5] = control;
empty[2][5][4] = control;
empty[2][5][5] = control;
empty[1][4][5] = control;
empty[1][5][4] = control;
empty[1][5][5] = control;
break;
case BIGGER:
control = 41;
empty[1][4][5] = control;
empty[1][5][4] = control;
empty[1][5][5] = control;
break;
case REDSTONE:
control = 152;
empty[1][4][5] = control;
empty[1][5][4] = control;
empty[1][5][5] = control;
break;
case STEAMPUNK:
control = 173;
break;
case ARS:
control = 159;
break;
case PLANK:
control = 22;
break;
case TOM:
control = 155;
break;
default:
break;
}
empty[1][4][4] = control;
JSONArray json = new JSONArray(empty);
HashMap<String, Object> seta = new HashMap<String, Object>();
seta.put("tardis_id", dbID);
seta.put("player", p.getName());
seta.put("json", json.toString());
qf.doInsert("ars", seta);
break;
case 3: // TARDIS Information System
qf.insertSyncControl(dbID, 13, blockLocStr, 0);
break;
case 4: // Temporal Circuit
qf.insertSyncControl(dbID, 11, blockLocStr, 0);
break;
case 5: // Keyboard
qf.insertSyncControl(dbID, 7, blockLocStr, 0);
break;
default:
break;
}
}
if (id == 124) {
// remember lamp blocks
Block lamp = world.getBlockAt(startx, starty, startz);
lampblocks.add(lamp);
if (plugin.getConfig().getInt("malfunction") > 0) {
// remember lamp block locations for malfunction
HashMap<String, Object> setlb = new HashMap<String, Object>();
String lloc = world.getName() + ":" + startx + ":" + starty + ":" + startz;
setlb.put("tardis_id", dbID);
setlb.put("location", lloc);
qf.doInsert("lamps", setlb);
}
}
if (id == 137 || id == -119 || ((schm.equals(TARDISConstants.SCHEMATIC.BIGGER) || schm.equals(TARDISConstants.SCHEMATIC.DELUXE)) && (id == 138 || id == -118))) {
/*
* command block - remember it to spawn the creeper on.
* could also be a beacon block, as the creeper sits
* over the beacon in the deluxe and bigger consoles.
*/
String creeploc = world.getName() + ":" + (startx + 0.5) + ":" + starty + ":" + (startz + 0.5);
set.put("creeper", creeploc);
switch (schm) {
case CUSTOM:
id = plugin.getConfig().getInt("custom_creeper_id");
break;
case BIGGER:
case DELUXE:
id = 138;
break;
default:
id = 98;
break;
}
}
if (id == 143 || id == -113) {
/*
* wood button will be coverted to the correct id by
* setBlock(), but remember it for the Artron Energy Capacitor.
*/
String woodbuttonloc = plugin.utils.makeLocationStr(world, startx, starty, startz);
qf.insertSyncControl(dbID, 6, woodbuttonloc, 0);
}
} else {
id = plugin.utils.parseNum(tmp);
data = 0;
}
// if it's an iron/gold/diamond/emerald/beacon/redstone block put it in the blocks table
if (id == 41 || id == 42 || id == 57 || id == 133 || id == -123 || id == 138 || id == -118 || id == 152 || id == -104) {
HashMap<String, Object> setpb = new HashMap<String, Object>();
String loc = plugin.utils.makeLocationStr(world, startx, starty, startz);
setpb.put("tardis_id", dbID);
setpb.put("location", loc);
setpb.put("police_box", 0);
qf.doInsert("blocks", setpb);
plugin.protectBlockMap.put(loc, dbID);
}
// if it's the door, don't set it just remember its block then do it at the end
if (id == 71) { // doors
postDoorBlocks.put(world.getBlockAt(startx, starty, startz), data);
} else if (id == 76) { // redstone torches
postTorchBlocks.put(world.getBlockAt(startx, starty, startz), data);
} else if (id == 29) { // wall signs
postStickyPistonBaseBlocks.put(world.getBlockAt(startx, starty, startz), data);
} else if (id == 33) { // wall signs
postPistonBaseBlocks.put(world.getBlockAt(startx, starty, startz), data);
} else if (id == 34) { // wall signs
postPistonExtensionBlocks.put(world.getBlockAt(startx, starty, startz), data);
} else if (id == 68) { // wall signs
postSignBlocks.put(world.getBlockAt(startx, starty, startz), data);
} else if (id == 97) { // monster egg stone for controls
switch (data) {
case 0:
postSaveSignBlock = world.getBlockAt(startx, starty, startz);
break;
case 1:
postTerminalBlock = world.getBlockAt(startx, starty, startz);
break;
case 2:
postARSBlock = world.getBlockAt(startx, starty, startz);
break;
case 3:
postTISBlock = world.getBlockAt(startx, starty, startz);
break;
case 4:
postTemporalBlock = world.getBlockAt(startx, starty, startz);
break;
case 5:
postKeyboardBlock = world.getBlockAt(startx, starty, startz);
break;
default:
break;
}
} else if (id == 100 && data == 15) { // mushroom stem for repeaters
// save repeater location
if (j < 6) {
String repeater = world.getName() + ":" + startx + ":" + starty + ":" + startz;
qf.insertSyncControl(dbID, j, repeater, 0);
switch (j) {
case 2:
postRepeaterBlocks.put(world.getBlockAt(startx, starty, startz), (byte) 2);
break;
case 3:
postRepeaterBlocks.put(world.getBlockAt(startx, starty, startz), (byte) 1);
break;
case 4:
postRepeaterBlocks.put(world.getBlockAt(startx, starty, startz), (byte) 3);
break;
default:
postRepeaterBlocks.put(world.getBlockAt(startx, starty, startz), (byte) 0);
break;
}
j++;
}
} else if (id == 19) { // sponge
int swap;
if (world.getWorldType().equals(WorldType.FLAT) || own_world || world.getName().equals("TARDIS_TimeVortex") || world.getGenerator() instanceof TARDISChunkGenerator) {
swap = 0;
} else {
swap = 1;
}
plugin.utils.setBlock(world, startx, starty, startz, swap, data);
} else {
plugin.utils.setBlock(world, startx, starty, startz, id, data);
}
}
startx += x;
}
startx = resetx;
startz += z;
}
startz = resetz;
starty += 1;
}
// put on the door, redstone torches, signs, and the repeaters
for (Map.Entry<Block, Byte> entry : postDoorBlocks.entrySet()) {
Block pdb = entry.getKey();
byte pddata = entry.getValue();
pdb.setTypeId(71);
pdb.setData(pddata, true);
}
for (Map.Entry<Block, Byte> entry : postTorchBlocks.entrySet()) {
Block ptb = entry.getKey();
byte ptdata = entry.getValue();
ptb.setTypeId(76);
ptb.setData(ptdata, true);
}
for (Map.Entry<Block, Byte> entry : postRepeaterBlocks.entrySet()) {
Block prb = entry.getKey();
byte ptdata = entry.getValue();
prb.setTypeId(93);
prb.setData(ptdata, true);
}
for (Map.Entry<Block, Byte> entry : postStickyPistonBaseBlocks.entrySet()) {
Block pspb = entry.getKey();
plugin.pistons.add(pspb);
byte pspdata = entry.getValue();
pspb.setTypeId(29);
pspb.setData(pspdata, true);
}
for (Map.Entry<Block, Byte> entry : postPistonBaseBlocks.entrySet()) {
Block ppb = entry.getKey();
plugin.pistons.add(ppb);
byte ppbdata = entry.getValue();
ppb.setTypeId(33);
ppb.setData(ppbdata, true);
}
for (Map.Entry<Block, Byte> entry : postPistonExtensionBlocks.entrySet()) {
Block ppeb = entry.getKey();
byte ppedata = entry.getValue();
ppeb.setTypeId(34);
ppeb.setData(ppedata, true);
}
for (Map.Entry<Block, Byte> entry : postSignBlocks.entrySet()) {
final Block psb = entry.getKey();
byte psdata = entry.getValue();
psb.setTypeId(68);
psb.setData(psdata, true);
if (psb.getType().equals(Material.WALL_SIGN)) {
Sign cs = (Sign) psb.getState();
cs.setLine(0, "Chameleon");
cs.setLine(1, "Circuit");
cs.setLine(2, ChatColor.RED + "OFF");
cs.setLine(3, "NEW");
cs.update();
}
}
if (postSaveSignBlock != null) {
postSaveSignBlock.setTypeId(68);
postSaveSignBlock.setData((byte) 3, true);
if (postSaveSignBlock.getType().equals(Material.WALL_SIGN)) {
Sign ss = (Sign) postSaveSignBlock.getState();
ss.setLine(0, "TARDIS");
ss.setLine(1, "Saved");
ss.setLine(2, "Locations");
ss.setLine(3, "");
ss.update();
}
}
if (postTerminalBlock != null) {
postTerminalBlock.setTypeId(68);
postTerminalBlock.setData((byte) 3, true);
if (postTerminalBlock.getType().equals(Material.WALL_SIGN)) {
Sign ts = (Sign) postTerminalBlock.getState();
ts.setLine(0, "");
ts.setLine(1, "Destination");
ts.setLine(2, "Terminal");
ts.setLine(3, "");
ts.update();
}
}
if (postARSBlock != null) {
postARSBlock.setTypeId(68);
postARSBlock.setData((byte) 3, true);
if (postARSBlock.getType().equals(Material.WALL_SIGN)) {
Sign as = (Sign) postARSBlock.getState();
as.setLine(0, "TARDIS");
as.setLine(1, "Architectural");
as.setLine(2, "Reconfiguration");
as.setLine(3, "System");
as.update();
}
}
if (postTISBlock != null) {
postTISBlock.setTypeId(68);
postTISBlock.setData((byte) 3, true);
if (postTISBlock.getType().equals(Material.WALL_SIGN)) {
Sign is = (Sign) postTISBlock.getState();
is.setLine(0, "-----");
is.setLine(1, "TARDIS");
is.setLine(2, "Information");
is.setLine(3, "System");
is.update();
}
}
if (postTemporalBlock != null) {
postTemporalBlock.setTypeId(68);
postTemporalBlock.setData((byte) 3, true);
if (postTemporalBlock.getType().equals(Material.WALL_SIGN)) {
Sign ms = (Sign) postTemporalBlock.getState();
ms.setLine(0, "");
ms.setLine(1, "Temporal");
ms.setLine(2, "Locator");
ms.setLine(3, "");
ms.update();
}
}
if (postKeyboardBlock != null) {
postKeyboardBlock.setTypeId(68);
postKeyboardBlock.setData((byte) 3, true);
if (postKeyboardBlock.getType().equals(Material.WALL_SIGN)) {
Sign ks = (Sign) postKeyboardBlock.getState();
ks.setLine(0, "Keyboard");
for (int i = 1; i < 4; i++) {
ks.setLine(i, "");
}
ks.update();
}
}
for (Block lamp : lampblocks) {
lamp.setType(Material.REDSTONE_LAMP_ON);
}
lampblocks.clear();
if (plugin.worldGuardOnServer && plugin.getConfig().getBoolean("use_worldguard")) {
plugin.wgutils.addWGProtection(p, wg1, wg2);
}
// finished processing - update tardis table!
qf.doUpdate("tardis", set, where);
}
/**
* Checks whether a chunk is available to build a TARDIS in.
*
* @param w the world the chunk is in.
* @param x the x coordinate of the chunk.
* @param z the z coordinate of the chunk.
* @param d an array of the schematic dimensions
* @return a list of Chunks.
*/
public List<Chunk> getChunks(World w, int x, int z, short[] d) {
List<Chunk> chunks = new ArrayList<Chunk>();
int cw = plugin.utils.roundUp(d[1], 16);
int cl = plugin.utils.roundUp(d[2], 16);
// check all the chunks that will be used by the schematic
for (int cx = 0; cx < cw; cx++) {
for (int cz = 0; cz < cl; cz++) {
Chunk chunk = w.getChunkAt((x + cx), (z + cz));
chunks.add(chunk);
}
}
return chunks;
}
}
| true | true | public void buildInner(TARDISConstants.SCHEMATIC schm, World world, int dbID, Player p, int middle_id, byte middle_data, int floor_id, byte floor_data) {
String[][][] s;
short[] d;
int level, row, col, id, x, z, startx, startz, resetx, resetz, j = 2;
boolean below = (!plugin.getConfig().getBoolean("create_worlds") && !plugin.getConfig().getBoolean("default_world"));
int starty;
if (below) {
starty = 15;
} else {
switch (schm) {
case DELUXE:
case ELEVENTH:
starty = 66;
break;
case BIGGER:
case REDSTONE:
starty = 65;
break;
default:
starty = 64;
break;
}
}
switch (schm) {
// TARDIS schematics supplied by Lord_Rahl and killeratnight at mcnovus.net
case BIGGER:
s = plugin.biggerschematic;
d = plugin.biggerdimensions;
break;
case DELUXE:
s = plugin.deluxeschematic;
d = plugin.deluxedimensions;
break;
case ELEVENTH:
s = plugin.eleventhschematic;
d = plugin.eleventhdimensions;
break;
case REDSTONE:
s = plugin.redstoneschematic;
d = plugin.redstonedimensions;
break;
case STEAMPUNK:
s = plugin.steampunkschematic;
d = plugin.steampunkdimensions;
break;
case PLANK:
s = plugin.plankschematic;
d = plugin.plankdimensions;
break;
case TOM:
s = plugin.tomschematic;
d = plugin.tomdimensions;
break;
case ARS:
s = plugin.arsschematic;
d = plugin.arsdimensions;
break;
case CUSTOM:
s = plugin.customschematic;
d = plugin.customdimensions;
break;
default:
s = plugin.budgetschematic;
d = plugin.budgetdimensions;
break;
}
short h = d[0];
short w = d[1];
short l = d[2];
byte data;
String tmp;
HashMap<Block, Byte> postDoorBlocks = new HashMap<Block, Byte>();
HashMap<Block, Byte> postTorchBlocks = new HashMap<Block, Byte>();
HashMap<Block, Byte> postSignBlocks = new HashMap<Block, Byte>();
HashMap<Block, Byte> postRepeaterBlocks = new HashMap<Block, Byte>();
HashMap<Block, Byte> postPistonBaseBlocks = new HashMap<Block, Byte>();
HashMap<Block, Byte> postStickyPistonBaseBlocks = new HashMap<Block, Byte>();
HashMap<Block, Byte> postPistonExtensionBlocks = new HashMap<Block, Byte>();
Block postSaveSignBlock = null;
Block postTerminalBlock = null;
Block postARSBlock = null;
Block postTISBlock = null;
Block postTemporalBlock = null;
Block postKeyboardBlock = null;
// calculate startx, starty, startz
int gsl[] = plugin.utils.getStartLocation(dbID);
startx = gsl[0];
resetx = gsl[1];
startz = gsl[2];
resetz = gsl[3];
x = gsl[4];
z = gsl[5];
boolean own_world = plugin.getConfig().getBoolean("create_worlds");
Location wg1 = new Location(world, startx, starty, startz);
Location wg2 = new Location(world, startx + (w - 1), starty + (h - 1), startz + (l - 1));
QueryFactory qf = new QueryFactory(plugin);
// get list of used chunks
List<Chunk> chunkList = getChunks(world, wg1.getChunk().getX(), wg1.getChunk().getZ(), d);
// update chunks list in DB
for (Chunk c : chunkList) {
HashMap<String, Object> set = new HashMap<String, Object>();
set.put("tardis_id", dbID);
set.put("world", world.getName());
set.put("x", c.getX());
set.put("z", c.getZ());
qf.doInsert("chunks", set);
}
// if for some reason this is not a TARDIS world, set the blocks to air first
if (below) {
for (level = 0; level < h; level++) {
for (row = 0; row < w; row++) {
for (col = 0; col < l; col++) {
plugin.utils.setBlock(world, startx, starty, startz, 0, (byte) 0);
startx += x;
}
startx = resetx;
startz += z;
}
startz = resetz;
starty += 1;
}
// reset start positions
startx = resetx;
starty = 15;
startz = resetz;
}
HashMap<String, Object> set = new HashMap<String, Object>();
HashMap<String, Object> where = new HashMap<String, Object>();
where.put("tardis_id", dbID);
for (level = 0; level < h; level++) {
for (row = 0; row < w; row++) {
for (col = 0; col < l; col++) {
tmp = s[level][row][col];
if (!tmp.equals("-")) {
if (tmp.contains(":")) {
String[] iddata = tmp.split(":");
id = plugin.utils.parseNum(iddata[0]);
data = Byte.parseByte(iddata[1]);
if (id == 7) {
// remember bedrock location to block off the beacon light
String bedrocloc = world.getName() + ":" + startx + ":" + starty + ":" + startz;
set.put("beacon", bedrocloc);
}
if (id == 35) { // wool
switch (data) {
case 1:
switch (middle_id) {
case 22: // if using the default Lapis Block - then use Orange Wool / Stained Clay
if (plugin.getConfig().getBoolean("use_clay")) {
id = 159;
}
break;
default:
id = middle_id;
data = middle_data;
}
break;
case 8:
if (!schm.equals(TARDISConstants.SCHEMATIC.ELEVENTH)) {
switch (floor_id) {
case 22: // if using the default Lapis Block - then use Light Grey Wool / Stained Clay
if (plugin.getConfig().getBoolean("use_clay")) {
id = 159;
}
break;
default:
id = floor_id;
data = floor_data;
}
} else {
if (plugin.getConfig().getBoolean("use_clay")) {
id = 159;
}
}
break;
default:
if (plugin.getConfig().getBoolean("use_clay")) {
id = 159;
}
break;
}
}
if (id == 52) { // scanner button
/*
* mob spawner will be converted to the correct id by
* setBlock(), but remember it for the scanner.
*/
String scanloc = world.getName() + ":" + startx + ":" + starty + ":" + startz;
set.put("scanner", scanloc);
}
if (id == 54) { // chest
// remember the location of the condenser chest
String chest = world.getName() + ":" + startx + ":" + starty + ":" + startz;
set.put("condenser", chest);
}
if (id == 68) { // chameleon circuit sign
String chameleonloc = world.getName() + ":" + startx + ":" + starty + ":" + startz;
set.put("chameleon", chameleonloc);
set.put("chamele_on", 0);
}
if (id == 71 && data < (byte) 8) { // iron door bottom
HashMap<String, Object> setd = new HashMap<String, Object>();
String doorloc = world.getName() + ":" + startx + ":" + starty + ":" + startz;
setd.put("tardis_id", dbID);
setd.put("door_type", 1);
setd.put("door_location", doorloc);
setd.put("door_direction", "SOUTH");
qf.doInsert("doors", setd);
// if create_worlds is true, set the world spawn
if (own_world) {
if (plugin.pm.isPluginEnabled("Multiverse-Core")) {
Plugin mvplugin = plugin.pm.getPlugin("Multiverse-Core");
if (mvplugin instanceof MultiverseCore) {
MultiverseCore mvc = (MultiverseCore) mvplugin;
MultiverseWorld foundWorld = mvc.getMVWorldManager().getMVWorld(world.getName());
Location spawn = new Location(world, (startx + 0.5), starty, (startz + 1.5), 0, 0);
foundWorld.setSpawnLocation(spawn);
}
} else {
world.setSpawnLocation(startx, starty, (startz + 1));
}
}
}
if (id == 77) { // stone button
// remember the location of this button
String button = plugin.utils.makeLocationStr(world, startx, starty, startz);
qf.insertSyncControl(dbID, 1, button, 0);
}
if (id == 92) {
/*
* This block will be converted to a lever by
* setBlock(), but remember it so we can use it as the handbrake!
*/
String handbrakeloc = plugin.utils.makeLocationStr(world, startx, starty, startz);
qf.insertSyncControl(dbID, 0, handbrakeloc, 0);
}
if (id == 97) { // silverfish stone
String blockLocStr = (new Location(world, startx, starty, startz)).toString();
switch (data) {
case 0: // Save Sign
String save_loc = world.getName() + ":" + startx + ":" + starty + ":" + startz;
set.put("save_sign", save_loc);
break;
case 1: // Destination Terminal
qf.insertSyncControl(dbID, 9, blockLocStr, 0);
break;
case 2: // Architectural Reconfiguration System
qf.insertSyncControl(dbID, 10, blockLocStr, 0);
// create default json
int[][][] empty = new int[3][9][9];
for (int y = 0; y < 3; y++) {
for (int ars_x = 0; ars_x < 9; ars_x++) {
for (int ars_z = 0; ars_z < 9; ars_z++) {
empty[y][ars_x][ars_z] = 1;
}
}
}
int control = 42;
switch (schm) {
case DELUXE:
control = 57;
empty[2][4][4] = control;
empty[2][4][5] = control;
empty[2][5][4] = control;
empty[2][5][5] = control;
empty[1][4][5] = control;
empty[1][5][4] = control;
empty[1][5][5] = control;
break;
case ELEVENTH:
control = 133;
empty[2][4][4] = control;
empty[2][4][5] = control;
empty[2][5][4] = control;
empty[2][5][5] = control;
empty[1][4][5] = control;
empty[1][5][4] = control;
empty[1][5][5] = control;
break;
case BIGGER:
control = 41;
empty[1][4][5] = control;
empty[1][5][4] = control;
empty[1][5][5] = control;
break;
case REDSTONE:
control = 152;
empty[1][4][5] = control;
empty[1][5][4] = control;
empty[1][5][5] = control;
break;
case STEAMPUNK:
control = 173;
break;
case ARS:
control = 159;
break;
case PLANK:
control = 22;
break;
case TOM:
control = 155;
break;
default:
break;
}
empty[1][4][4] = control;
JSONArray json = new JSONArray(empty);
HashMap<String, Object> seta = new HashMap<String, Object>();
seta.put("tardis_id", dbID);
seta.put("player", p.getName());
seta.put("json", json.toString());
qf.doInsert("ars", seta);
break;
case 3: // TARDIS Information System
qf.insertSyncControl(dbID, 13, blockLocStr, 0);
break;
case 4: // Temporal Circuit
qf.insertSyncControl(dbID, 11, blockLocStr, 0);
break;
case 5: // Keyboard
qf.insertSyncControl(dbID, 7, blockLocStr, 0);
break;
default:
break;
}
}
if (id == 124) {
// remember lamp blocks
Block lamp = world.getBlockAt(startx, starty, startz);
lampblocks.add(lamp);
if (plugin.getConfig().getInt("malfunction") > 0) {
// remember lamp block locations for malfunction
HashMap<String, Object> setlb = new HashMap<String, Object>();
String lloc = world.getName() + ":" + startx + ":" + starty + ":" + startz;
setlb.put("tardis_id", dbID);
setlb.put("location", lloc);
qf.doInsert("lamps", setlb);
}
}
if (id == 137 || id == -119 || ((schm.equals(TARDISConstants.SCHEMATIC.BIGGER) || schm.equals(TARDISConstants.SCHEMATIC.DELUXE)) && (id == 138 || id == -118))) {
/*
* command block - remember it to spawn the creeper on.
* could also be a beacon block, as the creeper sits
* over the beacon in the deluxe and bigger consoles.
*/
String creeploc = world.getName() + ":" + (startx + 0.5) + ":" + starty + ":" + (startz + 0.5);
set.put("creeper", creeploc);
switch (schm) {
case CUSTOM:
id = plugin.getConfig().getInt("custom_creeper_id");
break;
case BIGGER:
case DELUXE:
id = 138;
break;
default:
id = 98;
break;
}
}
if (id == 143 || id == -113) {
/*
* wood button will be coverted to the correct id by
* setBlock(), but remember it for the Artron Energy Capacitor.
*/
String woodbuttonloc = plugin.utils.makeLocationStr(world, startx, starty, startz);
qf.insertSyncControl(dbID, 6, woodbuttonloc, 0);
}
} else {
id = plugin.utils.parseNum(tmp);
data = 0;
}
// if it's an iron/gold/diamond/emerald/beacon/redstone block put it in the blocks table
if (id == 41 || id == 42 || id == 57 || id == 133 || id == -123 || id == 138 || id == -118 || id == 152 || id == -104) {
HashMap<String, Object> setpb = new HashMap<String, Object>();
String loc = plugin.utils.makeLocationStr(world, startx, starty, startz);
setpb.put("tardis_id", dbID);
setpb.put("location", loc);
setpb.put("police_box", 0);
qf.doInsert("blocks", setpb);
plugin.protectBlockMap.put(loc, dbID);
}
// if it's the door, don't set it just remember its block then do it at the end
if (id == 71) { // doors
postDoorBlocks.put(world.getBlockAt(startx, starty, startz), data);
} else if (id == 76) { // redstone torches
postTorchBlocks.put(world.getBlockAt(startx, starty, startz), data);
} else if (id == 29) { // wall signs
postStickyPistonBaseBlocks.put(world.getBlockAt(startx, starty, startz), data);
} else if (id == 33) { // wall signs
postPistonBaseBlocks.put(world.getBlockAt(startx, starty, startz), data);
} else if (id == 34) { // wall signs
postPistonExtensionBlocks.put(world.getBlockAt(startx, starty, startz), data);
} else if (id == 68) { // wall signs
postSignBlocks.put(world.getBlockAt(startx, starty, startz), data);
} else if (id == 97) { // monster egg stone for controls
switch (data) {
case 0:
postSaveSignBlock = world.getBlockAt(startx, starty, startz);
break;
case 1:
postTerminalBlock = world.getBlockAt(startx, starty, startz);
break;
case 2:
postARSBlock = world.getBlockAt(startx, starty, startz);
break;
case 3:
postTISBlock = world.getBlockAt(startx, starty, startz);
break;
case 4:
postTemporalBlock = world.getBlockAt(startx, starty, startz);
break;
case 5:
postKeyboardBlock = world.getBlockAt(startx, starty, startz);
break;
default:
break;
}
} else if (id == 100 && data == 15) { // mushroom stem for repeaters
// save repeater location
if (j < 6) {
String repeater = world.getName() + ":" + startx + ":" + starty + ":" + startz;
qf.insertSyncControl(dbID, j, repeater, 0);
switch (j) {
case 2:
postRepeaterBlocks.put(world.getBlockAt(startx, starty, startz), (byte) 2);
break;
case 3:
postRepeaterBlocks.put(world.getBlockAt(startx, starty, startz), (byte) 1);
break;
case 4:
postRepeaterBlocks.put(world.getBlockAt(startx, starty, startz), (byte) 3);
break;
default:
postRepeaterBlocks.put(world.getBlockAt(startx, starty, startz), (byte) 0);
break;
}
j++;
}
} else if (id == 19) { // sponge
int swap;
if (world.getWorldType().equals(WorldType.FLAT) || own_world || world.getName().equals("TARDIS_TimeVortex") || world.getGenerator() instanceof TARDISChunkGenerator) {
swap = 0;
} else {
swap = 1;
}
plugin.utils.setBlock(world, startx, starty, startz, swap, data);
} else {
plugin.utils.setBlock(world, startx, starty, startz, id, data);
}
}
startx += x;
}
startx = resetx;
startz += z;
}
startz = resetz;
starty += 1;
}
// put on the door, redstone torches, signs, and the repeaters
for (Map.Entry<Block, Byte> entry : postDoorBlocks.entrySet()) {
Block pdb = entry.getKey();
byte pddata = entry.getValue();
pdb.setTypeId(71);
pdb.setData(pddata, true);
}
for (Map.Entry<Block, Byte> entry : postTorchBlocks.entrySet()) {
Block ptb = entry.getKey();
byte ptdata = entry.getValue();
ptb.setTypeId(76);
ptb.setData(ptdata, true);
}
for (Map.Entry<Block, Byte> entry : postRepeaterBlocks.entrySet()) {
Block prb = entry.getKey();
byte ptdata = entry.getValue();
prb.setTypeId(93);
prb.setData(ptdata, true);
}
for (Map.Entry<Block, Byte> entry : postStickyPistonBaseBlocks.entrySet()) {
Block pspb = entry.getKey();
plugin.pistons.add(pspb);
byte pspdata = entry.getValue();
pspb.setTypeId(29);
pspb.setData(pspdata, true);
}
for (Map.Entry<Block, Byte> entry : postPistonBaseBlocks.entrySet()) {
Block ppb = entry.getKey();
plugin.pistons.add(ppb);
byte ppbdata = entry.getValue();
ppb.setTypeId(33);
ppb.setData(ppbdata, true);
}
for (Map.Entry<Block, Byte> entry : postPistonExtensionBlocks.entrySet()) {
Block ppeb = entry.getKey();
byte ppedata = entry.getValue();
ppeb.setTypeId(34);
ppeb.setData(ppedata, true);
}
for (Map.Entry<Block, Byte> entry : postSignBlocks.entrySet()) {
final Block psb = entry.getKey();
byte psdata = entry.getValue();
psb.setTypeId(68);
psb.setData(psdata, true);
if (psb.getType().equals(Material.WALL_SIGN)) {
Sign cs = (Sign) psb.getState();
cs.setLine(0, "Chameleon");
cs.setLine(1, "Circuit");
cs.setLine(2, ChatColor.RED + "OFF");
cs.setLine(3, "NEW");
cs.update();
}
}
if (postSaveSignBlock != null) {
postSaveSignBlock.setTypeId(68);
postSaveSignBlock.setData((byte) 3, true);
if (postSaveSignBlock.getType().equals(Material.WALL_SIGN)) {
Sign ss = (Sign) postSaveSignBlock.getState();
ss.setLine(0, "TARDIS");
ss.setLine(1, "Saved");
ss.setLine(2, "Locations");
ss.setLine(3, "");
ss.update();
}
}
if (postTerminalBlock != null) {
postTerminalBlock.setTypeId(68);
postTerminalBlock.setData((byte) 3, true);
if (postTerminalBlock.getType().equals(Material.WALL_SIGN)) {
Sign ts = (Sign) postTerminalBlock.getState();
ts.setLine(0, "");
ts.setLine(1, "Destination");
ts.setLine(2, "Terminal");
ts.setLine(3, "");
ts.update();
}
}
if (postARSBlock != null) {
postARSBlock.setTypeId(68);
postARSBlock.setData((byte) 3, true);
if (postARSBlock.getType().equals(Material.WALL_SIGN)) {
Sign as = (Sign) postARSBlock.getState();
as.setLine(0, "TARDIS");
as.setLine(1, "Architectural");
as.setLine(2, "Reconfiguration");
as.setLine(3, "System");
as.update();
}
}
if (postTISBlock != null) {
postTISBlock.setTypeId(68);
postTISBlock.setData((byte) 3, true);
if (postTISBlock.getType().equals(Material.WALL_SIGN)) {
Sign is = (Sign) postTISBlock.getState();
is.setLine(0, "-----");
is.setLine(1, "TARDIS");
is.setLine(2, "Information");
is.setLine(3, "System");
is.update();
}
}
if (postTemporalBlock != null) {
postTemporalBlock.setTypeId(68);
postTemporalBlock.setData((byte) 3, true);
if (postTemporalBlock.getType().equals(Material.WALL_SIGN)) {
Sign ms = (Sign) postTemporalBlock.getState();
ms.setLine(0, "");
ms.setLine(1, "Temporal");
ms.setLine(2, "Locator");
ms.setLine(3, "");
ms.update();
}
}
if (postKeyboardBlock != null) {
postKeyboardBlock.setTypeId(68);
postKeyboardBlock.setData((byte) 3, true);
if (postKeyboardBlock.getType().equals(Material.WALL_SIGN)) {
Sign ks = (Sign) postKeyboardBlock.getState();
ks.setLine(0, "Keyboard");
for (int i = 1; i < 4; i++) {
ks.setLine(i, "");
}
ks.update();
}
}
for (Block lamp : lampblocks) {
lamp.setType(Material.REDSTONE_LAMP_ON);
}
lampblocks.clear();
if (plugin.worldGuardOnServer && plugin.getConfig().getBoolean("use_worldguard")) {
plugin.wgutils.addWGProtection(p, wg1, wg2);
}
// finished processing - update tardis table!
qf.doUpdate("tardis", set, where);
}
| public void buildInner(TARDISConstants.SCHEMATIC schm, World world, int dbID, Player p, int middle_id, byte middle_data, int floor_id, byte floor_data) {
String[][][] s;
short[] d;
int level, row, col, id, x, z, startx, startz, resetx, resetz, j = 2;
boolean below = (!plugin.getConfig().getBoolean("create_worlds") && !plugin.getConfig().getBoolean("default_world"));
int starty;
if (below) {
starty = 15;
} else {
switch (schm) {
case REDSTONE:
starty = 65;
break;
default:
starty = 64;
break;
}
}
switch (schm) {
// TARDIS schematics supplied by Lord_Rahl and killeratnight at mcnovus.net
case BIGGER:
s = plugin.biggerschematic;
d = plugin.biggerdimensions;
break;
case DELUXE:
s = plugin.deluxeschematic;
d = plugin.deluxedimensions;
break;
case ELEVENTH:
s = plugin.eleventhschematic;
d = plugin.eleventhdimensions;
break;
case REDSTONE:
s = plugin.redstoneschematic;
d = plugin.redstonedimensions;
break;
case STEAMPUNK:
s = plugin.steampunkschematic;
d = plugin.steampunkdimensions;
break;
case PLANK:
s = plugin.plankschematic;
d = plugin.plankdimensions;
break;
case TOM:
s = plugin.tomschematic;
d = plugin.tomdimensions;
break;
case ARS:
s = plugin.arsschematic;
d = plugin.arsdimensions;
break;
case CUSTOM:
s = plugin.customschematic;
d = plugin.customdimensions;
break;
default:
s = plugin.budgetschematic;
d = plugin.budgetdimensions;
break;
}
short h = d[0];
short w = d[1];
short l = d[2];
byte data;
String tmp;
HashMap<Block, Byte> postDoorBlocks = new HashMap<Block, Byte>();
HashMap<Block, Byte> postTorchBlocks = new HashMap<Block, Byte>();
HashMap<Block, Byte> postSignBlocks = new HashMap<Block, Byte>();
HashMap<Block, Byte> postRepeaterBlocks = new HashMap<Block, Byte>();
HashMap<Block, Byte> postPistonBaseBlocks = new HashMap<Block, Byte>();
HashMap<Block, Byte> postStickyPistonBaseBlocks = new HashMap<Block, Byte>();
HashMap<Block, Byte> postPistonExtensionBlocks = new HashMap<Block, Byte>();
Block postSaveSignBlock = null;
Block postTerminalBlock = null;
Block postARSBlock = null;
Block postTISBlock = null;
Block postTemporalBlock = null;
Block postKeyboardBlock = null;
// calculate startx, starty, startz
int gsl[] = plugin.utils.getStartLocation(dbID);
startx = gsl[0];
resetx = gsl[1];
startz = gsl[2];
resetz = gsl[3];
x = gsl[4];
z = gsl[5];
boolean own_world = plugin.getConfig().getBoolean("create_worlds");
Location wg1 = new Location(world, startx, starty, startz);
Location wg2 = new Location(world, startx + (w - 1), starty + (h - 1), startz + (l - 1));
QueryFactory qf = new QueryFactory(plugin);
// get list of used chunks
List<Chunk> chunkList = getChunks(world, wg1.getChunk().getX(), wg1.getChunk().getZ(), d);
// update chunks list in DB
for (Chunk c : chunkList) {
HashMap<String, Object> set = new HashMap<String, Object>();
set.put("tardis_id", dbID);
set.put("world", world.getName());
set.put("x", c.getX());
set.put("z", c.getZ());
qf.doInsert("chunks", set);
}
// if for some reason this is not a TARDIS world, set the blocks to air first
if (below) {
for (level = 0; level < h; level++) {
for (row = 0; row < w; row++) {
for (col = 0; col < l; col++) {
plugin.utils.setBlock(world, startx, starty, startz, 0, (byte) 0);
startx += x;
}
startx = resetx;
startz += z;
}
startz = resetz;
starty += 1;
}
// reset start positions
startx = resetx;
starty = 15;
startz = resetz;
}
HashMap<String, Object> set = new HashMap<String, Object>();
HashMap<String, Object> where = new HashMap<String, Object>();
where.put("tardis_id", dbID);
for (level = 0; level < h; level++) {
for (row = 0; row < w; row++) {
for (col = 0; col < l; col++) {
tmp = s[level][row][col];
if (!tmp.equals("-")) {
if (tmp.contains(":")) {
String[] iddata = tmp.split(":");
id = plugin.utils.parseNum(iddata[0]);
data = Byte.parseByte(iddata[1]);
if (id == 7) {
// remember bedrock location to block off the beacon light
String bedrocloc = world.getName() + ":" + startx + ":" + starty + ":" + startz;
set.put("beacon", bedrocloc);
}
if (id == 35) { // wool
switch (data) {
case 1:
switch (middle_id) {
case 22: // if using the default Lapis Block - then use Orange Wool / Stained Clay
if (plugin.getConfig().getBoolean("use_clay")) {
id = 159;
}
break;
default:
id = middle_id;
data = middle_data;
}
break;
case 8:
if (!schm.equals(TARDISConstants.SCHEMATIC.ELEVENTH)) {
switch (floor_id) {
case 22: // if using the default Lapis Block - then use Light Grey Wool / Stained Clay
if (plugin.getConfig().getBoolean("use_clay")) {
id = 159;
}
break;
default:
id = floor_id;
data = floor_data;
}
} else {
if (plugin.getConfig().getBoolean("use_clay")) {
id = 159;
}
}
break;
default:
if (plugin.getConfig().getBoolean("use_clay")) {
id = 159;
}
break;
}
}
if (id == 52) { // scanner button
/*
* mob spawner will be converted to the correct id by
* setBlock(), but remember it for the scanner.
*/
String scanloc = world.getName() + ":" + startx + ":" + starty + ":" + startz;
set.put("scanner", scanloc);
}
if (id == 54) { // chest
// remember the location of the condenser chest
String chest = world.getName() + ":" + startx + ":" + starty + ":" + startz;
set.put("condenser", chest);
}
if (id == 68) { // chameleon circuit sign
String chameleonloc = world.getName() + ":" + startx + ":" + starty + ":" + startz;
set.put("chameleon", chameleonloc);
set.put("chamele_on", 0);
}
if (id == 71 && data < (byte) 8) { // iron door bottom
HashMap<String, Object> setd = new HashMap<String, Object>();
String doorloc = world.getName() + ":" + startx + ":" + starty + ":" + startz;
setd.put("tardis_id", dbID);
setd.put("door_type", 1);
setd.put("door_location", doorloc);
setd.put("door_direction", "SOUTH");
qf.doInsert("doors", setd);
// if create_worlds is true, set the world spawn
if (own_world) {
if (plugin.pm.isPluginEnabled("Multiverse-Core")) {
Plugin mvplugin = plugin.pm.getPlugin("Multiverse-Core");
if (mvplugin instanceof MultiverseCore) {
MultiverseCore mvc = (MultiverseCore) mvplugin;
MultiverseWorld foundWorld = mvc.getMVWorldManager().getMVWorld(world.getName());
Location spawn = new Location(world, (startx + 0.5), starty, (startz + 1.5), 0, 0);
foundWorld.setSpawnLocation(spawn);
}
} else {
world.setSpawnLocation(startx, starty, (startz + 1));
}
}
}
if (id == 77) { // stone button
// remember the location of this button
String button = plugin.utils.makeLocationStr(world, startx, starty, startz);
qf.insertSyncControl(dbID, 1, button, 0);
}
if (id == 92) {
/*
* This block will be converted to a lever by
* setBlock(), but remember it so we can use it as the handbrake!
*/
String handbrakeloc = plugin.utils.makeLocationStr(world, startx, starty, startz);
qf.insertSyncControl(dbID, 0, handbrakeloc, 0);
}
if (id == 97) { // silverfish stone
String blockLocStr = (new Location(world, startx, starty, startz)).toString();
switch (data) {
case 0: // Save Sign
String save_loc = world.getName() + ":" + startx + ":" + starty + ":" + startz;
set.put("save_sign", save_loc);
break;
case 1: // Destination Terminal
qf.insertSyncControl(dbID, 9, blockLocStr, 0);
break;
case 2: // Architectural Reconfiguration System
qf.insertSyncControl(dbID, 10, blockLocStr, 0);
// create default json
int[][][] empty = new int[3][9][9];
for (int y = 0; y < 3; y++) {
for (int ars_x = 0; ars_x < 9; ars_x++) {
for (int ars_z = 0; ars_z < 9; ars_z++) {
empty[y][ars_x][ars_z] = 1;
}
}
}
int control = 42;
switch (schm) {
case DELUXE:
control = 57;
empty[2][4][4] = control;
empty[2][4][5] = control;
empty[2][5][4] = control;
empty[2][5][5] = control;
empty[1][4][5] = control;
empty[1][5][4] = control;
empty[1][5][5] = control;
break;
case ELEVENTH:
control = 133;
empty[2][4][4] = control;
empty[2][4][5] = control;
empty[2][5][4] = control;
empty[2][5][5] = control;
empty[1][4][5] = control;
empty[1][5][4] = control;
empty[1][5][5] = control;
break;
case BIGGER:
control = 41;
empty[1][4][5] = control;
empty[1][5][4] = control;
empty[1][5][5] = control;
break;
case REDSTONE:
control = 152;
empty[1][4][5] = control;
empty[1][5][4] = control;
empty[1][5][5] = control;
break;
case STEAMPUNK:
control = 173;
break;
case ARS:
control = 159;
break;
case PLANK:
control = 22;
break;
case TOM:
control = 155;
break;
default:
break;
}
empty[1][4][4] = control;
JSONArray json = new JSONArray(empty);
HashMap<String, Object> seta = new HashMap<String, Object>();
seta.put("tardis_id", dbID);
seta.put("player", p.getName());
seta.put("json", json.toString());
qf.doInsert("ars", seta);
break;
case 3: // TARDIS Information System
qf.insertSyncControl(dbID, 13, blockLocStr, 0);
break;
case 4: // Temporal Circuit
qf.insertSyncControl(dbID, 11, blockLocStr, 0);
break;
case 5: // Keyboard
qf.insertSyncControl(dbID, 7, blockLocStr, 0);
break;
default:
break;
}
}
if (id == 124) {
// remember lamp blocks
Block lamp = world.getBlockAt(startx, starty, startz);
lampblocks.add(lamp);
if (plugin.getConfig().getInt("malfunction") > 0) {
// remember lamp block locations for malfunction
HashMap<String, Object> setlb = new HashMap<String, Object>();
String lloc = world.getName() + ":" + startx + ":" + starty + ":" + startz;
setlb.put("tardis_id", dbID);
setlb.put("location", lloc);
qf.doInsert("lamps", setlb);
}
}
if (id == 137 || id == -119 || ((schm.equals(TARDISConstants.SCHEMATIC.BIGGER) || schm.equals(TARDISConstants.SCHEMATIC.DELUXE)) && (id == 138 || id == -118))) {
/*
* command block - remember it to spawn the creeper on.
* could also be a beacon block, as the creeper sits
* over the beacon in the deluxe and bigger consoles.
*/
String creeploc = world.getName() + ":" + (startx + 0.5) + ":" + starty + ":" + (startz + 0.5);
set.put("creeper", creeploc);
switch (schm) {
case CUSTOM:
id = plugin.getConfig().getInt("custom_creeper_id");
break;
case BIGGER:
case DELUXE:
id = 138;
break;
default:
id = 98;
break;
}
}
if (id == 143 || id == -113) {
/*
* wood button will be coverted to the correct id by
* setBlock(), but remember it for the Artron Energy Capacitor.
*/
String woodbuttonloc = plugin.utils.makeLocationStr(world, startx, starty, startz);
qf.insertSyncControl(dbID, 6, woodbuttonloc, 0);
}
} else {
id = plugin.utils.parseNum(tmp);
data = 0;
}
// if it's an iron/gold/diamond/emerald/beacon/redstone block put it in the blocks table
if (id == 41 || id == 42 || id == 57 || id == 133 || id == -123 || id == 138 || id == -118 || id == 152 || id == -104) {
HashMap<String, Object> setpb = new HashMap<String, Object>();
String loc = plugin.utils.makeLocationStr(world, startx, starty, startz);
setpb.put("tardis_id", dbID);
setpb.put("location", loc);
setpb.put("police_box", 0);
qf.doInsert("blocks", setpb);
plugin.protectBlockMap.put(loc, dbID);
}
// if it's the door, don't set it just remember its block then do it at the end
if (id == 71) { // doors
postDoorBlocks.put(world.getBlockAt(startx, starty, startz), data);
} else if (id == 76) { // redstone torches
postTorchBlocks.put(world.getBlockAt(startx, starty, startz), data);
} else if (id == 29) { // wall signs
postStickyPistonBaseBlocks.put(world.getBlockAt(startx, starty, startz), data);
} else if (id == 33) { // wall signs
postPistonBaseBlocks.put(world.getBlockAt(startx, starty, startz), data);
} else if (id == 34) { // wall signs
postPistonExtensionBlocks.put(world.getBlockAt(startx, starty, startz), data);
} else if (id == 68) { // wall signs
postSignBlocks.put(world.getBlockAt(startx, starty, startz), data);
} else if (id == 97) { // monster egg stone for controls
switch (data) {
case 0:
postSaveSignBlock = world.getBlockAt(startx, starty, startz);
break;
case 1:
postTerminalBlock = world.getBlockAt(startx, starty, startz);
break;
case 2:
postARSBlock = world.getBlockAt(startx, starty, startz);
break;
case 3:
postTISBlock = world.getBlockAt(startx, starty, startz);
break;
case 4:
postTemporalBlock = world.getBlockAt(startx, starty, startz);
break;
case 5:
postKeyboardBlock = world.getBlockAt(startx, starty, startz);
break;
default:
break;
}
} else if (id == 100 && data == 15) { // mushroom stem for repeaters
// save repeater location
if (j < 6) {
String repeater = world.getName() + ":" + startx + ":" + starty + ":" + startz;
qf.insertSyncControl(dbID, j, repeater, 0);
switch (j) {
case 2:
postRepeaterBlocks.put(world.getBlockAt(startx, starty, startz), (byte) 2);
break;
case 3:
postRepeaterBlocks.put(world.getBlockAt(startx, starty, startz), (byte) 1);
break;
case 4:
postRepeaterBlocks.put(world.getBlockAt(startx, starty, startz), (byte) 3);
break;
default:
postRepeaterBlocks.put(world.getBlockAt(startx, starty, startz), (byte) 0);
break;
}
j++;
}
} else if (id == 19) { // sponge
int swap;
if (world.getWorldType().equals(WorldType.FLAT) || own_world || world.getName().equals("TARDIS_TimeVortex") || world.getGenerator() instanceof TARDISChunkGenerator) {
swap = 0;
} else {
swap = 1;
}
plugin.utils.setBlock(world, startx, starty, startz, swap, data);
} else {
plugin.utils.setBlock(world, startx, starty, startz, id, data);
}
}
startx += x;
}
startx = resetx;
startz += z;
}
startz = resetz;
starty += 1;
}
// put on the door, redstone torches, signs, and the repeaters
for (Map.Entry<Block, Byte> entry : postDoorBlocks.entrySet()) {
Block pdb = entry.getKey();
byte pddata = entry.getValue();
pdb.setTypeId(71);
pdb.setData(pddata, true);
}
for (Map.Entry<Block, Byte> entry : postTorchBlocks.entrySet()) {
Block ptb = entry.getKey();
byte ptdata = entry.getValue();
ptb.setTypeId(76);
ptb.setData(ptdata, true);
}
for (Map.Entry<Block, Byte> entry : postRepeaterBlocks.entrySet()) {
Block prb = entry.getKey();
byte ptdata = entry.getValue();
prb.setTypeId(93);
prb.setData(ptdata, true);
}
for (Map.Entry<Block, Byte> entry : postStickyPistonBaseBlocks.entrySet()) {
Block pspb = entry.getKey();
plugin.pistons.add(pspb);
byte pspdata = entry.getValue();
pspb.setTypeId(29);
pspb.setData(pspdata, true);
}
for (Map.Entry<Block, Byte> entry : postPistonBaseBlocks.entrySet()) {
Block ppb = entry.getKey();
plugin.pistons.add(ppb);
byte ppbdata = entry.getValue();
ppb.setTypeId(33);
ppb.setData(ppbdata, true);
}
for (Map.Entry<Block, Byte> entry : postPistonExtensionBlocks.entrySet()) {
Block ppeb = entry.getKey();
byte ppedata = entry.getValue();
ppeb.setTypeId(34);
ppeb.setData(ppedata, true);
}
for (Map.Entry<Block, Byte> entry : postSignBlocks.entrySet()) {
final Block psb = entry.getKey();
byte psdata = entry.getValue();
psb.setTypeId(68);
psb.setData(psdata, true);
if (psb.getType().equals(Material.WALL_SIGN)) {
Sign cs = (Sign) psb.getState();
cs.setLine(0, "Chameleon");
cs.setLine(1, "Circuit");
cs.setLine(2, ChatColor.RED + "OFF");
cs.setLine(3, "NEW");
cs.update();
}
}
if (postSaveSignBlock != null) {
postSaveSignBlock.setTypeId(68);
postSaveSignBlock.setData((byte) 3, true);
if (postSaveSignBlock.getType().equals(Material.WALL_SIGN)) {
Sign ss = (Sign) postSaveSignBlock.getState();
ss.setLine(0, "TARDIS");
ss.setLine(1, "Saved");
ss.setLine(2, "Locations");
ss.setLine(3, "");
ss.update();
}
}
if (postTerminalBlock != null) {
postTerminalBlock.setTypeId(68);
postTerminalBlock.setData((byte) 3, true);
if (postTerminalBlock.getType().equals(Material.WALL_SIGN)) {
Sign ts = (Sign) postTerminalBlock.getState();
ts.setLine(0, "");
ts.setLine(1, "Destination");
ts.setLine(2, "Terminal");
ts.setLine(3, "");
ts.update();
}
}
if (postARSBlock != null) {
postARSBlock.setTypeId(68);
postARSBlock.setData((byte) 3, true);
if (postARSBlock.getType().equals(Material.WALL_SIGN)) {
Sign as = (Sign) postARSBlock.getState();
as.setLine(0, "TARDIS");
as.setLine(1, "Architectural");
as.setLine(2, "Reconfiguration");
as.setLine(3, "System");
as.update();
}
}
if (postTISBlock != null) {
postTISBlock.setTypeId(68);
postTISBlock.setData((byte) 3, true);
if (postTISBlock.getType().equals(Material.WALL_SIGN)) {
Sign is = (Sign) postTISBlock.getState();
is.setLine(0, "-----");
is.setLine(1, "TARDIS");
is.setLine(2, "Information");
is.setLine(3, "System");
is.update();
}
}
if (postTemporalBlock != null) {
postTemporalBlock.setTypeId(68);
postTemporalBlock.setData((byte) 3, true);
if (postTemporalBlock.getType().equals(Material.WALL_SIGN)) {
Sign ms = (Sign) postTemporalBlock.getState();
ms.setLine(0, "");
ms.setLine(1, "Temporal");
ms.setLine(2, "Locator");
ms.setLine(3, "");
ms.update();
}
}
if (postKeyboardBlock != null) {
postKeyboardBlock.setTypeId(68);
postKeyboardBlock.setData((byte) 3, true);
if (postKeyboardBlock.getType().equals(Material.WALL_SIGN)) {
Sign ks = (Sign) postKeyboardBlock.getState();
ks.setLine(0, "Keyboard");
for (int i = 1; i < 4; i++) {
ks.setLine(i, "");
}
ks.update();
}
}
for (Block lamp : lampblocks) {
lamp.setType(Material.REDSTONE_LAMP_ON);
}
lampblocks.clear();
if (plugin.worldGuardOnServer && plugin.getConfig().getBoolean("use_worldguard")) {
plugin.wgutils.addWGProtection(p, wg1, wg2);
}
// finished processing - update tardis table!
qf.doUpdate("tardis", set, where);
}
|
diff --git a/monitorization/console/src/pt/com/broker/monitorization/db/queries/agents/AllAgentsGeneralInfoQuery.java b/monitorization/console/src/pt/com/broker/monitorization/db/queries/agents/AllAgentsGeneralInfoQuery.java
index 5b487b9b..85a93554 100644
--- a/monitorization/console/src/pt/com/broker/monitorization/db/queries/agents/AllAgentsGeneralInfoQuery.java
+++ b/monitorization/console/src/pt/com/broker/monitorization/db/queries/agents/AllAgentsGeneralInfoQuery.java
@@ -1,105 +1,105 @@
package pt.com.broker.monitorization.db.queries.agents;
import java.sql.ResultSet;
import java.util.List;
import java.util.Map;
import org.caudexorigo.jdbc.Db;
import org.caudexorigo.jdbc.DbPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pt.com.broker.monitorization.AgentHostname;
public class AllAgentsGeneralInfoQuery
{
private static final Logger log = LoggerFactory.getLogger(AllAgentsGeneralInfoQuery.class);
private static String QUERY = "SELECT agents.agent_name , last_event_for_subject_predicate_agent('agent', 'status', agents.agent_name, now(), '00:10') AS status , last_event_input_message_for_agent(agents.agent_name, now(), '00:10') AS input , last_event_ouput_message_for_agent(agents.agent_name, now(), '00:10') AS output , last_event_for_subject_predicate_agent('faults', 'rate', agents.agent_name, now(), '00:10') AS faulTrate , last_event_for_subject_predicate_agent('system-message', 'failed-delivery', agents.agent_name, now(), '00:10') AS pending_sys_msg , last_event_for_subject_predicate_agent('dropbox', 'count', agents.agent_name, now(), '00:10') AS dropboxcount FROM (SELECT DISTINCT agent_name FROM raw_data WHERE event_time > (now() - '00:10'::time) ) AS agents ORDER BY 3 DESC";
public String getId()
{
return "allAgentGeneralInfo";
}
public String getJsonData(Map<String, List<String>> params)
{
Db db = null;
StringBuilder sb = new StringBuilder();
try
{
db = DbPool.pick();
ResultSet queryResult = getResultSet(db, params);
if (queryResult == null)
return "";
boolean first = true;
while (queryResult.next())
{
if (first)
{
first = false;
}
else
{
sb.append(",");
}
int idx = 1;
sb.append("{");
sb.append("\"agentName\":\"");
String agentName = queryResult.getString(idx++);
sb.append(agentName);
sb.append("\",");
sb.append("\"agentHostname\":\"");
sb.append(AgentHostname.get(agentName));
sb.append("\",");
sb.append("\"status\":\"");
sb.append( (queryResult.getDouble(idx++) == 1) ? "Ok" : "Down" );
sb.append("\",");
sb.append("\"inputRate\":\"");
sb.append(queryResult.getDouble(idx++));
sb.append("\",");
sb.append("\"outputRate\":\"");
sb.append(queryResult.getDouble(idx++));
sb.append("\",");
sb.append("\"faultRate\":\"");
sb.append(queryResult.getDouble(idx++));
sb.append("\",");
sb.append("\"pendingAckSystemMsg\":\"");
sb.append(queryResult.getDouble(idx++));
sb.append("\",");
sb.append("\"dropboxCount\":\"");
sb.append(queryResult.getDouble(idx++));
sb.append("\"");
sb.append("}");
}
}
catch (Throwable t)
{
- log.error("Failed to get all queue genral info", t);
+ log.error("Failed to get agents general information", t);
}
finally
{
DbPool.release(db);
}
return sb.toString();
}
protected ResultSet getResultSet(Db db, Map<String, List<String>> params)
{
return db.runRetrievalPreparedStatement(QUERY);
}
}
| true | true | public String getJsonData(Map<String, List<String>> params)
{
Db db = null;
StringBuilder sb = new StringBuilder();
try
{
db = DbPool.pick();
ResultSet queryResult = getResultSet(db, params);
if (queryResult == null)
return "";
boolean first = true;
while (queryResult.next())
{
if (first)
{
first = false;
}
else
{
sb.append(",");
}
int idx = 1;
sb.append("{");
sb.append("\"agentName\":\"");
String agentName = queryResult.getString(idx++);
sb.append(agentName);
sb.append("\",");
sb.append("\"agentHostname\":\"");
sb.append(AgentHostname.get(agentName));
sb.append("\",");
sb.append("\"status\":\"");
sb.append( (queryResult.getDouble(idx++) == 1) ? "Ok" : "Down" );
sb.append("\",");
sb.append("\"inputRate\":\"");
sb.append(queryResult.getDouble(idx++));
sb.append("\",");
sb.append("\"outputRate\":\"");
sb.append(queryResult.getDouble(idx++));
sb.append("\",");
sb.append("\"faultRate\":\"");
sb.append(queryResult.getDouble(idx++));
sb.append("\",");
sb.append("\"pendingAckSystemMsg\":\"");
sb.append(queryResult.getDouble(idx++));
sb.append("\",");
sb.append("\"dropboxCount\":\"");
sb.append(queryResult.getDouble(idx++));
sb.append("\"");
sb.append("}");
}
}
catch (Throwable t)
{
log.error("Failed to get all queue genral info", t);
}
finally
{
DbPool.release(db);
}
return sb.toString();
}
| public String getJsonData(Map<String, List<String>> params)
{
Db db = null;
StringBuilder sb = new StringBuilder();
try
{
db = DbPool.pick();
ResultSet queryResult = getResultSet(db, params);
if (queryResult == null)
return "";
boolean first = true;
while (queryResult.next())
{
if (first)
{
first = false;
}
else
{
sb.append(",");
}
int idx = 1;
sb.append("{");
sb.append("\"agentName\":\"");
String agentName = queryResult.getString(idx++);
sb.append(agentName);
sb.append("\",");
sb.append("\"agentHostname\":\"");
sb.append(AgentHostname.get(agentName));
sb.append("\",");
sb.append("\"status\":\"");
sb.append( (queryResult.getDouble(idx++) == 1) ? "Ok" : "Down" );
sb.append("\",");
sb.append("\"inputRate\":\"");
sb.append(queryResult.getDouble(idx++));
sb.append("\",");
sb.append("\"outputRate\":\"");
sb.append(queryResult.getDouble(idx++));
sb.append("\",");
sb.append("\"faultRate\":\"");
sb.append(queryResult.getDouble(idx++));
sb.append("\",");
sb.append("\"pendingAckSystemMsg\":\"");
sb.append(queryResult.getDouble(idx++));
sb.append("\",");
sb.append("\"dropboxCount\":\"");
sb.append(queryResult.getDouble(idx++));
sb.append("\"");
sb.append("}");
}
}
catch (Throwable t)
{
log.error("Failed to get agents general information", t);
}
finally
{
DbPool.release(db);
}
return sb.toString();
}
|
diff --git a/src/main/java/net/pms/PMS.java b/src/main/java/net/pms/PMS.java
index 87d8e1e9..3edd7990 100644
--- a/src/main/java/net/pms/PMS.java
+++ b/src/main/java/net/pms/PMS.java
@@ -1,1097 +1,1097 @@
/*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2008 A.Brochard
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2
* of the License only.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package net.pms;
import com.sun.jna.Platform;
import net.pms.configuration.Build;
import net.pms.configuration.PmsConfiguration;
import net.pms.configuration.RendererConfiguration;
import net.pms.dlna.DLNAMediaDatabase;
import net.pms.dlna.RootFolder;
import net.pms.dlna.virtual.MediaLibrary;
import net.pms.encoders.Player;
import net.pms.encoders.PlayerFactory;
import net.pms.external.ExternalFactory;
import net.pms.external.ExternalListener;
import net.pms.formats.Format;
import net.pms.formats.FormatFactory;
import net.pms.newgui.DummyFrame;
import net.pms.newgui.IFrame;
import net.pms.io.*;
import net.pms.logging.FrameAppender;
import net.pms.logging.LoggingConfigFileLoader;
import net.pms.network.HTTPServer;
import net.pms.network.ProxyServer;
import net.pms.network.UPNPHelper;
import net.pms.newgui.LooksFrame;
import net.pms.newgui.ProfileChooser;
import net.pms.update.AutoUpdater;
import net.pms.util.*;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.event.ConfigurationEvent;
import org.apache.commons.configuration.event.ConfigurationListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.*;
import java.awt.*;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.net.BindException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.logging.LogManager;
public class PMS {
private static final String SCROLLBARS = "scrollbars";
private static final String NATIVELOOK = "nativelook";
private static final String CONSOLE = "console";
private static final String NOCONSOLE = "noconsole";
private static final String PROFILES = "profiles";
private static Boolean isHeadless;
/**
* @deprecated The version has moved to the resources/project.properties file. Use {@link #getVersion()} instead.
*/
@Deprecated
public static String VERSION;
public static final String AVS_SEPARATOR = "\1";
// (innot): The logger used for all logging.
private static final Logger LOGGER = LoggerFactory.getLogger(PMS.class);
// TODO(tcox): This shouldn't be static
private static PmsConfiguration configuration;
/**
* Universally Unique Identifier used in the UPnP server.
*/
private String uuid;
/**
* Relative location of a context sensitive help page in the documentation
* directory.
*/
private static String helpPage = "index.html";
/**
* Returns a pointer to the PMS GUI's main window.
* @return {@link net.pms.newgui.IFrame} Main PMS window.
*/
public IFrame getFrame() {
return frame;
}
/**
* Returns the root folder for a given renderer. There could be the case
* where a given media renderer needs a different root structure.
*
* @param renderer {@link net.pms.configuration.RendererConfiguration}
* is the renderer for which to get the RootFolder structure. If <code>null</code>,
* then the default renderer is used.
* @return {@link net.pms.dlna.RootFolder} The root folder structure for a given renderer
*/
public RootFolder getRootFolder(RendererConfiguration renderer) {
// something to do here for multiple directories views for each renderer
if (renderer == null) {
renderer = RendererConfiguration.getDefaultConf();
}
return renderer.getRootFolder();
}
/**
* Pointer to a running PMS server.
*/
private static PMS instance = null;
/**
* @deprecated This field is not used and will be removed in the future.
*/
@Deprecated
public final static SimpleDateFormat sdfDate = new SimpleDateFormat("HH:mm:ss.SSS", Locale.US);
/**
* @deprecated This field is not used and will be removed in the future.
*/
@Deprecated
public final static SimpleDateFormat sdfHour = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
/**
* Array of {@link net.pms.configuration.RendererConfiguration} that have been found by PMS.
*/
private final ArrayList<RendererConfiguration> foundRenderers = new ArrayList<RendererConfiguration>();
/**
* @deprecated Use {@link #setRendererFound(RendererConfiguration)} instead.
*/
@Deprecated
public void setRendererfound(RendererConfiguration renderer) {
setRendererFound(renderer);
}
/**
* Adds a {@link net.pms.configuration.RendererConfiguration} to the list of media renderers found.
* The list is being used, for example, to give the user a graphical representation of the found
* media renderers.
*
* @param renderer {@link net.pms.configuration.RendererConfiguration}
* @since 1.82.0
*/
public void setRendererFound(RendererConfiguration renderer) {
if (!foundRenderers.contains(renderer) && !renderer.isFDSSDP()) {
foundRenderers.add(renderer);
frame.addRendererIcon(renderer.getRank(), renderer.getRendererName(), renderer.getRendererIcon());
frame.setStatusCode(0, Messages.getString("PMS.18"), "apply-220.png");
}
}
/**
* HTTP server that serves the XML files needed by UPnP server and the media files.
*/
private HTTPServer server;
/**
* User friendly name for the server.
*/
private String serverName;
// FIXME unused
private ProxyServer proxyServer;
public ProxyServer getProxy() {
return proxyServer;
}
public ArrayList<Process> currentProcesses = new ArrayList<Process>();
private PMS() { }
/**
* {@link net.pms.newgui.IFrame} object that represents the PMS GUI.
*/
private IFrame frame;
/**
* @see com.sun.jna.Platform#isWindows()
*/
public boolean isWindows() {
return Platform.isWindows();
}
/**
* Interface to Windows-specific functions, like Windows Registry. registry is set by {@link #init()}.
* @see net.pms.io.WinUtils
*/
private SystemUtils registry;
/**
* @see net.pms.io.WinUtils
*/
public SystemUtils getRegistry() {
return registry;
}
/**
* Executes a new Process and creates a fork that waits for its results.
* TODO Extend explanation on where this is being used.
* @param name Symbolic name for the process to be launched, only used in the trace log
* @param error (boolean) Set to true if you want PMS to add error messages to the trace pane
* @param workDir (File) optional working directory to run the process in
* @param params (array of Strings) array containing the command to call and its arguments
* @return Returns true if the command exited as expected
* @throws Exception TODO: Check which exceptions to use
*/
private boolean checkProcessExistence(String name, boolean error, File workDir, String... params) throws Exception {
LOGGER.debug("launching: " + params[0]);
try {
ProcessBuilder pb = new ProcessBuilder(params);
if (workDir != null) {
pb.directory(workDir);
}
final Process process = pb.start();
OutputTextConsumer stderrConsumer = new OutputTextConsumer(process.getErrorStream(), false);
stderrConsumer.start();
OutputTextConsumer outConsumer = new OutputTextConsumer(process.getInputStream(), false);
outConsumer.start();
Runnable r = new Runnable() {
public void run() {
ProcessUtil.waitFor(process);
}
};
Thread checkThread = new Thread(r, "PMS Checker");
checkThread.start();
checkThread.join(60000);
checkThread.interrupt();
checkThread = null;
// XXX no longer used
if (params[0].equals("vlc") && stderrConsumer.getResults().get(0).startsWith("VLC")) {
return true;
}
// XXX no longer used
if (params[0].equals("ffmpeg") && stderrConsumer.getResults().get(0).startsWith("FF")) {
return true;
}
int exit = process.exitValue();
if (exit != 0) {
if (error) {
LOGGER.info("[" + exit + "] Cannot launch " + name + " / Check the presence of " + params[0] + " ...");
}
return false;
}
return true;
} catch (Exception e) {
if (error) {
LOGGER.error("Cannot launch " + name + " / Check the presence of " + params[0] + " ...", e);
}
return false;
}
}
/**
* @see System#err
*/
@SuppressWarnings("unused")
private final PrintStream stderr = System.err;
/**
* Main resource database that supports search capabilities. Also known as media cache.
* @see net.pms.dlna.DLNAMediaDatabase
*/
private DLNAMediaDatabase database;
private void initializeDatabase() {
database = new DLNAMediaDatabase("medias"); // TODO: rename "medias" -> "cache"
database.init(false);
}
/**
* Used to get the database. Needed in the case of the Xbox 360, that requires a database.
* for its queries.
* @return (DLNAMediaDatabase) a reference to the database instance or <b>null</b> if one isn't defined
* (e.g. if the cache is disabled).
*/
public synchronized DLNAMediaDatabase getDatabase() {
if (configuration.getUseCache()) {
if (database == null) {
initializeDatabase();
}
return database;
}
return null;
}
private void displayBanner() throws IOException {
LOGGER.info("Starting " + PropertiesUtil.getProjectProperties().get("project.name") + " " + getVersion());
LOGGER.info("by shagrath / 2008-2013");
LOGGER.info("http://ps3mediaserver.org");
LOGGER.info("https://github.com/ps3mediaserver/ps3mediaserver");
LOGGER.info("");
String commitId = PropertiesUtil.getProjectProperties().get("git.commit.id");
String commitTime = PropertiesUtil.getProjectProperties().get("git.commit.time");
String shortCommitId = commitId.substring(0, 9);
LOGGER.info("Build: " + shortCommitId + " (" + commitTime + ")");
// Log system properties
logSystemInfo();
String cwd = new File("").getAbsolutePath();
LOGGER.info("Working directory: " + cwd);
LOGGER.info("Temp directory: " + configuration.getTempFolder());
// Verify the java.io.tmpdir is writable; JNA requires it.
// Note: the configured tempFolder has already been checked, but it
// may differ from the java.io.tmpdir so double check to be sure.
File javaTmpdir = new File(System.getProperty("java.io.tmpdir"));
if (!FileUtil.isDirectoryWritable(javaTmpdir)) {
LOGGER.error("The Java temp directory \"{}\" is not writable for PMS!", javaTmpdir.getAbsolutePath());
LOGGER.error("Please make sure the directory is writable for user \"{}\"", System.getProperty("user.name"));
throw new IOException("Cannot write to Java temp directory");
}
LOGGER.info("Logging config file: {}", LoggingConfigFileLoader.getConfigFilePath());
HashMap<String, String> lfps = LoggingConfigFileLoader.getLogFilePaths();
// debug.log filename(s) and path(s)
if (lfps != null && lfps.size() > 0) {
if (lfps.size() == 1) {
Entry<String, String> entry = lfps.entrySet().iterator().next();
LOGGER.info(String.format("%s: %s", entry.getKey(), entry.getValue()));
} else {
LOGGER.info("Logging to multiple files:");
Iterator<Entry<String, String>> logsIterator = lfps.entrySet().iterator();
Entry<String, String> entry;
while (logsIterator.hasNext()) {
entry = logsIterator.next();
LOGGER.info(String.format("%s: %s", entry.getKey(), entry.getValue()));
}
}
}
LOGGER.info("");
LOGGER.info("Profile directory: {}", configuration.getProfileDirectory());
String profilePath = configuration.getProfilePath();
LOGGER.info("Profile path: {}", profilePath);
File profileFile = new File(profilePath);
if (profileFile.exists()) {
String permissions = String.format("%s%s",
FileUtil.isFileReadable(profileFile) ? "r" : "-",
FileUtil.isFileWritable(profileFile) ? "w" : "-"
);
LOGGER.info("Profile permissions: {}", permissions);
} else {
LOGGER.info("Profile permissions: no such file");
}
LOGGER.info("Profile name: {}", configuration.getProfileName());
LOGGER.info("");
}
/**
* Initialisation procedure for PMS.
* @return true if the server has been initialized correctly. false if the server could
* not be set to listen on the UPnP port.
* @throws Exception
*/
private boolean init() throws Exception {
// The public VERSION field is deprecated.
// This is a temporary fix for backwards compatibility
VERSION = getVersion();
// call this as early as possible
displayBanner();
AutoUpdater autoUpdater = null;
if (Build.isUpdatable()) {
String serverURL = Build.getUpdateServerURL();
autoUpdater = new AutoUpdater(serverURL, getVersion());
}
registry = createSystemUtils();
if (System.getProperty(CONSOLE) == null) {
frame = new LooksFrame(autoUpdater, configuration);
} else {
LOGGER.info("GUI environment not available");
LOGGER.info("Switching to console mode");
frame = new DummyFrame();
}
/*
* we're here:
*
* main() -> createInstance() -> init()
*
* which means we haven't created the instance returned by get()
* yet, so the frame appender can't access the frame in the
* standard way i.e. PMS.get().getFrame(). we solve it by
* inverting control ("don't call us; we'll call you") i.e.
* we notify the appender when the frame is ready rather than
* e.g. making getFrame() static and requiring the frame
* appender to poll it.
*
* XXX an event bus (e.g. MBassador or Guava EventBus
* (if they fix the memory-leak issue)) notification
- * would be cleaner and could suport other lifecycle
+ * would be cleaner and could support other lifecycle
* notifications (see above).
*/
FrameAppender.setFrame(frame);
configuration.addConfigurationListener(new ConfigurationListener() {
@Override
public void configurationChanged(ConfigurationEvent event) {
if ((!event.isBeforeUpdate())
&& PmsConfiguration.NEED_RELOAD_FLAGS.contains(event.getPropertyName())) {
frame.setReloadable(true);
}
}
});
frame.setStatusCode(0, Messages.getString("PMS.130"), "connect_no-220.png");
RendererConfiguration.loadRendererConfigurations(configuration);
LOGGER.info("Checking MPlayer font cache. It can take a minute or so.");
checkProcessExistence("MPlayer", true, null, configuration.getMplayerPath(), "dummy");
if (isWindows()) {
checkProcessExistence("MPlayer", true, configuration.getTempFolder(), configuration.getMplayerPath(), "dummy");
}
LOGGER.info("Done!");
// check the existence of Vsfilter.dll
if (registry.isAvis() && registry.getAvsPluginsDir() != null) {
LOGGER.info("Found AviSynth plugins dir: " + registry.getAvsPluginsDir().getAbsolutePath());
File vsFilterdll = new File(registry.getAvsPluginsDir(), "VSFilter.dll");
if (!vsFilterdll.exists()) {
LOGGER.info("VSFilter.dll is not in the AviSynth plugins directory. This can cause problems when trying to play subtitled videos with AviSynth");
}
}
// Check if VLC is found
String vlcVersion = registry.getVlcVersion();
String vlcPath = registry.getVlcPath();
if (vlcVersion != null && vlcPath != null) {
LOGGER.info("Found VLC version " + vlcVersion + " at: " + vlcPath);
Version vlc = new Version(vlcVersion);
Version requiredVersion = new Version("2.0.2");
if (vlc.compareTo(requiredVersion) <= 0) {
LOGGER.error("Only VLC versions 2.0.2 and above are supported");
}
}
// check if Kerio is installed
if (registry.isKerioFirewall()) {
LOGGER.info("Detected Kerio firewall");
}
// force use of specific dvr ms muxer when it's installed in the right place
File dvrsMsffmpegmuxer = new File("win32/dvrms/ffmpeg_MPGMUX.exe");
if (dvrsMsffmpegmuxer.exists()) {
configuration.setFfmpegAlternativePath(dvrsMsffmpegmuxer.getAbsolutePath());
}
// disable jaudiotagger logging
LogManager.getLogManager().readConfiguration(new ByteArrayInputStream("org.jaudiotagger.level=OFF".getBytes()));
// wrap System.err
System.setErr(new PrintStream(new SystemErrWrapper(), true));
server = new HTTPServer(configuration.getServerPort());
/*
* XXX: keep this here (i.e. after registerExtensions and before registerPlayers) so that plugins
* can register custom players correctly (e.g. in the GUI) and/or add/replace custom formats
*
* XXX: if a plugin requires initialization/notification even earlier than
* this, then a new external listener implementing a new callback should be added
* e.g. StartupListener.registeredExtensions()
*/
try {
ExternalFactory.lookup();
} catch (Exception e) {
LOGGER.error("Error loading plugins", e);
}
// a static block in Player doesn't work (i.e. is called too late).
// this must always be called *after* the plugins have loaded.
// here's as good a place as any
Player.initializeFinalizeTranscoderArgsListeners();
// Initialize a player factory to register all players
PlayerFactory.initialize(configuration);
// Instantiate listeners that require registered players.
ExternalFactory.instantiateLateListeners();
// Any plugin-defined players are now registered, create the GUI view.
frame.addEngines();
boolean binding = false;
try {
binding = server.start();
} catch (BindException b) {
LOGGER.info("FATAL ERROR: Unable to bind on port: " + configuration.getServerPort() + ", because: " + b.getMessage());
LOGGER.info("Maybe another process is running or the hostname is wrong.");
}
new Thread("Connection Checker") {
@Override
public void run() {
try {
Thread.sleep(7000);
} catch (InterruptedException e) { }
if (foundRenderers.isEmpty()) {
frame.setStatusCode(0, Messages.getString("PMS.0"), "messagebox_critical-220.png");
} else {
frame.setStatusCode(0, Messages.getString("PMS.18"), "apply-220.png");
}
}
}.start();
if (!binding) {
return false;
}
// initialize the cache
if (configuration.getUseCache()) {
initializeDatabase(); // XXX: this must be done *before* new MediaLibrary -> new MediaLibraryFolder
mediaLibrary = new MediaLibrary();
LOGGER.info("A tiny cache admin interface is available at: http://" + server.getHost() + ":" + server.getPort() + "/console/home");
}
// XXX: this must be called:
// a) *after* loading plugins i.e. plugins register root folders then RootFolder.discoverChildren adds them
// b) *after* mediaLibrary is initialized, if enabled (above)
getRootFolder(RendererConfiguration.getDefaultConf());
frame.serverReady();
// UPNPHelper.sendByeBye();
Runtime.getRuntime().addShutdownHook(new Thread("PMS Listeners Stopper") {
@Override
public void run() {
try {
for (ExternalListener l : ExternalFactory.getExternalListeners()) {
l.shutdown();
}
UPNPHelper.shutDownListener();
UPNPHelper.sendByeBye();
LOGGER.debug("Forcing shutdown of all active processes");
for (Process p : currentProcesses) {
try {
p.exitValue();
} catch (IllegalThreadStateException ise) {
LOGGER.trace("Forcing shutdown of process: " + p);
ProcessUtil.destroy(p);
}
}
get().getServer().stop();
Thread.sleep(500);
} catch (InterruptedException e) {
LOGGER.debug("Caught exception", e);
}
}
});
UPNPHelper.sendAlive();
LOGGER.trace("Waiting 250 milliseconds...");
Thread.sleep(250);
UPNPHelper.listen();
return true;
}
private MediaLibrary mediaLibrary;
/**
* Returns the MediaLibrary used by PMS.
* @return (MediaLibrary) Used mediaLibrary, if any. null if none is in use.
*/
public MediaLibrary getLibrary() {
return mediaLibrary;
}
private SystemUtils createSystemUtils() {
if (Platform.isWindows()) {
return new WinUtils();
} else {
if (Platform.isMac()) {
return new MacSystemUtils();
} else {
if (Platform.isSolaris()) {
return new SolarisUtils();
} else {
return new BasicSystemUtils();
}
}
}
}
/**
* Executes the needed commands in order to make PMS a Windows service that starts whenever the machine is started.
* This function is called from the Network tab.
* @return true if PMS could be installed as a Windows service.
* @see net.pms.newgui.GeneralTab#build()
*/
public boolean installWin32Service() {
LOGGER.info(Messages.getString("PMS.41"));
String cmdArray[] = new String[]{ "win32/service/wrapper.exe", "-r", "wrapper.conf" };
OutputParams output = new OutputParams(configuration);
output.noexitcheck = true;
ProcessWrapperImpl pwuninstall = new ProcessWrapperImpl(cmdArray, output);
pwuninstall.runInSameThread();
cmdArray = new String[]{ "win32/service/wrapper.exe", "-i", "wrapper.conf" };
ProcessWrapperImpl pwInstall = new ProcessWrapperImpl(cmdArray, new OutputParams(configuration));
pwInstall.runInSameThread();
return pwInstall.isSuccess();
}
/**
* @deprecated Use {@link #getFoldersConf()} instead.
*/
@Deprecated
public File[] getFoldersConf(boolean log) {
return getFoldersConf();
}
/**
* Transforms a comma-separated list of directory entries into an array of {@link String}.
* Checks that the directory exists and is a valid directory.
*
* @return {@link java.io.File}[] Array of directories.
* @throws java.io.IOException
*/
public File[] getFoldersConf() {
String folders = getConfiguration().getFolders();
if (folders == null || folders.length() == 0) {
return null;
}
ArrayList<File> directories = new ArrayList<File>();
String[] foldersArray = folders.split(",");
for (String folder : foldersArray) {
// unescape embedded commas. note: backslashing isn't safe as it conflicts with
// Windows path separators:
// http://ps3mediaserver.org/forum/viewtopic.php?f=14&t=8883&start=250#p43520
folder = folder.replaceAll(",", ",");
// this is called *way* too often
// so log it so we can fix it.
LOGGER.info("Checking shared folder: " + folder);
File file = new File(folder);
if (file.exists()) {
if (!file.isDirectory()) {
LOGGER.warn("The file " + folder + " is not a directory! Please remove it from your Shared folders list on the Navigation/Share Settings tab");
}
} else {
LOGGER.warn("The directory " + folder + " does not exist. Please remove it from your Shared folders list on the Navigation/Share Settings tab");
}
// add the file even if there are problems so that the user can update the shared folders as required.
directories.add(file);
}
File f[] = new File[directories.size()];
directories.toArray(f);
return f;
}
/**
* Restarts the server. The trigger is either a button on the main PMS window or via
* an action item.
* @throws java.io.IOException
*/
// XXX: don't try to optimize this by reusing the same server instance.
// see the comment above HTTPServer.stop()
public void reset() {
TaskRunner.getInstance().submitNamed("restart", true, new Runnable() {
public void run() {
try {
LOGGER.trace("Waiting 1 second...");
UPNPHelper.sendByeBye();
server.stop();
server = null;
RendererConfiguration.resetAllRenderers();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
LOGGER.trace("Caught exception", e);
}
server = new HTTPServer(configuration.getServerPort());
server.start();
UPNPHelper.sendAlive();
frame.setReloadable(false);
} catch (IOException e) {
LOGGER.error("error during restart :" +e.getMessage(), e);
}
}
});
}
// Cannot remove these methods because of backwards compatibility;
// none of the PMS code uses it, but some plugins still do.
/**
* @deprecated Use the SLF4J logging API instead.
* Adds a message to the debug stream, or {@link System#out} in case the
* debug stream has not been set up yet.
* @param msg {@link String} to be added to the debug stream.
*/
@Deprecated
public static void debug(String msg) {
LOGGER.trace(msg);
}
/**
* @deprecated Use the SLF4J logging API instead.
* Adds a message to the info stream.
* @param msg {@link String} to be added to the info stream.
*/
@Deprecated
public static void info(String msg) {
LOGGER.debug(msg);
}
/**
* @deprecated Use the SLF4J logging API instead.
* Adds a message to the minimal stream. This stream is also
* shown in the Trace tab.
* @param msg {@link String} to be added to the minimal stream.
*/
@Deprecated
public static void minimal(String msg) {
LOGGER.info(msg);
}
/**
* @deprecated Use the SLF4J logging API instead.
* Adds a message to the error stream. This is usually called by
* statements that are in a try/catch block.
* @param msg {@link String} to be added to the error stream
* @param t {@link Throwable} comes from an {@link Exception}
*/
@Deprecated
public static void error(String msg, Throwable t) {
LOGGER.error(msg, t);
}
/**
* Creates a new random {@link #uuid}. These are used to uniquely identify the server to renderers (i.e.
* renderers treat multiple servers with the same UUID as the same server).
* @return {@link String} with an Universally Unique Identifier.
*/
// XXX don't use the MAC address to seed the UUID as it breaks multiple profiles:
// http://www.ps3mediaserver.org/forum/viewtopic.php?f=6&p=75542#p75542
public synchronized String usn() {
if (uuid == null) {
// retrieve UUID from configuration
uuid = getConfiguration().getUuid();
if (uuid == null) {
uuid = UUID.randomUUID().toString();
LOGGER.info("Generated new random UUID: {}", uuid);
// save the newly-generated UUID
getConfiguration().setUuid(uuid);
try {
getConfiguration().save();
} catch (ConfigurationException e) {
LOGGER.error("Failed to save configuration with new UUID", e);
}
}
LOGGER.info("Using the following UUID configured in PMS.conf: {}", uuid);
}
return "uuid:" + uuid;
}
/**
* Returns the user friendly name of the UPnP server.
* @return {@link String} with the user friendly name.
*/
public String getServerName() {
if (serverName == null) {
StringBuilder sb = new StringBuilder();
sb.append(System.getProperty("os.name").replace(" ", "_"));
sb.append("-");
sb.append(System.getProperty("os.arch").replace(" ", "_"));
sb.append("-");
sb.append(System.getProperty("os.version").replace(" ", "_"));
sb.append(", UPnP/1.0, PMS/" + getVersion());
serverName = sb.toString();
}
return serverName;
}
/**
* Returns the PMS instance.
* @return {@link net.pms.PMS}
*/
public static PMS get() {
// XXX when PMS is run as an application, the instance is initialized via the createInstance call in main().
// However, plugin tests may need access to a PMS instance without going
// to the trouble of launching the PMS application, so we provide a fallback
// initialization here. Either way, createInstance() should only be called once (see below)
if (instance == null) {
createInstance();
}
return instance;
}
private synchronized static void createInstance() {
assert instance == null; // this should only be called once
instance = new PMS();
try {
if (instance.init()) {
LOGGER.info("The server should now appear on your renderer");
} else {
LOGGER.error("A serious error occurred during PMS init");
}
} catch (Exception e) {
LOGGER.error("A serious error occurred during PMS init", e);
}
}
/**
* @deprecated Use {@link net.pms.formats.FormatFactory#getAssociatedExtension(String)}
* instead.
*
* @param filename
* @return The format.
*/
@Deprecated
public Format getAssociatedExtension(String filename) {
return FormatFactory.getAssociatedExtension(filename);
}
public static void main(String args[]) throws IOException, ConfigurationException {
boolean displayProfileChooser = false;
// FIXME (breaking change): use a standard argument
// format (and a standard argument processor) e.g.
// --console, --scrollbars &c.
if (args.length > 0) {
for (int a = 0; a < args.length; a++) {
if (args[a].equals(CONSOLE)) {
System.setProperty(CONSOLE, Boolean.toString(true));
} else if (args[a].equals(NATIVELOOK)) {
System.setProperty(NATIVELOOK, Boolean.toString(true));
} else if (args[a].equals(SCROLLBARS)) {
System.setProperty(SCROLLBARS, Boolean.toString(true));
} else if (args[a].equals(NOCONSOLE)) {
System.setProperty(NOCONSOLE, Boolean.toString(true));
} else if (args[a].equals(PROFILES)) {
displayProfileChooser = true;
}
}
}
try {
Toolkit.getDefaultToolkit();
if (isHeadless()) {
if (System.getProperty(NOCONSOLE) == null) {
System.setProperty(CONSOLE, Boolean.toString(true));
}
}
} catch (Throwable t) {
System.err.println("Toolkit error: " + t.getClass().getName() + ": " + t.getMessage());
if (System.getProperty(NOCONSOLE) == null) {
System.setProperty(CONSOLE, Boolean.toString(true));
}
}
if (!isHeadless() && displayProfileChooser) {
ProfileChooser.display();
}
try {
setConfiguration(new PmsConfiguration());
assert getConfiguration() != null;
// Load the (optional) logback config file.
// This has to be called after 'new PmsConfiguration'
// as the logging starts immediately and some filters
// need the PmsConfiguration.
// XXX not sure this is (still) true: the only filter
// we use is ch.qos.logback.classic.filter.ThresholdFilter
LoggingConfigFileLoader.load();
// create the PMS instance returned by get()
createInstance(); // calls new() then init()
} catch (Throwable t) {
String errorMessage = String.format(
"Configuration error: %s: %s",
t.getClass().getName(),
t.getMessage()
);
System.err.println(errorMessage);
t.printStackTrace();
if (!isHeadless() && instance != null) {
JOptionPane.showMessageDialog(
((JFrame) (SwingUtilities.getWindowAncestor((Component) instance.getFrame()))),
errorMessage,
Messages.getString("PMS.42"),
JOptionPane.ERROR_MESSAGE
);
}
}
}
public HTTPServer getServer() {
return server;
}
/**
* @deprecated Use {@link net.pms.formats.FormatFactory#getExtensions()} instead.
*
* @return The list of formats.
*/
public ArrayList<Format> getExtensions() {
return FormatFactory.getExtensions();
}
public void save() {
try {
configuration.save();
} catch (ConfigurationException e) {
LOGGER.error("Could not save configuration", e);
}
}
public void storeFileInCache(File file, int formatType) {
if (getConfiguration().getUseCache()
&& !getDatabase().isDataExists(file.getAbsolutePath(), file.lastModified())) {
getDatabase().insertData(file.getAbsolutePath(), file.lastModified(), formatType, null);
}
}
/**
* Retrieves the {@link net.pms.configuration.PmsConfiguration PmsConfiguration} object
* that contains all configured settings for PMS. The object provides getters for all
* configurable PMS settings.
*
* @return The configuration object
*/
public static PmsConfiguration getConfiguration() {
return configuration;
}
/**
* Sets the {@link net.pms.configuration.PmsConfiguration PmsConfiguration} object
* that contains all configured settings for PMS. The object provides getters for all
* configurable PMS settings.
*
* @param conf The configuration object.
*/
public static void setConfiguration(PmsConfiguration conf) {
configuration = conf;
}
/**
* Returns the project version for PMS.
*
* @return The project version.
*/
public static String getVersion() {
return PropertiesUtil.getProjectProperties().get("project.version");
}
/**
* Log system properties identifying Java, the OS and encoding and log
* warnings where appropriate.
*/
private void logSystemInfo() {
long memoryInMB = Runtime.getRuntime().maxMemory() / 1048576;
LOGGER.info("Java: " + System.getProperty("java.version") + "-" + System.getProperty("java.vendor"));
LOGGER.info("OS: " + System.getProperty("os.name") + " " + System.getProperty("os.arch") + " " + System.getProperty("os.version"));
LOGGER.info("Encoding: " + System.getProperty("file.encoding"));
LOGGER.info("Memory: " + memoryInMB + " " + Messages.getString("StatusTab.12"));
LOGGER.info("");
if (Platform.isMac()) {
// The binaries shipped with the Mac OS X version of PMS are being
// compiled against specific OS versions, making them incompatible
// with older versions. Warn the user about this when necessary.
String osVersion = System.getProperty("os.version");
// Split takes a regular expression, so escape the dot.
String[] versionNumbers = osVersion.split("\\.");
if (versionNumbers.length > 1) {
try {
int osVersionMinor = Integer.parseInt(versionNumbers[1]);
if (osVersionMinor < 6) {
LOGGER.warn("-----------------------------------------------------------------");
LOGGER.warn("WARNING!");
LOGGER.warn("PMS ships with binaries compiled for Mac OS X 10.6 or higher.");
LOGGER.warn("You are running an older version of Mac OS X so PMS may not work!");
LOGGER.warn("More information in the FAQ:");
LOGGER.warn("http://www.ps3mediaserver.org/forum/viewtopic.php?f=6&t=3507&p=66371#p66371");
LOGGER.warn("-----------------------------------------------------------------");
LOGGER.warn("");
}
} catch (NumberFormatException e) {
LOGGER.debug("Cannot parse minor os.version number");
}
}
}
}
/**
* Check if server is running in headless (console) mode.
*
* @return true if server is running in headless (console) mode, false otherwise
*/
public static synchronized boolean isHeadless() {
if (isHeadless == null) {
try {
javax.swing.JDialog d = new javax.swing.JDialog();
d.dispose();
isHeadless = false;
} catch (Throwable throwable) {
isHeadless = true;
}
}
return isHeadless;
}
/**
* Sets the relative URL of a context sensitive help page located in the
* documentation directory.
*
* @param page The help page.
*/
public static void setHelpPage(String page) {
helpPage = page;
}
/**
* Returns the relative URL of a context sensitive help page in the
* documentation directory.
*
* @return The help page.
*/
public static String getHelpPage() {
return helpPage;
}
}
| true | true | private boolean init() throws Exception {
// The public VERSION field is deprecated.
// This is a temporary fix for backwards compatibility
VERSION = getVersion();
// call this as early as possible
displayBanner();
AutoUpdater autoUpdater = null;
if (Build.isUpdatable()) {
String serverURL = Build.getUpdateServerURL();
autoUpdater = new AutoUpdater(serverURL, getVersion());
}
registry = createSystemUtils();
if (System.getProperty(CONSOLE) == null) {
frame = new LooksFrame(autoUpdater, configuration);
} else {
LOGGER.info("GUI environment not available");
LOGGER.info("Switching to console mode");
frame = new DummyFrame();
}
/*
* we're here:
*
* main() -> createInstance() -> init()
*
* which means we haven't created the instance returned by get()
* yet, so the frame appender can't access the frame in the
* standard way i.e. PMS.get().getFrame(). we solve it by
* inverting control ("don't call us; we'll call you") i.e.
* we notify the appender when the frame is ready rather than
* e.g. making getFrame() static and requiring the frame
* appender to poll it.
*
* XXX an event bus (e.g. MBassador or Guava EventBus
* (if they fix the memory-leak issue)) notification
* would be cleaner and could suport other lifecycle
* notifications (see above).
*/
FrameAppender.setFrame(frame);
configuration.addConfigurationListener(new ConfigurationListener() {
@Override
public void configurationChanged(ConfigurationEvent event) {
if ((!event.isBeforeUpdate())
&& PmsConfiguration.NEED_RELOAD_FLAGS.contains(event.getPropertyName())) {
frame.setReloadable(true);
}
}
});
frame.setStatusCode(0, Messages.getString("PMS.130"), "connect_no-220.png");
RendererConfiguration.loadRendererConfigurations(configuration);
LOGGER.info("Checking MPlayer font cache. It can take a minute or so.");
checkProcessExistence("MPlayer", true, null, configuration.getMplayerPath(), "dummy");
if (isWindows()) {
checkProcessExistence("MPlayer", true, configuration.getTempFolder(), configuration.getMplayerPath(), "dummy");
}
LOGGER.info("Done!");
// check the existence of Vsfilter.dll
if (registry.isAvis() && registry.getAvsPluginsDir() != null) {
LOGGER.info("Found AviSynth plugins dir: " + registry.getAvsPluginsDir().getAbsolutePath());
File vsFilterdll = new File(registry.getAvsPluginsDir(), "VSFilter.dll");
if (!vsFilterdll.exists()) {
LOGGER.info("VSFilter.dll is not in the AviSynth plugins directory. This can cause problems when trying to play subtitled videos with AviSynth");
}
}
// Check if VLC is found
String vlcVersion = registry.getVlcVersion();
String vlcPath = registry.getVlcPath();
if (vlcVersion != null && vlcPath != null) {
LOGGER.info("Found VLC version " + vlcVersion + " at: " + vlcPath);
Version vlc = new Version(vlcVersion);
Version requiredVersion = new Version("2.0.2");
if (vlc.compareTo(requiredVersion) <= 0) {
LOGGER.error("Only VLC versions 2.0.2 and above are supported");
}
}
// check if Kerio is installed
if (registry.isKerioFirewall()) {
LOGGER.info("Detected Kerio firewall");
}
// force use of specific dvr ms muxer when it's installed in the right place
File dvrsMsffmpegmuxer = new File("win32/dvrms/ffmpeg_MPGMUX.exe");
if (dvrsMsffmpegmuxer.exists()) {
configuration.setFfmpegAlternativePath(dvrsMsffmpegmuxer.getAbsolutePath());
}
// disable jaudiotagger logging
LogManager.getLogManager().readConfiguration(new ByteArrayInputStream("org.jaudiotagger.level=OFF".getBytes()));
// wrap System.err
System.setErr(new PrintStream(new SystemErrWrapper(), true));
server = new HTTPServer(configuration.getServerPort());
/*
* XXX: keep this here (i.e. after registerExtensions and before registerPlayers) so that plugins
* can register custom players correctly (e.g. in the GUI) and/or add/replace custom formats
*
* XXX: if a plugin requires initialization/notification even earlier than
* this, then a new external listener implementing a new callback should be added
* e.g. StartupListener.registeredExtensions()
*/
try {
ExternalFactory.lookup();
} catch (Exception e) {
LOGGER.error("Error loading plugins", e);
}
// a static block in Player doesn't work (i.e. is called too late).
// this must always be called *after* the plugins have loaded.
// here's as good a place as any
Player.initializeFinalizeTranscoderArgsListeners();
// Initialize a player factory to register all players
PlayerFactory.initialize(configuration);
// Instantiate listeners that require registered players.
ExternalFactory.instantiateLateListeners();
// Any plugin-defined players are now registered, create the GUI view.
frame.addEngines();
boolean binding = false;
try {
binding = server.start();
} catch (BindException b) {
LOGGER.info("FATAL ERROR: Unable to bind on port: " + configuration.getServerPort() + ", because: " + b.getMessage());
LOGGER.info("Maybe another process is running or the hostname is wrong.");
}
new Thread("Connection Checker") {
@Override
public void run() {
try {
Thread.sleep(7000);
} catch (InterruptedException e) { }
if (foundRenderers.isEmpty()) {
frame.setStatusCode(0, Messages.getString("PMS.0"), "messagebox_critical-220.png");
} else {
frame.setStatusCode(0, Messages.getString("PMS.18"), "apply-220.png");
}
}
}.start();
if (!binding) {
return false;
}
// initialize the cache
if (configuration.getUseCache()) {
initializeDatabase(); // XXX: this must be done *before* new MediaLibrary -> new MediaLibraryFolder
mediaLibrary = new MediaLibrary();
LOGGER.info("A tiny cache admin interface is available at: http://" + server.getHost() + ":" + server.getPort() + "/console/home");
}
// XXX: this must be called:
// a) *after* loading plugins i.e. plugins register root folders then RootFolder.discoverChildren adds them
// b) *after* mediaLibrary is initialized, if enabled (above)
getRootFolder(RendererConfiguration.getDefaultConf());
frame.serverReady();
// UPNPHelper.sendByeBye();
Runtime.getRuntime().addShutdownHook(new Thread("PMS Listeners Stopper") {
@Override
public void run() {
try {
for (ExternalListener l : ExternalFactory.getExternalListeners()) {
l.shutdown();
}
UPNPHelper.shutDownListener();
UPNPHelper.sendByeBye();
LOGGER.debug("Forcing shutdown of all active processes");
for (Process p : currentProcesses) {
try {
p.exitValue();
} catch (IllegalThreadStateException ise) {
LOGGER.trace("Forcing shutdown of process: " + p);
ProcessUtil.destroy(p);
}
}
get().getServer().stop();
Thread.sleep(500);
} catch (InterruptedException e) {
LOGGER.debug("Caught exception", e);
}
}
});
UPNPHelper.sendAlive();
LOGGER.trace("Waiting 250 milliseconds...");
Thread.sleep(250);
UPNPHelper.listen();
return true;
}
| private boolean init() throws Exception {
// The public VERSION field is deprecated.
// This is a temporary fix for backwards compatibility
VERSION = getVersion();
// call this as early as possible
displayBanner();
AutoUpdater autoUpdater = null;
if (Build.isUpdatable()) {
String serverURL = Build.getUpdateServerURL();
autoUpdater = new AutoUpdater(serverURL, getVersion());
}
registry = createSystemUtils();
if (System.getProperty(CONSOLE) == null) {
frame = new LooksFrame(autoUpdater, configuration);
} else {
LOGGER.info("GUI environment not available");
LOGGER.info("Switching to console mode");
frame = new DummyFrame();
}
/*
* we're here:
*
* main() -> createInstance() -> init()
*
* which means we haven't created the instance returned by get()
* yet, so the frame appender can't access the frame in the
* standard way i.e. PMS.get().getFrame(). we solve it by
* inverting control ("don't call us; we'll call you") i.e.
* we notify the appender when the frame is ready rather than
* e.g. making getFrame() static and requiring the frame
* appender to poll it.
*
* XXX an event bus (e.g. MBassador or Guava EventBus
* (if they fix the memory-leak issue)) notification
* would be cleaner and could support other lifecycle
* notifications (see above).
*/
FrameAppender.setFrame(frame);
configuration.addConfigurationListener(new ConfigurationListener() {
@Override
public void configurationChanged(ConfigurationEvent event) {
if ((!event.isBeforeUpdate())
&& PmsConfiguration.NEED_RELOAD_FLAGS.contains(event.getPropertyName())) {
frame.setReloadable(true);
}
}
});
frame.setStatusCode(0, Messages.getString("PMS.130"), "connect_no-220.png");
RendererConfiguration.loadRendererConfigurations(configuration);
LOGGER.info("Checking MPlayer font cache. It can take a minute or so.");
checkProcessExistence("MPlayer", true, null, configuration.getMplayerPath(), "dummy");
if (isWindows()) {
checkProcessExistence("MPlayer", true, configuration.getTempFolder(), configuration.getMplayerPath(), "dummy");
}
LOGGER.info("Done!");
// check the existence of Vsfilter.dll
if (registry.isAvis() && registry.getAvsPluginsDir() != null) {
LOGGER.info("Found AviSynth plugins dir: " + registry.getAvsPluginsDir().getAbsolutePath());
File vsFilterdll = new File(registry.getAvsPluginsDir(), "VSFilter.dll");
if (!vsFilterdll.exists()) {
LOGGER.info("VSFilter.dll is not in the AviSynth plugins directory. This can cause problems when trying to play subtitled videos with AviSynth");
}
}
// Check if VLC is found
String vlcVersion = registry.getVlcVersion();
String vlcPath = registry.getVlcPath();
if (vlcVersion != null && vlcPath != null) {
LOGGER.info("Found VLC version " + vlcVersion + " at: " + vlcPath);
Version vlc = new Version(vlcVersion);
Version requiredVersion = new Version("2.0.2");
if (vlc.compareTo(requiredVersion) <= 0) {
LOGGER.error("Only VLC versions 2.0.2 and above are supported");
}
}
// check if Kerio is installed
if (registry.isKerioFirewall()) {
LOGGER.info("Detected Kerio firewall");
}
// force use of specific dvr ms muxer when it's installed in the right place
File dvrsMsffmpegmuxer = new File("win32/dvrms/ffmpeg_MPGMUX.exe");
if (dvrsMsffmpegmuxer.exists()) {
configuration.setFfmpegAlternativePath(dvrsMsffmpegmuxer.getAbsolutePath());
}
// disable jaudiotagger logging
LogManager.getLogManager().readConfiguration(new ByteArrayInputStream("org.jaudiotagger.level=OFF".getBytes()));
// wrap System.err
System.setErr(new PrintStream(new SystemErrWrapper(), true));
server = new HTTPServer(configuration.getServerPort());
/*
* XXX: keep this here (i.e. after registerExtensions and before registerPlayers) so that plugins
* can register custom players correctly (e.g. in the GUI) and/or add/replace custom formats
*
* XXX: if a plugin requires initialization/notification even earlier than
* this, then a new external listener implementing a new callback should be added
* e.g. StartupListener.registeredExtensions()
*/
try {
ExternalFactory.lookup();
} catch (Exception e) {
LOGGER.error("Error loading plugins", e);
}
// a static block in Player doesn't work (i.e. is called too late).
// this must always be called *after* the plugins have loaded.
// here's as good a place as any
Player.initializeFinalizeTranscoderArgsListeners();
// Initialize a player factory to register all players
PlayerFactory.initialize(configuration);
// Instantiate listeners that require registered players.
ExternalFactory.instantiateLateListeners();
// Any plugin-defined players are now registered, create the GUI view.
frame.addEngines();
boolean binding = false;
try {
binding = server.start();
} catch (BindException b) {
LOGGER.info("FATAL ERROR: Unable to bind on port: " + configuration.getServerPort() + ", because: " + b.getMessage());
LOGGER.info("Maybe another process is running or the hostname is wrong.");
}
new Thread("Connection Checker") {
@Override
public void run() {
try {
Thread.sleep(7000);
} catch (InterruptedException e) { }
if (foundRenderers.isEmpty()) {
frame.setStatusCode(0, Messages.getString("PMS.0"), "messagebox_critical-220.png");
} else {
frame.setStatusCode(0, Messages.getString("PMS.18"), "apply-220.png");
}
}
}.start();
if (!binding) {
return false;
}
// initialize the cache
if (configuration.getUseCache()) {
initializeDatabase(); // XXX: this must be done *before* new MediaLibrary -> new MediaLibraryFolder
mediaLibrary = new MediaLibrary();
LOGGER.info("A tiny cache admin interface is available at: http://" + server.getHost() + ":" + server.getPort() + "/console/home");
}
// XXX: this must be called:
// a) *after* loading plugins i.e. plugins register root folders then RootFolder.discoverChildren adds them
// b) *after* mediaLibrary is initialized, if enabled (above)
getRootFolder(RendererConfiguration.getDefaultConf());
frame.serverReady();
// UPNPHelper.sendByeBye();
Runtime.getRuntime().addShutdownHook(new Thread("PMS Listeners Stopper") {
@Override
public void run() {
try {
for (ExternalListener l : ExternalFactory.getExternalListeners()) {
l.shutdown();
}
UPNPHelper.shutDownListener();
UPNPHelper.sendByeBye();
LOGGER.debug("Forcing shutdown of all active processes");
for (Process p : currentProcesses) {
try {
p.exitValue();
} catch (IllegalThreadStateException ise) {
LOGGER.trace("Forcing shutdown of process: " + p);
ProcessUtil.destroy(p);
}
}
get().getServer().stop();
Thread.sleep(500);
} catch (InterruptedException e) {
LOGGER.debug("Caught exception", e);
}
}
});
UPNPHelper.sendAlive();
LOGGER.trace("Waiting 250 milliseconds...");
Thread.sleep(250);
UPNPHelper.listen();
return true;
}
|
diff --git a/src/test/java/edu/northwestern/bioinformatics/studycalendar/service/NotificationServiceTest.java b/src/test/java/edu/northwestern/bioinformatics/studycalendar/service/NotificationServiceTest.java
index fa7a75dcd..9789434e6 100644
--- a/src/test/java/edu/northwestern/bioinformatics/studycalendar/service/NotificationServiceTest.java
+++ b/src/test/java/edu/northwestern/bioinformatics/studycalendar/service/NotificationServiceTest.java
@@ -1,44 +1,45 @@
package edu.northwestern.bioinformatics.studycalendar.service;
import edu.northwestern.bioinformatics.studycalendar.dao.StudySubjectAssignmentDao;
import edu.northwestern.bioinformatics.studycalendar.domain.StudySubjectAssignment;
import edu.northwestern.bioinformatics.studycalendar.testing.StudyCalendarTestCase;
import org.easymock.classextension.EasyMock;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author Saurabh Agrawal
*/
public class NotificationServiceTest extends StudyCalendarTestCase {
private NotificationService notificationService;
private StudySubjectAssignmentDao studySubjectAssignmentDao;
private Integer numberOfDays;
@Override
protected void setUp() throws Exception {
super.setUp();
studySubjectAssignmentDao = registerDaoMockFor(StudySubjectAssignmentDao.class);
numberOfDays = 14;
notificationService = new NotificationService();
notificationService.setNumberOfDays(numberOfDays);
notificationService.setStudySubjectAssignmentDao(studySubjectAssignmentDao);
}
public void testAddNotificationIfNothingIsScheduledForPatient() {
List<StudySubjectAssignment> studySubjectAssignments = new ArrayList<StudySubjectAssignment>();
StudySubjectAssignment studySubjectAssignment = new StudySubjectAssignment();
studySubjectAssignments.add(studySubjectAssignment);
- org.easymock.EasyMock.expect(studySubjectAssignmentDao.getAllAssignmenetsWhichHaveNoActivityBeyondADate(EasyMock.isA(Date.class))).andReturn(studySubjectAssignments);
+ EasyMock.expect(studySubjectAssignmentDao.getAllAssignmenetsWhichHaveNoActivityBeyondADate(EasyMock.isA(Date.class))).andReturn(studySubjectAssignments);
+ studySubjectAssignmentDao.save(studySubjectAssignment);
replayMocks();
notificationService.addNotificationIfNothingIsScheduledForPatient();
verifyMocks();
assertEquals("assignment must have one notification", 1, studySubjectAssignment.getNotifications().size());
}
}
| true | true | public void testAddNotificationIfNothingIsScheduledForPatient() {
List<StudySubjectAssignment> studySubjectAssignments = new ArrayList<StudySubjectAssignment>();
StudySubjectAssignment studySubjectAssignment = new StudySubjectAssignment();
studySubjectAssignments.add(studySubjectAssignment);
org.easymock.EasyMock.expect(studySubjectAssignmentDao.getAllAssignmenetsWhichHaveNoActivityBeyondADate(EasyMock.isA(Date.class))).andReturn(studySubjectAssignments);
replayMocks();
notificationService.addNotificationIfNothingIsScheduledForPatient();
verifyMocks();
assertEquals("assignment must have one notification", 1, studySubjectAssignment.getNotifications().size());
}
| public void testAddNotificationIfNothingIsScheduledForPatient() {
List<StudySubjectAssignment> studySubjectAssignments = new ArrayList<StudySubjectAssignment>();
StudySubjectAssignment studySubjectAssignment = new StudySubjectAssignment();
studySubjectAssignments.add(studySubjectAssignment);
EasyMock.expect(studySubjectAssignmentDao.getAllAssignmenetsWhichHaveNoActivityBeyondADate(EasyMock.isA(Date.class))).andReturn(studySubjectAssignments);
studySubjectAssignmentDao.save(studySubjectAssignment);
replayMocks();
notificationService.addNotificationIfNothingIsScheduledForPatient();
verifyMocks();
assertEquals("assignment must have one notification", 1, studySubjectAssignment.getNotifications().size());
}
|
diff --git a/zeppelin-zengine/src/main/java/com/nflabs/zeppelin/util/Util.java b/zeppelin-zengine/src/main/java/com/nflabs/zeppelin/util/Util.java
index d955e0ff..51efb270 100644
--- a/zeppelin-zengine/src/main/java/com/nflabs/zeppelin/util/Util.java
+++ b/zeppelin-zengine/src/main/java/com/nflabs/zeppelin/util/Util.java
@@ -1,163 +1,163 @@
package com.nflabs.zeppelin.util;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Util {
public static String [] split(String str, char split){
return split(str, new String[]{String.valueOf(split)}, false);
}
public static String [] split(String str, String [] splitters, boolean includeSplitter){
String escapeSeq = "\"',;<%>";
char escapeChar = '\\';
String [] blockStart = new String[]{ "\"", "'", "<%", "N_<"};
String [] blockEnd = new String[]{ "\"", "'", "%>", "N_>"};
return split(str, escapeSeq, escapeChar, blockStart, blockEnd, splitters, includeSplitter);
}
public static String [] split(
String str,
String escapeSeq,
char escapeChar,
String [] blockStart,
String [] blockEnd,
String [] splitters,
boolean includeSplitter
){
List<String> splits = new ArrayList<String>();
String curString ="";
boolean escape = false; // true when escape char is found
int lastEscapeOffset = -1;
int blockStartPos = -1;
List<Integer> blockStack = new LinkedList<Integer>();
for(int i=0; i<str.length();i++){
char c = str.charAt(i);
// escape char detected
if(c==escapeChar && escape == false){
escape = true;
continue;
}
// escaped char comes
if(escape==true){
if(escapeSeq.indexOf(c)<0){
curString += escapeChar;
}
curString += c;
escape = false;
- lastEscapeOffset = i;
+ lastEscapeOffset = curString.length();
continue;
}
if(blockStack.size()>0){ // inside of block
curString += c;
// check multichar block
boolean multicharBlockDetected = false;
for(int b=0; b<blockStart.length; b++){
if(blockStartPos>=0 && getBlockStr(blockStart[b]).compareTo(str.substring(blockStartPos, i))==0){
blockStack.remove(0);
blockStack.add(0, b);
multicharBlockDetected = true;
break;
}
}
if(multicharBlockDetected==true) continue;
// check if current block is nestable
if(isNestedBlock(blockStart[blockStack.get(0)])==true){
// try to find nested block start
if(curString.substring(lastEscapeOffset+1).endsWith(getBlockStr(blockStart[blockStack.get(0)]))==true){
blockStack.add(0, blockStack.get(0)); // block is started
blockStartPos = i;
continue;
}
}
// check if block is finishing
if(curString.substring(lastEscapeOffset+1).endsWith(getBlockStr(blockEnd[blockStack.get(0)]))){
// the block closer is one of the splitters (and not nested block)
if(isNestedBlock(blockEnd[blockStack.get(0)])==false){
for(String splitter : splitters){
if(splitter.compareTo(getBlockStr(blockEnd[blockStack.get(0)]))==0){
splits.add(curString);
if(includeSplitter==true){
splits.add(splitter);
}
curString = "";
lastEscapeOffset = -1;
break;
}
}
}
blockStartPos = -1;
blockStack.remove(0);
continue;
}
} else { // not in the block
boolean splitted = false;
for(String splitter : splitters){
// forward check for splitter
if(splitter.compareTo(str.substring(i, Math.min(i+splitter.length(), str.length())))==0){
splits.add(curString);
if(includeSplitter==true){
splits.add(splitter);
}
curString = "";
lastEscapeOffset = -1;
i+=splitter.length()-1;
splitted = true;
break;
}
}
if(splitted == true){
continue;
}
// add char to current string
curString += c;
// check if block is started
for(int b=0; b<blockStart.length;b++){
if(curString.substring(lastEscapeOffset+1).endsWith(getBlockStr(blockStart[b]))==true){
blockStack.add(0, b); // block is started
blockStartPos = i;
break;
}
}
}
}
if(curString.length()>0)
splits.add(curString.trim());
return splits.toArray(new String[]{});
}
private static String getBlockStr(String blockDef){
if(blockDef.startsWith("N_")){
return blockDef.substring("N_".length());
} else {
return blockDef;
}
}
private static boolean isNestedBlock(String blockDef){
if(blockDef.startsWith("N_")){
return true;
} else {
return false;
}
}
}
| true | true | public static String [] split(
String str,
String escapeSeq,
char escapeChar,
String [] blockStart,
String [] blockEnd,
String [] splitters,
boolean includeSplitter
){
List<String> splits = new ArrayList<String>();
String curString ="";
boolean escape = false; // true when escape char is found
int lastEscapeOffset = -1;
int blockStartPos = -1;
List<Integer> blockStack = new LinkedList<Integer>();
for(int i=0; i<str.length();i++){
char c = str.charAt(i);
// escape char detected
if(c==escapeChar && escape == false){
escape = true;
continue;
}
// escaped char comes
if(escape==true){
if(escapeSeq.indexOf(c)<0){
curString += escapeChar;
}
curString += c;
escape = false;
lastEscapeOffset = i;
continue;
}
if(blockStack.size()>0){ // inside of block
curString += c;
// check multichar block
boolean multicharBlockDetected = false;
for(int b=0; b<blockStart.length; b++){
if(blockStartPos>=0 && getBlockStr(blockStart[b]).compareTo(str.substring(blockStartPos, i))==0){
blockStack.remove(0);
blockStack.add(0, b);
multicharBlockDetected = true;
break;
}
}
if(multicharBlockDetected==true) continue;
// check if current block is nestable
if(isNestedBlock(blockStart[blockStack.get(0)])==true){
// try to find nested block start
if(curString.substring(lastEscapeOffset+1).endsWith(getBlockStr(blockStart[blockStack.get(0)]))==true){
blockStack.add(0, blockStack.get(0)); // block is started
blockStartPos = i;
continue;
}
}
// check if block is finishing
if(curString.substring(lastEscapeOffset+1).endsWith(getBlockStr(blockEnd[blockStack.get(0)]))){
// the block closer is one of the splitters (and not nested block)
if(isNestedBlock(blockEnd[blockStack.get(0)])==false){
for(String splitter : splitters){
if(splitter.compareTo(getBlockStr(blockEnd[blockStack.get(0)]))==0){
splits.add(curString);
if(includeSplitter==true){
splits.add(splitter);
}
curString = "";
lastEscapeOffset = -1;
break;
}
}
}
blockStartPos = -1;
blockStack.remove(0);
continue;
}
} else { // not in the block
boolean splitted = false;
for(String splitter : splitters){
// forward check for splitter
if(splitter.compareTo(str.substring(i, Math.min(i+splitter.length(), str.length())))==0){
splits.add(curString);
if(includeSplitter==true){
splits.add(splitter);
}
curString = "";
lastEscapeOffset = -1;
i+=splitter.length()-1;
splitted = true;
break;
}
}
if(splitted == true){
continue;
}
// add char to current string
curString += c;
// check if block is started
for(int b=0; b<blockStart.length;b++){
if(curString.substring(lastEscapeOffset+1).endsWith(getBlockStr(blockStart[b]))==true){
blockStack.add(0, b); // block is started
blockStartPos = i;
break;
}
}
}
}
if(curString.length()>0)
splits.add(curString.trim());
return splits.toArray(new String[]{});
}
| public static String [] split(
String str,
String escapeSeq,
char escapeChar,
String [] blockStart,
String [] blockEnd,
String [] splitters,
boolean includeSplitter
){
List<String> splits = new ArrayList<String>();
String curString ="";
boolean escape = false; // true when escape char is found
int lastEscapeOffset = -1;
int blockStartPos = -1;
List<Integer> blockStack = new LinkedList<Integer>();
for(int i=0; i<str.length();i++){
char c = str.charAt(i);
// escape char detected
if(c==escapeChar && escape == false){
escape = true;
continue;
}
// escaped char comes
if(escape==true){
if(escapeSeq.indexOf(c)<0){
curString += escapeChar;
}
curString += c;
escape = false;
lastEscapeOffset = curString.length();
continue;
}
if(blockStack.size()>0){ // inside of block
curString += c;
// check multichar block
boolean multicharBlockDetected = false;
for(int b=0; b<blockStart.length; b++){
if(blockStartPos>=0 && getBlockStr(blockStart[b]).compareTo(str.substring(blockStartPos, i))==0){
blockStack.remove(0);
blockStack.add(0, b);
multicharBlockDetected = true;
break;
}
}
if(multicharBlockDetected==true) continue;
// check if current block is nestable
if(isNestedBlock(blockStart[blockStack.get(0)])==true){
// try to find nested block start
if(curString.substring(lastEscapeOffset+1).endsWith(getBlockStr(blockStart[blockStack.get(0)]))==true){
blockStack.add(0, blockStack.get(0)); // block is started
blockStartPos = i;
continue;
}
}
// check if block is finishing
if(curString.substring(lastEscapeOffset+1).endsWith(getBlockStr(blockEnd[blockStack.get(0)]))){
// the block closer is one of the splitters (and not nested block)
if(isNestedBlock(blockEnd[blockStack.get(0)])==false){
for(String splitter : splitters){
if(splitter.compareTo(getBlockStr(blockEnd[blockStack.get(0)]))==0){
splits.add(curString);
if(includeSplitter==true){
splits.add(splitter);
}
curString = "";
lastEscapeOffset = -1;
break;
}
}
}
blockStartPos = -1;
blockStack.remove(0);
continue;
}
} else { // not in the block
boolean splitted = false;
for(String splitter : splitters){
// forward check for splitter
if(splitter.compareTo(str.substring(i, Math.min(i+splitter.length(), str.length())))==0){
splits.add(curString);
if(includeSplitter==true){
splits.add(splitter);
}
curString = "";
lastEscapeOffset = -1;
i+=splitter.length()-1;
splitted = true;
break;
}
}
if(splitted == true){
continue;
}
// add char to current string
curString += c;
// check if block is started
for(int b=0; b<blockStart.length;b++){
if(curString.substring(lastEscapeOffset+1).endsWith(getBlockStr(blockStart[b]))==true){
blockStack.add(0, b); // block is started
blockStartPos = i;
break;
}
}
}
}
if(curString.length()>0)
splits.add(curString.trim());
return splits.toArray(new String[]{});
}
|
diff --git a/ij/gui/StackWindow.java b/ij/gui/StackWindow.java
index e1da874f..fc633694 100644
--- a/ij/gui/StackWindow.java
+++ b/ij/gui/StackWindow.java
@@ -1,262 +1,262 @@
package ij.gui;
import ij.*;
import ij.measure.Calibration;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
/** This class is an extended ImageWindow used to display image stacks. */
public class StackWindow extends ImageWindow implements Runnable, AdjustmentListener, ActionListener, MouseWheelListener {
protected Scrollbar sliceSelector; // for backward compatibity with Image5D
protected ScrollbarWithLabel cSelector, zSelector, tSelector;
protected Thread thread;
protected volatile boolean done;
protected volatile int slice;
private ScrollbarWithLabel animationSelector;
boolean hyperStack;
int nChannels=1, nSlices=1, nFrames=1;
int c=1, z=1, t=1;
public StackWindow(ImagePlus imp) {
this(imp, null);
}
public StackWindow(ImagePlus imp, ImageCanvas ic) {
super(imp, ic);
ImageStack s = imp.getStack();
int stackSize = s.getSize();
nSlices = stackSize;
hyperStack = imp.getOpenAsHyperStack();
imp.setOpenAsHyperStack(false);
int[] dim = imp.getDimensions();
int nDimensions = 2+(dim[2]>1?1:0)+(dim[3]>1?1:0)+(dim[4]>1?1:0);
if (nDimensions<=3 && dim[2]!=nSlices) hyperStack = false;
if (hyperStack) {
nChannels = dim[2];
nSlices = dim[3];
nFrames = dim[4];
}
//IJ.log("StackWindow: "+hyperStack+" "+nChannels+" "+nSlices+" "+nFrames);
if (nSlices==stackSize) hyperStack = false;
if (nChannels*nSlices*nFrames!=stackSize) hyperStack = false;
addMouseWheelListener(this);
ImageJ ij = IJ.getInstance();
if (nChannels>1) {
cSelector = new ScrollbarWithLabel(this, 1, 1, 1, nChannels+1, 'c');
add(cSelector);
if (ij!=null) cSelector.addKeyListener(ij);
cSelector.addAdjustmentListener(this);
cSelector.setFocusable(false); // prevents scroll bar from blinking on Windows
cSelector.setUnitIncrement(1);
cSelector.setBlockIncrement(1);
}
if (nSlices>1) {
- char label = nChannels>1||nFrames>1?'z':'t';
- if (nSlices==dim[2]) label = 'c';
- zSelector = new ScrollbarWithLabel(this, 1, 1, 1, nSlices+1, label);
- if (label=='t') animationSelector = zSelector;
+ //char label = nChannels>1||nFrames>1?'z':'t';
+ //if (nSlices==dim[2]) label = 'c';
+ zSelector = new ScrollbarWithLabel(this, 1, 1, 1, nSlices+1, 'z');
+ //if (label=='t') animationSelector = zSelector;
add(zSelector);
if (ij!=null) zSelector.addKeyListener(ij);
zSelector.addAdjustmentListener(this);
zSelector.setFocusable(false);
int blockIncrement = nSlices/10;
if (blockIncrement<1) blockIncrement = 1;
zSelector.setUnitIncrement(1);
zSelector.setBlockIncrement(blockIncrement);
sliceSelector = zSelector.bar;
}
if (nFrames>1) {
animationSelector = tSelector = new ScrollbarWithLabel(this, 1, 1, 1, nFrames+1, 't');
add(tSelector);
if (ij!=null) tSelector.addKeyListener(ij);
tSelector.addAdjustmentListener(this);
tSelector.setFocusable(false);
int blockIncrement = nFrames/10;
if (blockIncrement<1) blockIncrement = 1;
tSelector.setUnitIncrement(1);
tSelector.setBlockIncrement(blockIncrement);
}
if (sliceSelector==null && this.getClass().getName().indexOf("Image5D")!=-1)
sliceSelector = new Scrollbar(); // prevents Image5D from crashing
//IJ.log(nChannels+" "+nSlices+" "+nFrames);
pack();
ic = imp.getCanvas();
if (ic!=null) ic.setMaxBounds();
show();
int previousSlice = imp.getCurrentSlice();
if (previousSlice>1 && previousSlice<=stackSize)
imp.setSlice(previousSlice);
else
imp.setSlice(1);
thread = new Thread(this, "zSelector");
thread.start();
}
public synchronized void adjustmentValueChanged(AdjustmentEvent e) {
if (!running2) {
if (e.getSource()==cSelector) {
c = cSelector.getValue();
if (c==imp.getChannel()&&e.getAdjustmentType()==AdjustmentEvent.TRACK) return;
} else if (e.getSource()==zSelector) {
z = zSelector.getValue();
if (z==imp.getSlice()&&e.getAdjustmentType()==AdjustmentEvent.TRACK) return;
} else if (e.getSource()==tSelector) {
t = tSelector.getValue();
if (t==imp.getFrame()&&e.getAdjustmentType()==AdjustmentEvent.TRACK) return;
}
updatePosition();
notify();
}
}
void updatePosition() {
slice = (t-1)*nChannels*nSlices + (z-1)*nChannels + c;
imp.updatePosition(c, z, t);
}
public void actionPerformed(ActionEvent e) {
}
public void mouseWheelMoved(MouseWheelEvent event) {
synchronized(this) {
int rotation = event.getWheelRotation();
if (hyperStack) {
if (rotation>0)
IJ.runPlugIn("ij.plugin.Animator", "next");
else if (rotation<0)
IJ.runPlugIn("ij.plugin.Animator", "previous");
} else {
int slice = imp.getCurrentSlice() + rotation;
if (slice<1)
slice = 1;
else if (slice>imp.getStack().getSize())
slice = imp.getStack().getSize();
imp.setSlice(slice);
}
}
}
public boolean close() {
if (!super.close())
return false;
synchronized(this) {
done = true;
notify();
}
return true;
}
/** Displays the specified slice and updates the stack scrollbar. */
public void showSlice(int index) {
if (index>=1 && index<=imp.getStackSize())
imp.setSlice(index);
}
/** Updates the stack scrollbar. */
public void updateSliceSelector() {
if (hyperStack) return;
int stackSize = imp.getStackSize();
int max = zSelector.getMaximum();
if (max!=(stackSize+1))
zSelector.setMaximum(stackSize+1);
zSelector.setValue(imp.getCurrentSlice());
}
public void run() {
while (!done) {
synchronized(this) {
try {wait();}
catch(InterruptedException e) {}
}
if (done) return;
if (slice>0) {
int s = slice;
slice = 0;
if (s!=imp.getCurrentSlice())
imp.setSlice(s);
}
}
}
public String createSubtitle() {
String subtitle = super.createSubtitle();
if (!hyperStack) return subtitle;
String s="";
int[] dim = imp.getDimensions();
int channels=dim[2], slices=dim[3], frames=dim[4];
if (channels>1) {
s += "c:"+imp.getChannel()+"/"+channels;
if (slices>1||frames>1) s += " ";
}
if (slices>1) {
s += "z:"+imp.getSlice()+"/"+slices;
if (frames>1) s += " ";
}
if (frames>1)
s += "t:"+imp.getFrame()+"/"+frames;
if (running2) return s;
int index = subtitle.indexOf(";");
if (index!=-1) {
int index2 = subtitle.indexOf("(");
if (index2>=0 && index2<index && subtitle.length()>index2+4 && !subtitle.substring(index2+1, index2+4).equals("ch:")) {
index = index2;
s = s + " ";
}
subtitle = subtitle.substring(index, subtitle.length());
} else
subtitle = "";
return s + subtitle;
}
public boolean isHyperStack() {
return hyperStack;
}
public void setPosition(int channel, int slice, int frame) {
if (cSelector!=null && channel!=c) {
c = channel;
cSelector.setValue(channel);
}
if (zSelector!=null && slice!=z) {
z = slice;
zSelector.setValue(slice);
}
if (tSelector!=null && frame!=t) {
t = frame;
tSelector.setValue(frame);
}
updatePosition();
if (this.slice>0) {
int s = this.slice;
this.slice = 0;
if (s!=imp.getCurrentSlice())
imp.setSlice(s);
}
}
public boolean validDimensions() {
int c = imp.getNChannels();
int z = imp.getNSlices();
int t = imp.getNFrames();
if (c!=nChannels||z!=nSlices||t!=nFrames||c*z*t!=imp.getStackSize())
return false;
else
return true;
}
public void setAnimate(boolean b) {
if (running2!=b && animationSelector!=null)
animationSelector.updatePlayPauseIcon();
running2 = b;
}
public boolean getAnimate() {
return running2;
}
public ScrollbarWithLabel getCSelector() { return cSelector; }
public ScrollbarWithLabel getZSelector() { return zSelector; }
public ScrollbarWithLabel getTSelector() { return tSelector; }
}
| true | true | public StackWindow(ImagePlus imp, ImageCanvas ic) {
super(imp, ic);
ImageStack s = imp.getStack();
int stackSize = s.getSize();
nSlices = stackSize;
hyperStack = imp.getOpenAsHyperStack();
imp.setOpenAsHyperStack(false);
int[] dim = imp.getDimensions();
int nDimensions = 2+(dim[2]>1?1:0)+(dim[3]>1?1:0)+(dim[4]>1?1:0);
if (nDimensions<=3 && dim[2]!=nSlices) hyperStack = false;
if (hyperStack) {
nChannels = dim[2];
nSlices = dim[3];
nFrames = dim[4];
}
//IJ.log("StackWindow: "+hyperStack+" "+nChannels+" "+nSlices+" "+nFrames);
if (nSlices==stackSize) hyperStack = false;
if (nChannels*nSlices*nFrames!=stackSize) hyperStack = false;
addMouseWheelListener(this);
ImageJ ij = IJ.getInstance();
if (nChannels>1) {
cSelector = new ScrollbarWithLabel(this, 1, 1, 1, nChannels+1, 'c');
add(cSelector);
if (ij!=null) cSelector.addKeyListener(ij);
cSelector.addAdjustmentListener(this);
cSelector.setFocusable(false); // prevents scroll bar from blinking on Windows
cSelector.setUnitIncrement(1);
cSelector.setBlockIncrement(1);
}
if (nSlices>1) {
char label = nChannels>1||nFrames>1?'z':'t';
if (nSlices==dim[2]) label = 'c';
zSelector = new ScrollbarWithLabel(this, 1, 1, 1, nSlices+1, label);
if (label=='t') animationSelector = zSelector;
add(zSelector);
if (ij!=null) zSelector.addKeyListener(ij);
zSelector.addAdjustmentListener(this);
zSelector.setFocusable(false);
int blockIncrement = nSlices/10;
if (blockIncrement<1) blockIncrement = 1;
zSelector.setUnitIncrement(1);
zSelector.setBlockIncrement(blockIncrement);
sliceSelector = zSelector.bar;
}
if (nFrames>1) {
animationSelector = tSelector = new ScrollbarWithLabel(this, 1, 1, 1, nFrames+1, 't');
add(tSelector);
if (ij!=null) tSelector.addKeyListener(ij);
tSelector.addAdjustmentListener(this);
tSelector.setFocusable(false);
int blockIncrement = nFrames/10;
if (blockIncrement<1) blockIncrement = 1;
tSelector.setUnitIncrement(1);
tSelector.setBlockIncrement(blockIncrement);
}
if (sliceSelector==null && this.getClass().getName().indexOf("Image5D")!=-1)
sliceSelector = new Scrollbar(); // prevents Image5D from crashing
//IJ.log(nChannels+" "+nSlices+" "+nFrames);
pack();
ic = imp.getCanvas();
if (ic!=null) ic.setMaxBounds();
show();
int previousSlice = imp.getCurrentSlice();
if (previousSlice>1 && previousSlice<=stackSize)
imp.setSlice(previousSlice);
else
imp.setSlice(1);
thread = new Thread(this, "zSelector");
thread.start();
}
| public StackWindow(ImagePlus imp, ImageCanvas ic) {
super(imp, ic);
ImageStack s = imp.getStack();
int stackSize = s.getSize();
nSlices = stackSize;
hyperStack = imp.getOpenAsHyperStack();
imp.setOpenAsHyperStack(false);
int[] dim = imp.getDimensions();
int nDimensions = 2+(dim[2]>1?1:0)+(dim[3]>1?1:0)+(dim[4]>1?1:0);
if (nDimensions<=3 && dim[2]!=nSlices) hyperStack = false;
if (hyperStack) {
nChannels = dim[2];
nSlices = dim[3];
nFrames = dim[4];
}
//IJ.log("StackWindow: "+hyperStack+" "+nChannels+" "+nSlices+" "+nFrames);
if (nSlices==stackSize) hyperStack = false;
if (nChannels*nSlices*nFrames!=stackSize) hyperStack = false;
addMouseWheelListener(this);
ImageJ ij = IJ.getInstance();
if (nChannels>1) {
cSelector = new ScrollbarWithLabel(this, 1, 1, 1, nChannels+1, 'c');
add(cSelector);
if (ij!=null) cSelector.addKeyListener(ij);
cSelector.addAdjustmentListener(this);
cSelector.setFocusable(false); // prevents scroll bar from blinking on Windows
cSelector.setUnitIncrement(1);
cSelector.setBlockIncrement(1);
}
if (nSlices>1) {
//char label = nChannels>1||nFrames>1?'z':'t';
//if (nSlices==dim[2]) label = 'c';
zSelector = new ScrollbarWithLabel(this, 1, 1, 1, nSlices+1, 'z');
//if (label=='t') animationSelector = zSelector;
add(zSelector);
if (ij!=null) zSelector.addKeyListener(ij);
zSelector.addAdjustmentListener(this);
zSelector.setFocusable(false);
int blockIncrement = nSlices/10;
if (blockIncrement<1) blockIncrement = 1;
zSelector.setUnitIncrement(1);
zSelector.setBlockIncrement(blockIncrement);
sliceSelector = zSelector.bar;
}
if (nFrames>1) {
animationSelector = tSelector = new ScrollbarWithLabel(this, 1, 1, 1, nFrames+1, 't');
add(tSelector);
if (ij!=null) tSelector.addKeyListener(ij);
tSelector.addAdjustmentListener(this);
tSelector.setFocusable(false);
int blockIncrement = nFrames/10;
if (blockIncrement<1) blockIncrement = 1;
tSelector.setUnitIncrement(1);
tSelector.setBlockIncrement(blockIncrement);
}
if (sliceSelector==null && this.getClass().getName().indexOf("Image5D")!=-1)
sliceSelector = new Scrollbar(); // prevents Image5D from crashing
//IJ.log(nChannels+" "+nSlices+" "+nFrames);
pack();
ic = imp.getCanvas();
if (ic!=null) ic.setMaxBounds();
show();
int previousSlice = imp.getCurrentSlice();
if (previousSlice>1 && previousSlice<=stackSize)
imp.setSlice(previousSlice);
else
imp.setSlice(1);
thread = new Thread(this, "zSelector");
thread.start();
}
|
diff --git a/webapp/java/uk/ac/ed/ph/mathplayground/webapp/LaTeXInputServlet.java b/webapp/java/uk/ac/ed/ph/mathplayground/webapp/LaTeXInputServlet.java
index 58917dd..54d80b9 100644
--- a/webapp/java/uk/ac/ed/ph/mathplayground/webapp/LaTeXInputServlet.java
+++ b/webapp/java/uk/ac/ed/ph/mathplayground/webapp/LaTeXInputServlet.java
@@ -1,241 +1,246 @@
/* $Id:TryOutServlet.java 158 2008-07-31 10:48:14Z davemckain $
*
* Copyright 2008 University of Edinburgh.
* All Rights Reserved
*/
package uk.ac.ed.ph.mathplayground.webapp;
import uk.ac.ed.ph.mathplayground.RawMaximaSession;
import uk.ac.ed.ph.snuggletex.DOMOutputOptions;
import uk.ac.ed.ph.snuggletex.InputError;
import uk.ac.ed.ph.snuggletex.MathMLWebPageOptions;
import uk.ac.ed.ph.snuggletex.SnuggleEngine;
import uk.ac.ed.ph.snuggletex.SnuggleInput;
import uk.ac.ed.ph.snuggletex.SnuggleSession;
import uk.ac.ed.ph.snuggletex.DOMOutputOptions.ErrorOutputOptions;
import uk.ac.ed.ph.snuggletex.MathMLWebPageOptions.WebPageType;
import uk.ac.ed.ph.snuggletex.definitions.Globals;
import uk.ac.ed.ph.snuggletex.internal.XMLUtilities;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Trivial servlet demonstrating the conversion of LaTeX input into other forms.
*
* @author David McKain
* @version $Revision:158 $
*/
public final class LaTeXInputServlet extends BaseServlet {
private static final long serialVersionUID = 4376587500238353176L;
/** Logger so that we can log what users are trying out to allow us to improve things */
private Logger log = Logger.getLogger(LaTeXInputServlet.class);
/** Location of XSLT controlling page layout */
public static final String LATEX_INPUT_XSLT_LOCATION = "/WEB-INF/latexinput.xsl";
public static final String PMATHML_TO_CMATHML_LOCATION = "/WEB-INF/pmathml-to-cmathml.xsl";
public static final String CMATHML_TO_MAXIMA_LOCATION = "/WEB-INF/cmathml-to-maxima.xsl";
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
doRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doRequest(request, response);
}
private void doRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/* Read in input LaTeX, using some placeholder text if nothing was provided */
String rawInputLaTeX = request.getParameter("input");
String resultingInputLaTeX;
if (rawInputLaTeX!=null) {
/* Tidy up line endings */
resultingInputLaTeX = rawInputLaTeX.replaceAll("(\r\n|\r|\n)", "\n");
}
else {
/* Use some default input */
resultingInputLaTeX = "1+x";
}
/* Parse the LaTeX */
SnuggleEngine engine = new SnuggleEngine();
SnuggleSession session = engine.createSession();
/* NOTE: Must turn on inference of Math structure here */
session.getConfiguration().setInferringMathStructure(true);
SnuggleInput input = new SnuggleInput("\\[ " + resultingInputLaTeX + " \\]", "Form Input");
session.parseInput(input);
/* Set up web output options */
MathMLWebPageOptions options = new MathMLWebPageOptions();
options.setMathVariantMapping(true);
options.setAddingMathAnnotations(true);
options.setPageType(WebPageType.CROSS_BROWSER_XHTML);
options.setErrorOutputOptions(ErrorOutputOptions.XHTML);
options.setTitle("LaTeX to MathML and Maxima");
options.setAddingTitleHeading(false); /* We'll put our own title in */
options.setIndenting(true);
options.setCSSStylesheetURLs(
request.getContextPath() + "/includes/physics.css"
);
/* Get text results */
String[] resultArray;
try {
resultArray = createOutputXMLStrings(session, options);
}
catch (Exception e) {
throw new ServletException(e);
}
/* Log what was done */
- log.info("Results:\nInput: " + resultingInputLaTeX
- + "\nPMathML: " + resultArray[0]
- + "\nCMathML: " + resultArray[1]
- + "\nMaxima Input: " + resultArray[2]
- + "\nMaxima Output: " + resultArray[3]
- + "\n======================================");
+ if (resultArray!=null) {
+ log.info("Success Result:\nInput: " + resultingInputLaTeX
+ + "\nPMathML: " + resultArray[0]
+ + "\nCMathML: " + resultArray[1]
+ + "\nMaxima Input: " + resultArray[2]
+ + "\nMaxima Output: " + resultArray[3]
+ + "\n======================================");
+ }
+ else {
+ log.warn("Failed on input " + resultingInputLaTeX);
+ }
/* Create XSLT to generate the resulting page */
Transformer viewStylesheet;
try {
viewStylesheet = compileStylesheet(LATEX_INPUT_XSLT_LOCATION).newTransformer();
viewStylesheet.setParameter("context-path", request.getContextPath());
viewStylesheet.setParameter("latex-input", resultingInputLaTeX);
if (resultArray!=null) {
viewStylesheet.setParameter("pmathml", resultArray[0]);
viewStylesheet.setParameter("cmathml", resultArray[1]);
viewStylesheet.setParameter("maxima-input", resultArray[2]);
viewStylesheet.setParameter("maxima-output", resultArray[3]);
}
}
catch (TransformerConfigurationException e) {
throw new ServletException("Could not create stylesheet from Templates", e);
}
options.setStylesheet(viewStylesheet);
/* Generate and serve the resulting web page */
try {
session.writeWebPage(options, response, response.getOutputStream());
}
catch (Exception e) {
throw new ServletException("Unexpected Exception", e);
}
}
private String[] createOutputXMLStrings(SnuggleSession session, DOMOutputOptions options)
throws ServletException, TransformerException {
/* Create MathML doc with temp fake root */
DocumentBuilder documentBuilder = XMLUtilities.createNSAwareDocumentBuilder();
Document pmathmlDocument = documentBuilder.newDocument();
Element temporaryRoot = pmathmlDocument.createElementNS(Globals.MATHML_NAMESPACE, "temp");
pmathmlDocument.appendChild(temporaryRoot);
/* Build document content using SnuggleTeX */
session.buildDOMSubtree(temporaryRoot, options);
/* See if there were any errors */
List<InputError> errors = session.getErrors();
if (!errors.isEmpty()) {
return null;
}
/* If no errors, make sure we got a single <math/> element */
NodeList nodeList = temporaryRoot.getChildNodes();
if (nodeList.getLength()!=1) {
throw new RuntimeException("Expected SnuggleTeX output to be a single <math/> element");
}
Node resultNode = nodeList.item(0);
if (resultNode.getNodeType()!=Node.ELEMENT_NODE && !resultNode.getLocalName().equals("math")) {
throw new RuntimeException("Expected SnuggleTeX output to be a single <math/> element");
}
/* Make the <math/> element the new document root */
Element mathmlElement = (Element) resultNode;
pmathmlDocument.removeChild(temporaryRoot);
pmathmlDocument.appendChild(mathmlElement);
/* Try to convert to Content MathML */
Document cmathmlDocument = documentBuilder.newDocument();
Transformer ptocStylesheet = compileStylesheet(PMATHML_TO_CMATHML_LOCATION).newTransformer();
ptocStylesheet.transform(new DOMSource(pmathmlDocument), new DOMResult(cmathmlDocument));
/* Serialise P and C MathML for geeks */
TransformerFactory transformerFactory = XMLUtilities.createTransformerFactory();
StringWriter pmathmlWriter = new StringWriter();
StringWriter cmathmlWriter = new StringWriter();
createSerializer(transformerFactory).transform(new DOMSource(pmathmlDocument), new StreamResult(pmathmlWriter));
createSerializer(transformerFactory).transform(new DOMSource(cmathmlDocument), new StreamResult(cmathmlWriter));
String pmathml = pmathmlWriter.toString();
String cmathml = cmathmlWriter.toString();
/* Hunt out any failure annotation.
* TODO: Should use XPath for this!
*/
String maximaInput;
String maximaOutput;
if (cmathml.indexOf("Presentation-to-Content-MathML-failure")!=-1) {
maximaInput = "(Failed conversion to intermediate Content MathML)";
maximaOutput = "(N/A)";
}
else {
/* Convert Content MathML to Maxima Input */
StringWriter maximaWriter = new StringWriter();
Transformer ctoMaximaStylesheet = compileStylesheet(CMATHML_TO_MAXIMA_LOCATION).newTransformer();
ctoMaximaStylesheet.transform(new DOMSource(cmathmlDocument), new StreamResult(maximaWriter));
maximaInput = maximaWriter.toString();
/* Now pass to Maxima */
RawMaximaSession maximaSession = new RawMaximaSession();
try {
maximaSession.open();
maximaOutput = maximaSession.executeRaw(maximaInput + ";");
maximaSession.close();
}
catch (Exception e) {
maximaOutput = "Exception occurred speaking to Maxima: " + e.toString();
}
}
/* Return results */
return new String[] { pmathml, cmathml, maximaInput, maximaOutput };
}
private Transformer createSerializer(TransformerFactory factory) throws TransformerConfigurationException {
Transformer serializer = factory.newTransformer();
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
serializer.setOutputProperty(OutputKeys.ENCODING, "US-ASCII");
return serializer;
}
}
| true | true | private void doRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/* Read in input LaTeX, using some placeholder text if nothing was provided */
String rawInputLaTeX = request.getParameter("input");
String resultingInputLaTeX;
if (rawInputLaTeX!=null) {
/* Tidy up line endings */
resultingInputLaTeX = rawInputLaTeX.replaceAll("(\r\n|\r|\n)", "\n");
}
else {
/* Use some default input */
resultingInputLaTeX = "1+x";
}
/* Parse the LaTeX */
SnuggleEngine engine = new SnuggleEngine();
SnuggleSession session = engine.createSession();
/* NOTE: Must turn on inference of Math structure here */
session.getConfiguration().setInferringMathStructure(true);
SnuggleInput input = new SnuggleInput("\\[ " + resultingInputLaTeX + " \\]", "Form Input");
session.parseInput(input);
/* Set up web output options */
MathMLWebPageOptions options = new MathMLWebPageOptions();
options.setMathVariantMapping(true);
options.setAddingMathAnnotations(true);
options.setPageType(WebPageType.CROSS_BROWSER_XHTML);
options.setErrorOutputOptions(ErrorOutputOptions.XHTML);
options.setTitle("LaTeX to MathML and Maxima");
options.setAddingTitleHeading(false); /* We'll put our own title in */
options.setIndenting(true);
options.setCSSStylesheetURLs(
request.getContextPath() + "/includes/physics.css"
);
/* Get text results */
String[] resultArray;
try {
resultArray = createOutputXMLStrings(session, options);
}
catch (Exception e) {
throw new ServletException(e);
}
/* Log what was done */
log.info("Results:\nInput: " + resultingInputLaTeX
+ "\nPMathML: " + resultArray[0]
+ "\nCMathML: " + resultArray[1]
+ "\nMaxima Input: " + resultArray[2]
+ "\nMaxima Output: " + resultArray[3]
+ "\n======================================");
/* Create XSLT to generate the resulting page */
Transformer viewStylesheet;
try {
viewStylesheet = compileStylesheet(LATEX_INPUT_XSLT_LOCATION).newTransformer();
viewStylesheet.setParameter("context-path", request.getContextPath());
viewStylesheet.setParameter("latex-input", resultingInputLaTeX);
if (resultArray!=null) {
viewStylesheet.setParameter("pmathml", resultArray[0]);
viewStylesheet.setParameter("cmathml", resultArray[1]);
viewStylesheet.setParameter("maxima-input", resultArray[2]);
viewStylesheet.setParameter("maxima-output", resultArray[3]);
}
}
catch (TransformerConfigurationException e) {
throw new ServletException("Could not create stylesheet from Templates", e);
}
options.setStylesheet(viewStylesheet);
/* Generate and serve the resulting web page */
try {
session.writeWebPage(options, response, response.getOutputStream());
}
catch (Exception e) {
throw new ServletException("Unexpected Exception", e);
}
}
| private void doRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/* Read in input LaTeX, using some placeholder text if nothing was provided */
String rawInputLaTeX = request.getParameter("input");
String resultingInputLaTeX;
if (rawInputLaTeX!=null) {
/* Tidy up line endings */
resultingInputLaTeX = rawInputLaTeX.replaceAll("(\r\n|\r|\n)", "\n");
}
else {
/* Use some default input */
resultingInputLaTeX = "1+x";
}
/* Parse the LaTeX */
SnuggleEngine engine = new SnuggleEngine();
SnuggleSession session = engine.createSession();
/* NOTE: Must turn on inference of Math structure here */
session.getConfiguration().setInferringMathStructure(true);
SnuggleInput input = new SnuggleInput("\\[ " + resultingInputLaTeX + " \\]", "Form Input");
session.parseInput(input);
/* Set up web output options */
MathMLWebPageOptions options = new MathMLWebPageOptions();
options.setMathVariantMapping(true);
options.setAddingMathAnnotations(true);
options.setPageType(WebPageType.CROSS_BROWSER_XHTML);
options.setErrorOutputOptions(ErrorOutputOptions.XHTML);
options.setTitle("LaTeX to MathML and Maxima");
options.setAddingTitleHeading(false); /* We'll put our own title in */
options.setIndenting(true);
options.setCSSStylesheetURLs(
request.getContextPath() + "/includes/physics.css"
);
/* Get text results */
String[] resultArray;
try {
resultArray = createOutputXMLStrings(session, options);
}
catch (Exception e) {
throw new ServletException(e);
}
/* Log what was done */
if (resultArray!=null) {
log.info("Success Result:\nInput: " + resultingInputLaTeX
+ "\nPMathML: " + resultArray[0]
+ "\nCMathML: " + resultArray[1]
+ "\nMaxima Input: " + resultArray[2]
+ "\nMaxima Output: " + resultArray[3]
+ "\n======================================");
}
else {
log.warn("Failed on input " + resultingInputLaTeX);
}
/* Create XSLT to generate the resulting page */
Transformer viewStylesheet;
try {
viewStylesheet = compileStylesheet(LATEX_INPUT_XSLT_LOCATION).newTransformer();
viewStylesheet.setParameter("context-path", request.getContextPath());
viewStylesheet.setParameter("latex-input", resultingInputLaTeX);
if (resultArray!=null) {
viewStylesheet.setParameter("pmathml", resultArray[0]);
viewStylesheet.setParameter("cmathml", resultArray[1]);
viewStylesheet.setParameter("maxima-input", resultArray[2]);
viewStylesheet.setParameter("maxima-output", resultArray[3]);
}
}
catch (TransformerConfigurationException e) {
throw new ServletException("Could not create stylesheet from Templates", e);
}
options.setStylesheet(viewStylesheet);
/* Generate and serve the resulting web page */
try {
session.writeWebPage(options, response, response.getOutputStream());
}
catch (Exception e) {
throw new ServletException("Unexpected Exception", e);
}
}
|
diff --git a/src/edacc/model/ClientDAO.java b/src/edacc/model/ClientDAO.java
index 984f1dc..c93e619 100755
--- a/src/edacc/model/ClientDAO.java
+++ b/src/edacc/model/ClientDAO.java
@@ -1,180 +1,180 @@
package edacc.model;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
/**
*
* @author simon
*/
public class ClientDAO {
protected static final String table = "Client";
protected static final String updateQuery = "UPDATE " + table + " SET message =? WHERE idClient=?";
private static final ObjectCache<Client> cache = new ObjectCache<Client>();
private static HashSet<Integer> getClientIds() throws SQLException {
HashSet<Integer> res = new HashSet<Integer>();
PreparedStatement st = DatabaseConnector.getInstance().getConn().prepareStatement("SELECT idClient FROM " + table);
ResultSet rs = st.executeQuery();
while (rs.next()) {
res.add(rs.getInt("idClient"));
}
rs.close();
st.close();
return res;
}
private static String getIntArray(Collection<Integer> c) {
String res = "(";
Iterator<Integer> it = c.iterator();
while (it.hasNext()) {
res += "" + it.next();
if (it.hasNext()) {
res += ",";
}
}
res += ")";
return res;
}
public static synchronized ArrayList<Client> getClients() throws SQLException {
ArrayList<Client> clients = new ArrayList<Client>();
HashSet<Integer> clientIds = getClientIds();
ArrayList<Integer> idsModified = new ArrayList<Integer>();
ArrayList<Client> deletedClients = new ArrayList<Client>();
for (Client c : cache.values()) {
if (clientIds.contains(c.getId())) {
idsModified.add(c.getId());
} else {
deletedClients.add(c);
}
clientIds.remove(c.getId());
}
if (!idsModified.isEmpty()) {
PreparedStatement st = DatabaseConnector.getInstance().getConn().prepareStatement("SELECT idClient, message, jobs_wait_time, current_wait_time, TIMESTAMPDIFF(SECOND, lastReport, NOW()) > 20 AS dead, IF(walltime=0,0,TIMESTAMPDIFF(SECOND,NOW(),TIMESTAMPADD(SECOND,walltime,startTimestamp))) AS timeleft FROM " + table + " WHERE idClient IN " + getIntArray(idsModified));
ResultSet rs = st.executeQuery();
while (rs.next()) {
Client c = cache.getCached(rs.getInt("idClient"));
c.setMessage(rs.getString("message"));
c.setDead(rs.getBoolean("dead"));
c.setWait_time(rs.getInt("jobs_wait_time"));
c.setCurrent_wait_time(rs.getInt("current_wait_time"));
c.setTimeleft(rs.getInt("timeleft"));
}
rs.close();
st.close();
}
if (!clientIds.isEmpty()) {
PreparedStatement st = DatabaseConnector.getInstance().getConn().prepareStatement("SELECT idClient, numCores, numThreads, hyperthreading, turboboost, CPUName, cacheSize, cpuflags, memory, memoryFree, cpuinfo, meminfo, message, gridQueue_idgridQueue, lastReport, TIMESTAMPDIFF(SECOND, lastReport, NOW()) > 20 AS dead, IF(walltime=0,0,TIMESTAMPDIFF(SECOND,NOW(),TIMESTAMPADD(SECOND,walltime,startTimestamp))) AS timeleft, jobs_wait_time, current_wait_time FROM " + table + " WHERE idClient IN " + getIntArray(clientIds));
ResultSet rs = st.executeQuery();
while (rs.next()) {
Client c = new Client(rs);
cache.cache(c);
}
rs.close();
st.close();
}
- for (Client c : cache.values()) {
- clients.add(c);
- }
for (Client c : deletedClients) {
c.setDeleted();
c.notifyObservers();
cache.remove(c);
}
+ for (Client c : cache.values()) {
+ clients.add(c);
+ }
PreparedStatement st = DatabaseConnector.getInstance().getConn().prepareStatement("SELECT Experiment_idExperiment, Client_idClient, numCores FROM Experiment_has_Client WHERE numCores > 0");
ResultSet rs = st.executeQuery();
HashMap<Client, HashMap<Experiment, Integer>> map = new HashMap<Client, HashMap<Experiment, Integer>>();
while (rs.next()) {
int clientId = rs.getInt("Client_idClient");
int numCores = rs.getInt("numCores");
Client c = cache.getCached(clientId);
if (c == null) {
continue;
}
Experiment exp = ExperimentDAO.getById(rs.getInt("Experiment_idExperiment"));
HashMap<Experiment, Integer> tmp = map.get(c);
if (tmp == null) {
tmp = new HashMap<Experiment, Integer>();
map.put(c, tmp);
}
tmp.put(exp, numCores);
}
st.close();
for (Client c : cache.values()) {
HashMap<Experiment, Integer> tmp = map.get(c);
if (tmp != null) {
c.setComputingExperiments(tmp);
} else {
c.setComputingExperiments(new HashMap<Experiment, Integer>());
}
if (c.isModified()) {
c.notifyObservers();
c.setSaved();
}
}
return clients;
}
public static int getJobCount(Client client) throws SQLException {
final String query = "SELECT COUNT(idJob) FROM ExperimentResults WHERE Client_idClient = ?";
PreparedStatement ps = DatabaseConnector.getInstance().getConn().prepareStatement(query);
ps.setInt(1, client.getId());
ResultSet rs = ps.executeQuery();
int res = 0;
if (rs.next()) {
res = rs.getInt(1);
} else {
res = 0;
}
rs.close();
ps.close();
return res;
}
public static void sendMessage(Integer clientId, String message) throws SQLException {
if (message.equals("")) {
return;
}
if (message.charAt(message.length() - 1) != '\n') {
message += '\n';
}
final String query = "UPDATE Client SET message = CONCAT(message, ?) WHERE idClient = ?";
PreparedStatement ps = DatabaseConnector.getInstance().getConn().prepareStatement(query);
ps.setString(1, message);
ps.setInt(2, clientId);
ps.executeUpdate();
ps.close();
}
public static void sendMessage(Client client, String message) throws SQLException {
sendMessage(client.getId(), message);
}
public static void removeDeadClients() throws SQLException {
final String query = "DELETE FROM Client WHERE TIMESTAMPDIFF(SECOND, lastReport, NOW()) > 20";
PreparedStatement ps = DatabaseConnector.getInstance().getConn().prepareStatement(query);
ps.executeUpdate();
ps.close();
// update cache; will notify client browser
getClients();
}
public static void clearCache() {
cache.clear();
}
}
| false | true | public static synchronized ArrayList<Client> getClients() throws SQLException {
ArrayList<Client> clients = new ArrayList<Client>();
HashSet<Integer> clientIds = getClientIds();
ArrayList<Integer> idsModified = new ArrayList<Integer>();
ArrayList<Client> deletedClients = new ArrayList<Client>();
for (Client c : cache.values()) {
if (clientIds.contains(c.getId())) {
idsModified.add(c.getId());
} else {
deletedClients.add(c);
}
clientIds.remove(c.getId());
}
if (!idsModified.isEmpty()) {
PreparedStatement st = DatabaseConnector.getInstance().getConn().prepareStatement("SELECT idClient, message, jobs_wait_time, current_wait_time, TIMESTAMPDIFF(SECOND, lastReport, NOW()) > 20 AS dead, IF(walltime=0,0,TIMESTAMPDIFF(SECOND,NOW(),TIMESTAMPADD(SECOND,walltime,startTimestamp))) AS timeleft FROM " + table + " WHERE idClient IN " + getIntArray(idsModified));
ResultSet rs = st.executeQuery();
while (rs.next()) {
Client c = cache.getCached(rs.getInt("idClient"));
c.setMessage(rs.getString("message"));
c.setDead(rs.getBoolean("dead"));
c.setWait_time(rs.getInt("jobs_wait_time"));
c.setCurrent_wait_time(rs.getInt("current_wait_time"));
c.setTimeleft(rs.getInt("timeleft"));
}
rs.close();
st.close();
}
if (!clientIds.isEmpty()) {
PreparedStatement st = DatabaseConnector.getInstance().getConn().prepareStatement("SELECT idClient, numCores, numThreads, hyperthreading, turboboost, CPUName, cacheSize, cpuflags, memory, memoryFree, cpuinfo, meminfo, message, gridQueue_idgridQueue, lastReport, TIMESTAMPDIFF(SECOND, lastReport, NOW()) > 20 AS dead, IF(walltime=0,0,TIMESTAMPDIFF(SECOND,NOW(),TIMESTAMPADD(SECOND,walltime,startTimestamp))) AS timeleft, jobs_wait_time, current_wait_time FROM " + table + " WHERE idClient IN " + getIntArray(clientIds));
ResultSet rs = st.executeQuery();
while (rs.next()) {
Client c = new Client(rs);
cache.cache(c);
}
rs.close();
st.close();
}
for (Client c : cache.values()) {
clients.add(c);
}
for (Client c : deletedClients) {
c.setDeleted();
c.notifyObservers();
cache.remove(c);
}
PreparedStatement st = DatabaseConnector.getInstance().getConn().prepareStatement("SELECT Experiment_idExperiment, Client_idClient, numCores FROM Experiment_has_Client WHERE numCores > 0");
ResultSet rs = st.executeQuery();
HashMap<Client, HashMap<Experiment, Integer>> map = new HashMap<Client, HashMap<Experiment, Integer>>();
while (rs.next()) {
int clientId = rs.getInt("Client_idClient");
int numCores = rs.getInt("numCores");
Client c = cache.getCached(clientId);
if (c == null) {
continue;
}
Experiment exp = ExperimentDAO.getById(rs.getInt("Experiment_idExperiment"));
HashMap<Experiment, Integer> tmp = map.get(c);
if (tmp == null) {
tmp = new HashMap<Experiment, Integer>();
map.put(c, tmp);
}
tmp.put(exp, numCores);
}
st.close();
for (Client c : cache.values()) {
HashMap<Experiment, Integer> tmp = map.get(c);
if (tmp != null) {
c.setComputingExperiments(tmp);
} else {
c.setComputingExperiments(new HashMap<Experiment, Integer>());
}
if (c.isModified()) {
c.notifyObservers();
c.setSaved();
}
}
return clients;
}
| public static synchronized ArrayList<Client> getClients() throws SQLException {
ArrayList<Client> clients = new ArrayList<Client>();
HashSet<Integer> clientIds = getClientIds();
ArrayList<Integer> idsModified = new ArrayList<Integer>();
ArrayList<Client> deletedClients = new ArrayList<Client>();
for (Client c : cache.values()) {
if (clientIds.contains(c.getId())) {
idsModified.add(c.getId());
} else {
deletedClients.add(c);
}
clientIds.remove(c.getId());
}
if (!idsModified.isEmpty()) {
PreparedStatement st = DatabaseConnector.getInstance().getConn().prepareStatement("SELECT idClient, message, jobs_wait_time, current_wait_time, TIMESTAMPDIFF(SECOND, lastReport, NOW()) > 20 AS dead, IF(walltime=0,0,TIMESTAMPDIFF(SECOND,NOW(),TIMESTAMPADD(SECOND,walltime,startTimestamp))) AS timeleft FROM " + table + " WHERE idClient IN " + getIntArray(idsModified));
ResultSet rs = st.executeQuery();
while (rs.next()) {
Client c = cache.getCached(rs.getInt("idClient"));
c.setMessage(rs.getString("message"));
c.setDead(rs.getBoolean("dead"));
c.setWait_time(rs.getInt("jobs_wait_time"));
c.setCurrent_wait_time(rs.getInt("current_wait_time"));
c.setTimeleft(rs.getInt("timeleft"));
}
rs.close();
st.close();
}
if (!clientIds.isEmpty()) {
PreparedStatement st = DatabaseConnector.getInstance().getConn().prepareStatement("SELECT idClient, numCores, numThreads, hyperthreading, turboboost, CPUName, cacheSize, cpuflags, memory, memoryFree, cpuinfo, meminfo, message, gridQueue_idgridQueue, lastReport, TIMESTAMPDIFF(SECOND, lastReport, NOW()) > 20 AS dead, IF(walltime=0,0,TIMESTAMPDIFF(SECOND,NOW(),TIMESTAMPADD(SECOND,walltime,startTimestamp))) AS timeleft, jobs_wait_time, current_wait_time FROM " + table + " WHERE idClient IN " + getIntArray(clientIds));
ResultSet rs = st.executeQuery();
while (rs.next()) {
Client c = new Client(rs);
cache.cache(c);
}
rs.close();
st.close();
}
for (Client c : deletedClients) {
c.setDeleted();
c.notifyObservers();
cache.remove(c);
}
for (Client c : cache.values()) {
clients.add(c);
}
PreparedStatement st = DatabaseConnector.getInstance().getConn().prepareStatement("SELECT Experiment_idExperiment, Client_idClient, numCores FROM Experiment_has_Client WHERE numCores > 0");
ResultSet rs = st.executeQuery();
HashMap<Client, HashMap<Experiment, Integer>> map = new HashMap<Client, HashMap<Experiment, Integer>>();
while (rs.next()) {
int clientId = rs.getInt("Client_idClient");
int numCores = rs.getInt("numCores");
Client c = cache.getCached(clientId);
if (c == null) {
continue;
}
Experiment exp = ExperimentDAO.getById(rs.getInt("Experiment_idExperiment"));
HashMap<Experiment, Integer> tmp = map.get(c);
if (tmp == null) {
tmp = new HashMap<Experiment, Integer>();
map.put(c, tmp);
}
tmp.put(exp, numCores);
}
st.close();
for (Client c : cache.values()) {
HashMap<Experiment, Integer> tmp = map.get(c);
if (tmp != null) {
c.setComputingExperiments(tmp);
} else {
c.setComputingExperiments(new HashMap<Experiment, Integer>());
}
if (c.isModified()) {
c.notifyObservers();
c.setSaved();
}
}
return clients;
}
|
diff --git a/src/com/android/contacts/editor/ExternalRawContactEditorView.java b/src/com/android/contacts/editor/ExternalRawContactEditorView.java
index 89cace0e6..e1a669b70 100644
--- a/src/com/android/contacts/editor/ExternalRawContactEditorView.java
+++ b/src/com/android/contacts/editor/ExternalRawContactEditorView.java
@@ -1,229 +1,229 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.contacts.editor;
import com.android.contacts.ContactsUtils;
import com.android.contacts.R;
import com.android.contacts.editor.ExternalRawContactEditorView.Listener;
import com.android.contacts.model.AccountType;
import com.android.contacts.model.DataKind;
import com.android.contacts.model.EntityDelta;
import com.android.contacts.model.EntityDelta.ValuesDelta;
import com.android.contacts.model.EntityModifier;
import android.accounts.Account;
import android.content.ContentUris;
import android.content.Context;
import android.net.Uri;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.RawContacts;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Custom view that displays external contacts in the edit screen.
*/
public class ExternalRawContactEditorView extends BaseRawContactEditorView
implements OnClickListener {
private LayoutInflater mInflater;
private View mPhotoStub;
private TextView mName;
private TextView mReadOnlyWarning;
private Button mEditExternallyButton;
private ViewGroup mGeneral;
private ImageView mAccountIcon;
private TextView mAccountTypeTextView;
private TextView mAccountNameTextView;
private String mAccountName;
private String mAccountType;
private long mRawContactId = -1;
private Listener mListener;
public interface Listener {
void onExternalEditorRequest(Account account, Uri uri);
}
public ExternalRawContactEditorView(Context context) {
super(context);
}
public ExternalRawContactEditorView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setListener(Listener listener) {
mListener = listener;
}
/** {@inheritDoc} */
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mInflater = (LayoutInflater)getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
mPhotoStub = findViewById(R.id.stub_photo);
mName = (TextView) findViewById(R.id.read_only_name);
mReadOnlyWarning = (TextView) findViewById(R.id.read_only_warning);
mEditExternallyButton = (Button) findViewById(R.id.button_edit_externally);
mEditExternallyButton.setOnClickListener(this);
mGeneral = (ViewGroup)findViewById(R.id.sect_general);
mAccountIcon = (ImageView) findViewById(R.id.account_icon);
mAccountTypeTextView = (TextView) findViewById(R.id.account_type);
mAccountNameTextView = (TextView) findViewById(R.id.account_name);
}
/**
* Set the internal state for this view, given a current
* {@link EntityDelta} state and the {@link AccountType} that
* apply to that state.
*/
@Override
public void setState(EntityDelta state, AccountType type, ViewIdGenerator vig) {
// Remove any existing sections
mGeneral.removeAllViews();
// Bail if invalid state or source
if (state == null || type == null) return;
// Make sure we have StructuredName
EntityModifier.ensureKindExists(state, type, StructuredName.CONTENT_ITEM_TYPE);
// Fill in the header info
ValuesDelta values = state.getValues();
mAccountName = values.getAsString(RawContacts.ACCOUNT_NAME);
mAccountType = values.getAsString(RawContacts.ACCOUNT_TYPE);
CharSequence accountType = type.getDisplayLabel(mContext);
if (TextUtils.isEmpty(accountType)) {
accountType = mContext.getString(R.string.account_phone);
}
if (!TextUtils.isEmpty(mAccountName)) {
mAccountNameTextView.setText(
mContext.getString(R.string.from_account_format, mAccountName));
}
mAccountTypeTextView.setText(mContext.getString(R.string.account_type_format, accountType));
mAccountIcon.setImageDrawable(type.getDisplayIcon(mContext));
mRawContactId = values.getAsLong(RawContacts._ID);
ValuesDelta primary;
// Photo
DataKind kind = type.getKindForMimetype(Photo.CONTENT_ITEM_TYPE);
if (kind != null) {
EntityModifier.ensureKindExists(state, type, Photo.CONTENT_ITEM_TYPE);
boolean hasPhotoEditor = type.getKindForMimetype(Photo.CONTENT_ITEM_TYPE) != null;
setHasPhotoEditor(hasPhotoEditor);
primary = state.getPrimaryEntry(Photo.CONTENT_ITEM_TYPE);
getPhotoEditor().setValues(kind, primary, state, type.readOnly, vig);
if (!hasPhotoEditor || !getPhotoEditor().hasSetPhoto()) {
mPhotoStub.setVisibility(View.GONE);
} else {
mPhotoStub.setVisibility(View.VISIBLE);
}
} else {
mPhotoStub.setVisibility(View.VISIBLE);
}
// Name
primary = state.getPrimaryEntry(StructuredName.CONTENT_ITEM_TYPE);
mName.setText(primary.getAsString(StructuredName.DISPLAY_NAME));
if (type.readOnly) {
- mReadOnlyWarning.setText(mContext.getString(R.string.contact_read_only, accountType));
+ mReadOnlyWarning.setText(mContext.getString(R.string.contact_read_only));
mReadOnlyWarning.setVisibility(View.VISIBLE);
mEditExternallyButton.setVisibility(View.GONE);
} else {
mReadOnlyWarning.setVisibility(View.GONE);
mEditExternallyButton.setVisibility(View.VISIBLE);
}
// Phones
ArrayList<ValuesDelta> phones = state.getMimeEntries(Phone.CONTENT_ITEM_TYPE);
if (phones != null) {
for (ValuesDelta phone : phones) {
View field = mInflater.inflate(
R.layout.item_read_only_field, mGeneral, false);
TextView v;
v = (TextView) field.findViewById(R.id.label);
v.setText(mContext.getText(R.string.phoneLabelsGroup));
v = (TextView) field.findViewById(R.id.data);
v.setText(PhoneNumberUtils.formatNumber(phone.getAsString(Phone.NUMBER),
phone.getAsString(Phone.NORMALIZED_NUMBER),
ContactsUtils.getCurrentCountryIso(getContext())));
mGeneral.addView(field);
}
}
// Emails
ArrayList<ValuesDelta> emails = state.getMimeEntries(Email.CONTENT_ITEM_TYPE);
if (emails != null) {
for (ValuesDelta email : emails) {
View field = mInflater.inflate(
R.layout.item_read_only_field, mGeneral, false);
TextView v;
v = (TextView) field.findViewById(R.id.label);
v.setText(mContext.getText(R.string.emailLabelsGroup));
v = (TextView) field.findViewById(R.id.data);
v.setText(email.getAsString(Email.DATA));
mGeneral.addView(field);
}
}
// Hide mGeneral if it's empty
if (mGeneral.getChildCount() > 0) {
mGeneral.setVisibility(View.VISIBLE);
} else {
mGeneral.setVisibility(View.GONE);
}
}
@Override
public long getRawContactId() {
return mRawContactId;
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.button_edit_externally) {
if (mListener != null) {
mListener.onExternalEditorRequest(new Account(mAccountName, mAccountType),
ContentUris.withAppendedId(RawContacts.CONTENT_URI, mRawContactId));
}
}
}
}
| true | true | public void setState(EntityDelta state, AccountType type, ViewIdGenerator vig) {
// Remove any existing sections
mGeneral.removeAllViews();
// Bail if invalid state or source
if (state == null || type == null) return;
// Make sure we have StructuredName
EntityModifier.ensureKindExists(state, type, StructuredName.CONTENT_ITEM_TYPE);
// Fill in the header info
ValuesDelta values = state.getValues();
mAccountName = values.getAsString(RawContacts.ACCOUNT_NAME);
mAccountType = values.getAsString(RawContacts.ACCOUNT_TYPE);
CharSequence accountType = type.getDisplayLabel(mContext);
if (TextUtils.isEmpty(accountType)) {
accountType = mContext.getString(R.string.account_phone);
}
if (!TextUtils.isEmpty(mAccountName)) {
mAccountNameTextView.setText(
mContext.getString(R.string.from_account_format, mAccountName));
}
mAccountTypeTextView.setText(mContext.getString(R.string.account_type_format, accountType));
mAccountIcon.setImageDrawable(type.getDisplayIcon(mContext));
mRawContactId = values.getAsLong(RawContacts._ID);
ValuesDelta primary;
// Photo
DataKind kind = type.getKindForMimetype(Photo.CONTENT_ITEM_TYPE);
if (kind != null) {
EntityModifier.ensureKindExists(state, type, Photo.CONTENT_ITEM_TYPE);
boolean hasPhotoEditor = type.getKindForMimetype(Photo.CONTENT_ITEM_TYPE) != null;
setHasPhotoEditor(hasPhotoEditor);
primary = state.getPrimaryEntry(Photo.CONTENT_ITEM_TYPE);
getPhotoEditor().setValues(kind, primary, state, type.readOnly, vig);
if (!hasPhotoEditor || !getPhotoEditor().hasSetPhoto()) {
mPhotoStub.setVisibility(View.GONE);
} else {
mPhotoStub.setVisibility(View.VISIBLE);
}
} else {
mPhotoStub.setVisibility(View.VISIBLE);
}
// Name
primary = state.getPrimaryEntry(StructuredName.CONTENT_ITEM_TYPE);
mName.setText(primary.getAsString(StructuredName.DISPLAY_NAME));
if (type.readOnly) {
mReadOnlyWarning.setText(mContext.getString(R.string.contact_read_only, accountType));
mReadOnlyWarning.setVisibility(View.VISIBLE);
mEditExternallyButton.setVisibility(View.GONE);
} else {
mReadOnlyWarning.setVisibility(View.GONE);
mEditExternallyButton.setVisibility(View.VISIBLE);
}
// Phones
ArrayList<ValuesDelta> phones = state.getMimeEntries(Phone.CONTENT_ITEM_TYPE);
if (phones != null) {
for (ValuesDelta phone : phones) {
View field = mInflater.inflate(
R.layout.item_read_only_field, mGeneral, false);
TextView v;
v = (TextView) field.findViewById(R.id.label);
v.setText(mContext.getText(R.string.phoneLabelsGroup));
v = (TextView) field.findViewById(R.id.data);
v.setText(PhoneNumberUtils.formatNumber(phone.getAsString(Phone.NUMBER),
phone.getAsString(Phone.NORMALIZED_NUMBER),
ContactsUtils.getCurrentCountryIso(getContext())));
mGeneral.addView(field);
}
}
// Emails
ArrayList<ValuesDelta> emails = state.getMimeEntries(Email.CONTENT_ITEM_TYPE);
if (emails != null) {
for (ValuesDelta email : emails) {
View field = mInflater.inflate(
R.layout.item_read_only_field, mGeneral, false);
TextView v;
v = (TextView) field.findViewById(R.id.label);
v.setText(mContext.getText(R.string.emailLabelsGroup));
v = (TextView) field.findViewById(R.id.data);
v.setText(email.getAsString(Email.DATA));
mGeneral.addView(field);
}
}
// Hide mGeneral if it's empty
if (mGeneral.getChildCount() > 0) {
mGeneral.setVisibility(View.VISIBLE);
} else {
mGeneral.setVisibility(View.GONE);
}
}
| public void setState(EntityDelta state, AccountType type, ViewIdGenerator vig) {
// Remove any existing sections
mGeneral.removeAllViews();
// Bail if invalid state or source
if (state == null || type == null) return;
// Make sure we have StructuredName
EntityModifier.ensureKindExists(state, type, StructuredName.CONTENT_ITEM_TYPE);
// Fill in the header info
ValuesDelta values = state.getValues();
mAccountName = values.getAsString(RawContacts.ACCOUNT_NAME);
mAccountType = values.getAsString(RawContacts.ACCOUNT_TYPE);
CharSequence accountType = type.getDisplayLabel(mContext);
if (TextUtils.isEmpty(accountType)) {
accountType = mContext.getString(R.string.account_phone);
}
if (!TextUtils.isEmpty(mAccountName)) {
mAccountNameTextView.setText(
mContext.getString(R.string.from_account_format, mAccountName));
}
mAccountTypeTextView.setText(mContext.getString(R.string.account_type_format, accountType));
mAccountIcon.setImageDrawable(type.getDisplayIcon(mContext));
mRawContactId = values.getAsLong(RawContacts._ID);
ValuesDelta primary;
// Photo
DataKind kind = type.getKindForMimetype(Photo.CONTENT_ITEM_TYPE);
if (kind != null) {
EntityModifier.ensureKindExists(state, type, Photo.CONTENT_ITEM_TYPE);
boolean hasPhotoEditor = type.getKindForMimetype(Photo.CONTENT_ITEM_TYPE) != null;
setHasPhotoEditor(hasPhotoEditor);
primary = state.getPrimaryEntry(Photo.CONTENT_ITEM_TYPE);
getPhotoEditor().setValues(kind, primary, state, type.readOnly, vig);
if (!hasPhotoEditor || !getPhotoEditor().hasSetPhoto()) {
mPhotoStub.setVisibility(View.GONE);
} else {
mPhotoStub.setVisibility(View.VISIBLE);
}
} else {
mPhotoStub.setVisibility(View.VISIBLE);
}
// Name
primary = state.getPrimaryEntry(StructuredName.CONTENT_ITEM_TYPE);
mName.setText(primary.getAsString(StructuredName.DISPLAY_NAME));
if (type.readOnly) {
mReadOnlyWarning.setText(mContext.getString(R.string.contact_read_only));
mReadOnlyWarning.setVisibility(View.VISIBLE);
mEditExternallyButton.setVisibility(View.GONE);
} else {
mReadOnlyWarning.setVisibility(View.GONE);
mEditExternallyButton.setVisibility(View.VISIBLE);
}
// Phones
ArrayList<ValuesDelta> phones = state.getMimeEntries(Phone.CONTENT_ITEM_TYPE);
if (phones != null) {
for (ValuesDelta phone : phones) {
View field = mInflater.inflate(
R.layout.item_read_only_field, mGeneral, false);
TextView v;
v = (TextView) field.findViewById(R.id.label);
v.setText(mContext.getText(R.string.phoneLabelsGroup));
v = (TextView) field.findViewById(R.id.data);
v.setText(PhoneNumberUtils.formatNumber(phone.getAsString(Phone.NUMBER),
phone.getAsString(Phone.NORMALIZED_NUMBER),
ContactsUtils.getCurrentCountryIso(getContext())));
mGeneral.addView(field);
}
}
// Emails
ArrayList<ValuesDelta> emails = state.getMimeEntries(Email.CONTENT_ITEM_TYPE);
if (emails != null) {
for (ValuesDelta email : emails) {
View field = mInflater.inflate(
R.layout.item_read_only_field, mGeneral, false);
TextView v;
v = (TextView) field.findViewById(R.id.label);
v.setText(mContext.getText(R.string.emailLabelsGroup));
v = (TextView) field.findViewById(R.id.data);
v.setText(email.getAsString(Email.DATA));
mGeneral.addView(field);
}
}
// Hide mGeneral if it's empty
if (mGeneral.getChildCount() > 0) {
mGeneral.setVisibility(View.VISIBLE);
} else {
mGeneral.setVisibility(View.GONE);
}
}
|
diff --git a/src/edu/buffalo/cse/ir/wikiindexer/wikipedia/test/WikipediaParserTest.java b/src/edu/buffalo/cse/ir/wikiindexer/wikipedia/test/WikipediaParserTest.java
index 89420d9..237644f 100644
--- a/src/edu/buffalo/cse/ir/wikiindexer/wikipedia/test/WikipediaParserTest.java
+++ b/src/edu/buffalo/cse/ir/wikiindexer/wikipedia/test/WikipediaParserTest.java
@@ -1,201 +1,201 @@
/**
*
*/
package edu.buffalo.cse.ir.wikiindexer.wikipedia.test;
import static org.junit.Assert.*;
import org.junit.Test;
import edu.buffalo.cse.ir.wikiindexer.wikipedia.WikipediaParser;
/**
* @author nikhillo
*
*/
public class WikipediaParserTest {
/**
* Test method for {@link edu.buffalo.cse.ir.wikiindexer.wikipedia.WikipediaParser#parseSectionTitle(java.lang.String)}.
*/
@Test
public final void testParseSectionTitle() {
//null test
assertEquals(null, WikipediaParser.parseSectionTitle(null));
//empty test
assertEquals("", WikipediaParser.parseSectionTitle(""));
//level 1 test
assertEquals("section", WikipediaParser.parseSectionTitle("== section =="));
//level 2 test
assertEquals("section", WikipediaParser.parseSectionTitle("=== section ==="));
//level 3 test
assertEquals("section", WikipediaParser.parseSectionTitle("==== section ===="));
//level 4 test
assertEquals("section", WikipediaParser.parseSectionTitle("===== section ====="));
//level 5 test
assertEquals("section", WikipediaParser.parseSectionTitle("====== section ======"));
}
/**
* Test method for {@link edu.buffalo.cse.ir.wikiindexer.wikipedia.WikipediaParser#parseListItem(java.lang.String)}.
*/
@Test
public final void testParseListItem() {
//null test
assertEquals(null, WikipediaParser.parseListItem(null));
//empty test
assertEquals("", WikipediaParser.parseListItem(""));
//unordered list level 1
assertEquals("unordered item", WikipediaParser.parseListItem("* unordered item"));
//unordered list level 2
assertEquals("unordered item", WikipediaParser.parseListItem("** unordered item"));
//unordered list level 4
assertEquals("unordered item", WikipediaParser.parseListItem("**** unordered item"));
//ordered list level 1
assertEquals("ordered item", WikipediaParser.parseListItem("# ordered item"));
//ordered lists level 3
assertEquals("ordered item", WikipediaParser.parseListItem("### ordered item"));
//definition list
assertEquals("definition item", WikipediaParser.parseListItem(": definition item"));
/* TODO: Add more tests */
}
/**
* Test method for {@link edu.buffalo.cse.ir.wikiindexer.wikipedia.WikipediaParser#parseTextFormatting(java.lang.String)}.
*/
@Test
public final void testParseTextFormatting() {
//null tests
assertEquals(null, WikipediaParser.parseTextFormatting(null));
//empty test
assertEquals("", WikipediaParser.parseTextFormatting(""));
//test italics
assertEquals("This is italicized text test", WikipediaParser.parseTextFormatting("This is ''italicized text'' test"));
//test bold
assertEquals("This is bold text test", WikipediaParser.parseTextFormatting("This is '''bold text''' test"));
//test both
assertEquals("This is italics bold test", WikipediaParser.parseTextFormatting("This is '''''italics bold''''' test"));
//test both 2
assertEquals("This is italics and bold text test", WikipediaParser.parseTextFormatting("This is ''italics'' and '''bold''' text test"));
/* TODO: Add more tests */
}
/**
* Test method for {@link edu.buffalo.cse.ir.wikiindexer.wikipedia.WikipediaParser#parseTagFormatting(java.lang.String)}.
*/
@Test
public final void testParseTagFormatting() {
//null test
assertEquals(null, WikipediaParser.parseTagFormatting(null));
//empty test
assertEquals("", WikipediaParser.parseTagFormatting(""));
//empty tag test
assertEquals("Watch the disappear", WikipediaParser.parseTagFormatting("Watch the <tag/> disappear"));
//tag with content
assertEquals("I should not vanish", WikipediaParser.parseTagFormatting("<random> I should not vanish </random>"));
//tag with attributes
assertEquals("Attributes or not, I'm still here", WikipediaParser.parseTagFormatting("<mytag val='some' otherval ='more'> Attributes or not, I'm still here</mytag>"));
//html escaping
assertEquals("Did you get me right?", WikipediaParser.parseTagFormatting("<painful attr1='yes' attr2='no' >Did you get me right?</pain>"));
assertEquals("{{tl|cite book}}", WikipediaParser.parseTagFormatting("<nowiki>{{tl|cite book}}</nowiki>"));
}
/**
* Test method for {@link edu.buffalo.cse.ir.wikiindexer.wikipedia.WikipediaParser#parseTemplates(java.lang.String)}.
*/
@Test
public final void testParseTemplates() {
assertEquals("", WikipediaParser.parseTemplates("{{UK-singer-stub}}"));
assertEquals("", WikipediaParser.parseTemplates("{{YouTube|TnIpQhDn4Zg|Russ Conway playing Side Saddle}}"));
assertEquals("", WikipediaParser.parseTemplates("{{Unreferenced stub|auto=yes|date=December 2009}}"));
assertEquals("", WikipediaParser.parseTemplates("{{Reflist}}"));
assertEquals("", WikipediaParser.parseTemplates("{{Persondata |NAME = Kay, Kathie" +
"|ALTERNATIVE NAMES = Connie Wood" +
"|SHORT DESCRIPTION = Singer" +
"|DATE OF BIRTH = 20 November 1918" +
"|PLACE OF BIRTH = [[Gainsborough, Lincolnshire|Gainsborough]], [[Lincolnshire]], [[England]], UK" +
"|DATE OF DEATH = 9 March 2005" +
"|PLACE OF DEATH = [[Largs]], [[Ayrshire]], [[Scotland]], UK" +
"}}"));
}
/**
* Test method for {@link edu.buffalo.cse.ir.wikiindexer.wikipedia.WikipediaParser#parseLinks(java.lang.String)}.
*/
@SuppressWarnings("deprecation")
@Test
public final void testParseLinks() {
//null and empty checks
assertEquals(new Object[]{"",""}, WikipediaParser.parseLinks(""));
assertEquals(new Object[]{"",""}, WikipediaParser.parseLinks(null));
//simple links
- assertEquals(new Object[]{"Lone Star State","Texas"}, WikipediaParser.parseLinks("[[Texas|LOne Star State]]"));
+ assertEquals(new Object[]{"Lone Star State","Texas"}, WikipediaParser.parseLinks("[[Texas|Lone Star State]]"));
//auto capitalization
assertEquals(new Object[]{"London has public transport", "Public_transport"}, WikipediaParser.parseLinks("London has [[public transport]]"));
//drop after _ and , automatically
- assertEquals(new Object[]{"kingdom", "kingdom_(biology)"}, WikipediaParser.parseLinks("[[kingdom (biology)|]]"));
+ assertEquals(new Object[]{"kingdom", "Kingdom_(biology)"}, WikipediaParser.parseLinks("[[kingdom (biology)|]]"));
assertEquals(new Object[]{"Seattle", "Seattle,_Washington"}, WikipediaParser.parseLinks("[[Seattle, Washington|]]"));
//outside namespace, not interested
assertEquals(new Object[]{"Village pump", ""}, WikipediaParser.parseLinks("[[Wikipedia:Village pump|]]"));
assertEquals(new Object[]{"Manual of Style", ""}, WikipediaParser.parseLinks("[[Wikipedia:Manual of Style (headings)|]]"));
assertEquals(new Object[]{"Wiktionary:Hello",""}, WikipediaParser.parseLinks("[[Wiktionary:Hello]]"));
assertEquals(new Object[]{"Wiktionary:fr:bonjour",""}, WikipediaParser.parseLinks("[[Wiktionary:fr:bonjour|]]"));
assertEquals(new Object[]{"Sound",""}, WikipediaParser.parseLinks("[[media:Classical guitar scale.ogg|Sound]]"));
assertEquals(new Object[]{"",""}, WikipediaParser.parseLinks("[[File:wiki.png]]"));
assertEquals(new Object[]{"Wikipedia encyclopedia",""}, WikipediaParser.parseLinks("[[File:wiki.png|right|Wikipedia encyclopedia]]"));
assertEquals(new Object[]{"Wikipedia logo",""}, WikipediaParser.parseLinks("[[File:wiki.png|frame|alt=Puzzle globe|Wikipedia logo]]"));
//blending etc.
assertEquals(new Object[]{"New York also has public transportation", "Public_transport"}, WikipediaParser.parseLinks("New York also has [[public transport|public transportation]]"));
assertEquals(new Object[]{"San Francisco also has public transportation", "Public_transport"}, WikipediaParser.parseLinks("San Francisco also has [[public transport]]ation"));
- assertEquals(new Object[]{"A micro-second", "micro-"}, WikipediaParser.parseLinks("A [[micro-]]<nowiki />second."));
+ assertEquals(new Object[]{"A micro-second", "Micro-"}, WikipediaParser.parseLinks("A [[micro-]]<nowiki />second."));
assertEquals(new Object[]{"Wikipedia:Manual of Style#Links",""}, WikipediaParser.parseLinks("[[Wikipedia:Manual of Style#Links|]]"));
//categories: the method should parse 'em but not index
assertEquals(new Object[]{"Character sets",""}, WikipediaParser.parseLinks("[[Category:Character sets]]"));
//same as above, but gos in the index not categories
assertEquals(new Object[]{"Category:Character sets",""}, WikipediaParser.parseLinks("[[:Category:Character sets]]"));
//language links: parse but dont add to main index
assertEquals(new Object[]{"es:Plancton",""}, WikipediaParser.parseLinks("[[es:Plancton]]"));
assertEquals(new Object[]{"ru:Планктон",""}, WikipediaParser.parseLinks("[[ru:Планктон]]"));
//external links
assertEquals(new Object[]{"Wikipedia",""}, WikipediaParser.parseLinks("[http://www.wikipedia.org Wikipedia]"));
assertEquals(new Object[]{"",""}, WikipediaParser.parseLinks("[http://www.wikipedia.org]"));
}
}
| false | true | public final void testParseLinks() {
//null and empty checks
assertEquals(new Object[]{"",""}, WikipediaParser.parseLinks(""));
assertEquals(new Object[]{"",""}, WikipediaParser.parseLinks(null));
//simple links
assertEquals(new Object[]{"Lone Star State","Texas"}, WikipediaParser.parseLinks("[[Texas|LOne Star State]]"));
//auto capitalization
assertEquals(new Object[]{"London has public transport", "Public_transport"}, WikipediaParser.parseLinks("London has [[public transport]]"));
//drop after _ and , automatically
assertEquals(new Object[]{"kingdom", "kingdom_(biology)"}, WikipediaParser.parseLinks("[[kingdom (biology)|]]"));
assertEquals(new Object[]{"Seattle", "Seattle,_Washington"}, WikipediaParser.parseLinks("[[Seattle, Washington|]]"));
//outside namespace, not interested
assertEquals(new Object[]{"Village pump", ""}, WikipediaParser.parseLinks("[[Wikipedia:Village pump|]]"));
assertEquals(new Object[]{"Manual of Style", ""}, WikipediaParser.parseLinks("[[Wikipedia:Manual of Style (headings)|]]"));
assertEquals(new Object[]{"Wiktionary:Hello",""}, WikipediaParser.parseLinks("[[Wiktionary:Hello]]"));
assertEquals(new Object[]{"Wiktionary:fr:bonjour",""}, WikipediaParser.parseLinks("[[Wiktionary:fr:bonjour|]]"));
assertEquals(new Object[]{"Sound",""}, WikipediaParser.parseLinks("[[media:Classical guitar scale.ogg|Sound]]"));
assertEquals(new Object[]{"",""}, WikipediaParser.parseLinks("[[File:wiki.png]]"));
assertEquals(new Object[]{"Wikipedia encyclopedia",""}, WikipediaParser.parseLinks("[[File:wiki.png|right|Wikipedia encyclopedia]]"));
assertEquals(new Object[]{"Wikipedia logo",""}, WikipediaParser.parseLinks("[[File:wiki.png|frame|alt=Puzzle globe|Wikipedia logo]]"));
//blending etc.
assertEquals(new Object[]{"New York also has public transportation", "Public_transport"}, WikipediaParser.parseLinks("New York also has [[public transport|public transportation]]"));
assertEquals(new Object[]{"San Francisco also has public transportation", "Public_transport"}, WikipediaParser.parseLinks("San Francisco also has [[public transport]]ation"));
assertEquals(new Object[]{"A micro-second", "micro-"}, WikipediaParser.parseLinks("A [[micro-]]<nowiki />second."));
assertEquals(new Object[]{"Wikipedia:Manual of Style#Links",""}, WikipediaParser.parseLinks("[[Wikipedia:Manual of Style#Links|]]"));
//categories: the method should parse 'em but not index
assertEquals(new Object[]{"Character sets",""}, WikipediaParser.parseLinks("[[Category:Character sets]]"));
//same as above, but gos in the index not categories
assertEquals(new Object[]{"Category:Character sets",""}, WikipediaParser.parseLinks("[[:Category:Character sets]]"));
//language links: parse but dont add to main index
assertEquals(new Object[]{"es:Plancton",""}, WikipediaParser.parseLinks("[[es:Plancton]]"));
assertEquals(new Object[]{"ru:Планктон",""}, WikipediaParser.parseLinks("[[ru:Планктон]]"));
//external links
assertEquals(new Object[]{"Wikipedia",""}, WikipediaParser.parseLinks("[http://www.wikipedia.org Wikipedia]"));
assertEquals(new Object[]{"",""}, WikipediaParser.parseLinks("[http://www.wikipedia.org]"));
}
}
| public final void testParseLinks() {
//null and empty checks
assertEquals(new Object[]{"",""}, WikipediaParser.parseLinks(""));
assertEquals(new Object[]{"",""}, WikipediaParser.parseLinks(null));
//simple links
assertEquals(new Object[]{"Lone Star State","Texas"}, WikipediaParser.parseLinks("[[Texas|Lone Star State]]"));
//auto capitalization
assertEquals(new Object[]{"London has public transport", "Public_transport"}, WikipediaParser.parseLinks("London has [[public transport]]"));
//drop after _ and , automatically
assertEquals(new Object[]{"kingdom", "Kingdom_(biology)"}, WikipediaParser.parseLinks("[[kingdom (biology)|]]"));
assertEquals(new Object[]{"Seattle", "Seattle,_Washington"}, WikipediaParser.parseLinks("[[Seattle, Washington|]]"));
//outside namespace, not interested
assertEquals(new Object[]{"Village pump", ""}, WikipediaParser.parseLinks("[[Wikipedia:Village pump|]]"));
assertEquals(new Object[]{"Manual of Style", ""}, WikipediaParser.parseLinks("[[Wikipedia:Manual of Style (headings)|]]"));
assertEquals(new Object[]{"Wiktionary:Hello",""}, WikipediaParser.parseLinks("[[Wiktionary:Hello]]"));
assertEquals(new Object[]{"Wiktionary:fr:bonjour",""}, WikipediaParser.parseLinks("[[Wiktionary:fr:bonjour|]]"));
assertEquals(new Object[]{"Sound",""}, WikipediaParser.parseLinks("[[media:Classical guitar scale.ogg|Sound]]"));
assertEquals(new Object[]{"",""}, WikipediaParser.parseLinks("[[File:wiki.png]]"));
assertEquals(new Object[]{"Wikipedia encyclopedia",""}, WikipediaParser.parseLinks("[[File:wiki.png|right|Wikipedia encyclopedia]]"));
assertEquals(new Object[]{"Wikipedia logo",""}, WikipediaParser.parseLinks("[[File:wiki.png|frame|alt=Puzzle globe|Wikipedia logo]]"));
//blending etc.
assertEquals(new Object[]{"New York also has public transportation", "Public_transport"}, WikipediaParser.parseLinks("New York also has [[public transport|public transportation]]"));
assertEquals(new Object[]{"San Francisco also has public transportation", "Public_transport"}, WikipediaParser.parseLinks("San Francisco also has [[public transport]]ation"));
assertEquals(new Object[]{"A micro-second", "Micro-"}, WikipediaParser.parseLinks("A [[micro-]]<nowiki />second."));
assertEquals(new Object[]{"Wikipedia:Manual of Style#Links",""}, WikipediaParser.parseLinks("[[Wikipedia:Manual of Style#Links|]]"));
//categories: the method should parse 'em but not index
assertEquals(new Object[]{"Character sets",""}, WikipediaParser.parseLinks("[[Category:Character sets]]"));
//same as above, but gos in the index not categories
assertEquals(new Object[]{"Category:Character sets",""}, WikipediaParser.parseLinks("[[:Category:Character sets]]"));
//language links: parse but dont add to main index
assertEquals(new Object[]{"es:Plancton",""}, WikipediaParser.parseLinks("[[es:Plancton]]"));
assertEquals(new Object[]{"ru:Планктон",""}, WikipediaParser.parseLinks("[[ru:Планктон]]"));
//external links
assertEquals(new Object[]{"Wikipedia",""}, WikipediaParser.parseLinks("[http://www.wikipedia.org Wikipedia]"));
assertEquals(new Object[]{"",""}, WikipediaParser.parseLinks("[http://www.wikipedia.org]"));
}
}
|
diff --git a/PuzzleApplet.java b/PuzzleApplet.java
index 23eda81..f401ecf 100644
--- a/PuzzleApplet.java
+++ b/PuzzleApplet.java
@@ -1,614 +1,612 @@
/*
* PuzzleApplet.java: NestedVM applet for the puzzle collection
*/
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.util.*;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.Timer;
import java.util.List;
import org.ibex.nestedvm.Runtime;
public class PuzzleApplet extends JApplet implements Runtime.CallJavaCB {
private static final long serialVersionUID = 1L;
private static final int CFG_SETTINGS = 0, CFG_SEED = 1, CFG_DESC = 2,
LEFT_BUTTON = 0x0200, MIDDLE_BUTTON = 0x201, RIGHT_BUTTON = 0x202,
LEFT_DRAG = 0x203, MIDDLE_DRAG = 0x204, RIGHT_DRAG = 0x205,
LEFT_RELEASE = 0x206, CURSOR_UP = 0x209, CURSOR_DOWN = 0x20a,
CURSOR_LEFT = 0x20b, CURSOR_RIGHT = 0x20c, MOD_CTRL = 0x1000,
MOD_SHFT = 0x2000, MOD_NUM_KEYPAD = 0x4000, ALIGN_VCENTRE = 0x100,
ALIGN_HCENTRE = 0x001, ALIGN_HRIGHT = 0x002, C_STRING = 0,
C_CHOICES = 1, C_BOOLEAN = 2;
private JFrame mainWindow;
private JMenu typeMenu;
private JMenuItem solveCommand;
private Color[] colors;
private JLabel statusBar;
private PuzzlePanel pp;
private Runtime runtime;
private String[] puzzle_args;
private Graphics2D gg;
private Timer timer;
private int xarg1, xarg2, xarg3;
private int[] xPoints, yPoints;
private BufferedImage[] blitters = new BufferedImage[512];
private ConfigDialog dlg;
static {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void init() {
try {
Container cp = getContentPane();
cp.setLayout(new BorderLayout());
runtime = (Runtime) Class.forName("PuzzleEngine").newInstance();
runtime.setCallJavaCB(this);
JMenuBar menubar = new JMenuBar();
JMenu jm;
menubar.add(jm = new JMenu("Game"));
addMenuItemWithKey(jm, "New", 'n');
addMenuItemCallback(jm, "Restart", "jcallback_restart_event");
addMenuItemCallback(jm, "Specific...", "jcallback_config_event", CFG_DESC);
addMenuItemCallback(jm, "Random Seed...", "jcallback_config_event", CFG_SEED);
jm.addSeparator();
addMenuItemWithKey(jm, "Undo", 'u');
addMenuItemWithKey(jm, "Redo", 'r');
jm.addSeparator();
solveCommand = addMenuItemCallback(jm, "Solve", "jcallback_solve_event");
solveCommand.setEnabled(false);
if (mainWindow != null) {
jm.addSeparator();
addMenuItemWithKey(jm, "Exit", 'q');
}
menubar.add(typeMenu = new JMenu("Type"));
typeMenu.setVisible(false);
menubar.add(jm = new JMenu("Help"));
addMenuItemCallback(jm, "About", "jcallback_about_event");
setJMenuBar(menubar);
cp.add(pp = new PuzzlePanel(), BorderLayout.CENTER);
pp.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
int key = -1;
int shift = e.isShiftDown() ? MOD_SHFT : 0;
int ctrl = e.isControlDown() ? MOD_CTRL : 0;
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
case KeyEvent.VK_KP_LEFT:
key = shift | ctrl | CURSOR_LEFT;
break;
case KeyEvent.VK_RIGHT:
case KeyEvent.VK_KP_RIGHT:
key = shift | ctrl | CURSOR_RIGHT;
break;
case KeyEvent.VK_UP:
case KeyEvent.VK_KP_UP:
key = shift | ctrl | CURSOR_UP;
break;
case KeyEvent.VK_DOWN:
case KeyEvent.VK_KP_DOWN:
key = shift | ctrl | CURSOR_DOWN;
break;
case KeyEvent.VK_PAGE_UP:
key = shift | ctrl | MOD_NUM_KEYPAD | '9';
break;
case KeyEvent.VK_PAGE_DOWN:
key = shift | ctrl | MOD_NUM_KEYPAD | '3';
break;
case KeyEvent.VK_HOME:
key = shift | ctrl | MOD_NUM_KEYPAD | '7';
break;
case KeyEvent.VK_END:
key = shift | ctrl | MOD_NUM_KEYPAD | '1';
break;
default:
if (e.getKeyCode() >= KeyEvent.VK_NUMPAD0 && e.getKeyCode() <=KeyEvent.VK_NUMPAD9) {
key = MOD_NUM_KEYPAD | (e.getKeyCode() - KeyEvent.VK_NUMPAD0+'0');
}
break;
}
if (key != -1) {
runtimeCall("jcallback_key_event", new int[] {0, 0, key});
}
}
public void keyTyped(KeyEvent e) {
runtimeCall("jcallback_key_event", new int[] {0, 0, e.getKeyChar()});
}
});
pp.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
mousePressedReleased(e, true);
}
public void mousePressed(MouseEvent e) {
pp.requestFocus();
mousePressedReleased(e, false);
}
private void mousePressedReleased(MouseEvent e, boolean released) {
int button;
if ((e.getModifiers() & (InputEvent.BUTTON2_MASK | InputEvent.SHIFT_MASK)) != 0)
button = MIDDLE_BUTTON;
else if ((e.getModifiers() & (InputEvent.BUTTON3_MASK | InputEvent.ALT_MASK)) != 0)
button = RIGHT_BUTTON;
else if ((e.getModifiers() & (InputEvent.BUTTON1_MASK)) != 0)
button = LEFT_BUTTON;
else
return;
if (released)
button += LEFT_RELEASE - LEFT_BUTTON;
runtimeCall("jcallback_key_event", new int[] {e.getX(), e.getY(), button});
}
});
pp.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
int button;
if ((e.getModifiers() & (InputEvent.BUTTON2_MASK | InputEvent.SHIFT_MASK)) != 0)
button = MIDDLE_DRAG;
else if ((e.getModifiers() & (InputEvent.BUTTON3_MASK | InputEvent.ALT_MASK)) != 0)
button = RIGHT_DRAG;
else
button = LEFT_DRAG;
runtimeCall("jcallback_key_event", new int[] {e.getX(), e.getY(), button});
}
});
pp.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
handleResized();
}
});
pp.setFocusable(true);
pp.requestFocus();
timer = new Timer(20, new ActionListener() {
public void actionPerformed(ActionEvent e) {
runtimeCall("jcallback_timer_func", new int[0]);
}
});
String gameid;
try {
gameid = getParameter("game_id");
} catch (java.lang.NullPointerException ex) {
gameid = null;
}
if (gameid == null) {
puzzle_args = null;
} else {
puzzle_args = new String[2];
puzzle_args[0] = "puzzle";
puzzle_args[1] = gameid;
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
runtime.start(puzzle_args);
runtime.execute();
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void destroy() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
runtime.execute();
if (mainWindow != null) {
mainWindow.dispose();
System.exit(0);
}
}
});
}
protected void handleResized() {
pp.createBackBuffer(pp.getWidth(), pp.getHeight(), colors[0]);
runtimeCall("jcallback_resize", new int[] {pp.getWidth(), pp.getHeight()});
}
private void addMenuItemWithKey(JMenu jm, String name, int key) {
addMenuItemCallback(jm, name, "jcallback_menu_key_event", key);
}
private JMenuItem addMenuItemCallback(JMenu jm, String name, final String callback, final int arg) {
return addMenuItemCallback(jm, name, callback, new int[] {arg});
}
private JMenuItem addMenuItemCallback(JMenu jm, String name, final String callback) {
return addMenuItemCallback(jm, name, callback, new int[0]);
}
private JMenuItem addMenuItemCallback(JMenu jm, String name, final String callback, final int[] args) {
JMenuItem jmi;
if (jm == typeMenu)
typeMenu.add(jmi = new JCheckBoxMenuItem(name));
else
jm.add(jmi = new JMenuItem(name));
jmi.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
runtimeCall(callback, args);
}
});
return jmi;
}
protected void runtimeCall(String func, int[] args) {
if (runtimeCallWithResult(func, args) == 42 && mainWindow != null) {
destroy();
}
}
protected int runtimeCallWithResult(String func, int[] args) {
try {
return runtime.call(func, args);
} catch (Runtime.CallException ex) {
ex.printStackTrace();
return 42;
}
}
private void buildConfigureMenuItem() {
if (typeMenu.isVisible()) {
typeMenu.addSeparator();
} else {
typeMenu.setVisible(true);
}
addMenuItemCallback(typeMenu, "Custom...", "jcallback_config_event", CFG_SETTINGS);
}
private void addTypeItem(String name, final int ptrGameParams) {
typeMenu.setVisible(true);
addMenuItemCallback(typeMenu, name, "jcallback_preset_event", ptrGameParams);
}
public int call(int cmd, int arg1, int arg2, int arg3) {
try {
switch(cmd) {
case 0: // initialize
if (mainWindow != null) mainWindow.setTitle(runtime.cstring(arg1));
if ((arg2 & 1) != 0) buildConfigureMenuItem();
if ((arg2 & 2) != 0) addStatusBar();
if ((arg2 & 4) != 0) solveCommand.setEnabled(true);
colors = new Color[arg3];
return 0;
case 1: // Type menu item
addTypeItem(runtime.cstring(arg1), arg2);
return 0;
case 2: // MessageBox
JOptionPane.showMessageDialog(this, runtime.cstring(arg2), runtime.cstring(arg1), arg3 == 0 ? JOptionPane.INFORMATION_MESSAGE : JOptionPane.ERROR_MESSAGE);
return 0;
case 3: // Resize
pp.setPreferredSize(new Dimension(arg1, arg2));
if (mainWindow != null) mainWindow.pack();
handleResized();
if (mainWindow != null) mainWindow.setVisible(true);
return 0;
case 4: // drawing tasks
switch(arg1) {
case 0:
String text = runtime.cstring(arg2);
if (text.equals("")) text = " ";
System.out.println("status '" + text + "'");
statusBar.setText(text); break;
case 1:
gg = pp.backBuffer.createGraphics();
if (arg2 != 0 || arg3 != 0) {
gg.setColor(Color.black);
gg.fillRect(0, 0, arg2, getHeight());
gg.fillRect(0, 0, getWidth(), arg3);
gg.fillRect(getWidth() - arg2, 0, arg2, getHeight());
gg.fillRect(0, getHeight() - arg3, getWidth(), arg3);
gg.setClip(arg2, arg3, getWidth()-2*arg2, getHeight()-2*arg3);
}
break;
case 2: gg.dispose(); pp.repaint(); break;
case 3: gg.setClip(arg2, arg3, xarg1, xarg2); break;
case 4:
if (arg2 == 0 && arg3 == 0) {
gg.fillRect(0, 0, getWidth(), getHeight());
} else {
gg.setClip(arg2, arg3, getWidth()-2*arg2, getHeight()-2*arg3);
}
break;
case 5:
gg.setColor(colors[xarg3]);
gg.fillRect(arg2, arg3, xarg1, xarg2);
break;
case 6:
gg.setColor(colors[xarg3]);
gg.drawLine(arg2, arg3, xarg1, xarg2);
break;
case 7:
xPoints = new int[arg2];
yPoints = new int[arg2];
break;
case 8:
if (arg3 != -1) {
gg.setColor(colors[arg3]);
gg.fillPolygon(xPoints, yPoints, xPoints.length);
}
gg.setColor(colors[arg2]);
gg.drawPolygon(xPoints, yPoints, xPoints.length);
break;
case 9:
if (arg3 != -1) {
gg.setColor(colors[arg3]);
gg.fillOval(xarg1-xarg3, xarg2-xarg3, xarg3*2, xarg3*2);
}
gg.setColor(colors[arg2]);
gg.drawOval(xarg1-xarg3, xarg2-xarg3, xarg3*2, xarg3*2);
break;
case 10:
for(int i=0; i<blitters.length; i++) {
if (blitters[i] == null) {
blitters[i] = new BufferedImage(arg2, arg3, BufferedImage.TYPE_3BYTE_BGR);
return i;
}
}
throw new RuntimeException("No free blitter found!");
case 11: blitters[arg2] = null; break;
case 12:
timer.start(); break;
case 13:
timer.stop(); break;
}
return 0;
case 5: // more arguments
xarg1 = arg1;
xarg2 = arg2;
xarg3 = arg3;
return 0;
case 6: // polygon vertex
xPoints[arg1]=arg2;
yPoints[arg1]=arg3;
return 0;
case 7: // string
gg.setColor(colors[arg2]);
{
String text = runtime.cstring(arg3);
Font ft = new Font((xarg3 & 0x10) != 0 ? "Monospaced" : "Dialog",
Font.PLAIN, 100);
int height100 = this.getFontMetrics(ft).getHeight();
ft = ft.deriveFont(arg1 * 100 / (float)height100);
FontMetrics fm = this.getFontMetrics(ft);
int asc = fm.getAscent(), desc = fm.getDescent();
if ((xarg3 & ALIGN_VCENTRE) != 0)
xarg2 += asc - (asc+desc)/2;
- else
- xarg2 += asc;
int wid = fm.stringWidth(text);
if ((xarg3 & ALIGN_HCENTRE) != 0)
xarg1 -= wid / 2;
else if ((xarg3 & ALIGN_HRIGHT) != 0)
xarg1 -= wid;
gg.setFont(ft);
gg.drawString(text, xarg1, xarg2);
}
return 0;
case 8: // blitter_save
Graphics g2 = blitters[arg1].createGraphics();
g2.drawImage(pp.backBuffer, 0, 0, blitters[arg1].getWidth(), blitters[arg1].getHeight(),
arg2, arg3, arg2 + blitters[arg1].getWidth(), arg3 + blitters[arg1].getHeight(), this);
g2.dispose();
return 0;
case 9: // blitter_load
gg.drawImage(blitters[arg1], arg2, arg3, this);
return 0;
case 10: // dialog_init
dlg= new ConfigDialog(this, runtime.cstring(arg1));
return 0;
case 11: // dialog_add_control
{
int sval_ptr = arg1;
int ival = arg2;
int ptr = xarg1;
int type=xarg2;
String name = runtime.cstring(xarg3);
switch(type) {
case C_STRING:
dlg.addTextBox(ptr, name, runtime.cstring(sval_ptr));
break;
case C_BOOLEAN:
dlg.addCheckBox(ptr, name, ival != 0);
break;
case C_CHOICES:
dlg.addComboBox(ptr, name, runtime.cstring(sval_ptr), ival);
}
}
return 0;
case 12:
dlg.finish();
dlg = null;
return 0;
case 13: // tick a menu item
if (arg1 < 0) arg1 = typeMenu.getItemCount() - 1;
for (int i = 0; i < typeMenu.getItemCount(); i++) {
if (typeMenu.getMenuComponent(i) instanceof JCheckBoxMenuItem) {
((JCheckBoxMenuItem)typeMenu.getMenuComponent(i)).setSelected(arg1 == i);
}
}
return 0;
default:
if (cmd >= 1024 && cmd < 2048) { // palette
colors[cmd-1024] = new Color(arg1, arg2, arg3);
}
if (cmd == 1024) {
pp.setBackground(colors[0]);
if (statusBar != null) statusBar.setBackground(colors[0]);
this.setBackground(colors[0]);
}
return 0;
}
} catch (Throwable ex) {
ex.printStackTrace();
System.exit(-1);
return 0;
}
}
private void addStatusBar() {
statusBar = new JLabel("test");
statusBar.setBorder(new BevelBorder(BevelBorder.LOWERED));
getContentPane().add(BorderLayout.SOUTH,statusBar);
}
// Standalone runner
public static void main(String[] args) {
final PuzzleApplet a = new PuzzleApplet();
JFrame jf = new JFrame("Loading...");
jf.getContentPane().setLayout(new BorderLayout());
jf.getContentPane().add(a, BorderLayout.CENTER);
a.mainWindow=jf;
a.init();
a.start();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
a.stop();
a.destroy();
}
});
jf.setVisible(true);
}
public static class PuzzlePanel extends JPanel {
private static final long serialVersionUID = 1L;
protected BufferedImage backBuffer;
public PuzzlePanel() {
setPreferredSize(new Dimension(100,100));
createBackBuffer(100,100, Color.black);
}
public void createBackBuffer(int w, int h, Color bg) {
if (w > 0 && h > 0) {
backBuffer = new BufferedImage(w,h, BufferedImage.TYPE_3BYTE_BGR);
Graphics g = backBuffer.createGraphics();
g.setColor(bg);
g.fillRect(0, 0, w, h);
g.dispose();
}
}
protected void paintComponent(Graphics g) {
g.drawImage(backBuffer, 0, 0, this);
}
}
public static class ConfigComponent {
public int type;
public int configItemPointer;
public JComponent component;
public ConfigComponent(int type, int configItemPointer, JComponent component) {
this.type = type;
this.configItemPointer = configItemPointer;
this.component = component;
}
}
public class ConfigDialog extends JDialog {
private GridBagConstraints gbcLeft = new GridBagConstraints(
GridBagConstraints.RELATIVE, GridBagConstraints.RELATIVE, 1, 1,
0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 0, 0), 0, 0);
private GridBagConstraints gbcRight = new GridBagConstraints(
GridBagConstraints.RELATIVE, GridBagConstraints.RELATIVE,
GridBagConstraints.REMAINDER, 1, 1.0, 0,
GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
new Insets(5, 5, 5, 5), 0, 0);
private GridBagConstraints gbcBottom = new GridBagConstraints(
GridBagConstraints.RELATIVE, GridBagConstraints.RELATIVE,
GridBagConstraints.REMAINDER, GridBagConstraints.REMAINDER,
1.0, 1.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0);
private static final long serialVersionUID = 1L;
private List components = new ArrayList();
public ConfigDialog(JApplet parent, String title) {
super(JOptionPane.getFrameForComponent(parent), title, true);
getContentPane().setLayout(new GridBagLayout());
}
public void addTextBox(int ptr, String name, String value) {
getContentPane().add(new JLabel(name), gbcLeft);
JComponent c = new JTextField(value, 25);
getContentPane().add(c, gbcRight);
components.add(new ConfigComponent(C_STRING, ptr, c));
}
public void addCheckBox(int ptr, String name, boolean selected) {
JComponent c = new JCheckBox(name, selected);
getContentPane().add(c, gbcRight);
components.add(new ConfigComponent(C_BOOLEAN, ptr, c));
}
public void addComboBox(int ptr, String name, String values, int selected) {
getContentPane().add(new JLabel(name), gbcLeft);
StringTokenizer st = new StringTokenizer(values.substring(1), values.substring(0,1));
JComboBox c = new JComboBox();
c.setEditable(false);
while(st.hasMoreTokens())
c.addItem(st.nextToken());
c.setSelectedIndex(selected);
getContentPane().add(c, gbcRight);
components.add(new ConfigComponent(C_CHOICES, ptr, c));
}
public void finish() {
JPanel buttons = new JPanel(new GridLayout(1, 2, 5, 5));
getContentPane().add(buttons, gbcBottom);
JButton b;
buttons.add(b=new JButton("OK"));
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
save();
dispose();
}
});
getRootPane().setDefaultButton(b);
buttons.add(b=new JButton("Cancel"));
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private void save() {
for (int i = 0; i < components.size(); i++) {
ConfigComponent cc = (ConfigComponent) components.get(i);
switch(cc.type) {
case C_STRING:
JTextField jtf = (JTextField)cc.component;
runtimeCall("jcallback_config_set_string", new int[] {cc.configItemPointer, runtime.strdup(jtf.getText())});
break;
case C_BOOLEAN:
JCheckBox jcb = (JCheckBox)cc.component;
runtimeCall("jcallback_config_set_boolean", new int[] {cc.configItemPointer, jcb.isSelected()?1:0});
break;
case C_CHOICES:
JComboBox jcm = (JComboBox)cc.component;
runtimeCall("jcallback_config_set_choice", new int[] {cc.configItemPointer, jcm.getSelectedIndex()});
break;
}
}
runtimeCall("jcallback_config_ok", new int[0]);
}
}
}
| true | true | public int call(int cmd, int arg1, int arg2, int arg3) {
try {
switch(cmd) {
case 0: // initialize
if (mainWindow != null) mainWindow.setTitle(runtime.cstring(arg1));
if ((arg2 & 1) != 0) buildConfigureMenuItem();
if ((arg2 & 2) != 0) addStatusBar();
if ((arg2 & 4) != 0) solveCommand.setEnabled(true);
colors = new Color[arg3];
return 0;
case 1: // Type menu item
addTypeItem(runtime.cstring(arg1), arg2);
return 0;
case 2: // MessageBox
JOptionPane.showMessageDialog(this, runtime.cstring(arg2), runtime.cstring(arg1), arg3 == 0 ? JOptionPane.INFORMATION_MESSAGE : JOptionPane.ERROR_MESSAGE);
return 0;
case 3: // Resize
pp.setPreferredSize(new Dimension(arg1, arg2));
if (mainWindow != null) mainWindow.pack();
handleResized();
if (mainWindow != null) mainWindow.setVisible(true);
return 0;
case 4: // drawing tasks
switch(arg1) {
case 0:
String text = runtime.cstring(arg2);
if (text.equals("")) text = " ";
System.out.println("status '" + text + "'");
statusBar.setText(text); break;
case 1:
gg = pp.backBuffer.createGraphics();
if (arg2 != 0 || arg3 != 0) {
gg.setColor(Color.black);
gg.fillRect(0, 0, arg2, getHeight());
gg.fillRect(0, 0, getWidth(), arg3);
gg.fillRect(getWidth() - arg2, 0, arg2, getHeight());
gg.fillRect(0, getHeight() - arg3, getWidth(), arg3);
gg.setClip(arg2, arg3, getWidth()-2*arg2, getHeight()-2*arg3);
}
break;
case 2: gg.dispose(); pp.repaint(); break;
case 3: gg.setClip(arg2, arg3, xarg1, xarg2); break;
case 4:
if (arg2 == 0 && arg3 == 0) {
gg.fillRect(0, 0, getWidth(), getHeight());
} else {
gg.setClip(arg2, arg3, getWidth()-2*arg2, getHeight()-2*arg3);
}
break;
case 5:
gg.setColor(colors[xarg3]);
gg.fillRect(arg2, arg3, xarg1, xarg2);
break;
case 6:
gg.setColor(colors[xarg3]);
gg.drawLine(arg2, arg3, xarg1, xarg2);
break;
case 7:
xPoints = new int[arg2];
yPoints = new int[arg2];
break;
case 8:
if (arg3 != -1) {
gg.setColor(colors[arg3]);
gg.fillPolygon(xPoints, yPoints, xPoints.length);
}
gg.setColor(colors[arg2]);
gg.drawPolygon(xPoints, yPoints, xPoints.length);
break;
case 9:
if (arg3 != -1) {
gg.setColor(colors[arg3]);
gg.fillOval(xarg1-xarg3, xarg2-xarg3, xarg3*2, xarg3*2);
}
gg.setColor(colors[arg2]);
gg.drawOval(xarg1-xarg3, xarg2-xarg3, xarg3*2, xarg3*2);
break;
case 10:
for(int i=0; i<blitters.length; i++) {
if (blitters[i] == null) {
blitters[i] = new BufferedImage(arg2, arg3, BufferedImage.TYPE_3BYTE_BGR);
return i;
}
}
throw new RuntimeException("No free blitter found!");
case 11: blitters[arg2] = null; break;
case 12:
timer.start(); break;
case 13:
timer.stop(); break;
}
return 0;
case 5: // more arguments
xarg1 = arg1;
xarg2 = arg2;
xarg3 = arg3;
return 0;
case 6: // polygon vertex
xPoints[arg1]=arg2;
yPoints[arg1]=arg3;
return 0;
case 7: // string
gg.setColor(colors[arg2]);
{
String text = runtime.cstring(arg3);
Font ft = new Font((xarg3 & 0x10) != 0 ? "Monospaced" : "Dialog",
Font.PLAIN, 100);
int height100 = this.getFontMetrics(ft).getHeight();
ft = ft.deriveFont(arg1 * 100 / (float)height100);
FontMetrics fm = this.getFontMetrics(ft);
int asc = fm.getAscent(), desc = fm.getDescent();
if ((xarg3 & ALIGN_VCENTRE) != 0)
xarg2 += asc - (asc+desc)/2;
else
xarg2 += asc;
int wid = fm.stringWidth(text);
if ((xarg3 & ALIGN_HCENTRE) != 0)
xarg1 -= wid / 2;
else if ((xarg3 & ALIGN_HRIGHT) != 0)
xarg1 -= wid;
gg.setFont(ft);
gg.drawString(text, xarg1, xarg2);
}
return 0;
case 8: // blitter_save
Graphics g2 = blitters[arg1].createGraphics();
g2.drawImage(pp.backBuffer, 0, 0, blitters[arg1].getWidth(), blitters[arg1].getHeight(),
arg2, arg3, arg2 + blitters[arg1].getWidth(), arg3 + blitters[arg1].getHeight(), this);
g2.dispose();
return 0;
case 9: // blitter_load
gg.drawImage(blitters[arg1], arg2, arg3, this);
return 0;
case 10: // dialog_init
dlg= new ConfigDialog(this, runtime.cstring(arg1));
return 0;
case 11: // dialog_add_control
{
int sval_ptr = arg1;
int ival = arg2;
int ptr = xarg1;
int type=xarg2;
String name = runtime.cstring(xarg3);
switch(type) {
case C_STRING:
dlg.addTextBox(ptr, name, runtime.cstring(sval_ptr));
break;
case C_BOOLEAN:
dlg.addCheckBox(ptr, name, ival != 0);
break;
case C_CHOICES:
dlg.addComboBox(ptr, name, runtime.cstring(sval_ptr), ival);
}
}
return 0;
case 12:
dlg.finish();
dlg = null;
return 0;
case 13: // tick a menu item
if (arg1 < 0) arg1 = typeMenu.getItemCount() - 1;
for (int i = 0; i < typeMenu.getItemCount(); i++) {
if (typeMenu.getMenuComponent(i) instanceof JCheckBoxMenuItem) {
((JCheckBoxMenuItem)typeMenu.getMenuComponent(i)).setSelected(arg1 == i);
}
}
return 0;
default:
if (cmd >= 1024 && cmd < 2048) { // palette
colors[cmd-1024] = new Color(arg1, arg2, arg3);
}
if (cmd == 1024) {
pp.setBackground(colors[0]);
if (statusBar != null) statusBar.setBackground(colors[0]);
this.setBackground(colors[0]);
}
return 0;
}
} catch (Throwable ex) {
ex.printStackTrace();
System.exit(-1);
return 0;
}
}
| public int call(int cmd, int arg1, int arg2, int arg3) {
try {
switch(cmd) {
case 0: // initialize
if (mainWindow != null) mainWindow.setTitle(runtime.cstring(arg1));
if ((arg2 & 1) != 0) buildConfigureMenuItem();
if ((arg2 & 2) != 0) addStatusBar();
if ((arg2 & 4) != 0) solveCommand.setEnabled(true);
colors = new Color[arg3];
return 0;
case 1: // Type menu item
addTypeItem(runtime.cstring(arg1), arg2);
return 0;
case 2: // MessageBox
JOptionPane.showMessageDialog(this, runtime.cstring(arg2), runtime.cstring(arg1), arg3 == 0 ? JOptionPane.INFORMATION_MESSAGE : JOptionPane.ERROR_MESSAGE);
return 0;
case 3: // Resize
pp.setPreferredSize(new Dimension(arg1, arg2));
if (mainWindow != null) mainWindow.pack();
handleResized();
if (mainWindow != null) mainWindow.setVisible(true);
return 0;
case 4: // drawing tasks
switch(arg1) {
case 0:
String text = runtime.cstring(arg2);
if (text.equals("")) text = " ";
System.out.println("status '" + text + "'");
statusBar.setText(text); break;
case 1:
gg = pp.backBuffer.createGraphics();
if (arg2 != 0 || arg3 != 0) {
gg.setColor(Color.black);
gg.fillRect(0, 0, arg2, getHeight());
gg.fillRect(0, 0, getWidth(), arg3);
gg.fillRect(getWidth() - arg2, 0, arg2, getHeight());
gg.fillRect(0, getHeight() - arg3, getWidth(), arg3);
gg.setClip(arg2, arg3, getWidth()-2*arg2, getHeight()-2*arg3);
}
break;
case 2: gg.dispose(); pp.repaint(); break;
case 3: gg.setClip(arg2, arg3, xarg1, xarg2); break;
case 4:
if (arg2 == 0 && arg3 == 0) {
gg.fillRect(0, 0, getWidth(), getHeight());
} else {
gg.setClip(arg2, arg3, getWidth()-2*arg2, getHeight()-2*arg3);
}
break;
case 5:
gg.setColor(colors[xarg3]);
gg.fillRect(arg2, arg3, xarg1, xarg2);
break;
case 6:
gg.setColor(colors[xarg3]);
gg.drawLine(arg2, arg3, xarg1, xarg2);
break;
case 7:
xPoints = new int[arg2];
yPoints = new int[arg2];
break;
case 8:
if (arg3 != -1) {
gg.setColor(colors[arg3]);
gg.fillPolygon(xPoints, yPoints, xPoints.length);
}
gg.setColor(colors[arg2]);
gg.drawPolygon(xPoints, yPoints, xPoints.length);
break;
case 9:
if (arg3 != -1) {
gg.setColor(colors[arg3]);
gg.fillOval(xarg1-xarg3, xarg2-xarg3, xarg3*2, xarg3*2);
}
gg.setColor(colors[arg2]);
gg.drawOval(xarg1-xarg3, xarg2-xarg3, xarg3*2, xarg3*2);
break;
case 10:
for(int i=0; i<blitters.length; i++) {
if (blitters[i] == null) {
blitters[i] = new BufferedImage(arg2, arg3, BufferedImage.TYPE_3BYTE_BGR);
return i;
}
}
throw new RuntimeException("No free blitter found!");
case 11: blitters[arg2] = null; break;
case 12:
timer.start(); break;
case 13:
timer.stop(); break;
}
return 0;
case 5: // more arguments
xarg1 = arg1;
xarg2 = arg2;
xarg3 = arg3;
return 0;
case 6: // polygon vertex
xPoints[arg1]=arg2;
yPoints[arg1]=arg3;
return 0;
case 7: // string
gg.setColor(colors[arg2]);
{
String text = runtime.cstring(arg3);
Font ft = new Font((xarg3 & 0x10) != 0 ? "Monospaced" : "Dialog",
Font.PLAIN, 100);
int height100 = this.getFontMetrics(ft).getHeight();
ft = ft.deriveFont(arg1 * 100 / (float)height100);
FontMetrics fm = this.getFontMetrics(ft);
int asc = fm.getAscent(), desc = fm.getDescent();
if ((xarg3 & ALIGN_VCENTRE) != 0)
xarg2 += asc - (asc+desc)/2;
int wid = fm.stringWidth(text);
if ((xarg3 & ALIGN_HCENTRE) != 0)
xarg1 -= wid / 2;
else if ((xarg3 & ALIGN_HRIGHT) != 0)
xarg1 -= wid;
gg.setFont(ft);
gg.drawString(text, xarg1, xarg2);
}
return 0;
case 8: // blitter_save
Graphics g2 = blitters[arg1].createGraphics();
g2.drawImage(pp.backBuffer, 0, 0, blitters[arg1].getWidth(), blitters[arg1].getHeight(),
arg2, arg3, arg2 + blitters[arg1].getWidth(), arg3 + blitters[arg1].getHeight(), this);
g2.dispose();
return 0;
case 9: // blitter_load
gg.drawImage(blitters[arg1], arg2, arg3, this);
return 0;
case 10: // dialog_init
dlg= new ConfigDialog(this, runtime.cstring(arg1));
return 0;
case 11: // dialog_add_control
{
int sval_ptr = arg1;
int ival = arg2;
int ptr = xarg1;
int type=xarg2;
String name = runtime.cstring(xarg3);
switch(type) {
case C_STRING:
dlg.addTextBox(ptr, name, runtime.cstring(sval_ptr));
break;
case C_BOOLEAN:
dlg.addCheckBox(ptr, name, ival != 0);
break;
case C_CHOICES:
dlg.addComboBox(ptr, name, runtime.cstring(sval_ptr), ival);
}
}
return 0;
case 12:
dlg.finish();
dlg = null;
return 0;
case 13: // tick a menu item
if (arg1 < 0) arg1 = typeMenu.getItemCount() - 1;
for (int i = 0; i < typeMenu.getItemCount(); i++) {
if (typeMenu.getMenuComponent(i) instanceof JCheckBoxMenuItem) {
((JCheckBoxMenuItem)typeMenu.getMenuComponent(i)).setSelected(arg1 == i);
}
}
return 0;
default:
if (cmd >= 1024 && cmd < 2048) { // palette
colors[cmd-1024] = new Color(arg1, arg2, arg3);
}
if (cmd == 1024) {
pp.setBackground(colors[0]);
if (statusBar != null) statusBar.setBackground(colors[0]);
this.setBackground(colors[0]);
}
return 0;
}
} catch (Throwable ex) {
ex.printStackTrace();
System.exit(-1);
return 0;
}
}
|
diff --git a/pact/pact-compiler/src/main/java/eu/stratosphere/pact/compiler/jobgen/JSONGenerator.java b/pact/pact-compiler/src/main/java/eu/stratosphere/pact/compiler/jobgen/JSONGenerator.java
index e70e042bc..1ddc6181b 100644
--- a/pact/pact-compiler/src/main/java/eu/stratosphere/pact/compiler/jobgen/JSONGenerator.java
+++ b/pact/pact-compiler/src/main/java/eu/stratosphere/pact/compiler/jobgen/JSONGenerator.java
@@ -1,521 +1,522 @@
/***********************************************************************************************************************
*
* Copyright (C) 2010 by the Stratosphere project (http://stratosphere.eu)
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
**********************************************************************************************************************/
package eu.stratosphere.pact.compiler.jobgen;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collections;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import eu.stratosphere.pact.common.contract.CompilerHints;
import eu.stratosphere.pact.common.plan.Visitor;
import eu.stratosphere.pact.common.util.FieldSet;
import eu.stratosphere.pact.compiler.CompilerException;
import eu.stratosphere.pact.compiler.GlobalProperties;
import eu.stratosphere.pact.compiler.LocalProperties;
import eu.stratosphere.pact.compiler.PartitionProperty;
import eu.stratosphere.pact.compiler.plan.OptimizedPlan;
import eu.stratosphere.pact.compiler.plan.OptimizerNode;
import eu.stratosphere.pact.compiler.plan.PactConnection;
import eu.stratosphere.pact.compiler.plan.PactConnection.TempMode;
import eu.stratosphere.pact.compiler.plan.UnionNode;
/**
* Translator for @see eu.stratosphere.pact.compiler.plan.OptimizedPlan into a JSON representation.
*
* @author Fabian Hueske ([email protected])
*/
public class JSONGenerator implements Visitor<OptimizerNode> {
// ------------------------------------------------------------------------
// Members
// ------------------------------------------------------------------------
private Hashtable<OptimizerNode, Integer> nodeIds; // resolves pact nodes to ids
int nodeCnt; // resolves pact nodes to ids
StringBuffer jsonString; // builds the json string
/**
* Generates a JSON representation from the @see eu.stratosphere.pact.compiler.plan.OptimizedPlan
* and writes it to a file.
*
* @param plan
* Plan that is translated to JSON
* @param jsonFile
* File to which the JSON output is written
* @throws IOException
*/
public void writeJSONFile(OptimizedPlan plan, File jsonFile) throws IOException {
FileWriter fw;
fw = new FileWriter(jsonFile);
fw.write(compilePlanToJSON(plan));
fw.close();
}
/**
* Translates a @see eu.stratosphere.pact.compiler.plan.OptimizedPlan in a JSON representation.
*
* @param plan
* Plan that is translated to JSON
* @return The JSON representation of the plan
*/
public String compilePlanToJSON(OptimizedPlan plan) {
// initialization to assign node ids
this.nodeIds = new Hashtable<OptimizerNode, Integer>();
this.nodeCnt = 0;
// init JSON string builder
this.jsonString = new StringBuffer();
// JSON header
this.jsonString.append("{\n\t\"nodes\": [\n\n");
// Generate JSON for plan
plan.accept(this);
// JSON Footer
this.jsonString.deleteCharAt(this.jsonString.lastIndexOf(","));
this.jsonString.append("\t]\n}");
// return JSON string
return this.jsonString.toString();
}
@Override
public boolean preVisit(OptimizerNode visitable) {
if (visitable instanceof UnionNode) return true;
// visit each node and assign a unique id
if (!this.nodeIds.containsKey(visitable)) {
this.nodeIds.put(visitable, this.nodeCnt++);
return true;
}
return false;
}
@Override
public void postVisit(OptimizerNode visitable) {
// determine node type
String type;
switch (visitable.getPactType()) {
case DataSink:
type = "sink";
break;
case DataSource:
type = "source";
break;
case Union:
return;
default:
type = "pact";
break;
}
// start a new node
this.jsonString.append("\t{\n");
// output node id
this.jsonString.append("\t\t\"id\": " + this.nodeIds.get(visitable));
this.jsonString.append(",\n\t\t\"type\": \"" + type + "\"");
// output node contents
String contents;
switch (visitable.getPactType()) {
case DataSink:
contents = visitable.getPactContract().toString();
break;
case DataSource:
contents = visitable.getPactContract().toString();
break;
default:
jsonString.append(",\n\t\t\"pact\": \"" + visitable.getName() + "\"");
contents = visitable.getPactContract().getName();
break;
}
this.jsonString.append(",\n\t\t\"contents\": \"" + contents + "\"");
// output contract
// OutputContract outContr = visitable.getOutputContract();
// if (outContr != null && outContr != OutputContract.None) {
// jsonString.append(",\n\t\t\"outputcontract\": \"" + outContr.name() + "\"");
// }
// degree of parallelism
this.jsonString.append(",\n\t\t\"parallelism\": \""
+ (visitable.getDegreeOfParallelism() >= 1 ? visitable.getDegreeOfParallelism() : "default") + "\"");
// output node predecessors
List<PactConnection> inConns = visitable.getIncomingConnections();
String child1name = "", child2name = "";
if (inConns != null && inConns.size() > 0) {
// start predecessor list
this.jsonString.append(",\n\t\t\"predecessors\": [");
int connCnt = 0;
int inputNum = 0;
for(PactConnection conn : inConns) {
OptimizerNode inputNode = conn.getSourcePact();
List<OptimizerNode> inConnForInput;
if (inputNode instanceof UnionNode) {
inConnForInput = new LinkedList<OptimizerNode>();
for (PactConnection inputOfUnion : inputNode.getIncomingConnections()) {
inConnForInput.add(inputOfUnion.getSourcePact());
}
}
else {
inConnForInput = Collections.singletonList(inputNode);
}
for (OptimizerNode source : inConnForInput) {
this.jsonString.append(connCnt == 0 ? "\n" : ",\n");
if (connCnt == 0) {
child1name += child1name.length() > 0 ? ", " : "";
child1name += source.getPactContract().getName();
} else if (connCnt == 1) {
child2name += child2name.length() > 0 ? ", " : "";
child2name = source.getPactContract().getName();
}
// output predecessor id
this.jsonString.append("\t\t\t{\"id\": " + this.nodeIds.get(source));
// output connection side
if (inConns.size() == 2) {
this.jsonString.append(", \"side\": \"" + (inputNum == 0 ? "first" : "second") + "\"");
}
// output shipping strategy and channel type
String shipStrategy = null;
String channelType = null;
switch (conn.getShipStrategy()) {
case NONE:
// nothing
break;
case FORWARD:
shipStrategy = "Local Forward";
channelType = "memory";
break;
case BROADCAST:
shipStrategy = "Broadcast";
channelType = "network";
break;
case PARTITION_HASH:
shipStrategy = "Partition";
channelType = "network";
break;
case PARTITION_RANGE:
shipStrategy = "Partition (range)";
channelType = "network";
break;
case PARTITION_LOCAL_HASH:
shipStrategy = "Partition local";
channelType = "memory";
+ break;
case SFR:
shipStrategy = "SFR";
channelType = "network";
break;
default:
throw new CompilerException("Unknown ship strategy '" + conn.getShipStrategy().name()
+ "' in JSON generator.");
}
if (shipStrategy != null) {
this.jsonString.append(", \"shippingStrategy\": \"" + shipStrategy + "\"");
}
if (channelType != null) {
this.jsonString.append(", \"channelType\": \"" + channelType + "\"");
}
if (conn.getTempMode() != TempMode.NONE) {
String tempMode = conn.getTempMode().toString();
this.jsonString.append(", \"tempMode\": \"" + tempMode + "\"");
}
this.jsonString.append('}');
connCnt++;
}
inputNum++;
}
// finish predecessors
this.jsonString.append("\t\t]");
}
// local strategy
String locString = null;
if (visitable.getLocalStrategy() != null) {
switch (visitable.getLocalStrategy()) {
case NONE:
// nothing
break;
case HYBRIDHASH_FIRST:
locString = "Hybrid Hash (build: " + child1name + ")";
break;
case HYBRIDHASH_SECOND:
locString = "Hybrid Hash (build: " + child2name + ")";
break;
case MMHASH_FIRST:
locString = "Main-Memory Hash (build: " + child1name + ")";
break;
case MMHASH_SECOND:
locString = "Main-Memory Hash (build: " + child2name + ")";
break;
case NESTEDLOOP_BLOCKED_OUTER_FIRST:
locString = "Nested Loops (Blocked Outer: " + child1name + ")";
break;
case NESTEDLOOP_BLOCKED_OUTER_SECOND:
locString = "Nested Loops (Blocked Outer: " + child2name + ")";
break;
case NESTEDLOOP_STREAMED_OUTER_FIRST:
locString = "Nested Loops (Streamed Outer: " + child1name + ")";
break;
case NESTEDLOOP_STREAMED_OUTER_SECOND:
locString = "Nested Loops (Streamed Outer: " + child2name + ")";
break;
case SORT_BOTH_MERGE:
locString = "Sort-Both-Merge";
break;
case SORT_FIRST_MERGE:
locString = "Sort-First-Merge";
break;
case SORT_SECOND_MERGE:
locString = "Sort-Second-Merge";
break;
case MERGE:
locString = "Merge";
break;
case SORT:
locString = "Sort";
break;
case COMBININGSORT:
locString = "Sort with Combiner";
break;
case SORT_SELF_NESTEDLOOP:
locString = "Sort Self-Nested-Loops";
break;
case SELF_NESTEDLOOP:
locString = "Self-Nested-Loops";
break;
default:
throw new CompilerException("Unknown local strategy '" + visitable.getLocalStrategy().name()
+ "' in JSON generator.");
}
if (locString != null) {
this.jsonString.append(",\n\t\t\"local_strategy\": \"");
this.jsonString.append(locString);
this.jsonString.append("\"");
}
}
{
// output node global properties
GlobalProperties gp = visitable.getGlobalProperties();
this.jsonString.append(",\n\t\t\"global_properties\": [\n");
addProperty(jsonString, "Partitioning", gp.getPartitioning().name(), true);
if (gp.getPartitioning() != PartitionProperty.NONE) {
addProperty(jsonString, "Partitioned on", gp.getPartitionedFields().toString(), false);
}
if (gp.getOrdering() != null) {
addProperty(jsonString, "Order", gp.getOrdering().toString(), false);
}
else {
addProperty(jsonString, "Order", "(none)", false);
}
if (visitable.getUniqueFields() == null || visitable.getUniqueFields().size() == 0) {
addProperty(jsonString, "Uniqueness", "not unique", false);
}
else {
addProperty(jsonString, "Uniqueness", visitable.getUniqueFields().toString(), false);
}
this.jsonString.append("\n\t\t]");
}
{
// output node local properties
LocalProperties lp = visitable.getLocalProperties();
this.jsonString.append(",\n\t\t\"local_properties\": [\n");
if (lp.getOrdering() != null) {
addProperty(jsonString, "Order", lp.getOrdering().toString(), true);
}
else {
addProperty(jsonString, "Order", "(none)", true);
}
if (visitable.getUniqueFields() == null || visitable.getUniqueFields().size() == 0) {
addProperty(jsonString, "Uniqueness", "not unique", false);
}
else {
addProperty(jsonString, "Uniqueness", visitable.getUniqueFields().toString(), false);
}
addProperty(jsonString, "Grouping", lp.isGrouped() ? "grouped": "not grouped", false);
if (lp.isGrouped()) {
addProperty(jsonString, "Grouped on", lp.getGroupedFields().toString(), false);
}
this.jsonString.append("\n\t\t]");
}
// output node size estimates
this.jsonString.append(",\n\t\t\"properties\": [\n");
addProperty(this.jsonString, "Est. Cardinality", visitable.getEstimatedNumRecords() == -1 ? "(unknown)"
: formatNumber(visitable.getEstimatedNumRecords()), true);
String estCardinality = "(unknown)";
if (visitable.getEstimatedCardinalities().size() > 0) {
estCardinality = "";
for (Entry<FieldSet, Long> entry : visitable.getEstimatedCardinalities().entrySet()) {
estCardinality += "[" + entry.getKey().toString() + "->" + entry.getValue() + "]";
}
}
addProperty(jsonString, "Est. Cardinality/fields", estCardinality, false);
addProperty(jsonString, "Est. Output Size", visitable.getEstimatedOutputSize() == -1 ? "(unknown)"
: formatNumber(visitable.getEstimatedOutputSize(), "B"), false);
this.jsonString.append("\t\t]");
// output node cost
if (visitable.getNodeCosts() != null) {
this.jsonString.append(",\n\t\t\"costs\": [\n");
addProperty(this.jsonString, "Network", visitable.getNodeCosts().getNetworkCost() == -1 ? "(unknown)"
: formatNumber(visitable.getNodeCosts().getNetworkCost(), "B"), true);
addProperty(this.jsonString, "Disk I/O", visitable.getNodeCosts().getSecondaryStorageCost() == -1 ? "(unknown)"
: formatNumber(visitable.getNodeCosts().getSecondaryStorageCost(), "B"), false);
addProperty(this.jsonString, "Cumulative Network",
visitable.getCumulativeCosts().getNetworkCost() == -1 ? "(unknown)" : formatNumber(visitable
.getCumulativeCosts().getNetworkCost(), "B"), false);
addProperty(this.jsonString, "Cumulative Disk I/O",
visitable.getCumulativeCosts().getSecondaryStorageCost() == -1 ? "(unknown)" : formatNumber(visitable
.getCumulativeCosts().getSecondaryStorageCost(), "B"), false);
this.jsonString.append("\n\t\t]");
}
// output the node compiler hints
if (visitable.getPactContract().getCompilerHints() != null) {
CompilerHints hints = visitable.getPactContract().getCompilerHints();
CompilerHints defaults = new CompilerHints();
this.jsonString.append(",\n\t\t\"compiler_hints\": [\n");
String hintCardinality = "(none)";
if (hints.getDistinctCounts().size() > 0) {
hintCardinality = "";
for (Entry<FieldSet, Long> entry : visitable.getEstimatedCardinalities().entrySet()) {
hintCardinality += "[" + entry.getKey().toString() + "->" + entry.getValue() + "]";
}
}
addProperty(jsonString, "Cardinality", hintCardinality, true);
addProperty(jsonString, "Avg. Records/StubCall", hints.getAvgRecordsEmittedPerStubCall() == defaults.
getAvgRecordsEmittedPerStubCall() ? "(none)" : String.valueOf(hints.getAvgRecordsEmittedPerStubCall()), false);
String valuesKey = "(none)";
if (hints.getAvgNumRecordsPerDistinctFields().size() > 0) {
valuesKey = "";
for (Entry<FieldSet, Float> entry : hints.getAvgNumRecordsPerDistinctFields().entrySet()) {
valuesKey += "[" + entry.getKey().toString() + "->" + entry.getValue() + "]";
}
}
addProperty(jsonString, "Avg. Values/Distinct fields", valuesKey, false);
addProperty(jsonString, "Avg. Width (bytes)", hints.getAvgBytesPerRecord() == defaults
.getAvgBytesPerRecord() ? "(none)" : String.valueOf(hints.getAvgBytesPerRecord()), false);
this.jsonString.append("\t\t]");
}
// finish node
this.jsonString.append("\n\t},\n");
}
private void addProperty(StringBuffer jsonString, String name, String value, boolean first) {
if (!first) {
jsonString.append(",\n");
}
jsonString.append("\t\t\t{ \"name\": \"");
jsonString.append(name);
jsonString.append("\", \"value\": \"");
jsonString.append(value);
jsonString.append("\" }");
}
public static final String formatNumber(long number) {
return formatNumber(number, "");
}
public static final String formatNumber(long number, String suffix) {
final int fractionalDigits = 2;
StringBuilder bld = new StringBuilder();
bld.append(number);
int len = bld.length();
// get the power of 10 / 3
int pot = (len - (bld.charAt(0) == '-' ? 2 : 1)) / 3;
if (pot >= SIZE_SUFFIXES.length) {
pot = SIZE_SUFFIXES.length - 1;
} else if (pot < 0) {
pot = 0;
}
int beforeDecimal = len - pot * 3;
if (len > beforeDecimal + fractionalDigits) {
bld.setLength(beforeDecimal + fractionalDigits);
}
// insert decimal point
if (pot > 0) {
bld.insert(beforeDecimal, '.');
}
// insert number grouping before decimal point
for (int pos = beforeDecimal - 3; pos > 0; pos -= 3) {
bld.insert(pos, ',');
}
// append the suffix
bld.append(' ');
if (pot > 0) {
bld.append(SIZE_SUFFIXES[pot]);
}
bld.append(suffix);
return bld.toString();
}
private static final char[] SIZE_SUFFIXES = { 0, 'K', 'M', 'G', 'T' };
}
| true | true | public void postVisit(OptimizerNode visitable) {
// determine node type
String type;
switch (visitable.getPactType()) {
case DataSink:
type = "sink";
break;
case DataSource:
type = "source";
break;
case Union:
return;
default:
type = "pact";
break;
}
// start a new node
this.jsonString.append("\t{\n");
// output node id
this.jsonString.append("\t\t\"id\": " + this.nodeIds.get(visitable));
this.jsonString.append(",\n\t\t\"type\": \"" + type + "\"");
// output node contents
String contents;
switch (visitable.getPactType()) {
case DataSink:
contents = visitable.getPactContract().toString();
break;
case DataSource:
contents = visitable.getPactContract().toString();
break;
default:
jsonString.append(",\n\t\t\"pact\": \"" + visitable.getName() + "\"");
contents = visitable.getPactContract().getName();
break;
}
this.jsonString.append(",\n\t\t\"contents\": \"" + contents + "\"");
// output contract
// OutputContract outContr = visitable.getOutputContract();
// if (outContr != null && outContr != OutputContract.None) {
// jsonString.append(",\n\t\t\"outputcontract\": \"" + outContr.name() + "\"");
// }
// degree of parallelism
this.jsonString.append(",\n\t\t\"parallelism\": \""
+ (visitable.getDegreeOfParallelism() >= 1 ? visitable.getDegreeOfParallelism() : "default") + "\"");
// output node predecessors
List<PactConnection> inConns = visitable.getIncomingConnections();
String child1name = "", child2name = "";
if (inConns != null && inConns.size() > 0) {
// start predecessor list
this.jsonString.append(",\n\t\t\"predecessors\": [");
int connCnt = 0;
int inputNum = 0;
for(PactConnection conn : inConns) {
OptimizerNode inputNode = conn.getSourcePact();
List<OptimizerNode> inConnForInput;
if (inputNode instanceof UnionNode) {
inConnForInput = new LinkedList<OptimizerNode>();
for (PactConnection inputOfUnion : inputNode.getIncomingConnections()) {
inConnForInput.add(inputOfUnion.getSourcePact());
}
}
else {
inConnForInput = Collections.singletonList(inputNode);
}
for (OptimizerNode source : inConnForInput) {
this.jsonString.append(connCnt == 0 ? "\n" : ",\n");
if (connCnt == 0) {
child1name += child1name.length() > 0 ? ", " : "";
child1name += source.getPactContract().getName();
} else if (connCnt == 1) {
child2name += child2name.length() > 0 ? ", " : "";
child2name = source.getPactContract().getName();
}
// output predecessor id
this.jsonString.append("\t\t\t{\"id\": " + this.nodeIds.get(source));
// output connection side
if (inConns.size() == 2) {
this.jsonString.append(", \"side\": \"" + (inputNum == 0 ? "first" : "second") + "\"");
}
// output shipping strategy and channel type
String shipStrategy = null;
String channelType = null;
switch (conn.getShipStrategy()) {
case NONE:
// nothing
break;
case FORWARD:
shipStrategy = "Local Forward";
channelType = "memory";
break;
case BROADCAST:
shipStrategy = "Broadcast";
channelType = "network";
break;
case PARTITION_HASH:
shipStrategy = "Partition";
channelType = "network";
break;
case PARTITION_RANGE:
shipStrategy = "Partition (range)";
channelType = "network";
break;
case PARTITION_LOCAL_HASH:
shipStrategy = "Partition local";
channelType = "memory";
case SFR:
shipStrategy = "SFR";
channelType = "network";
break;
default:
throw new CompilerException("Unknown ship strategy '" + conn.getShipStrategy().name()
+ "' in JSON generator.");
}
if (shipStrategy != null) {
this.jsonString.append(", \"shippingStrategy\": \"" + shipStrategy + "\"");
}
if (channelType != null) {
this.jsonString.append(", \"channelType\": \"" + channelType + "\"");
}
if (conn.getTempMode() != TempMode.NONE) {
String tempMode = conn.getTempMode().toString();
this.jsonString.append(", \"tempMode\": \"" + tempMode + "\"");
}
this.jsonString.append('}');
connCnt++;
}
inputNum++;
}
// finish predecessors
this.jsonString.append("\t\t]");
}
// local strategy
String locString = null;
if (visitable.getLocalStrategy() != null) {
switch (visitable.getLocalStrategy()) {
case NONE:
// nothing
break;
case HYBRIDHASH_FIRST:
locString = "Hybrid Hash (build: " + child1name + ")";
break;
case HYBRIDHASH_SECOND:
locString = "Hybrid Hash (build: " + child2name + ")";
break;
case MMHASH_FIRST:
locString = "Main-Memory Hash (build: " + child1name + ")";
break;
case MMHASH_SECOND:
locString = "Main-Memory Hash (build: " + child2name + ")";
break;
case NESTEDLOOP_BLOCKED_OUTER_FIRST:
locString = "Nested Loops (Blocked Outer: " + child1name + ")";
break;
case NESTEDLOOP_BLOCKED_OUTER_SECOND:
locString = "Nested Loops (Blocked Outer: " + child2name + ")";
break;
case NESTEDLOOP_STREAMED_OUTER_FIRST:
locString = "Nested Loops (Streamed Outer: " + child1name + ")";
break;
case NESTEDLOOP_STREAMED_OUTER_SECOND:
locString = "Nested Loops (Streamed Outer: " + child2name + ")";
break;
case SORT_BOTH_MERGE:
locString = "Sort-Both-Merge";
break;
case SORT_FIRST_MERGE:
locString = "Sort-First-Merge";
break;
case SORT_SECOND_MERGE:
locString = "Sort-Second-Merge";
break;
case MERGE:
locString = "Merge";
break;
case SORT:
locString = "Sort";
break;
case COMBININGSORT:
locString = "Sort with Combiner";
break;
case SORT_SELF_NESTEDLOOP:
locString = "Sort Self-Nested-Loops";
break;
case SELF_NESTEDLOOP:
locString = "Self-Nested-Loops";
break;
default:
throw new CompilerException("Unknown local strategy '" + visitable.getLocalStrategy().name()
+ "' in JSON generator.");
}
if (locString != null) {
this.jsonString.append(",\n\t\t\"local_strategy\": \"");
this.jsonString.append(locString);
this.jsonString.append("\"");
}
}
{
// output node global properties
GlobalProperties gp = visitable.getGlobalProperties();
this.jsonString.append(",\n\t\t\"global_properties\": [\n");
addProperty(jsonString, "Partitioning", gp.getPartitioning().name(), true);
if (gp.getPartitioning() != PartitionProperty.NONE) {
addProperty(jsonString, "Partitioned on", gp.getPartitionedFields().toString(), false);
}
if (gp.getOrdering() != null) {
addProperty(jsonString, "Order", gp.getOrdering().toString(), false);
}
else {
addProperty(jsonString, "Order", "(none)", false);
}
if (visitable.getUniqueFields() == null || visitable.getUniqueFields().size() == 0) {
addProperty(jsonString, "Uniqueness", "not unique", false);
}
else {
addProperty(jsonString, "Uniqueness", visitable.getUniqueFields().toString(), false);
}
this.jsonString.append("\n\t\t]");
}
{
// output node local properties
LocalProperties lp = visitable.getLocalProperties();
this.jsonString.append(",\n\t\t\"local_properties\": [\n");
if (lp.getOrdering() != null) {
addProperty(jsonString, "Order", lp.getOrdering().toString(), true);
}
else {
addProperty(jsonString, "Order", "(none)", true);
}
if (visitable.getUniqueFields() == null || visitable.getUniqueFields().size() == 0) {
addProperty(jsonString, "Uniqueness", "not unique", false);
}
else {
addProperty(jsonString, "Uniqueness", visitable.getUniqueFields().toString(), false);
}
addProperty(jsonString, "Grouping", lp.isGrouped() ? "grouped": "not grouped", false);
if (lp.isGrouped()) {
addProperty(jsonString, "Grouped on", lp.getGroupedFields().toString(), false);
}
this.jsonString.append("\n\t\t]");
}
// output node size estimates
this.jsonString.append(",\n\t\t\"properties\": [\n");
addProperty(this.jsonString, "Est. Cardinality", visitable.getEstimatedNumRecords() == -1 ? "(unknown)"
: formatNumber(visitable.getEstimatedNumRecords()), true);
String estCardinality = "(unknown)";
if (visitable.getEstimatedCardinalities().size() > 0) {
estCardinality = "";
for (Entry<FieldSet, Long> entry : visitable.getEstimatedCardinalities().entrySet()) {
estCardinality += "[" + entry.getKey().toString() + "->" + entry.getValue() + "]";
}
}
addProperty(jsonString, "Est. Cardinality/fields", estCardinality, false);
addProperty(jsonString, "Est. Output Size", visitable.getEstimatedOutputSize() == -1 ? "(unknown)"
: formatNumber(visitable.getEstimatedOutputSize(), "B"), false);
this.jsonString.append("\t\t]");
// output node cost
if (visitable.getNodeCosts() != null) {
this.jsonString.append(",\n\t\t\"costs\": [\n");
addProperty(this.jsonString, "Network", visitable.getNodeCosts().getNetworkCost() == -1 ? "(unknown)"
: formatNumber(visitable.getNodeCosts().getNetworkCost(), "B"), true);
addProperty(this.jsonString, "Disk I/O", visitable.getNodeCosts().getSecondaryStorageCost() == -1 ? "(unknown)"
: formatNumber(visitable.getNodeCosts().getSecondaryStorageCost(), "B"), false);
addProperty(this.jsonString, "Cumulative Network",
visitable.getCumulativeCosts().getNetworkCost() == -1 ? "(unknown)" : formatNumber(visitable
.getCumulativeCosts().getNetworkCost(), "B"), false);
addProperty(this.jsonString, "Cumulative Disk I/O",
visitable.getCumulativeCosts().getSecondaryStorageCost() == -1 ? "(unknown)" : formatNumber(visitable
.getCumulativeCosts().getSecondaryStorageCost(), "B"), false);
this.jsonString.append("\n\t\t]");
}
// output the node compiler hints
if (visitable.getPactContract().getCompilerHints() != null) {
CompilerHints hints = visitable.getPactContract().getCompilerHints();
CompilerHints defaults = new CompilerHints();
this.jsonString.append(",\n\t\t\"compiler_hints\": [\n");
String hintCardinality = "(none)";
if (hints.getDistinctCounts().size() > 0) {
hintCardinality = "";
for (Entry<FieldSet, Long> entry : visitable.getEstimatedCardinalities().entrySet()) {
hintCardinality += "[" + entry.getKey().toString() + "->" + entry.getValue() + "]";
}
}
addProperty(jsonString, "Cardinality", hintCardinality, true);
addProperty(jsonString, "Avg. Records/StubCall", hints.getAvgRecordsEmittedPerStubCall() == defaults.
getAvgRecordsEmittedPerStubCall() ? "(none)" : String.valueOf(hints.getAvgRecordsEmittedPerStubCall()), false);
String valuesKey = "(none)";
if (hints.getAvgNumRecordsPerDistinctFields().size() > 0) {
valuesKey = "";
for (Entry<FieldSet, Float> entry : hints.getAvgNumRecordsPerDistinctFields().entrySet()) {
valuesKey += "[" + entry.getKey().toString() + "->" + entry.getValue() + "]";
}
}
addProperty(jsonString, "Avg. Values/Distinct fields", valuesKey, false);
addProperty(jsonString, "Avg. Width (bytes)", hints.getAvgBytesPerRecord() == defaults
.getAvgBytesPerRecord() ? "(none)" : String.valueOf(hints.getAvgBytesPerRecord()), false);
this.jsonString.append("\t\t]");
}
// finish node
this.jsonString.append("\n\t},\n");
}
| public void postVisit(OptimizerNode visitable) {
// determine node type
String type;
switch (visitable.getPactType()) {
case DataSink:
type = "sink";
break;
case DataSource:
type = "source";
break;
case Union:
return;
default:
type = "pact";
break;
}
// start a new node
this.jsonString.append("\t{\n");
// output node id
this.jsonString.append("\t\t\"id\": " + this.nodeIds.get(visitable));
this.jsonString.append(",\n\t\t\"type\": \"" + type + "\"");
// output node contents
String contents;
switch (visitable.getPactType()) {
case DataSink:
contents = visitable.getPactContract().toString();
break;
case DataSource:
contents = visitable.getPactContract().toString();
break;
default:
jsonString.append(",\n\t\t\"pact\": \"" + visitable.getName() + "\"");
contents = visitable.getPactContract().getName();
break;
}
this.jsonString.append(",\n\t\t\"contents\": \"" + contents + "\"");
// output contract
// OutputContract outContr = visitable.getOutputContract();
// if (outContr != null && outContr != OutputContract.None) {
// jsonString.append(",\n\t\t\"outputcontract\": \"" + outContr.name() + "\"");
// }
// degree of parallelism
this.jsonString.append(",\n\t\t\"parallelism\": \""
+ (visitable.getDegreeOfParallelism() >= 1 ? visitable.getDegreeOfParallelism() : "default") + "\"");
// output node predecessors
List<PactConnection> inConns = visitable.getIncomingConnections();
String child1name = "", child2name = "";
if (inConns != null && inConns.size() > 0) {
// start predecessor list
this.jsonString.append(",\n\t\t\"predecessors\": [");
int connCnt = 0;
int inputNum = 0;
for(PactConnection conn : inConns) {
OptimizerNode inputNode = conn.getSourcePact();
List<OptimizerNode> inConnForInput;
if (inputNode instanceof UnionNode) {
inConnForInput = new LinkedList<OptimizerNode>();
for (PactConnection inputOfUnion : inputNode.getIncomingConnections()) {
inConnForInput.add(inputOfUnion.getSourcePact());
}
}
else {
inConnForInput = Collections.singletonList(inputNode);
}
for (OptimizerNode source : inConnForInput) {
this.jsonString.append(connCnt == 0 ? "\n" : ",\n");
if (connCnt == 0) {
child1name += child1name.length() > 0 ? ", " : "";
child1name += source.getPactContract().getName();
} else if (connCnt == 1) {
child2name += child2name.length() > 0 ? ", " : "";
child2name = source.getPactContract().getName();
}
// output predecessor id
this.jsonString.append("\t\t\t{\"id\": " + this.nodeIds.get(source));
// output connection side
if (inConns.size() == 2) {
this.jsonString.append(", \"side\": \"" + (inputNum == 0 ? "first" : "second") + "\"");
}
// output shipping strategy and channel type
String shipStrategy = null;
String channelType = null;
switch (conn.getShipStrategy()) {
case NONE:
// nothing
break;
case FORWARD:
shipStrategy = "Local Forward";
channelType = "memory";
break;
case BROADCAST:
shipStrategy = "Broadcast";
channelType = "network";
break;
case PARTITION_HASH:
shipStrategy = "Partition";
channelType = "network";
break;
case PARTITION_RANGE:
shipStrategy = "Partition (range)";
channelType = "network";
break;
case PARTITION_LOCAL_HASH:
shipStrategy = "Partition local";
channelType = "memory";
break;
case SFR:
shipStrategy = "SFR";
channelType = "network";
break;
default:
throw new CompilerException("Unknown ship strategy '" + conn.getShipStrategy().name()
+ "' in JSON generator.");
}
if (shipStrategy != null) {
this.jsonString.append(", \"shippingStrategy\": \"" + shipStrategy + "\"");
}
if (channelType != null) {
this.jsonString.append(", \"channelType\": \"" + channelType + "\"");
}
if (conn.getTempMode() != TempMode.NONE) {
String tempMode = conn.getTempMode().toString();
this.jsonString.append(", \"tempMode\": \"" + tempMode + "\"");
}
this.jsonString.append('}');
connCnt++;
}
inputNum++;
}
// finish predecessors
this.jsonString.append("\t\t]");
}
// local strategy
String locString = null;
if (visitable.getLocalStrategy() != null) {
switch (visitable.getLocalStrategy()) {
case NONE:
// nothing
break;
case HYBRIDHASH_FIRST:
locString = "Hybrid Hash (build: " + child1name + ")";
break;
case HYBRIDHASH_SECOND:
locString = "Hybrid Hash (build: " + child2name + ")";
break;
case MMHASH_FIRST:
locString = "Main-Memory Hash (build: " + child1name + ")";
break;
case MMHASH_SECOND:
locString = "Main-Memory Hash (build: " + child2name + ")";
break;
case NESTEDLOOP_BLOCKED_OUTER_FIRST:
locString = "Nested Loops (Blocked Outer: " + child1name + ")";
break;
case NESTEDLOOP_BLOCKED_OUTER_SECOND:
locString = "Nested Loops (Blocked Outer: " + child2name + ")";
break;
case NESTEDLOOP_STREAMED_OUTER_FIRST:
locString = "Nested Loops (Streamed Outer: " + child1name + ")";
break;
case NESTEDLOOP_STREAMED_OUTER_SECOND:
locString = "Nested Loops (Streamed Outer: " + child2name + ")";
break;
case SORT_BOTH_MERGE:
locString = "Sort-Both-Merge";
break;
case SORT_FIRST_MERGE:
locString = "Sort-First-Merge";
break;
case SORT_SECOND_MERGE:
locString = "Sort-Second-Merge";
break;
case MERGE:
locString = "Merge";
break;
case SORT:
locString = "Sort";
break;
case COMBININGSORT:
locString = "Sort with Combiner";
break;
case SORT_SELF_NESTEDLOOP:
locString = "Sort Self-Nested-Loops";
break;
case SELF_NESTEDLOOP:
locString = "Self-Nested-Loops";
break;
default:
throw new CompilerException("Unknown local strategy '" + visitable.getLocalStrategy().name()
+ "' in JSON generator.");
}
if (locString != null) {
this.jsonString.append(",\n\t\t\"local_strategy\": \"");
this.jsonString.append(locString);
this.jsonString.append("\"");
}
}
{
// output node global properties
GlobalProperties gp = visitable.getGlobalProperties();
this.jsonString.append(",\n\t\t\"global_properties\": [\n");
addProperty(jsonString, "Partitioning", gp.getPartitioning().name(), true);
if (gp.getPartitioning() != PartitionProperty.NONE) {
addProperty(jsonString, "Partitioned on", gp.getPartitionedFields().toString(), false);
}
if (gp.getOrdering() != null) {
addProperty(jsonString, "Order", gp.getOrdering().toString(), false);
}
else {
addProperty(jsonString, "Order", "(none)", false);
}
if (visitable.getUniqueFields() == null || visitable.getUniqueFields().size() == 0) {
addProperty(jsonString, "Uniqueness", "not unique", false);
}
else {
addProperty(jsonString, "Uniqueness", visitable.getUniqueFields().toString(), false);
}
this.jsonString.append("\n\t\t]");
}
{
// output node local properties
LocalProperties lp = visitable.getLocalProperties();
this.jsonString.append(",\n\t\t\"local_properties\": [\n");
if (lp.getOrdering() != null) {
addProperty(jsonString, "Order", lp.getOrdering().toString(), true);
}
else {
addProperty(jsonString, "Order", "(none)", true);
}
if (visitable.getUniqueFields() == null || visitable.getUniqueFields().size() == 0) {
addProperty(jsonString, "Uniqueness", "not unique", false);
}
else {
addProperty(jsonString, "Uniqueness", visitable.getUniqueFields().toString(), false);
}
addProperty(jsonString, "Grouping", lp.isGrouped() ? "grouped": "not grouped", false);
if (lp.isGrouped()) {
addProperty(jsonString, "Grouped on", lp.getGroupedFields().toString(), false);
}
this.jsonString.append("\n\t\t]");
}
// output node size estimates
this.jsonString.append(",\n\t\t\"properties\": [\n");
addProperty(this.jsonString, "Est. Cardinality", visitable.getEstimatedNumRecords() == -1 ? "(unknown)"
: formatNumber(visitable.getEstimatedNumRecords()), true);
String estCardinality = "(unknown)";
if (visitable.getEstimatedCardinalities().size() > 0) {
estCardinality = "";
for (Entry<FieldSet, Long> entry : visitable.getEstimatedCardinalities().entrySet()) {
estCardinality += "[" + entry.getKey().toString() + "->" + entry.getValue() + "]";
}
}
addProperty(jsonString, "Est. Cardinality/fields", estCardinality, false);
addProperty(jsonString, "Est. Output Size", visitable.getEstimatedOutputSize() == -1 ? "(unknown)"
: formatNumber(visitable.getEstimatedOutputSize(), "B"), false);
this.jsonString.append("\t\t]");
// output node cost
if (visitable.getNodeCosts() != null) {
this.jsonString.append(",\n\t\t\"costs\": [\n");
addProperty(this.jsonString, "Network", visitable.getNodeCosts().getNetworkCost() == -1 ? "(unknown)"
: formatNumber(visitable.getNodeCosts().getNetworkCost(), "B"), true);
addProperty(this.jsonString, "Disk I/O", visitable.getNodeCosts().getSecondaryStorageCost() == -1 ? "(unknown)"
: formatNumber(visitable.getNodeCosts().getSecondaryStorageCost(), "B"), false);
addProperty(this.jsonString, "Cumulative Network",
visitable.getCumulativeCosts().getNetworkCost() == -1 ? "(unknown)" : formatNumber(visitable
.getCumulativeCosts().getNetworkCost(), "B"), false);
addProperty(this.jsonString, "Cumulative Disk I/O",
visitable.getCumulativeCosts().getSecondaryStorageCost() == -1 ? "(unknown)" : formatNumber(visitable
.getCumulativeCosts().getSecondaryStorageCost(), "B"), false);
this.jsonString.append("\n\t\t]");
}
// output the node compiler hints
if (visitable.getPactContract().getCompilerHints() != null) {
CompilerHints hints = visitable.getPactContract().getCompilerHints();
CompilerHints defaults = new CompilerHints();
this.jsonString.append(",\n\t\t\"compiler_hints\": [\n");
String hintCardinality = "(none)";
if (hints.getDistinctCounts().size() > 0) {
hintCardinality = "";
for (Entry<FieldSet, Long> entry : visitable.getEstimatedCardinalities().entrySet()) {
hintCardinality += "[" + entry.getKey().toString() + "->" + entry.getValue() + "]";
}
}
addProperty(jsonString, "Cardinality", hintCardinality, true);
addProperty(jsonString, "Avg. Records/StubCall", hints.getAvgRecordsEmittedPerStubCall() == defaults.
getAvgRecordsEmittedPerStubCall() ? "(none)" : String.valueOf(hints.getAvgRecordsEmittedPerStubCall()), false);
String valuesKey = "(none)";
if (hints.getAvgNumRecordsPerDistinctFields().size() > 0) {
valuesKey = "";
for (Entry<FieldSet, Float> entry : hints.getAvgNumRecordsPerDistinctFields().entrySet()) {
valuesKey += "[" + entry.getKey().toString() + "->" + entry.getValue() + "]";
}
}
addProperty(jsonString, "Avg. Values/Distinct fields", valuesKey, false);
addProperty(jsonString, "Avg. Width (bytes)", hints.getAvgBytesPerRecord() == defaults
.getAvgBytesPerRecord() ? "(none)" : String.valueOf(hints.getAvgBytesPerRecord()), false);
this.jsonString.append("\t\t]");
}
// finish node
this.jsonString.append("\n\t},\n");
}
|
diff --git a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/internal/reviews/ui/dialogs/AddCommentDialog.java b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/internal/reviews/ui/dialogs/AddCommentDialog.java
index 9fed8645..58c15056 100644
--- a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/internal/reviews/ui/dialogs/AddCommentDialog.java
+++ b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/internal/reviews/ui/dialogs/AddCommentDialog.java
@@ -1,212 +1,213 @@
/*******************************************************************************
* Copyright (c) 2011 Tasktop Technologies and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Tasktop Technologies - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.reviews.ui.dialogs;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.mylyn.commons.workbench.editors.CommonTextSupport;
import org.eclipse.mylyn.internal.reviews.ui.ReviewsUiPlugin;
import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin;
import org.eclipse.mylyn.internal.tasks.ui.editors.RichTextEditor;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorExtensions;
import org.eclipse.mylyn.reviews.core.model.IComment;
import org.eclipse.mylyn.reviews.core.model.IFileItem;
import org.eclipse.mylyn.reviews.core.model.IFileVersion;
import org.eclipse.mylyn.reviews.core.model.ILocation;
import org.eclipse.mylyn.reviews.core.model.IReviewItem;
import org.eclipse.mylyn.reviews.core.model.IReviewItemSet;
import org.eclipse.mylyn.reviews.core.spi.ReviewsConnector;
import org.eclipse.mylyn.reviews.core.spi.remote.emf.RemoteEmfConsumer;
import org.eclipse.mylyn.reviews.core.spi.remote.review.IReviewRemoteFactoryProvider;
import org.eclipse.mylyn.reviews.ui.ProgressDialog;
import org.eclipse.mylyn.reviews.ui.ReviewBehavior;
import org.eclipse.mylyn.tasks.core.ITask;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.tasks.ui.TasksUi;
import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorExtension;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.handlers.IHandlerService;
import org.eclipse.ui.statushandlers.StatusManager;
/**
* @author Steffen Pingel
* @author Miles Parker
*/
public class AddCommentDialog extends ProgressDialog {
private RichTextEditor commentEditor;
private final ILocation location;
private final ReviewBehavior reviewBehavior;
protected final ITask task;
protected FormToolkit toolkit;
private final IReviewItem item;
private CommonTextSupport textSupport;
public AddCommentDialog(Shell parentShell, ReviewBehavior reviewBehavior, IReviewItem item, ILocation location) {
super(parentShell);
this.reviewBehavior = reviewBehavior;
this.item = item;
this.location = location;
this.task = reviewBehavior.getTask();
}
@Override
public boolean close() {
if (getReturnCode() == OK) {
boolean shouldClose = performOperation(getComment());
if (!shouldClose) {
return false;
}
}
if (textSupport != null) {
textSupport.dispose();
}
return super.close();
}
public ILocation getLocation() {
return location;
}
public ITask getTask() {
return task;
}
private IComment getComment() {
IComment comment = item.createComment(getLocation(), commentEditor.getText());
return comment;
}
private boolean performOperation(final IComment comment) {
final AtomicReference<IStatus> result = new AtomicReference<IStatus>();
try {
run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
result.set(reviewBehavior.addComment(item, comment, monitor));
}
});
} catch (InvocationTargetException e) {
StatusManager.getManager().handle(
new Status(IStatus.ERROR, ReviewsUiPlugin.PLUGIN_ID,
"Unexpected error during execution of operation", e),
StatusManager.SHOW | StatusManager.LOG);
} catch (InterruptedException e) {
// cancelled
return false;
}
if (result.get().getSeverity() == IStatus.CANCEL) {
return false;
}
if (result.get().isOK()) {
item.getComments().add(comment);
IFileItem file = null;
if (item instanceof IFileItem) {
file = (IFileItem) item;
} else if (item instanceof IFileVersion) {
file = ((IFileVersion) item).getFile();
}
- if (file != null) {
+ if (file != null && file.getReview() != null) {
+ //Update any review item set observers IFF we belong to a review. (The set might represent a compare, in which case we won't have a relevant model object.)
TaskRepository taskRepository = TasksUi.getRepositoryManager().getRepository(
reviewBehavior.getTask().getConnectorKind(), reviewBehavior.getTask().getRepositoryUrl());
ReviewsConnector connector = (ReviewsConnector) TasksUiPlugin.getConnector(reviewBehavior.getTask()
.getConnectorKind());
IReviewRemoteFactoryProvider factoryProvider = (IReviewRemoteFactoryProvider) connector.getReviewClient(
taskRepository)
.getFactoryProvider();
RemoteEmfConsumer<IReviewItemSet, List<IFileItem>, String, ?, ?, Long> consumer = factoryProvider.getReviewItemSetContentFactory()
.getConsumerForLocalKey(file.getSet(), file.getSet().getId());
consumer.updateObservers();
consumer.release();
}
return true;
} else {
StatusManager.getManager().handle(result.get(), StatusManager.SHOW | StatusManager.LOG);
return false;
}
}
@Override
protected Control createDialogArea(Composite parent) {
toolkit = new FormToolkit(TasksUiPlugin.getDefault().getFormColors(parent.getDisplay()));
Control control = super.createDialogArea(parent);
return control;
}
@Override
protected Control createPageControls(Composite parent) {
setTitle("Add Comment");
setMessage("");
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(1, false));
commentEditor = createRichTextEditor(composite, ""); //$NON-NLS-1$
GridDataFactory.fillDefaults().grab(true, true).applyTo(commentEditor.getControl());
return composite;
}
protected RichTextEditor createRichTextEditor(Composite composite, String value) {
int style = SWT.FLAT | SWT.BORDER | SWT.MULTI | SWT.WRAP;
TaskRepository repository = TasksUi.getRepositoryManager().getRepository(task.getConnectorKind(),
task.getRepositoryUrl());
AbstractTaskEditorExtension extension = TaskEditorExtensions.getTaskEditorExtension(repository);
final RichTextEditor editor = new RichTextEditor(repository, style, null, extension, task);
editor.setText(value);
editor.setSpellCheckingEnabled(true);
editor.createControl(composite, toolkit);
IHandlerService handlerService = (IHandlerService) PlatformUI.getWorkbench().getService(IHandlerService.class);
if (handlerService != null) {
textSupport = new CommonTextSupport(handlerService);
textSupport.install(editor.getViewer(), true);
}
// HACK: this is to make sure that we can't have multiple things highlighted
editor.getViewer().getTextWidget().addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
}
public void focusLost(FocusEvent e) {
editor.getViewer().getTextWidget().setSelection(0);
}
});
return editor;
}
}
| true | true | private boolean performOperation(final IComment comment) {
final AtomicReference<IStatus> result = new AtomicReference<IStatus>();
try {
run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
result.set(reviewBehavior.addComment(item, comment, monitor));
}
});
} catch (InvocationTargetException e) {
StatusManager.getManager().handle(
new Status(IStatus.ERROR, ReviewsUiPlugin.PLUGIN_ID,
"Unexpected error during execution of operation", e),
StatusManager.SHOW | StatusManager.LOG);
} catch (InterruptedException e) {
// cancelled
return false;
}
if (result.get().getSeverity() == IStatus.CANCEL) {
return false;
}
if (result.get().isOK()) {
item.getComments().add(comment);
IFileItem file = null;
if (item instanceof IFileItem) {
file = (IFileItem) item;
} else if (item instanceof IFileVersion) {
file = ((IFileVersion) item).getFile();
}
if (file != null) {
TaskRepository taskRepository = TasksUi.getRepositoryManager().getRepository(
reviewBehavior.getTask().getConnectorKind(), reviewBehavior.getTask().getRepositoryUrl());
ReviewsConnector connector = (ReviewsConnector) TasksUiPlugin.getConnector(reviewBehavior.getTask()
.getConnectorKind());
IReviewRemoteFactoryProvider factoryProvider = (IReviewRemoteFactoryProvider) connector.getReviewClient(
taskRepository)
.getFactoryProvider();
RemoteEmfConsumer<IReviewItemSet, List<IFileItem>, String, ?, ?, Long> consumer = factoryProvider.getReviewItemSetContentFactory()
.getConsumerForLocalKey(file.getSet(), file.getSet().getId());
consumer.updateObservers();
consumer.release();
}
return true;
} else {
StatusManager.getManager().handle(result.get(), StatusManager.SHOW | StatusManager.LOG);
return false;
}
}
| private boolean performOperation(final IComment comment) {
final AtomicReference<IStatus> result = new AtomicReference<IStatus>();
try {
run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
result.set(reviewBehavior.addComment(item, comment, monitor));
}
});
} catch (InvocationTargetException e) {
StatusManager.getManager().handle(
new Status(IStatus.ERROR, ReviewsUiPlugin.PLUGIN_ID,
"Unexpected error during execution of operation", e),
StatusManager.SHOW | StatusManager.LOG);
} catch (InterruptedException e) {
// cancelled
return false;
}
if (result.get().getSeverity() == IStatus.CANCEL) {
return false;
}
if (result.get().isOK()) {
item.getComments().add(comment);
IFileItem file = null;
if (item instanceof IFileItem) {
file = (IFileItem) item;
} else if (item instanceof IFileVersion) {
file = ((IFileVersion) item).getFile();
}
if (file != null && file.getReview() != null) {
//Update any review item set observers IFF we belong to a review. (The set might represent a compare, in which case we won't have a relevant model object.)
TaskRepository taskRepository = TasksUi.getRepositoryManager().getRepository(
reviewBehavior.getTask().getConnectorKind(), reviewBehavior.getTask().getRepositoryUrl());
ReviewsConnector connector = (ReviewsConnector) TasksUiPlugin.getConnector(reviewBehavior.getTask()
.getConnectorKind());
IReviewRemoteFactoryProvider factoryProvider = (IReviewRemoteFactoryProvider) connector.getReviewClient(
taskRepository)
.getFactoryProvider();
RemoteEmfConsumer<IReviewItemSet, List<IFileItem>, String, ?, ?, Long> consumer = factoryProvider.getReviewItemSetContentFactory()
.getConsumerForLocalKey(file.getSet(), file.getSet().getId());
consumer.updateObservers();
consumer.release();
}
return true;
} else {
StatusManager.getManager().handle(result.get(), StatusManager.SHOW | StatusManager.LOG);
return false;
}
}
|
diff --git a/src/org/bouncycastle/bcpg/SignatureSubpacket.java b/src/org/bouncycastle/bcpg/SignatureSubpacket.java
index a70b0ed9..3c55776b 100644
--- a/src/org/bouncycastle/bcpg/SignatureSubpacket.java
+++ b/src/org/bouncycastle/bcpg/SignatureSubpacket.java
@@ -1,80 +1,80 @@
package org.bouncycastle.bcpg;
import java.io.*;
/**
* Basic type for a PGP Signature sub-packet.
*/
public class SignatureSubpacket
{
int type;
boolean critical;
protected byte[] data;
protected SignatureSubpacket(
int type,
boolean critical,
byte[] data)
{
this.type = type;
this.critical = critical;
this.data = data;
}
public int getType()
{
return type;
}
public boolean isCritical()
{
return critical;
}
/**
* return the generic data making up the packet.
*/
public byte[] getData()
{
return data;
}
public void encode(
OutputStream out)
throws IOException
{
int bodyLen = data.length + 1;
if (bodyLen < 192)
{
out.write((byte)bodyLen);
}
else if (bodyLen <= 8383)
{
bodyLen -= 192;
out.write((byte)(((bodyLen >> 8) & 0xff) + 192));
out.write((byte)bodyLen);
}
else
{
out.write(0xff);
out.write((byte)(bodyLen >> 24));
out.write((byte)(bodyLen >> 16));
out.write((byte)(bodyLen >> 8));
out.write((byte)bodyLen);
}
if (critical)
{
- out.write(0x80 & type);
+ out.write(0x80 | type);
}
else
{
out.write(type);
}
out.write(data);
}
}
| true | true | public void encode(
OutputStream out)
throws IOException
{
int bodyLen = data.length + 1;
if (bodyLen < 192)
{
out.write((byte)bodyLen);
}
else if (bodyLen <= 8383)
{
bodyLen -= 192;
out.write((byte)(((bodyLen >> 8) & 0xff) + 192));
out.write((byte)bodyLen);
}
else
{
out.write(0xff);
out.write((byte)(bodyLen >> 24));
out.write((byte)(bodyLen >> 16));
out.write((byte)(bodyLen >> 8));
out.write((byte)bodyLen);
}
if (critical)
{
out.write(0x80 & type);
}
else
{
out.write(type);
}
out.write(data);
}
| public void encode(
OutputStream out)
throws IOException
{
int bodyLen = data.length + 1;
if (bodyLen < 192)
{
out.write((byte)bodyLen);
}
else if (bodyLen <= 8383)
{
bodyLen -= 192;
out.write((byte)(((bodyLen >> 8) & 0xff) + 192));
out.write((byte)bodyLen);
}
else
{
out.write(0xff);
out.write((byte)(bodyLen >> 24));
out.write((byte)(bodyLen >> 16));
out.write((byte)(bodyLen >> 8));
out.write((byte)bodyLen);
}
if (critical)
{
out.write(0x80 | type);
}
else
{
out.write(type);
}
out.write(data);
}
|
diff --git a/src/main/java/nl/surfnet/bod/util/TimeStampBridge.java b/src/main/java/nl/surfnet/bod/util/TimeStampBridge.java
index db4d52b80..2199e4bdd 100644
--- a/src/main/java/nl/surfnet/bod/util/TimeStampBridge.java
+++ b/src/main/java/nl/surfnet/bod/util/TimeStampBridge.java
@@ -1,60 +1,60 @@
/**
* The owner of the original code is SURFnet BV.
*
* Portions created by the original owner are Copyright (C) 2011-2012 the
* original owner. All Rights Reserved.
*
* Portions created by other contributors are Copyright (C) the contributor.
* All Rights Reserved.
*
* Contributor(s):
* (Contributors insert name & email here)
*
* This file is part of the SURFnet7 Bandwidth on Demand software.
*
* The SURFnet7 Bandwidth on Demand software is free software: you can
* redistribute it and/or modify it under the terms of the BSD license
* included with this distribution.
*
* If the BSD license cannot be found with this distribution, it is available
* at the following location <http://www.opensource.org/licenses/BSD-3-Clause>
*/
package nl.surfnet.bod.util;
import java.sql.Timestamp;
import nl.surfnet.bod.web.WebUtils;
import org.hibernate.search.bridge.StringBridge;
import org.joda.time.DateTime;
/**
* Handles parsing of timestamps to a String so it can be searched. Needed since
* BoD uses joda timestamps and sql time stamps.
*
*/
public class TimeStampBridge implements StringBridge {
@Override
public String objectToString(Object object) {
- String result = null;
+ String result;
if (object == null) {
- // null
+ result = null;
}
else if (DateTime.class.isAssignableFrom(object.getClass())) {
DateTime dateTime = (DateTime) object;
result = dateTime.toString(WebUtils.DEFAULT_DATE_TIME_FORMATTER);
}
else if (Timestamp.class.isAssignableFrom(object.getClass())) {
Timestamp timestamp = (Timestamp) object;
result = WebUtils.DEFAULT_DATE_TIME_FORMATTER.print(timestamp.getTime());
}
else {
throw new IllegalArgumentException("Bridge is not suitable for handling objects of type: " + object);
}
return result;
}
}
| false | true | public String objectToString(Object object) {
String result = null;
if (object == null) {
// null
}
else if (DateTime.class.isAssignableFrom(object.getClass())) {
DateTime dateTime = (DateTime) object;
result = dateTime.toString(WebUtils.DEFAULT_DATE_TIME_FORMATTER);
}
else if (Timestamp.class.isAssignableFrom(object.getClass())) {
Timestamp timestamp = (Timestamp) object;
result = WebUtils.DEFAULT_DATE_TIME_FORMATTER.print(timestamp.getTime());
}
else {
throw new IllegalArgumentException("Bridge is not suitable for handling objects of type: " + object);
}
return result;
}
| public String objectToString(Object object) {
String result;
if (object == null) {
result = null;
}
else if (DateTime.class.isAssignableFrom(object.getClass())) {
DateTime dateTime = (DateTime) object;
result = dateTime.toString(WebUtils.DEFAULT_DATE_TIME_FORMATTER);
}
else if (Timestamp.class.isAssignableFrom(object.getClass())) {
Timestamp timestamp = (Timestamp) object;
result = WebUtils.DEFAULT_DATE_TIME_FORMATTER.print(timestamp.getTime());
}
else {
throw new IllegalArgumentException("Bridge is not suitable for handling objects of type: " + object);
}
return result;
}
|
diff --git a/drools-analytics/src/test/java/org/drools/analytics/AnalyzerTest.java b/drools-analytics/src/test/java/org/drools/analytics/AnalyzerTest.java
index 05dbc38d63..0b87ec3f7e 100644
--- a/drools-analytics/src/test/java/org/drools/analytics/AnalyzerTest.java
+++ b/drools-analytics/src/test/java/org/drools/analytics/AnalyzerTest.java
@@ -1,78 +1,78 @@
package org.drools.analytics;
import java.io.InputStreamReader;
import org.drools.RuleBase;
import org.drools.analytics.dao.AnalyticsResult;
import org.drools.analytics.report.components.AnalyticsMessageBase;
import org.drools.compiler.DrlParser;
import org.drools.lang.descr.PackageDescr;
import junit.framework.TestCase;
public class AnalyzerTest extends TestCase {
public void testAnalyzer() throws Exception {
Analyzer anal = new Analyzer();
DrlParser p = new DrlParser();
InputStreamReader reader = new InputStreamReader(this.getClass().getResourceAsStream("Misc3.drl"));
PackageDescr pkg = p.parse(reader);
assertFalse(p.hasErrors());
anal.addPackageDescr(pkg);
anal.fireAnalysis();
AnalyticsResult result = anal.getResult();
assertNotNull(result);
assertEquals(0, result.getBySeverity(AnalyticsMessageBase.Severity.ERROR).size());
assertEquals(17, result.getBySeverity(AnalyticsMessageBase.Severity.WARNING).size());
assertEquals(1, result.getBySeverity(AnalyticsMessageBase.Severity.NOTE).size());
//check it again
anal = new Analyzer();
p = new DrlParser();
reader = new InputStreamReader(this.getClass().getResourceAsStream("Misc3.drl"));
pkg = p.parse(reader);
assertFalse(p.hasErrors());
anal.addPackageDescr(pkg);
anal.fireAnalysis();
result = anal.getResult();
assertNotNull(result);
assertEquals(0, result.getBySeverity(AnalyticsMessageBase.Severity.ERROR).size());
- // These row has a problem
+ // This row has a problem
assertEquals( 17, result.getBySeverity(AnalyticsMessageBase.Severity.WARNING).size());
assertEquals(1, result.getBySeverity(AnalyticsMessageBase.Severity.NOTE).size());
}
public void testCacheKnowledgeBase() throws Exception {
Analyzer anal = new Analyzer();
DrlParser p = new DrlParser();
InputStreamReader reader = new InputStreamReader(this.getClass().getResourceAsStream("Misc3.drl"));
PackageDescr pkg = p.parse(reader);
assertFalse(p.hasErrors());
anal.addPackageDescr(pkg);
anal.fireAnalysis();
RuleBase original = Analyzer.analysisKnowledgeBase;
Analyzer anal2 = new Analyzer();
assertSame(original, Analyzer.analysisKnowledgeBase);
anal2.reloadAnalysisKnowledgeBase();
assertNotSame(original, Analyzer.analysisKnowledgeBase);
}
}
| true | true | public void testAnalyzer() throws Exception {
Analyzer anal = new Analyzer();
DrlParser p = new DrlParser();
InputStreamReader reader = new InputStreamReader(this.getClass().getResourceAsStream("Misc3.drl"));
PackageDescr pkg = p.parse(reader);
assertFalse(p.hasErrors());
anal.addPackageDescr(pkg);
anal.fireAnalysis();
AnalyticsResult result = anal.getResult();
assertNotNull(result);
assertEquals(0, result.getBySeverity(AnalyticsMessageBase.Severity.ERROR).size());
assertEquals(17, result.getBySeverity(AnalyticsMessageBase.Severity.WARNING).size());
assertEquals(1, result.getBySeverity(AnalyticsMessageBase.Severity.NOTE).size());
//check it again
anal = new Analyzer();
p = new DrlParser();
reader = new InputStreamReader(this.getClass().getResourceAsStream("Misc3.drl"));
pkg = p.parse(reader);
assertFalse(p.hasErrors());
anal.addPackageDescr(pkg);
anal.fireAnalysis();
result = anal.getResult();
assertNotNull(result);
assertEquals(0, result.getBySeverity(AnalyticsMessageBase.Severity.ERROR).size());
// These row has a problem
assertEquals( 17, result.getBySeverity(AnalyticsMessageBase.Severity.WARNING).size());
assertEquals(1, result.getBySeverity(AnalyticsMessageBase.Severity.NOTE).size());
}
| public void testAnalyzer() throws Exception {
Analyzer anal = new Analyzer();
DrlParser p = new DrlParser();
InputStreamReader reader = new InputStreamReader(this.getClass().getResourceAsStream("Misc3.drl"));
PackageDescr pkg = p.parse(reader);
assertFalse(p.hasErrors());
anal.addPackageDescr(pkg);
anal.fireAnalysis();
AnalyticsResult result = anal.getResult();
assertNotNull(result);
assertEquals(0, result.getBySeverity(AnalyticsMessageBase.Severity.ERROR).size());
assertEquals(17, result.getBySeverity(AnalyticsMessageBase.Severity.WARNING).size());
assertEquals(1, result.getBySeverity(AnalyticsMessageBase.Severity.NOTE).size());
//check it again
anal = new Analyzer();
p = new DrlParser();
reader = new InputStreamReader(this.getClass().getResourceAsStream("Misc3.drl"));
pkg = p.parse(reader);
assertFalse(p.hasErrors());
anal.addPackageDescr(pkg);
anal.fireAnalysis();
result = anal.getResult();
assertNotNull(result);
assertEquals(0, result.getBySeverity(AnalyticsMessageBase.Severity.ERROR).size());
// This row has a problem
assertEquals( 17, result.getBySeverity(AnalyticsMessageBase.Severity.WARNING).size());
assertEquals(1, result.getBySeverity(AnalyticsMessageBase.Severity.NOTE).size());
}
|
diff --git a/model/org/eclipse/cdt/internal/core/model/ext/CElementHandleFactory.java b/model/org/eclipse/cdt/internal/core/model/ext/CElementHandleFactory.java
index 688713325..a421b6dc9 100644
--- a/model/org/eclipse/cdt/internal/core/model/ext/CElementHandleFactory.java
+++ b/model/org/eclipse/cdt/internal/core/model/ext/CElementHandleFactory.java
@@ -1,111 +1,111 @@
/*******************************************************************************
* Copyright (c) 2006 Wind River Systems, Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Markus Schorn - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.model.ext;
import org.eclipse.cdt.core.dom.IName;
import org.eclipse.cdt.core.dom.ast.DOMException;
import org.eclipse.cdt.core.dom.ast.IBinding;
import org.eclipse.cdt.core.dom.ast.ICompositeType;
import org.eclipse.cdt.core.dom.ast.IEnumerator;
import org.eclipse.cdt.core.dom.ast.IField;
import org.eclipse.cdt.core.dom.ast.IFunction;
import org.eclipse.cdt.core.dom.ast.IScope;
import org.eclipse.cdt.core.dom.ast.IVariable;
import org.eclipse.cdt.core.dom.ast.c.ICCompositeTypeScope;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassScope;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassType;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPMethod;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPNamespace;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPNamespaceScope;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.text.IRegion;
/**
* Factory for creating CElement handles. These are a minimal implementation
* of the ICElement interface and can be used for displaying information about
* the index.
* @since 4.0
*/
public class CElementHandleFactory {
private CElementHandleFactory() {}
- public static ICElement create(ITranslationUnit tu, IBinding binding,
+ public static ICElementHandle create(ITranslationUnit tu, IBinding binding,
IRegion region, long timestamp) throws CoreException, DOMException {
ICElement parentElement= create(tu, binding.getScope());
if (parentElement == null) {
return null;
}
CElementHandle element= null;
if (binding instanceof ICPPMethod) {
element= new MethodHandle(parentElement, (ICPPMethod) binding);
}
else if (binding instanceof IFunction) {
element= new FunctionHandle(parentElement, (IFunction) binding);
}
else if (binding instanceof IField) {
element= new FieldHandle(parentElement, (IField) binding);
}
else if (binding instanceof IVariable) {
element= new VariableHandle(parentElement, (IVariable) binding);
}
else if (binding instanceof IEnumerator) {
element= new EnumeratorHandle(parentElement, (IEnumerator) binding);
}
else if (binding instanceof ICompositeType) {
element= new StructureHandle(parentElement, (ICompositeType) binding);
}
else if (binding instanceof ICPPNamespace) {
element= new NamespaceHandle(parentElement, (ICPPNamespace) binding);
}
if (element != null && region != null) {
element.setRangeOfID(region, timestamp);
}
return element;
}
private static ICElement create(ITranslationUnit tu, IScope scope) throws DOMException {
if (scope == null) {
return tu;
}
IName scopeName= scope.getScopeName();
if (scopeName == null) {
if (scope.getParent() == null) {
return tu;
}
return null; // unnamed namespace
}
ICElement parentElement= create(tu, scope.getParent());
if (parentElement == null) {
return null;
}
CElementHandle element= null;
if (scope instanceof ICPPClassScope) {
ICPPClassType type= ((ICPPClassScope) scope).getClassType();
element= new StructureHandle(parentElement, type);
}
else if (scope instanceof ICCompositeTypeScope) {
ICompositeType type= ((ICCompositeTypeScope) scope).getCompositeType();
element= new StructureHandle(parentElement, type);
}
else if (scope instanceof ICPPNamespaceScope) {
element= new NamespaceHandle(parentElement, new String(scopeName.toCharArray()));
}
return element;
}
}
| true | true | public static ICElement create(ITranslationUnit tu, IBinding binding,
IRegion region, long timestamp) throws CoreException, DOMException {
ICElement parentElement= create(tu, binding.getScope());
if (parentElement == null) {
return null;
}
CElementHandle element= null;
if (binding instanceof ICPPMethod) {
element= new MethodHandle(parentElement, (ICPPMethod) binding);
}
else if (binding instanceof IFunction) {
element= new FunctionHandle(parentElement, (IFunction) binding);
}
else if (binding instanceof IField) {
element= new FieldHandle(parentElement, (IField) binding);
}
else if (binding instanceof IVariable) {
element= new VariableHandle(parentElement, (IVariable) binding);
}
else if (binding instanceof IEnumerator) {
element= new EnumeratorHandle(parentElement, (IEnumerator) binding);
}
else if (binding instanceof ICompositeType) {
element= new StructureHandle(parentElement, (ICompositeType) binding);
}
else if (binding instanceof ICPPNamespace) {
element= new NamespaceHandle(parentElement, (ICPPNamespace) binding);
}
if (element != null && region != null) {
element.setRangeOfID(region, timestamp);
}
return element;
}
| public static ICElementHandle create(ITranslationUnit tu, IBinding binding,
IRegion region, long timestamp) throws CoreException, DOMException {
ICElement parentElement= create(tu, binding.getScope());
if (parentElement == null) {
return null;
}
CElementHandle element= null;
if (binding instanceof ICPPMethod) {
element= new MethodHandle(parentElement, (ICPPMethod) binding);
}
else if (binding instanceof IFunction) {
element= new FunctionHandle(parentElement, (IFunction) binding);
}
else if (binding instanceof IField) {
element= new FieldHandle(parentElement, (IField) binding);
}
else if (binding instanceof IVariable) {
element= new VariableHandle(parentElement, (IVariable) binding);
}
else if (binding instanceof IEnumerator) {
element= new EnumeratorHandle(parentElement, (IEnumerator) binding);
}
else if (binding instanceof ICompositeType) {
element= new StructureHandle(parentElement, (ICompositeType) binding);
}
else if (binding instanceof ICPPNamespace) {
element= new NamespaceHandle(parentElement, (ICPPNamespace) binding);
}
if (element != null && region != null) {
element.setRangeOfID(region, timestamp);
}
return element;
}
|
diff --git a/src/n/queens/State.java b/src/n/queens/State.java
index 9f1bed8..d02a8fb 100644
--- a/src/n/queens/State.java
+++ b/src/n/queens/State.java
@@ -1,59 +1,60 @@
package n.queens;
import n.queens.Queen;
import java.util.Random;
/**
*
* @author Rumal
*/
abstract class State {
int boardSize;
int cost;
protected Queen q[];
public State(int boardSize) {
int i;
this.boardSize = boardSize;
q = new Queen[boardSize];
cost = 0;
}
public State(int boardSize, Queen q[]) {
this.boardSize = boardSize;
this.q = q;
cost = 0;
}
abstract public State getNextState();
public void calculateCost() {
int i, j;
cost = 0;
for (i = 0; i < boardSize; i++) {
for (j = 0; j < boardSize; j++) {
- if (q[i].getIndexOfX() == q[j].getIndexOfX()
+ if (i==j) continue;
+ if (q[i].getIndexOfX() == q[j].getIndexOfX() // same row
|| q[i].getIndexOfY() == q[j].getIndexOfY() //same column
|| (q[i].getIndexOfX() - q[j].getIndexOfX() == q[i].getIndexOfY() - q[j].getIndexOfY()) // same diagonal
|| (q[i].getIndexOfX() - q[j].getIndexOfX() == q[j].getIndexOfY() - q[i].getIndexOfY())) { //same counter diagonal
cost++;
}
}
}
//this is due to double counting
cost = cost / 2;
}
public int getCost() {
calculateCost();
return cost;
}
public Queen[] getQueens() {
return q;
}
}
| true | true | public void calculateCost() {
int i, j;
cost = 0;
for (i = 0; i < boardSize; i++) {
for (j = 0; j < boardSize; j++) {
if (q[i].getIndexOfX() == q[j].getIndexOfX()
|| q[i].getIndexOfY() == q[j].getIndexOfY() //same column
|| (q[i].getIndexOfX() - q[j].getIndexOfX() == q[i].getIndexOfY() - q[j].getIndexOfY()) // same diagonal
|| (q[i].getIndexOfX() - q[j].getIndexOfX() == q[j].getIndexOfY() - q[i].getIndexOfY())) { //same counter diagonal
cost++;
}
}
}
//this is due to double counting
cost = cost / 2;
}
| public void calculateCost() {
int i, j;
cost = 0;
for (i = 0; i < boardSize; i++) {
for (j = 0; j < boardSize; j++) {
if (i==j) continue;
if (q[i].getIndexOfX() == q[j].getIndexOfX() // same row
|| q[i].getIndexOfY() == q[j].getIndexOfY() //same column
|| (q[i].getIndexOfX() - q[j].getIndexOfX() == q[i].getIndexOfY() - q[j].getIndexOfY()) // same diagonal
|| (q[i].getIndexOfX() - q[j].getIndexOfX() == q[j].getIndexOfY() - q[i].getIndexOfY())) { //same counter diagonal
cost++;
}
}
}
//this is due to double counting
cost = cost / 2;
}
|
diff --git a/src/View/ClassSelectionView.java b/src/View/ClassSelectionView.java
index 8306417..844a641 100644
--- a/src/View/ClassSelectionView.java
+++ b/src/View/ClassSelectionView.java
@@ -1,141 +1,141 @@
package View;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.*;
import org.newdawn.slick.state.*;
import Control.GlobalClassSelector;
import Model.Player;
import Model.PlayerModel;
import Model.Classes.*;
import Model.Obstacles.Obstacle;
import Model.Obstacles.ObstaclePillar;
public class ClassSelectionView extends BasicGameState implements ActionListener{
private String mouse = "No input yet";
Player player = null;
// private String classType = null;
Image backgroundImage;
Image selectButton;
Image classImage;
String classDescription = "";
String title = "";
Obstacle[] obstacles = new Obstacle[100];
public ClassSelectionView (int state){
}
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException{
backgroundImage = new Image("res/miscImages/sakura001.png");
selectButton = new Image("res/buttons/playButtons.png");
classImage = new Image("res/classImages/classes.png");
title = "Choose your class!";
}
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException{
g.setColor(Color.black);
g.drawImage(backgroundImage, 0, 0);
g.drawString(mouse, 500, 20);
g.drawImage(selectButton, 500, 550);
g.drawImage(classImage, 336, 100);
g.drawString(classDescription, 336, 450);
g.drawString(title, 550, 75);
}
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException{
int xPos = Mouse.getX();
int yPos = 720 - Mouse.getY();
mouse = "Mouse position: (" + xPos + "," + yPos + ")";
/*Random obsGenerator = new Random();
for(int i=0; i<obsGenerator.nextInt(50); i++){
obstacles[i] = new ObstaclePillar(obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1);
}*/
Input input = gc.getInput();
// Control = new PlayerController("Player", obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1, obstacles, "Warrior");
if((500<xPos && xPos<750) && (550<yPos && yPos<604)){
selectButton = new Image("res/buttons/playButton_hover.png");
if(player != null && input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
selectButton = new Image("res/buttons/playButton_pressed.png");
// System.out.println(GlobalClassSelector.getController().getPlayers().size());
GlobalClassSelector.getController().resetPlayers();
// System.out.println(GlobalClassSelector.getController().getPlayers().size());
GlobalClassSelector.getController().addPlayer(player, 0);
// System.out.println(GlobalClassSelector.getController().getPlayers().size());
//Addition of AI player
- GlobalClassSelector.getController().addPlayer(new ClassWarrior("Enemy", 600, 600, 1), 1);
+ GlobalClassSelector.getController().addPlayer(new ClassWarrior("Enemy", "ai", 600, 600, 1), 1);
// System.out.println(GlobalClassSelector.getController().getPlayers().size());
sbg.enterState(1);
}
}else{
selectButton = new Image("res/buttons/playButtons.png");
}
if((340<xPos && xPos<517) && (106<yPos && yPos<425)){
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
classImage = new Image("res/classImages/warriorSelected.png");
classDescription = "The heart of a warrior is filled with courage and strength. \n" +
"Your skills with weapons in close combat makes you a powerful \n" +
"force on the battlefield and a durable opponent for all who dares \n" +
"cross your way.";
- player = new ClassWarrior("Player", 120, 100, 0);
+ player = new ClassWarrior("Player", "player", 120, 100, 0);
// Control = new PlayerController("WarriorMan", obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1, obstacles, "Warrior");
}
}
if((518<xPos && xPos<719) && (106<yPos && yPos<425)){
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
classImage = new Image("res/classImages/hunterSelected.png");
classDescription = "Hunters are stealthy, wealthy and wise to the ways of \n" +
"their opponents. Able to take down tyrants without blinking an eye \n" +
"or breaking a bowstring, you'll range far and wide with this class.";
// classType = "Hunter";
- player = new ClassHunter("Player", 120, 100, 0);
+ player = new ClassHunter("Player", "player", 120, 100, 0);
// Control = new PlayerController("HunterMan", obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1, obstacles, "Hunter");
}
}
if((720<xPos && xPos<938) && (106<yPos && yPos<425)){
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
classImage = new Image("res/classImages/mageSelected.png");
classDescription = "Mages are the quintessential magic user. They attack from \n" +
"a distance, able to cause great harm or restrict a targets actions using \n" +
"their supreme knowledge of the elements.";
// classType = "Wizard";
- player = new ClassWizard("Player", 120, 100, 0);
+ player = new ClassWizard("Player", "player", 120, 100, 0);
// Control = new PlayerController("WizardMan", obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1, obstacles, "Wizard");
}
}
}
public int getID(){
return 3;
}
@Override
public void actionPerformed(ActionEvent arg0) {
}
}
| false | true | public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException{
int xPos = Mouse.getX();
int yPos = 720 - Mouse.getY();
mouse = "Mouse position: (" + xPos + "," + yPos + ")";
/*Random obsGenerator = new Random();
for(int i=0; i<obsGenerator.nextInt(50); i++){
obstacles[i] = new ObstaclePillar(obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1);
}*/
Input input = gc.getInput();
// Control = new PlayerController("Player", obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1, obstacles, "Warrior");
if((500<xPos && xPos<750) && (550<yPos && yPos<604)){
selectButton = new Image("res/buttons/playButton_hover.png");
if(player != null && input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
selectButton = new Image("res/buttons/playButton_pressed.png");
// System.out.println(GlobalClassSelector.getController().getPlayers().size());
GlobalClassSelector.getController().resetPlayers();
// System.out.println(GlobalClassSelector.getController().getPlayers().size());
GlobalClassSelector.getController().addPlayer(player, 0);
// System.out.println(GlobalClassSelector.getController().getPlayers().size());
//Addition of AI player
GlobalClassSelector.getController().addPlayer(new ClassWarrior("Enemy", 600, 600, 1), 1);
// System.out.println(GlobalClassSelector.getController().getPlayers().size());
sbg.enterState(1);
}
}else{
selectButton = new Image("res/buttons/playButtons.png");
}
if((340<xPos && xPos<517) && (106<yPos && yPos<425)){
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
classImage = new Image("res/classImages/warriorSelected.png");
classDescription = "The heart of a warrior is filled with courage and strength. \n" +
"Your skills with weapons in close combat makes you a powerful \n" +
"force on the battlefield and a durable opponent for all who dares \n" +
"cross your way.";
player = new ClassWarrior("Player", 120, 100, 0);
// Control = new PlayerController("WarriorMan", obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1, obstacles, "Warrior");
}
}
if((518<xPos && xPos<719) && (106<yPos && yPos<425)){
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
classImage = new Image("res/classImages/hunterSelected.png");
classDescription = "Hunters are stealthy, wealthy and wise to the ways of \n" +
"their opponents. Able to take down tyrants without blinking an eye \n" +
"or breaking a bowstring, you'll range far and wide with this class.";
// classType = "Hunter";
player = new ClassHunter("Player", 120, 100, 0);
// Control = new PlayerController("HunterMan", obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1, obstacles, "Hunter");
}
}
if((720<xPos && xPos<938) && (106<yPos && yPos<425)){
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
classImage = new Image("res/classImages/mageSelected.png");
classDescription = "Mages are the quintessential magic user. They attack from \n" +
"a distance, able to cause great harm or restrict a targets actions using \n" +
"their supreme knowledge of the elements.";
// classType = "Wizard";
player = new ClassWizard("Player", 120, 100, 0);
// Control = new PlayerController("WizardMan", obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1, obstacles, "Wizard");
}
}
}
| public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException{
int xPos = Mouse.getX();
int yPos = 720 - Mouse.getY();
mouse = "Mouse position: (" + xPos + "," + yPos + ")";
/*Random obsGenerator = new Random();
for(int i=0; i<obsGenerator.nextInt(50); i++){
obstacles[i] = new ObstaclePillar(obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1);
}*/
Input input = gc.getInput();
// Control = new PlayerController("Player", obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1, obstacles, "Warrior");
if((500<xPos && xPos<750) && (550<yPos && yPos<604)){
selectButton = new Image("res/buttons/playButton_hover.png");
if(player != null && input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
selectButton = new Image("res/buttons/playButton_pressed.png");
// System.out.println(GlobalClassSelector.getController().getPlayers().size());
GlobalClassSelector.getController().resetPlayers();
// System.out.println(GlobalClassSelector.getController().getPlayers().size());
GlobalClassSelector.getController().addPlayer(player, 0);
// System.out.println(GlobalClassSelector.getController().getPlayers().size());
//Addition of AI player
GlobalClassSelector.getController().addPlayer(new ClassWarrior("Enemy", "ai", 600, 600, 1), 1);
// System.out.println(GlobalClassSelector.getController().getPlayers().size());
sbg.enterState(1);
}
}else{
selectButton = new Image("res/buttons/playButtons.png");
}
if((340<xPos && xPos<517) && (106<yPos && yPos<425)){
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
classImage = new Image("res/classImages/warriorSelected.png");
classDescription = "The heart of a warrior is filled with courage and strength. \n" +
"Your skills with weapons in close combat makes you a powerful \n" +
"force on the battlefield and a durable opponent for all who dares \n" +
"cross your way.";
player = new ClassWarrior("Player", "player", 120, 100, 0);
// Control = new PlayerController("WarriorMan", obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1, obstacles, "Warrior");
}
}
if((518<xPos && xPos<719) && (106<yPos && yPos<425)){
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
classImage = new Image("res/classImages/hunterSelected.png");
classDescription = "Hunters are stealthy, wealthy and wise to the ways of \n" +
"their opponents. Able to take down tyrants without blinking an eye \n" +
"or breaking a bowstring, you'll range far and wide with this class.";
// classType = "Hunter";
player = new ClassHunter("Player", "player", 120, 100, 0);
// Control = new PlayerController("HunterMan", obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1, obstacles, "Hunter");
}
}
if((720<xPos && xPos<938) && (106<yPos && yPos<425)){
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
classImage = new Image("res/classImages/mageSelected.png");
classDescription = "Mages are the quintessential magic user. They attack from \n" +
"a distance, able to cause great harm or restrict a targets actions using \n" +
"their supreme knowledge of the elements.";
// classType = "Wizard";
player = new ClassWizard("Player", "player", 120, 100, 0);
// Control = new PlayerController("WizardMan", obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1, obstacles, "Wizard");
}
}
}
|
diff --git a/src/net/eonz/bukkit/psduo/signs/normal/DelaySign.java b/src/net/eonz/bukkit/psduo/signs/normal/DelaySign.java
index 99b2853..a03651e 100644
--- a/src/net/eonz/bukkit/psduo/signs/normal/DelaySign.java
+++ b/src/net/eonz/bukkit/psduo/signs/normal/DelaySign.java
@@ -1,129 +1,131 @@
package net.eonz.bukkit.psduo.signs.normal;
/*
* This code is Copyright (C) 2011 Chris Bode, Some Rights Reserved.
*
* Copyright (C) 1999-2002 Technical Pursuit Inc., All Rights Reserved. Patent
* Pending, Technical Pursuit Inc.
*
* Unless explicitly acquired and licensed from Licensor under the Technical
* Pursuit License ("TPL") Version 1.0 or greater, the contents of this file are
* subject to the Reciprocal Public License ("RPL") Version 1.1, or subsequent
* versions as allowed by the RPL, and You may not copy or use this file in
* either source code or executable form, except in compliance with the terms and
* conditions of the RPL.
*
* You may obtain a copy of both the TPL and the RPL (the "Licenses") from
* Technical Pursuit Inc. at http://www.technicalpursuit.com.
*
* All software distributed under the Licenses is provided strictly on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, AND TECHNICAL
* PURSUIT INC. HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT
* LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE, QUIET ENJOYMENT, OR NON-INFRINGEMENT. See the Licenses for specific
* language governing rights and limitations under the Licenses.
*/
import org.bukkit.event.block.BlockRedstoneEvent;
import org.bukkit.event.block.SignChangeEvent;
import net.eonz.bukkit.psduo.signs.PSSign;
import net.eonz.bukkit.psduo.signs.TriggerType;
public class DelaySign extends PSSign {
private boolean lastState;
private boolean out = false;
private boolean ticking = false;
protected void triggersign(TriggerType type, Object args) {
InputState is = this.getInput(1, (BlockRedstoneEvent) args);
if (is == InputState.HIGH && !lastState) {
lastState = true;
if (!ticking)
this.startTicking();
ticking = true;
} else if ((is == InputState.LOW || is == InputState.DISCONNECTED) && lastState) {
lastState = false;
if (!ticking)
this.startTicking();
ticking = true;
} else {
return;
}
}
private boolean[] states;
public boolean tick() {
short sum = 0;
for (int i = 0; i < (states.length - 1); i++) {
states[i] = states[i + 1];
sum += states[i] ? 1 : -1;
}
states[states.length - 1] = this.lastState;
sum += lastState ? 1 : -1;
if (out != states[0]) {
this.setOutput(states[0]);
out = states[0];
}
if (Math.abs(sum) == period) {
ticking = false;
return false;
}
return true;
}
public String getData() {
// This sign does not use data.
return "";
}
protected void setData(String data) {
// This sign does not use data.
}
private int period = 20;
protected void declare(boolean reload, SignChangeEvent event) {
String periodLine = this.getLines(event)[1].trim();
if (periodLine.length() > 0) {
try {
period = Integer.parseInt(periodLine);
} catch (Exception e) {
if (!reload)
this.main.alert(this.getOwnerName(), "Could not understand period, defaulting to 20. (1sec)");
period = 20;
}
if (period > 500 || period <= 0) {
period = 20;
if (!reload)
this.main.alert(this.getOwnerName(), "The period was either too long or too short. Allowed: 1-500");
}
} else {
period = 20;
}
if (!reload) {
this.clearArgLines(event);
this.setLine(1, Integer.toString(period), event);
}
main.sgc.register(this, TriggerType.REDSTONE_CHANGE);
if (!reload) {
this.init("Delay sign accepted.");
}
+ lastState = (this.getInput(1) == InputState.HIGH);
+ this.setOutput(lastState);
states = new boolean[period];
for (int i = 0; i < states.length; i++) {
- states[i] = false;
+ states[i] = lastState;
}
}
}
| false | true | protected void declare(boolean reload, SignChangeEvent event) {
String periodLine = this.getLines(event)[1].trim();
if (periodLine.length() > 0) {
try {
period = Integer.parseInt(periodLine);
} catch (Exception e) {
if (!reload)
this.main.alert(this.getOwnerName(), "Could not understand period, defaulting to 20. (1sec)");
period = 20;
}
if (period > 500 || period <= 0) {
period = 20;
if (!reload)
this.main.alert(this.getOwnerName(), "The period was either too long or too short. Allowed: 1-500");
}
} else {
period = 20;
}
if (!reload) {
this.clearArgLines(event);
this.setLine(1, Integer.toString(period), event);
}
main.sgc.register(this, TriggerType.REDSTONE_CHANGE);
if (!reload) {
this.init("Delay sign accepted.");
}
states = new boolean[period];
for (int i = 0; i < states.length; i++) {
states[i] = false;
}
}
| protected void declare(boolean reload, SignChangeEvent event) {
String periodLine = this.getLines(event)[1].trim();
if (periodLine.length() > 0) {
try {
period = Integer.parseInt(periodLine);
} catch (Exception e) {
if (!reload)
this.main.alert(this.getOwnerName(), "Could not understand period, defaulting to 20. (1sec)");
period = 20;
}
if (period > 500 || period <= 0) {
period = 20;
if (!reload)
this.main.alert(this.getOwnerName(), "The period was either too long or too short. Allowed: 1-500");
}
} else {
period = 20;
}
if (!reload) {
this.clearArgLines(event);
this.setLine(1, Integer.toString(period), event);
}
main.sgc.register(this, TriggerType.REDSTONE_CHANGE);
if (!reload) {
this.init("Delay sign accepted.");
}
lastState = (this.getInput(1) == InputState.HIGH);
this.setOutput(lastState);
states = new boolean[period];
for (int i = 0; i < states.length; i++) {
states[i] = lastState;
}
}
|
diff --git a/src/web/org/openmrs/web/controller/program/PatientProgramFormController.java b/src/web/org/openmrs/web/controller/program/PatientProgramFormController.java
index 7c8a01d0..50106d3c 100644
--- a/src/web/org/openmrs/web/controller/program/PatientProgramFormController.java
+++ b/src/web/org/openmrs/web/controller/program/PatientProgramFormController.java
@@ -1,106 +1,106 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.web.controller.program;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Patient;
import org.openmrs.PatientProgram;
import org.openmrs.Program;
import org.openmrs.api.ProgramWorkflowService;
import org.openmrs.api.context.Context;
import org.openmrs.web.WebConstants;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.view.RedirectView;
public class PatientProgramFormController implements Controller {
protected final Log log = LogFactory.getLog(getClass());
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
// can't do anything without a method
return null;
}
public ModelAndView enroll(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
String returnPage = request.getParameter("returnPage");
if (returnPage == null) {
throw new IllegalArgumentException("must specify a returnPage parameter in a call to enroll()");
}
String patientIdStr = request.getParameter("patientId");
String programIdStr = request.getParameter("programId");
String enrollmentDateStr = request.getParameter("dateEnrolled");
String completionDateStr = request.getParameter("dateCompleted");
log.debug("enroll " + patientIdStr + " in " + programIdStr + " on " + enrollmentDateStr);
ProgramWorkflowService pws = Context.getProgramWorkflowService();
// make sure we parse dates the same was as if we were using the initBinder + property editor method
CustomDateEditor cde = new CustomDateEditor(Context.getDateFormat(), true, 10);
cde.setAsText(enrollmentDateStr);
Date enrollmentDate = (Date) cde.getValue();
cde.setAsText(completionDateStr);
Date completionDate = (Date) cde.getValue();
Patient patient = Context.getPatientService().getPatient(Integer.valueOf(patientIdStr));
Program program = pws.getProgram(Integer.valueOf(programIdStr));
- if (!pws.getPatientPrograms(patient, program, null, enrollmentDate, completionDate, null, false).isEmpty())
+ if (!pws.getPatientPrograms(patient, program, null, completionDate, enrollmentDate, null, false).isEmpty())
request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Program.error.already");
else {
PatientProgram pp = new PatientProgram();
pp.setPatient(patient);
pp.setProgram(program);
pp.setDateEnrolled(enrollmentDate);
pp.setDateCompleted(completionDate);
Context.getProgramWorkflowService().savePatientProgram(pp);
}
return new ModelAndView(new RedirectView(returnPage));
}
public ModelAndView complete(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
String returnPage = request.getParameter("returnPage");
if (returnPage == null) {
throw new IllegalArgumentException("must specify a returnPage parameter in a call to enroll()");
}
String patientProgramIdStr = request.getParameter("patientProgramId");
String dateCompletedStr = request.getParameter("dateCompleted");
// make sure we parse dates the same was as if we were using the initBinder + property editor method
CustomDateEditor cde = new CustomDateEditor(Context.getDateFormat(), true, 10);
cde.setAsText(dateCompletedStr);
Date dateCompleted = (Date) cde.getValue();
PatientProgram p = Context.getProgramWorkflowService().getPatientProgram(Integer.valueOf(patientProgramIdStr));
p.setDateCompleted(dateCompleted);
Context.getProgramWorkflowService().savePatientProgram(p);
return new ModelAndView(new RedirectView(returnPage));
}
}
| true | true | public ModelAndView enroll(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
String returnPage = request.getParameter("returnPage");
if (returnPage == null) {
throw new IllegalArgumentException("must specify a returnPage parameter in a call to enroll()");
}
String patientIdStr = request.getParameter("patientId");
String programIdStr = request.getParameter("programId");
String enrollmentDateStr = request.getParameter("dateEnrolled");
String completionDateStr = request.getParameter("dateCompleted");
log.debug("enroll " + patientIdStr + " in " + programIdStr + " on " + enrollmentDateStr);
ProgramWorkflowService pws = Context.getProgramWorkflowService();
// make sure we parse dates the same was as if we were using the initBinder + property editor method
CustomDateEditor cde = new CustomDateEditor(Context.getDateFormat(), true, 10);
cde.setAsText(enrollmentDateStr);
Date enrollmentDate = (Date) cde.getValue();
cde.setAsText(completionDateStr);
Date completionDate = (Date) cde.getValue();
Patient patient = Context.getPatientService().getPatient(Integer.valueOf(patientIdStr));
Program program = pws.getProgram(Integer.valueOf(programIdStr));
if (!pws.getPatientPrograms(patient, program, null, enrollmentDate, completionDate, null, false).isEmpty())
request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Program.error.already");
else {
PatientProgram pp = new PatientProgram();
pp.setPatient(patient);
pp.setProgram(program);
pp.setDateEnrolled(enrollmentDate);
pp.setDateCompleted(completionDate);
Context.getProgramWorkflowService().savePatientProgram(pp);
}
return new ModelAndView(new RedirectView(returnPage));
}
| public ModelAndView enroll(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
String returnPage = request.getParameter("returnPage");
if (returnPage == null) {
throw new IllegalArgumentException("must specify a returnPage parameter in a call to enroll()");
}
String patientIdStr = request.getParameter("patientId");
String programIdStr = request.getParameter("programId");
String enrollmentDateStr = request.getParameter("dateEnrolled");
String completionDateStr = request.getParameter("dateCompleted");
log.debug("enroll " + patientIdStr + " in " + programIdStr + " on " + enrollmentDateStr);
ProgramWorkflowService pws = Context.getProgramWorkflowService();
// make sure we parse dates the same was as if we were using the initBinder + property editor method
CustomDateEditor cde = new CustomDateEditor(Context.getDateFormat(), true, 10);
cde.setAsText(enrollmentDateStr);
Date enrollmentDate = (Date) cde.getValue();
cde.setAsText(completionDateStr);
Date completionDate = (Date) cde.getValue();
Patient patient = Context.getPatientService().getPatient(Integer.valueOf(patientIdStr));
Program program = pws.getProgram(Integer.valueOf(programIdStr));
if (!pws.getPatientPrograms(patient, program, null, completionDate, enrollmentDate, null, false).isEmpty())
request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Program.error.already");
else {
PatientProgram pp = new PatientProgram();
pp.setPatient(patient);
pp.setProgram(program);
pp.setDateEnrolled(enrollmentDate);
pp.setDateCompleted(completionDate);
Context.getProgramWorkflowService().savePatientProgram(pp);
}
return new ModelAndView(new RedirectView(returnPage));
}
|
diff --git a/javasvn/src/org/tmatesoft/svn/core/internal/util/SVNFormatUtil.java b/javasvn/src/org/tmatesoft/svn/core/internal/util/SVNFormatUtil.java
index 3039b9b81..5b7ee8e95 100644
--- a/javasvn/src/org/tmatesoft/svn/core/internal/util/SVNFormatUtil.java
+++ b/javasvn/src/org/tmatesoft/svn/core/internal/util/SVNFormatUtil.java
@@ -1,91 +1,93 @@
/*
* ====================================================================
* Copyright (c) 2004 TMate Software Ltd. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://tmate.org/svn/license.html.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
* ====================================================================
*/
package org.tmatesoft.svn.core.internal.util;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;
/**
* @version 1.0
* @author TMate Software Ltd.
*/
public class SVNFormatUtil {
private static final DateFormat HUMAN_DATE_FORMAT =
new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss' 'ZZZZ' ('E', 'dd' 'MMM' 'yyyy')'");
private static final Date NULL_DATE = new Date(0);
public static String formatDate(Date date) {
return HUMAN_DATE_FORMAT.format(date != null ? date : NULL_DATE);
}
public static String formatString(String src, int width, boolean left) {
if (src.length() > width) {
return src.substring(0, width);
}
StringBuffer formatted = new StringBuffer();
if (left) {
formatted.append(src);
}
for (int i = 0; i < width - src.length(); i++) {
formatted.append(' ');
}
if (!left) {
formatted.append(src);
}
return formatted.toString();
}
// path relative to the program home directory, or absolute path
public static String formatPath(File file) {
String path;
String rootPath;
path = file.getAbsolutePath();
rootPath = new File("").getAbsolutePath();
path = path.replace(File.separatorChar, '/');
rootPath = rootPath.replace(File.separatorChar, '/');
- if (path.startsWith(rootPath)) {
- path = path.substring(rootPath.length());
+ if (path.equals(rootPath)) {
+ path = "";
+ } else if (path.startsWith(rootPath + "/")) {
+ path = path.substring(rootPath.length() + 1);
}
// remove all "./"
path = condensePath(path);
path = path.replace('/', File.separatorChar);
if (path.trim().length() == 0) {
path = ".";
}
return path;
}
private static String condensePath(String path) {
StringBuffer result = new StringBuffer();
for (StringTokenizer tokens = new StringTokenizer(path, "/", true); tokens
.hasMoreTokens();) {
String token = tokens.nextToken();
if (".".equals(token)) {
if (tokens.hasMoreTokens()) {
String nextToken = tokens.nextToken();
if (!nextToken.equals("/")) {
result.append(nextToken);
}
}
continue;
}
result.append(token);
}
return result.toString();
}
}
| true | true | public static String formatPath(File file) {
String path;
String rootPath;
path = file.getAbsolutePath();
rootPath = new File("").getAbsolutePath();
path = path.replace(File.separatorChar, '/');
rootPath = rootPath.replace(File.separatorChar, '/');
if (path.startsWith(rootPath)) {
path = path.substring(rootPath.length());
}
// remove all "./"
path = condensePath(path);
path = path.replace('/', File.separatorChar);
if (path.trim().length() == 0) {
path = ".";
}
return path;
}
| public static String formatPath(File file) {
String path;
String rootPath;
path = file.getAbsolutePath();
rootPath = new File("").getAbsolutePath();
path = path.replace(File.separatorChar, '/');
rootPath = rootPath.replace(File.separatorChar, '/');
if (path.equals(rootPath)) {
path = "";
} else if (path.startsWith(rootPath + "/")) {
path = path.substring(rootPath.length() + 1);
}
// remove all "./"
path = condensePath(path);
path = path.replace('/', File.separatorChar);
if (path.trim().length() == 0) {
path = ".";
}
return path;
}
|
diff --git a/src/main/java/org/mozilla/gecko/fxa/sync/FxAccountSyncAdapter.java b/src/main/java/org/mozilla/gecko/fxa/sync/FxAccountSyncAdapter.java
index 4ec3e1097..49d5ca58f 100644
--- a/src/main/java/org/mozilla/gecko/fxa/sync/FxAccountSyncAdapter.java
+++ b/src/main/java/org/mozilla/gecko/fxa/sync/FxAccountSyncAdapter.java
@@ -1,438 +1,438 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.gecko.fxa.sync;
import java.net.URI;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.mozilla.gecko.R;
import org.mozilla.gecko.background.common.log.Logger;
import org.mozilla.gecko.background.fxa.FxAccountClient;
import org.mozilla.gecko.background.fxa.FxAccountClient20;
import org.mozilla.gecko.background.fxa.SkewHandler;
import org.mozilla.gecko.browserid.BrowserIDKeyPair;
import org.mozilla.gecko.browserid.JSONWebTokenUtils;
import org.mozilla.gecko.browserid.RSACryptoImplementation;
import org.mozilla.gecko.browserid.verifier.BrowserIDRemoteVerifierClient;
import org.mozilla.gecko.browserid.verifier.BrowserIDVerifierDelegate;
import org.mozilla.gecko.fxa.FxAccountConstants;
import org.mozilla.gecko.fxa.activities.FxAccountStatusActivity;
import org.mozilla.gecko.fxa.authenticator.AndroidFxAccount;
import org.mozilla.gecko.fxa.authenticator.FxAccountAuthenticator;
import org.mozilla.gecko.fxa.login.FxAccountLoginStateMachine;
import org.mozilla.gecko.fxa.login.FxAccountLoginStateMachine.LoginStateMachineDelegate;
import org.mozilla.gecko.fxa.login.FxAccountLoginTransition.Transition;
import org.mozilla.gecko.fxa.login.Married;
import org.mozilla.gecko.fxa.login.State;
import org.mozilla.gecko.fxa.login.State.Action;
import org.mozilla.gecko.fxa.login.State.StateLabel;
import org.mozilla.gecko.sync.ExtendedJSONObject;
import org.mozilla.gecko.sync.GlobalSession;
import org.mozilla.gecko.sync.SharedPreferencesClientsDataDelegate;
import org.mozilla.gecko.sync.SyncConfiguration;
import org.mozilla.gecko.sync.Utils;
import org.mozilla.gecko.sync.crypto.KeyBundle;
import org.mozilla.gecko.sync.delegates.BaseGlobalSessionCallback;
import org.mozilla.gecko.sync.delegates.ClientsDataDelegate;
import org.mozilla.gecko.sync.net.AuthHeaderProvider;
import org.mozilla.gecko.sync.net.HawkAuthHeaderProvider;
import org.mozilla.gecko.sync.stage.GlobalSyncStage.Stage;
import org.mozilla.gecko.tokenserver.TokenServerClient;
import org.mozilla.gecko.tokenserver.TokenServerClientDelegate;
import org.mozilla.gecko.tokenserver.TokenServerException;
import org.mozilla.gecko.tokenserver.TokenServerToken;
import android.accounts.Account;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SyncResult;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
public class FxAccountSyncAdapter extends AbstractThreadedSyncAdapter {
private static final String LOG_TAG = FxAccountSyncAdapter.class.getSimpleName();
public static final int NOTIFICATION_ID = LOG_TAG.hashCode();
protected final ExecutorService executor;
public FxAccountSyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
this.executor = Executors.newSingleThreadExecutor();
}
protected static class SyncDelegate {
protected final Context context;
protected final CountDownLatch latch;
protected final SyncResult syncResult;
protected final AndroidFxAccount fxAccount;
public SyncDelegate(Context context, CountDownLatch latch, SyncResult syncResult, AndroidFxAccount fxAccount) {
if (context == null) {
throw new IllegalArgumentException("context must not be null");
}
if (latch == null) {
throw new IllegalArgumentException("latch must not be null");
}
if (syncResult == null) {
throw new IllegalArgumentException("syncResult must not be null");
}
if (fxAccount == null) {
throw new IllegalArgumentException("fxAccount must not be null");
}
this.context = context;
this.latch = latch;
this.syncResult = syncResult;
this.fxAccount = fxAccount;
}
/**
* No error! Say that we made progress.
*/
protected void setSyncResultSuccess() {
syncResult.stats.numUpdates += 1;
}
/**
* Soft error. Say that we made progress, so that Android will sync us again
* after exponential backoff.
*/
protected void setSyncResultSoftError() {
syncResult.stats.numUpdates += 1;
syncResult.stats.numIoExceptions += 1;
}
/**
* Hard error. We don't want Android to sync us again, even if we make
* progress, until the user intervenes.
*/
protected void setSyncResultHardError() {
syncResult.stats.numAuthExceptions += 1;
}
public void handleSuccess() {
Logger.info(LOG_TAG, "Sync succeeded.");
setSyncResultSuccess();
latch.countDown();
}
public void handleError(Exception e) {
Logger.error(LOG_TAG, "Got exception syncing.", e);
setSyncResultSoftError();
// This is awful, but we need to propagate bad assertions back up the
// chain somehow, and this will do for now.
if (e instanceof TokenServerException) {
// We should only get here *after* we're locked into the married state.
State state = fxAccount.getState();
if (state.getStateLabel() == StateLabel.Married) {
Married married = (Married) state;
fxAccount.setState(married.makeCohabitingState());
}
}
latch.countDown();
}
/**
* When the login machine terminates, we might not be in the
* <code>Married</code> state, and therefore we can't sync. This method
* messages as much to the user.
* <p>
* To avoid stopping us syncing altogether, we set a soft error rather than
* a hard error. In future, we would like to set a hard error if we are in,
* for example, the <code>Separated</code> state, and then have some user
* initiated activity mark the Android account as ready to sync again. This
* is tricky, though, so we play it safe for now.
*
* @param finalState
* that login machine ended in.
*/
public void handleCannotSync(State finalState) {
Logger.warn(LOG_TAG, "Cannot sync from state: " + finalState.getStateLabel());
showNotification(context, finalState);
setSyncResultSoftError();
latch.countDown();
}
}
/**
* A trivial global session callback that ignores backoff requests, upgrades,
* and authorization errors. It simply waits until the sync completes.
*/
protected static class SessionCallback implements BaseGlobalSessionCallback {
protected final SyncDelegate syncDelegate;
public SessionCallback(SyncDelegate syncDelegate) {
this.syncDelegate = syncDelegate;
}
@Override
public boolean shouldBackOff() {
return false;
}
@Override
public void requestBackoff(long backoff) {
}
@Override
public void informUpgradeRequiredResponse(GlobalSession session) {
}
@Override
public void informUnauthorizedResponse(GlobalSession globalSession, URI oldClusterURL) {
}
@Override
public void handleStageCompleted(Stage currentState, GlobalSession globalSession) {
}
@Override
public void handleSuccess(GlobalSession globalSession) {
Logger.info(LOG_TAG, "Global session succeeded.");
syncDelegate.handleSuccess();
}
@Override
public void handleError(GlobalSession globalSession, Exception e) {
Logger.warn(LOG_TAG, "Global session failed."); // Exception will be dumped by delegate below.
syncDelegate.handleError(e);
}
@Override
public void handleAborted(GlobalSession globalSession, String reason) {
Logger.warn(LOG_TAG, "Global session aborted: " + reason);
syncDelegate.handleError(null);
}
};
protected void syncWithAssertion(final String audience,
final String assertion,
URI tokenServerEndpointURI,
final String prefsPath,
final SharedPreferences sharedPrefs,
final KeyBundle syncKeyBundle,
final String clientState,
final BaseGlobalSessionCallback callback) {
TokenServerClient tokenServerclient = new TokenServerClient(tokenServerEndpointURI, executor);
tokenServerclient.getTokenFromBrowserIDAssertion(assertion, true, clientState, new TokenServerClientDelegate() {
@Override
public void handleSuccess(final TokenServerToken token) {
FxAccountConstants.pii(LOG_TAG, "Got token! uid is " + token.uid + " and endpoint is " + token.endpoint + ".");
FxAccountGlobalSession globalSession = null;
try {
ClientsDataDelegate clientsDataDelegate = new SharedPreferencesClientsDataDelegate(sharedPrefs);
// We compute skew over time using SkewHandler. This yields an unchanging
// skew adjustment that the HawkAuthHeaderProvider uses to adjust its
// timestamps. Eventually we might want this to adapt within the scope of a
// global session.
final SkewHandler tokenServerSkewHandler = SkewHandler.getSkewHandlerFromEndpointString(token.endpoint);
final long tokenServerSkew = tokenServerSkewHandler.getSkewInSeconds();
AuthHeaderProvider authHeaderProvider = new HawkAuthHeaderProvider(token.id, token.key.getBytes("UTF-8"), false, tokenServerSkew);
final Context context = getContext();
SyncConfiguration syncConfig = new SyncConfiguration(token.uid, authHeaderProvider, sharedPrefs, syncKeyBundle);
// EXTRAS
final Bundle extras = Bundle.EMPTY;
globalSession = new FxAccountGlobalSession(token.endpoint, syncConfig, callback, context, extras, clientsDataDelegate);
globalSession.start();
} catch (Exception e) {
callback.handleError(globalSession, e);
return;
}
}
@Override
public void handleFailure(TokenServerException e) {
debugAssertion(audience, assertion);
handleError(e);
}
@Override
public void handleError(Exception e) {
Logger.error(LOG_TAG, "Failed to get token.", e);
callback.handleError(null, e);
}
});
}
protected static void showNotification(Context context, State state) {
final NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
final Action action = state.getNeededAction();
if (action == Action.None) {
Logger.info(LOG_TAG, "State " + state.getStateLabel() + " needs no action; cancelling any existing notification.");
notificationManager.cancel(NOTIFICATION_ID);
return;
}
final String title = context.getResources().getString(R.string.fxaccount_sync_sign_in_error_notification_title);
final String text = context.getResources().getString(R.string.fxaccount_sync_sign_in_error_notification_text, state.email);
Logger.info(LOG_TAG, "State " + state.getStateLabel() + " needs action; offering notification with title: " + title);
FxAccountConstants.pii(LOG_TAG, "And text: " + text);
final Intent notificationIntent = new Intent(context, FxAccountStatusActivity.class);
final PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
final Builder builder = new NotificationCompat.Builder(context);
builder
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(R.drawable.ic_status_logo)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
/**
* A trivial Sync implementation that does not cache client keys,
* certificates, or tokens.
*
* This should be replaced with a full {@link FxAccountAuthenticator}-based
* token implementation.
*/
@Override
public void onPerformSync(final Account account, final Bundle extras, final String authority, ContentProviderClient provider, final SyncResult syncResult) {
Logger.setThreadLogTag(FxAccountConstants.GLOBAL_LOG_TAG);
Logger.resetLogging();
Logger.info(LOG_TAG, "Syncing FxAccount" +
" account named " + account.name +
" for authority " + authority +
" with instance " + this + ".");
final Context context = getContext();
final AndroidFxAccount fxAccount = new AndroidFxAccount(context, account);
if (FxAccountConstants.LOG_PERSONAL_INFORMATION) {
fxAccount.dump();
}
final CountDownLatch latch = new CountDownLatch(1);
final SyncDelegate syncDelegate = new SyncDelegate(getContext(), latch, syncResult, fxAccount);
try {
State state;
try {
state = fxAccount.getState();
} catch (Exception e) {
syncDelegate.handleError(e);
return;
}
final String prefsPath = fxAccount.getSyncPrefsPath();
// This will be the same chunk of SharedPreferences that GlobalSession/SyncConfiguration will later create.
final SharedPreferences sharedPrefs = context.getSharedPreferences(prefsPath, Utils.SHARED_PREFERENCES_MODE);
final String audience = fxAccount.getAudience();
final String authServerEndpoint = fxAccount.getAccountServerURI();
final String tokenServerEndpoint = fxAccount.getTokenServerURI();
final URI tokenServerEndpointURI = new URI(tokenServerEndpoint);
// TODO: why doesn't the loginPolicy extract the audience from the account?
final FxAccountClient client = new FxAccountClient20(authServerEndpoint, executor);
final FxAccountLoginStateMachine stateMachine = new FxAccountLoginStateMachine();
stateMachine.advance(state, StateLabel.Married, new LoginStateMachineDelegate() {
@Override
public FxAccountClient getClient() {
return client;
}
@Override
public long getCertificateDurationInMilliseconds() {
- return 60 * 60 * 1000;
+ return 12 * 60 * 60 * 1000;
}
@Override
public long getAssertionDurationInMilliseconds() {
return 15 * 60 * 1000;
}
@Override
public BrowserIDKeyPair generateKeyPair() throws NoSuchAlgorithmException {
return RSACryptoImplementation.generateKeyPair(1024);
}
@Override
public void handleTransition(Transition transition, State state) {
Logger.info(LOG_TAG, "handleTransition: " + transition + " to " + state.getStateLabel());
}
@Override
public void handleFinal(State state) {
Logger.info(LOG_TAG, "handleFinal: in " + state.getStateLabel());
fxAccount.setState(state);
try {
if (state.getStateLabel() != StateLabel.Married) {
syncDelegate.handleCannotSync(state);
return;
}
Married married = (Married) state;
final long now = System.currentTimeMillis();
SkewHandler skewHandler = SkewHandler.getSkewHandlerFromEndpointString(tokenServerEndpoint);
String assertion = married.generateAssertion(audience, JSONWebTokenUtils.DEFAULT_ASSERTION_ISSUER,
now + skewHandler.getSkewInMillis(),
this.getAssertionDurationInMilliseconds());
final BaseGlobalSessionCallback sessionCallback = new SessionCallback(syncDelegate);
syncWithAssertion(audience, assertion, tokenServerEndpointURI, prefsPath, sharedPrefs, married.getSyncKeyBundle(), married.getClientState(), sessionCallback);
} catch (Exception e) {
syncDelegate.handleError(e);
return;
}
}
});
latch.await();
} catch (Exception e) {
Logger.error(LOG_TAG, "Got error syncing.", e);
syncDelegate.handleError(e);
}
Logger.error(LOG_TAG, "Syncing done.");
}
protected void debugAssertion(String audience, String assertion) {
final CountDownLatch verifierLatch = new CountDownLatch(1);
BrowserIDRemoteVerifierClient client = new BrowserIDRemoteVerifierClient(URI.create(BrowserIDRemoteVerifierClient.DEFAULT_VERIFIER_URL));
client.verify(audience, assertion, new BrowserIDVerifierDelegate() {
@Override
public void handleSuccess(ExtendedJSONObject response) {
Logger.info(LOG_TAG, "Remote verifier returned success: " + response.toJSONString());
verifierLatch.countDown();
}
@Override
public void handleFailure(ExtendedJSONObject response) {
Logger.warn(LOG_TAG, "Remote verifier returned failure: " + response.toJSONString());
verifierLatch.countDown();
}
@Override
public void handleError(Exception e) {
Logger.error(LOG_TAG, "Remote verifier returned error.", e);
verifierLatch.countDown();
}
});
try {
verifierLatch.await();
} catch (InterruptedException e) {
Logger.error(LOG_TAG, "Got error.", e);
}
}
}
| true | true | public void onPerformSync(final Account account, final Bundle extras, final String authority, ContentProviderClient provider, final SyncResult syncResult) {
Logger.setThreadLogTag(FxAccountConstants.GLOBAL_LOG_TAG);
Logger.resetLogging();
Logger.info(LOG_TAG, "Syncing FxAccount" +
" account named " + account.name +
" for authority " + authority +
" with instance " + this + ".");
final Context context = getContext();
final AndroidFxAccount fxAccount = new AndroidFxAccount(context, account);
if (FxAccountConstants.LOG_PERSONAL_INFORMATION) {
fxAccount.dump();
}
final CountDownLatch latch = new CountDownLatch(1);
final SyncDelegate syncDelegate = new SyncDelegate(getContext(), latch, syncResult, fxAccount);
try {
State state;
try {
state = fxAccount.getState();
} catch (Exception e) {
syncDelegate.handleError(e);
return;
}
final String prefsPath = fxAccount.getSyncPrefsPath();
// This will be the same chunk of SharedPreferences that GlobalSession/SyncConfiguration will later create.
final SharedPreferences sharedPrefs = context.getSharedPreferences(prefsPath, Utils.SHARED_PREFERENCES_MODE);
final String audience = fxAccount.getAudience();
final String authServerEndpoint = fxAccount.getAccountServerURI();
final String tokenServerEndpoint = fxAccount.getTokenServerURI();
final URI tokenServerEndpointURI = new URI(tokenServerEndpoint);
// TODO: why doesn't the loginPolicy extract the audience from the account?
final FxAccountClient client = new FxAccountClient20(authServerEndpoint, executor);
final FxAccountLoginStateMachine stateMachine = new FxAccountLoginStateMachine();
stateMachine.advance(state, StateLabel.Married, new LoginStateMachineDelegate() {
@Override
public FxAccountClient getClient() {
return client;
}
@Override
public long getCertificateDurationInMilliseconds() {
return 60 * 60 * 1000;
}
@Override
public long getAssertionDurationInMilliseconds() {
return 15 * 60 * 1000;
}
@Override
public BrowserIDKeyPair generateKeyPair() throws NoSuchAlgorithmException {
return RSACryptoImplementation.generateKeyPair(1024);
}
@Override
public void handleTransition(Transition transition, State state) {
Logger.info(LOG_TAG, "handleTransition: " + transition + " to " + state.getStateLabel());
}
@Override
public void handleFinal(State state) {
Logger.info(LOG_TAG, "handleFinal: in " + state.getStateLabel());
fxAccount.setState(state);
try {
if (state.getStateLabel() != StateLabel.Married) {
syncDelegate.handleCannotSync(state);
return;
}
Married married = (Married) state;
final long now = System.currentTimeMillis();
SkewHandler skewHandler = SkewHandler.getSkewHandlerFromEndpointString(tokenServerEndpoint);
String assertion = married.generateAssertion(audience, JSONWebTokenUtils.DEFAULT_ASSERTION_ISSUER,
now + skewHandler.getSkewInMillis(),
this.getAssertionDurationInMilliseconds());
final BaseGlobalSessionCallback sessionCallback = new SessionCallback(syncDelegate);
syncWithAssertion(audience, assertion, tokenServerEndpointURI, prefsPath, sharedPrefs, married.getSyncKeyBundle(), married.getClientState(), sessionCallback);
} catch (Exception e) {
syncDelegate.handleError(e);
return;
}
}
});
latch.await();
} catch (Exception e) {
Logger.error(LOG_TAG, "Got error syncing.", e);
syncDelegate.handleError(e);
}
Logger.error(LOG_TAG, "Syncing done.");
}
| public void onPerformSync(final Account account, final Bundle extras, final String authority, ContentProviderClient provider, final SyncResult syncResult) {
Logger.setThreadLogTag(FxAccountConstants.GLOBAL_LOG_TAG);
Logger.resetLogging();
Logger.info(LOG_TAG, "Syncing FxAccount" +
" account named " + account.name +
" for authority " + authority +
" with instance " + this + ".");
final Context context = getContext();
final AndroidFxAccount fxAccount = new AndroidFxAccount(context, account);
if (FxAccountConstants.LOG_PERSONAL_INFORMATION) {
fxAccount.dump();
}
final CountDownLatch latch = new CountDownLatch(1);
final SyncDelegate syncDelegate = new SyncDelegate(getContext(), latch, syncResult, fxAccount);
try {
State state;
try {
state = fxAccount.getState();
} catch (Exception e) {
syncDelegate.handleError(e);
return;
}
final String prefsPath = fxAccount.getSyncPrefsPath();
// This will be the same chunk of SharedPreferences that GlobalSession/SyncConfiguration will later create.
final SharedPreferences sharedPrefs = context.getSharedPreferences(prefsPath, Utils.SHARED_PREFERENCES_MODE);
final String audience = fxAccount.getAudience();
final String authServerEndpoint = fxAccount.getAccountServerURI();
final String tokenServerEndpoint = fxAccount.getTokenServerURI();
final URI tokenServerEndpointURI = new URI(tokenServerEndpoint);
// TODO: why doesn't the loginPolicy extract the audience from the account?
final FxAccountClient client = new FxAccountClient20(authServerEndpoint, executor);
final FxAccountLoginStateMachine stateMachine = new FxAccountLoginStateMachine();
stateMachine.advance(state, StateLabel.Married, new LoginStateMachineDelegate() {
@Override
public FxAccountClient getClient() {
return client;
}
@Override
public long getCertificateDurationInMilliseconds() {
return 12 * 60 * 60 * 1000;
}
@Override
public long getAssertionDurationInMilliseconds() {
return 15 * 60 * 1000;
}
@Override
public BrowserIDKeyPair generateKeyPair() throws NoSuchAlgorithmException {
return RSACryptoImplementation.generateKeyPair(1024);
}
@Override
public void handleTransition(Transition transition, State state) {
Logger.info(LOG_TAG, "handleTransition: " + transition + " to " + state.getStateLabel());
}
@Override
public void handleFinal(State state) {
Logger.info(LOG_TAG, "handleFinal: in " + state.getStateLabel());
fxAccount.setState(state);
try {
if (state.getStateLabel() != StateLabel.Married) {
syncDelegate.handleCannotSync(state);
return;
}
Married married = (Married) state;
final long now = System.currentTimeMillis();
SkewHandler skewHandler = SkewHandler.getSkewHandlerFromEndpointString(tokenServerEndpoint);
String assertion = married.generateAssertion(audience, JSONWebTokenUtils.DEFAULT_ASSERTION_ISSUER,
now + skewHandler.getSkewInMillis(),
this.getAssertionDurationInMilliseconds());
final BaseGlobalSessionCallback sessionCallback = new SessionCallback(syncDelegate);
syncWithAssertion(audience, assertion, tokenServerEndpointURI, prefsPath, sharedPrefs, married.getSyncKeyBundle(), married.getClientState(), sessionCallback);
} catch (Exception e) {
syncDelegate.handleError(e);
return;
}
}
});
latch.await();
} catch (Exception e) {
Logger.error(LOG_TAG, "Got error syncing.", e);
syncDelegate.handleError(e);
}
Logger.error(LOG_TAG, "Syncing done.");
}
|
diff --git a/netbeans-virgo-maven-support/src/th/co/geniustree/virgo/maven/DeployActionBase.java b/netbeans-virgo-maven-support/src/th/co/geniustree/virgo/maven/DeployActionBase.java
index 59e584a..f7cc793 100644
--- a/netbeans-virgo-maven-support/src/th/co/geniustree/virgo/maven/DeployActionBase.java
+++ b/netbeans-virgo-maven-support/src/th/co/geniustree/virgo/maven/DeployActionBase.java
@@ -1,127 +1,128 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package th.co.geniustree.virgo.maven;
import java.awt.EventQueue;
import th.co.geniustree.virgo.server.api.ServerInstanceProviderUtils;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.logging.Logger;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MalformedObjectNameException;
import javax.management.ReflectionException;
import javax.swing.SwingWorker;
import org.apache.maven.project.MavenProject;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.netbeans.api.project.Project;
import org.netbeans.api.server.ServerInstance;
import org.netbeans.modules.maven.api.NbMavenProject;
import org.netbeans.modules.maven.api.execute.RunConfig;
import org.netbeans.modules.maven.api.execute.RunUtils;
import org.netbeans.spi.server.ServerInstanceProvider;
import org.openide.execution.ExecutorTask;
import org.openide.util.Exceptions;
import org.openide.util.Task;
import org.openide.util.TaskListener;
import th.co.geniustree.virgo.server.api.Deployer;
/**
*
* @author pramoth
*/
public abstract class DeployActionBase implements ActionListener {
protected final Project context;
public DeployActionBase(Project context) {
this.context = context;
}
@Override
public void actionPerformed(ActionEvent ev) {
try {
execute();
} catch (Exception ex) {
Exceptions.printStackTrace(ex);
}
}
protected void execute() throws IOException, MalformedObjectNameException, InstanceNotFoundException, MBeanException, ReflectionException {
NbMavenProject nbMavenProject = context.getLookup().lookup(NbMavenProject.class);
final MavenProject mavenProject = nbMavenProject.getMavenProject();
final File baseDir = mavenProject.getBasedir();
String finalFileName = "target/" + mavenProject.getBuild().getFinalName() + ".jar";
final File finalFile = new File(baseDir, finalFileName);
RunConfig createRunConfig = RunUtils.createRunConfig(mavenProject.getBasedir(), context, finalFileName, Arrays.asList("package"));
ExecutorTask task = RunUtils.run(createRunConfig);
task.addTaskListener(new TaskListener() {
@Override
public void taskFinished(Task task) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
executeDeployTask(mavenProject, finalFile);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
});
}
public abstract void doOperation(Deployer deployer, File finalFile, String symbolicName, String bundleVersion, boolean recover) throws Exception;
private void executeDeployTask(MavenProject mavenProject, final File finalFile) throws IOException {
final String symbolicName = BundleUtils.getSymbolicName(mavenProject);
final String bundleVersion = BundleUtils.getBundleVersion(finalFile);
ServerInstanceProvider virgoProvider = ServerInstanceProviderUtils.getVirgoServerInstanceProvider();
if (virgoProvider != null) {
List<ServerInstance> instances = virgoProvider.getInstances();
if (instances.isEmpty()) {
ServerInstanceProviderUtils.openWizard();
}
//User may be cancle wizard.
if (instances.isEmpty()) {
return;
}
final Deployer deployer = instances.get(0).getLookup().lookup(Deployer.class);
try {
final ProgressHandle handle = ProgressHandleFactory.createHandle("Deploy " + mavenProject.getBuild().getFinalName());
SwingWorker worker = new SwingWorker<Object, Object>() {
@Override
protected Object doInBackground() throws Exception {
handle.start();
doOperation(deployer, finalFile, symbolicName, bundleVersion, true);
return null;
}
@Override
protected void done() {
try {
get();
- handle.finish();
} catch (InterruptedException ex) {
Exceptions.printStackTrace(ex);
} catch (ExecutionException ex) {
Exceptions.printStackTrace(ex);
+ } finally {
+ handle.finish();
}
}
};
worker.execute();
} catch (Exception ex) {
Exceptions.printStackTrace(ex);
}
}
}
}
| false | true | private void executeDeployTask(MavenProject mavenProject, final File finalFile) throws IOException {
final String symbolicName = BundleUtils.getSymbolicName(mavenProject);
final String bundleVersion = BundleUtils.getBundleVersion(finalFile);
ServerInstanceProvider virgoProvider = ServerInstanceProviderUtils.getVirgoServerInstanceProvider();
if (virgoProvider != null) {
List<ServerInstance> instances = virgoProvider.getInstances();
if (instances.isEmpty()) {
ServerInstanceProviderUtils.openWizard();
}
//User may be cancle wizard.
if (instances.isEmpty()) {
return;
}
final Deployer deployer = instances.get(0).getLookup().lookup(Deployer.class);
try {
final ProgressHandle handle = ProgressHandleFactory.createHandle("Deploy " + mavenProject.getBuild().getFinalName());
SwingWorker worker = new SwingWorker<Object, Object>() {
@Override
protected Object doInBackground() throws Exception {
handle.start();
doOperation(deployer, finalFile, symbolicName, bundleVersion, true);
return null;
}
@Override
protected void done() {
try {
get();
handle.finish();
} catch (InterruptedException ex) {
Exceptions.printStackTrace(ex);
} catch (ExecutionException ex) {
Exceptions.printStackTrace(ex);
}
}
};
worker.execute();
} catch (Exception ex) {
Exceptions.printStackTrace(ex);
}
}
}
| private void executeDeployTask(MavenProject mavenProject, final File finalFile) throws IOException {
final String symbolicName = BundleUtils.getSymbolicName(mavenProject);
final String bundleVersion = BundleUtils.getBundleVersion(finalFile);
ServerInstanceProvider virgoProvider = ServerInstanceProviderUtils.getVirgoServerInstanceProvider();
if (virgoProvider != null) {
List<ServerInstance> instances = virgoProvider.getInstances();
if (instances.isEmpty()) {
ServerInstanceProviderUtils.openWizard();
}
//User may be cancle wizard.
if (instances.isEmpty()) {
return;
}
final Deployer deployer = instances.get(0).getLookup().lookup(Deployer.class);
try {
final ProgressHandle handle = ProgressHandleFactory.createHandle("Deploy " + mavenProject.getBuild().getFinalName());
SwingWorker worker = new SwingWorker<Object, Object>() {
@Override
protected Object doInBackground() throws Exception {
handle.start();
doOperation(deployer, finalFile, symbolicName, bundleVersion, true);
return null;
}
@Override
protected void done() {
try {
get();
} catch (InterruptedException ex) {
Exceptions.printStackTrace(ex);
} catch (ExecutionException ex) {
Exceptions.printStackTrace(ex);
} finally {
handle.finish();
}
}
};
worker.execute();
} catch (Exception ex) {
Exceptions.printStackTrace(ex);
}
}
}
|
diff --git a/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.java b/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.java
index a3c01fae6..4bfb1c2be 100644
--- a/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.java
+++ b/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.java
@@ -1,912 +1,912 @@
package org.apache.solr.update.processor;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CharsRef;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.request.CoreAdminRequest.RequestRecovery;
import org.apache.solr.cloud.CloudDescriptor;
import org.apache.solr.cloud.ZkController;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrException.ErrorCode;
import org.apache.solr.common.SolrInputField;
import org.apache.solr.common.cloud.CloudState;
import org.apache.solr.common.cloud.Slice;
import org.apache.solr.common.cloud.ZkCoreNodeProps;
import org.apache.solr.common.cloud.ZkNodeProps;
import org.apache.solr.common.cloud.ZkStateReader;
import org.apache.solr.common.cloud.ZooKeeperException;
import org.apache.solr.common.params.CoreAdminParams.CoreAdminAction;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.UpdateParams;
import org.apache.solr.common.util.Hash;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.core.CoreDescriptor;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrRequestInfo;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.schema.SchemaField;
import org.apache.solr.update.AddUpdateCommand;
import org.apache.solr.update.CommitUpdateCommand;
import org.apache.solr.update.DeleteUpdateCommand;
import org.apache.solr.update.SolrCmdDistributor;
import org.apache.solr.update.SolrCmdDistributor.Node;
import org.apache.solr.update.SolrCmdDistributor.Response;
import org.apache.solr.update.SolrCmdDistributor.StdNode;
import org.apache.solr.update.UpdateCommand;
import org.apache.solr.update.UpdateHandler;
import org.apache.solr.update.UpdateLog;
import org.apache.solr.update.VersionBucket;
import org.apache.solr.update.VersionInfo;
import org.apache.zookeeper.KeeperException;
// NOT mt-safe... create a new processor for each add thread
// TODO: we really should not wait for distrib after local? unless a certain replication factor is asked for
public class DistributedUpdateProcessor extends UpdateRequestProcessor {
public static final String SEEN_LEADER = "leader";
public static final String COMMIT_END_POINT = "commit_end_point";
public static final String DELETE_BY_QUERY_LEVEL = "dbq_level";
private final SolrQueryRequest req;
private final SolrQueryResponse rsp;
private final UpdateRequestProcessor next;
public static final String VERSION_FIELD = "_version_";
private final UpdateHandler updateHandler;
private final UpdateLog ulog;
private final VersionInfo vinfo;
private final boolean versionsStored;
private boolean returnVersions = true; // todo: default to false and make configurable
private NamedList addsResponse = null;
private NamedList deleteResponse = null;
private NamedList deleteByQueryResponse = null;
private CharsRef scratch;
private final SchemaField idField;
private final SolrCmdDistributor cmdDistrib;
private boolean zkEnabled = false;
private CloudDescriptor cloudDesc;
private String collection;
private ZkController zkController;
// these are setup at the start of each request processing
// method in this update processor
private boolean isLeader = true;
private boolean forwardToLeader = false;
private List<Node> nodes;
public DistributedUpdateProcessor(SolrQueryRequest req,
SolrQueryResponse rsp, UpdateRequestProcessor next) {
super(next);
this.rsp = rsp;
this.next = next;
this.idField = req.getSchema().getUniqueKeyField();
// version init
this.updateHandler = req.getCore().getUpdateHandler();
this.ulog = updateHandler.getUpdateLog();
this.vinfo = ulog == null ? null : ulog.getVersionInfo();
versionsStored = this.vinfo != null && this.vinfo.getVersionField() != null;
returnVersions = req.getParams().getBool(UpdateParams.VERSIONS ,false);
// TODO: better way to get the response, or pass back info to it?
SolrRequestInfo reqInfo = returnVersions ? SolrRequestInfo.getRequestInfo() : null;
this.req = req;
CoreDescriptor coreDesc = req.getCore().getCoreDescriptor();
this.zkEnabled = coreDesc.getCoreContainer().isZooKeeperAware();
//this.rsp = reqInfo != null ? reqInfo.getRsp() : null;
zkController = req.getCore().getCoreDescriptor().getCoreContainer().getZkController();
cloudDesc = coreDesc.getCloudDescriptor();
if (cloudDesc != null) {
collection = cloudDesc.getCollectionName();
}
cmdDistrib = new SolrCmdDistributor();
}
private List<Node> setupRequest(int hash) {
List<Node> nodes = null;
// if we are in zk mode...
if (zkEnabled) {
// the leader is...
// TODO: if there is no leader, wait and look again
// TODO: we are reading the leader from zk every time - we should cache
// this and watch for changes?? Just pull it from ZkController cluster state probably?
String shardId = getShard(hash, collection, zkController.getCloudState()); // get the right shard based on the hash...
try {
// TODO: if we find out we cannot talk to zk anymore, we should probably realize we are not
// a leader anymore - we shouldn't accept updates at all??
ZkCoreNodeProps leaderProps = new ZkCoreNodeProps(zkController.getZkStateReader().getLeaderProps(
collection, shardId));
String leaderNodeName = leaderProps.getCoreNodeName();
String coreName = req.getCore().getName();
String coreNodeName = zkController.getNodeName() + "_" + coreName;
isLeader = coreNodeName.equals(leaderNodeName);
if (req.getParams().getBool(SEEN_LEADER, false)) {
// we are coming from the leader, just go local - add no urls
forwardToLeader = false;
} else if (isLeader) {
// that means I want to forward onto my replicas...
// so get the replicas...
forwardToLeader = false;
List<ZkCoreNodeProps> replicaProps = zkController.getZkStateReader()
.getReplicaProps(collection, shardId, zkController.getNodeName(),
coreName);
if (replicaProps != null) {
nodes = new ArrayList<Node>(replicaProps.size());
for (ZkCoreNodeProps props : replicaProps) {
nodes.add(new StdNode(props));
}
}
} else {
// I need to forward onto the leader...
nodes = new ArrayList<Node>(1);
nodes.add(new RetryNode(leaderProps, zkController.getZkStateReader(), collection, shardId));
forwardToLeader = true;
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "",
e);
}
}
return nodes;
}
private String getShard(int hash, String collection, CloudState cloudState) {
// ranges should be part of the cloud state and eventually gotten from zk
// get the shard names
return cloudState.getShard(hash, collection);
}
// used for deleteByQyery to get the list of nodes this leader should forward to
private List<Node> setupRequest() {
List<Node> nodes = null;
String shardId = cloudDesc.getShardId();
try {
ZkCoreNodeProps leaderProps = new ZkCoreNodeProps(zkController.getZkStateReader().getLeaderProps(
collection, shardId));
String leaderNodeName = leaderProps.getCoreNodeName();
String coreName = req.getCore().getName();
String coreNodeName = zkController.getNodeName() + "_" + coreName;
isLeader = coreNodeName.equals(leaderNodeName);
// TODO: what if we are no longer the leader?
forwardToLeader = false;
List<ZkCoreNodeProps> replicaProps = zkController.getZkStateReader()
.getReplicaProps(collection, shardId, zkController.getNodeName(),
coreName);
if (replicaProps != null) {
nodes = new ArrayList<Node>(replicaProps.size());
for (ZkCoreNodeProps props : replicaProps) {
nodes.add(new StdNode(props));
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "",
e);
}
return nodes;
}
@Override
public void processAdd(AddUpdateCommand cmd) throws IOException {
// TODO: check for id field?
int hash = 0;
if (zkEnabled) {
zkCheck();
hash = hash(cmd);
nodes = setupRequest(hash);
} else {
// even in non zk mode, tests simulate updates from a leader
isLeader = !req.getParams().getBool(SEEN_LEADER, false);
}
boolean dropCmd = false;
if (!forwardToLeader) {
dropCmd = versionAdd(cmd);
}
if (dropCmd) {
// TODO: do we need to add anything to the response?
return;
}
ModifiableSolrParams params = null;
if (nodes != null) {
params = new ModifiableSolrParams(req.getParams());
if (isLeader) {
params.set(SEEN_LEADER, true);
}
cmdDistrib.distribAdd(cmd, nodes, params);
}
// TODO: what to do when no idField?
if (returnVersions && rsp != null && idField != null) {
if (addsResponse == null) {
addsResponse = new NamedList<String>();
rsp.add("adds",addsResponse);
}
if (scratch == null) scratch = new CharsRef();
idField.getType().indexedToReadable(cmd.getIndexedId(), scratch);
addsResponse.add(scratch.toString(), cmd.getVersion());
}
// TODO: keep track of errors? needs to be done at a higher level though since
// an id may fail before it gets to this processor.
// Given that, it may also make sense to move the version reporting out of this
// processor too.
}
// TODO: optionally fail if n replicas are not reached...
private void doFinish() {
// TODO: if not a forward and replication req is not specified, we could
// send in a background thread
cmdDistrib.finish();
Response response = cmdDistrib.getResponse();
// TODO - we may need to tell about more than one error...
// if its a forward, any fail is a problem -
// otherwise we assume things are fine if we got it locally
// until we start allowing min replication param
if (response.errors.size() > 0) {
// if one node is a RetryNode, this was a forward request
if (response.errors.get(0).node instanceof RetryNode) {
rsp.setException(response.errors.get(0).e);
}
// else
// for now we don't error - we assume if it was added locally, we
// succeeded
}
// if it is not a forward request, for each fail, try to tell them to
// recover - the doc was already added locally, so it should have been
// legit
// TODO: we should do this in the background it would seem
for (SolrCmdDistributor.Error error : response.errors) {
if (error.node instanceof RetryNode) {
// we don't try to force a leader to recover
// when we cannot forward to it
continue;
}
// TODO: we should force their state to recovering ??
// TODO: could be sent in parallel
// TODO: do retries??
// TODO: what if its is already recovering? Right now recoveries queue up -
// should they?
String recoveryUrl = error.node.getBaseUrl();
CommonsHttpSolrServer server;
log.info("try and ask " + recoveryUrl + " to recover");
try {
server = new CommonsHttpSolrServer(recoveryUrl);
server.setSoTimeout(5000);
server.setConnectionTimeout(5000);
RequestRecovery recoverRequestCmd = new RequestRecovery();
recoverRequestCmd.setAction(CoreAdminAction.REQUESTRECOVERY);
recoverRequestCmd.setCoreName(error.node.getCoreName());
server.request(recoverRequestCmd);
} catch (Exception e) {
log.info("Could not tell a replica to recover", e);
}
}
}
// must be synchronized by bucket
private void doLocalAdd(AddUpdateCommand cmd) throws IOException {
super.processAdd(cmd);
}
// must be synchronized by bucket
private void doLocalDelete(DeleteUpdateCommand cmd) throws IOException {
super.processDelete(cmd);
}
/**
* @param cmd
* @return whether or not to drop this cmd
* @throws IOException
*/
private boolean versionAdd(AddUpdateCommand cmd) throws IOException {
BytesRef idBytes = cmd.getIndexedId();
if (vinfo == null || idBytes == null) {
super.processAdd(cmd);
return false;
}
// This is only the hash for the bucket, and must be based only on the uniqueKey (i.e. do not use a pluggable hash here)
int bucketHash = Hash.murmurhash3_x86_32(idBytes.bytes, idBytes.offset, idBytes.length, 0);
// at this point, there is an update we need to try and apply.
// we may or may not be the leader.
// Find any existing version in the document
// TODO: don't reuse update commands any more!
long versionOnUpdate = cmd.getVersion();
if (versionOnUpdate == 0) {
SolrInputField versionField = cmd.getSolrInputDocument().getField(VersionInfo.VERSION_FIELD);
if (versionField != null) {
Object o = versionField.getValue();
versionOnUpdate = o instanceof Number ? ((Number) o).longValue() : Long.parseLong(o.toString());
} else {
// Find the version
String versionOnUpdateS = req.getParams().get(VERSION_FIELD);
versionOnUpdate = versionOnUpdateS == null ? 0 : Long.parseLong(versionOnUpdateS);
}
}
boolean isReplay = (cmd.getFlags() & UpdateCommand.REPLAY) != 0;
boolean leaderLogic = isLeader && !isReplay;
VersionBucket bucket = vinfo.bucket(bucketHash);
vinfo.lockForUpdate();
try {
synchronized (bucket) {
// we obtain the version when synchronized and then do the add so we can ensure that
// if version1 < version2 then version1 is actually added before version2.
// even if we don't store the version field, synchronizing on the bucket
// will enable us to know what version happened first, and thus enable
// realtime-get to work reliably.
// TODO: if versions aren't stored, do we need to set on the cmd anyway for some reason?
// there may be other reasons in the future for a version on the commands
if (versionsStored) {
long bucketVersion = bucket.highest;
if (leaderLogic) {
long version = vinfo.getNewClock();
cmd.setVersion(version);
cmd.getSolrInputDocument().setField(VersionInfo.VERSION_FIELD, version);
bucket.updateHighest(version);
} else {
// The leader forwarded us this update.
cmd.setVersion(versionOnUpdate);
if (ulog.getState() != UpdateLog.State.ACTIVE && (cmd.getFlags() & UpdateCommand.REPLAY) == 0) {
// we're not in an active state, and this update isn't from a replay, so buffer it.
cmd.setFlags(cmd.getFlags() | UpdateCommand.BUFFERING);
ulog.add(cmd);
return true;
}
// if we aren't the leader, then we need to check that updates were not re-ordered
if (bucketVersion != 0 && bucketVersion < versionOnUpdate) {
// we're OK... this update has a version higher than anything we've seen
// in this bucket so far, so we know that no reordering has yet occured.
bucket.updateHighest(versionOnUpdate);
} else {
// there have been updates higher than the current update. we need to check
// the specific version for this id.
Long lastVersion = vinfo.lookupVersion(cmd.getIndexedId());
if (lastVersion != null && Math.abs(lastVersion) >= versionOnUpdate) {
// This update is a repeat, or was reordered. We need to drop this update.
return true;
}
}
}
}
doLocalAdd(cmd);
} // end synchronized (bucket)
} finally {
vinfo.unlockForUpdate();
}
return false;
}
@Override
public void processDelete(DeleteUpdateCommand cmd) throws IOException {
if (!cmd.isDeleteById()) {
doDeleteByQuery(cmd);
return;
}
int hash = 0;
if (zkEnabled) {
zkCheck();
hash = hash(cmd);
nodes = setupRequest(hash);
} else {
// even in non zk mode, tests simulate updates from a leader
isLeader = !req.getParams().getBool(SEEN_LEADER, false);
}
boolean dropCmd = false;
if (!forwardToLeader) {
dropCmd = versionDelete(cmd);
}
if (dropCmd) {
// TODO: do we need to add anything to the response?
return;
}
ModifiableSolrParams params = null;
if (nodes != null) {
params = new ModifiableSolrParams(req.getParams());
if (isLeader) {
params.set(SEEN_LEADER, true);
}
cmdDistrib.distribDelete(cmd, nodes, params);
}
// cmd.getIndexId == null when delete by query
// TODO: what to do when no idField?
if (returnVersions && rsp != null && cmd.getIndexedId() != null && idField != null) {
if (deleteResponse == null) {
deleteResponse = new NamedList<String>();
rsp.add("deletes",deleteResponse);
}
if (scratch == null) scratch = new CharsRef();
idField.getType().indexedToReadable(cmd.getIndexedId(), scratch);
deleteResponse.add(scratch.toString(), cmd.getVersion()); // we're returning the version of the delete.. not the version of the doc we deleted.
}
}
public void doDeleteByQuery(DeleteUpdateCommand cmd) throws IOException {
// even in non zk mode, tests simulate updates from a leader
if(!zkEnabled) {
isLeader = !req.getParams().getBool(SEEN_LEADER, false);
} else {
zkCheck();
}
// Lev1: we are the first to receive this deleteByQuery, it must be forwarded to the leader of every shard
// Lev2: we are a leader receiving a forwarded deleteByQuery... we must:
// - block all updates (use VersionInfo)
// - flush *all* updates going to our replicas
// - forward the DBQ to our replicas and wait for the response
// - log + execute the local DBQ
// Lev3: we are a replica receiving a DBQ from our leader
// - log + execute the local DBQ
int dbqlevel = req.getParams().getInt(DELETE_BY_QUERY_LEVEL, 1);
if (zkEnabled && dbqlevel == 1) {
boolean leaderForAnyShard = false; // start off by assuming we are not a leader for any shard
Map<String,Slice> slices = zkController.getCloudState().getSlices(collection);
ModifiableSolrParams params = new ModifiableSolrParams(req.getParams());
- params.set("dbqlevel", 2);
+ params.set(DELETE_BY_QUERY_LEVEL, 2);
List<Node> leaders = new ArrayList<Node>(slices.size());
for (Map.Entry<String,Slice> sliceEntry : slices.entrySet()) {
String sliceName = sliceEntry.getKey();
ZkNodeProps leaderProps;
try {
leaderProps = zkController.getZkStateReader().getLeaderProps(collection, sliceName);
} catch (InterruptedException e) {
throw new SolrException(ErrorCode.SERVER_ERROR, "Exception finding leader for shard " + sliceName, e);
}
// TODO: What if leaders changed in the meantime?
// should we send out slice-at-a-time and if a node returns "hey, I'm not a leader" (or we get an error because it went down) then look up the new leader?
// Am I the leader for this slice?
ZkCoreNodeProps coreLeaderProps = new ZkCoreNodeProps(leaderProps);
String leaderNodeName = coreLeaderProps.getCoreNodeName();
String coreName = req.getCore().getName();
String coreNodeName = zkController.getNodeName() + "_" + coreName;
isLeader = coreNodeName.equals(leaderNodeName);
if (isLeader) {
// don't forward to ourself
leaderForAnyShard = true;
} else {
leaders.add(new StdNode(coreLeaderProps));
}
}
cmdDistrib.distribDelete(cmd, leaders, params);
if (!leaderForAnyShard) {
return;
}
// change the level to 2 so we look up and forward to our own replicas (if any)
dbqlevel = 2;
}
List<Node> replicas = null;
if (zkEnabled && dbqlevel == 2) {
// This core should be a leader
replicas = setupRequest();
}
if (vinfo == null) {
super.processDelete(cmd);
return;
}
// at this point, there is an update we need to try and apply.
// we may or may not be the leader.
// Find the version
long versionOnUpdate = cmd.getVersion();
if (versionOnUpdate == 0) {
String versionOnUpdateS = req.getParams().get(VERSION_FIELD);
versionOnUpdate = versionOnUpdateS == null ? 0 : Long.parseLong(versionOnUpdateS);
}
versionOnUpdate = Math.abs(versionOnUpdate); // normalize to positive version
boolean isReplay = (cmd.getFlags() & UpdateCommand.REPLAY) != 0;
boolean leaderLogic = isLeader && !isReplay;
if (!leaderLogic && versionOnUpdate==0) {
throw new SolrException(ErrorCode.BAD_REQUEST, "missing _version_ on update from leader");
}
vinfo.blockUpdates();
try {
if (versionsStored) {
if (leaderLogic) {
long version = vinfo.getNewClock();
cmd.setVersion(-version);
// TODO update versions in all buckets
// TODO: flush any adds to these replicas so they do not get reordered w.r.t. this DBQ
doLocalDelete(cmd);
// forward to all replicas
if (replicas != null) {
ModifiableSolrParams params = new ModifiableSolrParams(req.getParams());
- params.set("dbqlevel", 3);
+ params.set(DELETE_BY_QUERY_LEVEL, 3);
params.set(VERSION_FIELD, Long.toString(cmd.getVersion()));
params.set(SEEN_LEADER, "true");
cmdDistrib.distribDelete(cmd, replicas, params);
// wait for DBQ responses before releasing the update block to eliminate the possibility
// of an add being reordered.
// TODO: this isn't strictly necessary - we could do the same thing we do for PeerSync
// in DUH2 and add a clause that prevents deleting older docs.
cmdDistrib.finish();
}
} else {
cmd.setVersion(-versionOnUpdate);
if (ulog.getState() != UpdateLog.State.ACTIVE && (cmd.getFlags() & UpdateCommand.REPLAY) == 0) {
// we're not in an active state, and this update isn't from a replay, so buffer it.
cmd.setFlags(cmd.getFlags() | UpdateCommand.BUFFERING);
ulog.deleteByQuery(cmd);
return;
}
doLocalDelete(cmd);
}
}
// since we don't know which documents were deleted, the easiest thing to do is to invalidate
// all real-time caches (i.e. UpdateLog) which involves also getting a new version of the IndexReader
// (so cache misses will see up-to-date data)
} finally {
vinfo.unblockUpdates();
}
if (returnVersions && rsp != null) {
if (deleteByQueryResponse == null) {
deleteByQueryResponse = new NamedList<String>();
rsp.add("deleteByQuery",deleteByQueryResponse);
}
deleteByQueryResponse.add(cmd.getQuery(), cmd.getVersion());
}
}
private void zkCheck() {
int retries = 10;
while (!zkController.isConnected()) {
if (retries-- == 0) {
throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE, "Cannot talk to ZooKeeper - Updates are disabled.");
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
}
private boolean versionDelete(DeleteUpdateCommand cmd) throws IOException {
BytesRef idBytes = cmd.getIndexedId();
if (vinfo == null || idBytes == null) {
super.processDelete(cmd);
return false;
}
// This is only the hash for the bucket, and must be based only on the uniqueKey (i.e. do not use a pluggable hash here)
int bucketHash = Hash.murmurhash3_x86_32(idBytes.bytes, idBytes.offset, idBytes.length, 0);
// at this point, there is an update we need to try and apply.
// we may or may not be the leader.
// Find the version
long versionOnUpdate = cmd.getVersion();
if (versionOnUpdate == 0) {
String versionOnUpdateS = req.getParams().get(VERSION_FIELD);
versionOnUpdate = versionOnUpdateS == null ? 0 : Long.parseLong(versionOnUpdateS);
}
versionOnUpdate = Math.abs(versionOnUpdate); // normalize to positive version
boolean isReplay = (cmd.getFlags() & UpdateCommand.REPLAY) != 0;
boolean leaderLogic = isLeader && !isReplay;
if (!leaderLogic && versionOnUpdate==0) {
throw new SolrException(ErrorCode.BAD_REQUEST, "missing _version_ on update from leader");
}
VersionBucket bucket = vinfo.bucket(bucketHash);
vinfo.lockForUpdate();
try {
synchronized (bucket) {
if (versionsStored) {
long bucketVersion = bucket.highest;
if (leaderLogic) {
long version = vinfo.getNewClock();
cmd.setVersion(-version);
bucket.updateHighest(version);
} else {
cmd.setVersion(-versionOnUpdate);
if (ulog.getState() != UpdateLog.State.ACTIVE && (cmd.getFlags() & UpdateCommand.REPLAY) == 0) {
// we're not in an active state, and this update isn't from a replay, so buffer it.
cmd.setFlags(cmd.getFlags() | UpdateCommand.BUFFERING);
ulog.delete(cmd);
return true;
}
// if we aren't the leader, then we need to check that updates were not re-ordered
if (bucketVersion != 0 && bucketVersion < versionOnUpdate) {
// we're OK... this update has a version higher than anything we've seen
// in this bucket so far, so we know that no reordering has yet occured.
bucket.updateHighest(versionOnUpdate);
} else {
// there have been updates higher than the current update. we need to check
// the specific version for this id.
Long lastVersion = vinfo.lookupVersion(cmd.getIndexedId());
if (lastVersion != null && Math.abs(lastVersion) >= versionOnUpdate) {
// This update is a repeat, or was reordered. We need to drop this update.
return true;
}
}
}
}
doLocalDelete(cmd);
return false;
} // end synchronized (bucket)
} finally {
vinfo.unlockForUpdate();
}
}
@Override
public void processCommit(CommitUpdateCommand cmd) throws IOException {
if (zkEnabled) {
zkCheck();
}
if (vinfo != null) {
vinfo.lockForUpdate();
}
try {
if (ulog == null || ulog.getState() == UpdateLog.State.ACTIVE || (cmd.getFlags() & UpdateCommand.REPLAY) != 0) {
super.processCommit(cmd);
} else {
log.info("Ignoring commit while not ACTIVE - state: " + ulog.getState() + " replay:" + (cmd.getFlags() & UpdateCommand.REPLAY));
}
} finally {
if (vinfo != null) {
vinfo.unlockForUpdate();
}
}
// TODO: we should consider this? commit everyone in the current collection
if (zkEnabled) {
ModifiableSolrParams params = new ModifiableSolrParams(req.getParams());
if (!params.getBool(COMMIT_END_POINT, false)) {
params.set(COMMIT_END_POINT, true);
String nodeName = req.getCore().getCoreDescriptor().getCoreContainer()
.getZkController().getNodeName();
String shardZkNodeName = nodeName + "_" + req.getCore().getName();
List<Node> nodes = getCollectionUrls(req, req.getCore().getCoreDescriptor()
.getCloudDescriptor().getCollectionName(), shardZkNodeName);
if (nodes != null) {
cmdDistrib.distribCommit(cmd, nodes, params);
finish();
}
}
}
}
@Override
public void finish() throws IOException {
doFinish();
if (next != null && nodes == null) next.finish();
}
private List<Node> getCollectionUrls(SolrQueryRequest req, String collection, String shardZkNodeName) {
CloudState cloudState = req.getCore().getCoreDescriptor()
.getCoreContainer().getZkController().getCloudState();
List<Node> urls = new ArrayList<Node>();
Map<String,Slice> slices = cloudState.getSlices(collection);
if (slices == null) {
throw new ZooKeeperException(ErrorCode.BAD_REQUEST,
"Could not find collection in zk: " + cloudState);
}
for (Map.Entry<String,Slice> sliceEntry : slices.entrySet()) {
Slice replicas = slices.get(sliceEntry.getKey());
Map<String,ZkNodeProps> shardMap = replicas.getShards();
for (Entry<String,ZkNodeProps> entry : shardMap.entrySet()) {
ZkCoreNodeProps nodeProps = new ZkCoreNodeProps(entry.getValue());
if (cloudState.liveNodesContain(nodeProps.getNodeName()) && !entry.getKey().equals(shardZkNodeName)) {
urls.add(new StdNode(nodeProps));
}
}
}
if (urls.size() == 0) {
return null;
}
return urls;
}
// TODO: move this to AddUpdateCommand/DeleteUpdateCommand and cache it? And
// make the hash pluggable of course.
// The hash also needs to be pluggable
private int hash(AddUpdateCommand cmd) {
BytesRef br = cmd.getIndexedId();
return Hash.murmurhash3_x86_32(br.bytes, br.offset, br.length, 0);
}
private int hash(DeleteUpdateCommand cmd) {
BytesRef br = cmd.getIndexedId();
return Hash.murmurhash3_x86_32(br.bytes, br.offset, br.length, 0);
}
// RetryNodes are used in the case of 'forward to leader' where we want
// to try the latest leader on a fail in the case the leader just went down.
public static class RetryNode extends StdNode {
private ZkStateReader zkStateReader;
private String collection;
private String shardId;
public RetryNode(ZkCoreNodeProps nodeProps, ZkStateReader zkStateReader, String collection, String shardId) {
super(nodeProps);
this.zkStateReader = zkStateReader;
this.collection = collection;
this.shardId = shardId;
}
@Override
public String toString() {
return url;
}
@Override
public boolean checkRetry() {
ZkCoreNodeProps leaderProps;
try {
leaderProps = new ZkCoreNodeProps(zkStateReader.getLeaderProps(
collection, shardId));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
this.url = leaderProps.getCoreUrl();
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result
+ ((collection == null) ? 0 : collection.hashCode());
result = prime * result + ((shardId == null) ? 0 : shardId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!super.equals(obj)) return false;
if (getClass() != obj.getClass()) return false;
RetryNode other = (RetryNode) obj;
if (url == null) {
if (other.url != null) return false;
} else if (!url.equals(other.url)) return false;
return true;
}
}
}
| false | true | public void doDeleteByQuery(DeleteUpdateCommand cmd) throws IOException {
// even in non zk mode, tests simulate updates from a leader
if(!zkEnabled) {
isLeader = !req.getParams().getBool(SEEN_LEADER, false);
} else {
zkCheck();
}
// Lev1: we are the first to receive this deleteByQuery, it must be forwarded to the leader of every shard
// Lev2: we are a leader receiving a forwarded deleteByQuery... we must:
// - block all updates (use VersionInfo)
// - flush *all* updates going to our replicas
// - forward the DBQ to our replicas and wait for the response
// - log + execute the local DBQ
// Lev3: we are a replica receiving a DBQ from our leader
// - log + execute the local DBQ
int dbqlevel = req.getParams().getInt(DELETE_BY_QUERY_LEVEL, 1);
if (zkEnabled && dbqlevel == 1) {
boolean leaderForAnyShard = false; // start off by assuming we are not a leader for any shard
Map<String,Slice> slices = zkController.getCloudState().getSlices(collection);
ModifiableSolrParams params = new ModifiableSolrParams(req.getParams());
params.set("dbqlevel", 2);
List<Node> leaders = new ArrayList<Node>(slices.size());
for (Map.Entry<String,Slice> sliceEntry : slices.entrySet()) {
String sliceName = sliceEntry.getKey();
ZkNodeProps leaderProps;
try {
leaderProps = zkController.getZkStateReader().getLeaderProps(collection, sliceName);
} catch (InterruptedException e) {
throw new SolrException(ErrorCode.SERVER_ERROR, "Exception finding leader for shard " + sliceName, e);
}
// TODO: What if leaders changed in the meantime?
// should we send out slice-at-a-time and if a node returns "hey, I'm not a leader" (or we get an error because it went down) then look up the new leader?
// Am I the leader for this slice?
ZkCoreNodeProps coreLeaderProps = new ZkCoreNodeProps(leaderProps);
String leaderNodeName = coreLeaderProps.getCoreNodeName();
String coreName = req.getCore().getName();
String coreNodeName = zkController.getNodeName() + "_" + coreName;
isLeader = coreNodeName.equals(leaderNodeName);
if (isLeader) {
// don't forward to ourself
leaderForAnyShard = true;
} else {
leaders.add(new StdNode(coreLeaderProps));
}
}
cmdDistrib.distribDelete(cmd, leaders, params);
if (!leaderForAnyShard) {
return;
}
// change the level to 2 so we look up and forward to our own replicas (if any)
dbqlevel = 2;
}
List<Node> replicas = null;
if (zkEnabled && dbqlevel == 2) {
// This core should be a leader
replicas = setupRequest();
}
if (vinfo == null) {
super.processDelete(cmd);
return;
}
// at this point, there is an update we need to try and apply.
// we may or may not be the leader.
// Find the version
long versionOnUpdate = cmd.getVersion();
if (versionOnUpdate == 0) {
String versionOnUpdateS = req.getParams().get(VERSION_FIELD);
versionOnUpdate = versionOnUpdateS == null ? 0 : Long.parseLong(versionOnUpdateS);
}
versionOnUpdate = Math.abs(versionOnUpdate); // normalize to positive version
boolean isReplay = (cmd.getFlags() & UpdateCommand.REPLAY) != 0;
boolean leaderLogic = isLeader && !isReplay;
if (!leaderLogic && versionOnUpdate==0) {
throw new SolrException(ErrorCode.BAD_REQUEST, "missing _version_ on update from leader");
}
vinfo.blockUpdates();
try {
if (versionsStored) {
if (leaderLogic) {
long version = vinfo.getNewClock();
cmd.setVersion(-version);
// TODO update versions in all buckets
// TODO: flush any adds to these replicas so they do not get reordered w.r.t. this DBQ
doLocalDelete(cmd);
// forward to all replicas
if (replicas != null) {
ModifiableSolrParams params = new ModifiableSolrParams(req.getParams());
params.set("dbqlevel", 3);
params.set(VERSION_FIELD, Long.toString(cmd.getVersion()));
params.set(SEEN_LEADER, "true");
cmdDistrib.distribDelete(cmd, replicas, params);
// wait for DBQ responses before releasing the update block to eliminate the possibility
// of an add being reordered.
// TODO: this isn't strictly necessary - we could do the same thing we do for PeerSync
// in DUH2 and add a clause that prevents deleting older docs.
cmdDistrib.finish();
}
} else {
cmd.setVersion(-versionOnUpdate);
if (ulog.getState() != UpdateLog.State.ACTIVE && (cmd.getFlags() & UpdateCommand.REPLAY) == 0) {
// we're not in an active state, and this update isn't from a replay, so buffer it.
cmd.setFlags(cmd.getFlags() | UpdateCommand.BUFFERING);
ulog.deleteByQuery(cmd);
return;
}
doLocalDelete(cmd);
}
}
// since we don't know which documents were deleted, the easiest thing to do is to invalidate
// all real-time caches (i.e. UpdateLog) which involves also getting a new version of the IndexReader
// (so cache misses will see up-to-date data)
} finally {
vinfo.unblockUpdates();
}
if (returnVersions && rsp != null) {
if (deleteByQueryResponse == null) {
deleteByQueryResponse = new NamedList<String>();
rsp.add("deleteByQuery",deleteByQueryResponse);
}
deleteByQueryResponse.add(cmd.getQuery(), cmd.getVersion());
}
}
| public void doDeleteByQuery(DeleteUpdateCommand cmd) throws IOException {
// even in non zk mode, tests simulate updates from a leader
if(!zkEnabled) {
isLeader = !req.getParams().getBool(SEEN_LEADER, false);
} else {
zkCheck();
}
// Lev1: we are the first to receive this deleteByQuery, it must be forwarded to the leader of every shard
// Lev2: we are a leader receiving a forwarded deleteByQuery... we must:
// - block all updates (use VersionInfo)
// - flush *all* updates going to our replicas
// - forward the DBQ to our replicas and wait for the response
// - log + execute the local DBQ
// Lev3: we are a replica receiving a DBQ from our leader
// - log + execute the local DBQ
int dbqlevel = req.getParams().getInt(DELETE_BY_QUERY_LEVEL, 1);
if (zkEnabled && dbqlevel == 1) {
boolean leaderForAnyShard = false; // start off by assuming we are not a leader for any shard
Map<String,Slice> slices = zkController.getCloudState().getSlices(collection);
ModifiableSolrParams params = new ModifiableSolrParams(req.getParams());
params.set(DELETE_BY_QUERY_LEVEL, 2);
List<Node> leaders = new ArrayList<Node>(slices.size());
for (Map.Entry<String,Slice> sliceEntry : slices.entrySet()) {
String sliceName = sliceEntry.getKey();
ZkNodeProps leaderProps;
try {
leaderProps = zkController.getZkStateReader().getLeaderProps(collection, sliceName);
} catch (InterruptedException e) {
throw new SolrException(ErrorCode.SERVER_ERROR, "Exception finding leader for shard " + sliceName, e);
}
// TODO: What if leaders changed in the meantime?
// should we send out slice-at-a-time and if a node returns "hey, I'm not a leader" (or we get an error because it went down) then look up the new leader?
// Am I the leader for this slice?
ZkCoreNodeProps coreLeaderProps = new ZkCoreNodeProps(leaderProps);
String leaderNodeName = coreLeaderProps.getCoreNodeName();
String coreName = req.getCore().getName();
String coreNodeName = zkController.getNodeName() + "_" + coreName;
isLeader = coreNodeName.equals(leaderNodeName);
if (isLeader) {
// don't forward to ourself
leaderForAnyShard = true;
} else {
leaders.add(new StdNode(coreLeaderProps));
}
}
cmdDistrib.distribDelete(cmd, leaders, params);
if (!leaderForAnyShard) {
return;
}
// change the level to 2 so we look up and forward to our own replicas (if any)
dbqlevel = 2;
}
List<Node> replicas = null;
if (zkEnabled && dbqlevel == 2) {
// This core should be a leader
replicas = setupRequest();
}
if (vinfo == null) {
super.processDelete(cmd);
return;
}
// at this point, there is an update we need to try and apply.
// we may or may not be the leader.
// Find the version
long versionOnUpdate = cmd.getVersion();
if (versionOnUpdate == 0) {
String versionOnUpdateS = req.getParams().get(VERSION_FIELD);
versionOnUpdate = versionOnUpdateS == null ? 0 : Long.parseLong(versionOnUpdateS);
}
versionOnUpdate = Math.abs(versionOnUpdate); // normalize to positive version
boolean isReplay = (cmd.getFlags() & UpdateCommand.REPLAY) != 0;
boolean leaderLogic = isLeader && !isReplay;
if (!leaderLogic && versionOnUpdate==0) {
throw new SolrException(ErrorCode.BAD_REQUEST, "missing _version_ on update from leader");
}
vinfo.blockUpdates();
try {
if (versionsStored) {
if (leaderLogic) {
long version = vinfo.getNewClock();
cmd.setVersion(-version);
// TODO update versions in all buckets
// TODO: flush any adds to these replicas so they do not get reordered w.r.t. this DBQ
doLocalDelete(cmd);
// forward to all replicas
if (replicas != null) {
ModifiableSolrParams params = new ModifiableSolrParams(req.getParams());
params.set(DELETE_BY_QUERY_LEVEL, 3);
params.set(VERSION_FIELD, Long.toString(cmd.getVersion()));
params.set(SEEN_LEADER, "true");
cmdDistrib.distribDelete(cmd, replicas, params);
// wait for DBQ responses before releasing the update block to eliminate the possibility
// of an add being reordered.
// TODO: this isn't strictly necessary - we could do the same thing we do for PeerSync
// in DUH2 and add a clause that prevents deleting older docs.
cmdDistrib.finish();
}
} else {
cmd.setVersion(-versionOnUpdate);
if (ulog.getState() != UpdateLog.State.ACTIVE && (cmd.getFlags() & UpdateCommand.REPLAY) == 0) {
// we're not in an active state, and this update isn't from a replay, so buffer it.
cmd.setFlags(cmd.getFlags() | UpdateCommand.BUFFERING);
ulog.deleteByQuery(cmd);
return;
}
doLocalDelete(cmd);
}
}
// since we don't know which documents were deleted, the easiest thing to do is to invalidate
// all real-time caches (i.e. UpdateLog) which involves also getting a new version of the IndexReader
// (so cache misses will see up-to-date data)
} finally {
vinfo.unblockUpdates();
}
if (returnVersions && rsp != null) {
if (deleteByQueryResponse == null) {
deleteByQueryResponse = new NamedList<String>();
rsp.add("deleteByQuery",deleteByQueryResponse);
}
deleteByQueryResponse.add(cmd.getQuery(), cmd.getVersion());
}
}
|
diff --git a/src/main/java/edu/mit/cci/amtprojects/solver/SolverGenerationTask.java b/src/main/java/edu/mit/cci/amtprojects/solver/SolverGenerationTask.java
index 16e82dd..5cc0867 100644
--- a/src/main/java/edu/mit/cci/amtprojects/solver/SolverGenerationTask.java
+++ b/src/main/java/edu/mit/cci/amtprojects/solver/SolverGenerationTask.java
@@ -1,285 +1,285 @@
package edu.mit.cci.amtprojects.solver;
import edu.mit.cci.amtprojects.GenericTask;
import edu.mit.cci.amtprojects.HomePage;
import edu.mit.cci.amtprojects.util.Utils;
import org.apache.log4j.Logger;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.RestartResponseException;
import org.apache.wicket.ajax.AjaxEventBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.ajax.json.JSONException;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.basic.MultiLineLabel;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Check;
import org.apache.wicket.markup.html.form.CheckGroup;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.HiddenField;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.markup.repeater.data.ListDataProvider;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
/**
* User: jintrone
* Date: 10/15/12
* Time: 2:53 PM
*/
public class SolverGenerationTask extends GenericTask {
public static enum Mode {
CHOOSE, GENERATE, IMPROVE
}
private Mode mode = Mode.CHOOSE;
CheckGroup<Solution> group;
private SolverTaskModel model;
private static Logger log = Logger.getLogger(SolverGenerationTask.class);
public String getPhase() {
return mode.name();
}
public SolverGenerationTask(PageParameters param) {
super(param,true,true);
try {
model = new SolverTaskModel(batch());
} catch (JSONException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
throw new RestartResponseException(HomePage.class);
}
add(new Label("question", model.getQuestion().getText()));
List<Solution> sols = new ArrayList<Solution>(model.getCurrentStatus().getCurrentAnswers());
for (Iterator<Solution> sit = sols.iterator();sit.hasNext();) {
Solution s = sit.next();
if (s.getRound() == model.getCurrentStatus().getCurrentRound()) {
sit.remove();
}
}
group = new CheckGroup<Solution>("progenitors", new HashSet<Solution>()) {
public boolean isEnabled() {
return mode == Mode.IMPROVE;
}
};
final ImproveFragment improveFragment = new ImproveFragment("improveId", "improveMarkup", this);
Form<?> form = getForm();
form.add(improveFragment);
DataView<Solution> dataView = new DataView<Solution>("answers", new ListDataProvider<Solution>(sols)) {
@Override
protected void populateItem(Item<Solution> solutionItem) {
final Solution sol = solutionItem.getModelObject();
solutionItem.add(new Check<Solution>("check", solutionItem.getModel(), group).add(new AjaxEventBehavior("change") {
@Override
protected void onEvent(AjaxRequestTarget target) {
log.info("Got event");
if (!group.getModelObject().contains(sol)) {
group.getModelObject().add(sol);
} else {
group.getModelObject().remove(sol);
}
target.add(getForm());
}
}).add(new AttributeModifier("name", "parents")).add(new AttributeModifier("value", sol.getId() + "")));
solutionItem.add(new MultiLineLabel("text", sol.getText()));
solutionItem.add(new Label("score", sol.getToRanks().size() ==0?"<none>":String.format("%.2f", Utils.last(sol.getToRanks()).getRankValue())));
}
};
group.add(dataView);
form.add(new AttributeModifier("action", batch().getIsReal() ? "https://www.mturk.com/mturk/externalSubmit" : "http://workersandbox.mturk.com/mturk/externalSubmit"));
form.add(new AttributeModifier("method", "POST"));
form.setOutputMarkupId(true);
form.add(group);
- add(new ChooseFragment("chooseId", "chooseMarkup", this));
+ form.add(new ChooseFragment("chooseId", "chooseMarkup", this));
form.add(new GenerateFragment("generateId", "generateMarkup", this));
form.add(new HiddenField<String>("phase", new Model<String>(model.getCurrentStatus().getPhase().name())));
form.add(new HiddenField<Integer>("round", new Model<Integer>(model.getCurrentStatus().getCurrentRound())));
}
private class ChooseFragment extends Fragment {
public ChooseFragment(String id, String markupId, MarkupContainer markupProvider) {
super(id, markupId, markupProvider);
AjaxLink<?> create = new AjaxLink<Object>("generate") {
@Override
public void onClick(AjaxRequestTarget ajaxRequestTarget) {
SolverGenerationTask.this.mode = Mode.GENERATE;
ajaxRequestTarget.add(getForm());
}
};
AjaxLink<?> improve = new AjaxLink<Object>("improve") {
@Override
public void onClick(AjaxRequestTarget ajaxRequestTarget) {
SolverGenerationTask.this.mode = Mode.IMPROVE;
ajaxRequestTarget.add(getForm());
}
};
add(new Label("maxGenerateBonus", String.format("$%.2f", model.getMaxGeneratingBonus())));
add(new Label("maxCombiningBonus", String.format("$%.2f", model.getMaxCombiningBonus())));
add(create, improve);
}
public boolean isVisible() {
return mode == Mode.CHOOSE;
}
}
private class ImproveFragment extends Fragment {
TextArea<String> improvementText;
Button submit;
public ImproveFragment(String id, String markupId, MarkupContainer markupProvider) {
super(id, markupId, markupProvider);
AjaxLink<?> choose = new AjaxLink<Object>("choose") {
@Override
public void onClick(AjaxRequestTarget ajaxRequestTarget) {
SolverGenerationTask.this.mode = Mode.CHOOSE;
group.getModelObject().clear();
ajaxRequestTarget.add(getForm());
}
};
Label instructionsStep1 = new Label("step1","Select some answers to improve or combine. Please improve or combine the ideas in the selected answers. It is not necessary to use the same wording.");
instructionsStep1.add(new AttributeModifier("class", new Model<String>() {
public String getObject() {
return group.getModelObject().size() > 0 ? "done" : "notdone";
}
}));
add(instructionsStep1);
Label instructionsStep2 = new Label("step2","Add your answer below");
instructionsStep2.add(new AttributeModifier("class", new Model<String>() {
public String getObject() {
return group.getModelObject().size() > 0 ? "enabled" : "disabled";
}
}));
add(instructionsStep2);
add(choose);
add(improvementText = new TextArea<String>("improvementText") {
public boolean isEnabled() {
return group.getModelObject().size() > 0;
}
});
improvementText.add(new AttributeModifier("class",new Model<String>() {
public String getObject() {
return group.getModelObject().size() > 0?"done":"notdone";
}
}));
add(new Label("maxCombiningBonus", String.format("$%.2f", model.getMaxCombiningBonus())));
improvementText.add(new AttributeModifier("name", "solutiontext"));
add(submit = new Button("Submit") {
public boolean isVisible() {
return !isPreview();
}
public boolean isEnabled() {
return group.getModelObject().size() > 0;
}
});
submit.setOutputMarkupId(true);
}
public boolean isVisible() {
return mode == Mode.IMPROVE;
}
}
private class GenerateFragment extends Fragment {
public GenerateFragment(String id, String markupId, MarkupContainer markupProvider) {
super(id, markupId, markupProvider);
AjaxLink<?> choose = new AjaxLink<Object>("choose") {
@Override
public void onClick(AjaxRequestTarget ajaxRequestTarget) {
SolverGenerationTask.this.mode = Mode.CHOOSE;
ajaxRequestTarget.add(getForm());
}
};
add(choose);
add(new Label("maxBonus", String.format("$%.2f", model.getMaxGeneratingBonus())));
TextArea<String> ta = new TextArea<String>("generateText");
add(ta.add(new AttributeModifier("name", "solutiontext")));
add(new Button("Submit") {
public boolean isVisible() {
return !isPreview();
}
});
}
public boolean isVisible() {
return mode == Mode.GENERATE;
}
}
}
| true | true | public SolverGenerationTask(PageParameters param) {
super(param,true,true);
try {
model = new SolverTaskModel(batch());
} catch (JSONException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
throw new RestartResponseException(HomePage.class);
}
add(new Label("question", model.getQuestion().getText()));
List<Solution> sols = new ArrayList<Solution>(model.getCurrentStatus().getCurrentAnswers());
for (Iterator<Solution> sit = sols.iterator();sit.hasNext();) {
Solution s = sit.next();
if (s.getRound() == model.getCurrentStatus().getCurrentRound()) {
sit.remove();
}
}
group = new CheckGroup<Solution>("progenitors", new HashSet<Solution>()) {
public boolean isEnabled() {
return mode == Mode.IMPROVE;
}
};
final ImproveFragment improveFragment = new ImproveFragment("improveId", "improveMarkup", this);
Form<?> form = getForm();
form.add(improveFragment);
DataView<Solution> dataView = new DataView<Solution>("answers", new ListDataProvider<Solution>(sols)) {
@Override
protected void populateItem(Item<Solution> solutionItem) {
final Solution sol = solutionItem.getModelObject();
solutionItem.add(new Check<Solution>("check", solutionItem.getModel(), group).add(new AjaxEventBehavior("change") {
@Override
protected void onEvent(AjaxRequestTarget target) {
log.info("Got event");
if (!group.getModelObject().contains(sol)) {
group.getModelObject().add(sol);
} else {
group.getModelObject().remove(sol);
}
target.add(getForm());
}
}).add(new AttributeModifier("name", "parents")).add(new AttributeModifier("value", sol.getId() + "")));
solutionItem.add(new MultiLineLabel("text", sol.getText()));
solutionItem.add(new Label("score", sol.getToRanks().size() ==0?"<none>":String.format("%.2f", Utils.last(sol.getToRanks()).getRankValue())));
}
};
group.add(dataView);
form.add(new AttributeModifier("action", batch().getIsReal() ? "https://www.mturk.com/mturk/externalSubmit" : "http://workersandbox.mturk.com/mturk/externalSubmit"));
form.add(new AttributeModifier("method", "POST"));
form.setOutputMarkupId(true);
form.add(group);
add(new ChooseFragment("chooseId", "chooseMarkup", this));
form.add(new GenerateFragment("generateId", "generateMarkup", this));
form.add(new HiddenField<String>("phase", new Model<String>(model.getCurrentStatus().getPhase().name())));
form.add(new HiddenField<Integer>("round", new Model<Integer>(model.getCurrentStatus().getCurrentRound())));
}
| public SolverGenerationTask(PageParameters param) {
super(param,true,true);
try {
model = new SolverTaskModel(batch());
} catch (JSONException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
throw new RestartResponseException(HomePage.class);
}
add(new Label("question", model.getQuestion().getText()));
List<Solution> sols = new ArrayList<Solution>(model.getCurrentStatus().getCurrentAnswers());
for (Iterator<Solution> sit = sols.iterator();sit.hasNext();) {
Solution s = sit.next();
if (s.getRound() == model.getCurrentStatus().getCurrentRound()) {
sit.remove();
}
}
group = new CheckGroup<Solution>("progenitors", new HashSet<Solution>()) {
public boolean isEnabled() {
return mode == Mode.IMPROVE;
}
};
final ImproveFragment improveFragment = new ImproveFragment("improveId", "improveMarkup", this);
Form<?> form = getForm();
form.add(improveFragment);
DataView<Solution> dataView = new DataView<Solution>("answers", new ListDataProvider<Solution>(sols)) {
@Override
protected void populateItem(Item<Solution> solutionItem) {
final Solution sol = solutionItem.getModelObject();
solutionItem.add(new Check<Solution>("check", solutionItem.getModel(), group).add(new AjaxEventBehavior("change") {
@Override
protected void onEvent(AjaxRequestTarget target) {
log.info("Got event");
if (!group.getModelObject().contains(sol)) {
group.getModelObject().add(sol);
} else {
group.getModelObject().remove(sol);
}
target.add(getForm());
}
}).add(new AttributeModifier("name", "parents")).add(new AttributeModifier("value", sol.getId() + "")));
solutionItem.add(new MultiLineLabel("text", sol.getText()));
solutionItem.add(new Label("score", sol.getToRanks().size() ==0?"<none>":String.format("%.2f", Utils.last(sol.getToRanks()).getRankValue())));
}
};
group.add(dataView);
form.add(new AttributeModifier("action", batch().getIsReal() ? "https://www.mturk.com/mturk/externalSubmit" : "http://workersandbox.mturk.com/mturk/externalSubmit"));
form.add(new AttributeModifier("method", "POST"));
form.setOutputMarkupId(true);
form.add(group);
form.add(new ChooseFragment("chooseId", "chooseMarkup", this));
form.add(new GenerateFragment("generateId", "generateMarkup", this));
form.add(new HiddenField<String>("phase", new Model<String>(model.getCurrentStatus().getPhase().name())));
form.add(new HiddenField<Integer>("round", new Model<Integer>(model.getCurrentStatus().getCurrentRound())));
}
|
diff --git a/src/com/redhat/qe/tools/RemoteFileTasks.java b/src/com/redhat/qe/tools/RemoteFileTasks.java
index 2e7c087..99d5a56 100644
--- a/src/com/redhat/qe/tools/RemoteFileTasks.java
+++ b/src/com/redhat/qe/tools/RemoteFileTasks.java
@@ -1,171 +1,172 @@
package com.redhat.qe.tools;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import com.redhat.qe.auto.testng.LogMessageUtil;
import com.redhat.qe.auto.testopia.Assert;
import com.trilead.ssh2.Connection;
import com.trilead.ssh2.SCPClient;
public class RemoteFileTasks {
protected static Logger log = Logger.getLogger(RemoteFileTasks.class.getName());
public static final String stdoutFile = "/tmp/stdout";
public static final String stderrFile = "/tmp/stderr";
/**
* Create a file on a remote machine with given contents
* @param conn - A connection object already created to connect to ssh server
* @param filePath - path to the file you want to create (including dir and filename)
* @param contents - contents of the file you want to create
* @throws IOException
* @author jweiss
*/
public static void createFile(Connection conn, String filePath, String contents, String mode) throws IOException {
String dir = new File(filePath).getParent();
String fn = new File(filePath).getName();
log.log(Level.INFO, "Creating " + fn + " in " + dir + " on " + conn.getHostname(), LogMessageUtil.Style.Action);
SCPClient scp = new SCPClient(conn);
scp.put(contents.getBytes(), fn, dir, mode);
}
public static void createFile(Connection conn, String filePath, String contents) throws IOException {
createFile(conn, filePath, contents, "0755");
}
/**
* Use echo to create a file with the given contents. Then use chmod to give permissions to the file.
* @param runner
* @param filePath - absolute path to the file create
* @param contents - contents of the file
* @param perms - optional chmod options to apply to the filePath (e.g. "a+x")
* @return - exit code
* @author jsefler
*/
public static int createFile(SSHCommandRunner runner, String filePath, String contents, String perms) {
int exitCode = runCommandAndWait(runner, "echo -n -e '"+contents+"' > "+filePath, LogMessageUtil.action());
if (exitCode==0 && perms!=null) exitCode = runCommandAndWait(runner, "chmod "+perms+" "+filePath, LogMessageUtil.action());
return exitCode;
}
/**
* Copy file(s) onto a remote machine
* @param conn - A connection object already created to connect to ssh server
* @param dest - path where the file(s) should go on the remote machine (must be dir)
* @param source - one or more paths to the file(s) you want to copy to the remote dir
* @throws IOException
* @author jweiss
*/
public static void copyFile(Connection conn, String dest, String... sources ) throws IOException {
for (String source: sources)
log.log(Level.INFO, "Copying " + source + " to " + dest + " on " + conn.getHostname(), LogMessageUtil.Style.Action);
SCPClient scp = new SCPClient(conn);
scp.put(sources, dest);
}
/**
* Use sed to search and replace content within a file.<br>
* sed -i 's/regexp/replacement/g' filePath
* @param runner
* @param filePath - absolute path to the file to be searched and replaced
* @param regexp - the regular expression used to match a pattern for replacement
* @param replacement - the replacement content
* @return - exit code from sed
*/
public static int searchReplaceFile (SSHCommandRunner runner, String filePath, String regexp, String replacement) {
return runCommandAndWait(runner, "sed -i 's/"+regexp+"/"+replacement+"/g' " + filePath, LogMessageUtil.action());
}
/**
* Use grep to search for the existence of an extended regular expression within a file.<br>
* grep -E 'searchTerm' filePath
* @param runner
* @param filePath - absolute path to the file to be searched
* @param pattern - an extended regular expression (man grep for help)
* @return - exit code from grep
*/
public static int grepFile (SSHCommandRunner runner, String filePath, String pattern) {
return runCommandAndWait(runner, "grep -E '" + pattern + "' " + filePath, LogMessageUtil.info());
}
/**
* Use sed to delete lines from a file.<br>
* sed -i '/containingText/d' filePath
* @param runner
* @param filePath - absolute path to the file from which lines will be deleted
* @param containingText - delete lines containing a match to this text
* @return - exit code from sed
* @author jsefler
*/
public static int deleteLines (SSHCommandRunner runner, String filePath, String containingText) {
return runCommandAndWait(runner, "sed -i '/"+containingText+"/d' " + filePath, LogMessageUtil.action());
}
/**
* Test for the existence of a file.<br>
* test -e filePath && echo 1 || echo 0
* @param runner
* @param filePath - absolute path to the file to test for existence
* @return 1 (file exists), 0 (file does not exist), -1 (could not determine existence)
* @author jsefler
*/
public static int testFileExists (SSHCommandRunner runner, String filePath) {
runCommandAndWait(runner, "test -e "+filePath+" && echo 1 || echo 0", LogMessageUtil.info());
if (runner.getStdout().trim().equals("1")) return 1;
if (runner.getStdout().trim().equals("0")) return 0;
return -1;
}
public static int runCommandAndWait(SSHCommandRunner runner, String command, LogRecord logRecord){
return runner.runCommandAndWait(command,logRecord);
//return runner.runCommandAndWait(command,Long.valueOf(30000),logRecord); // timeout after 30 sec
}
public static int runAugeasCommand(SSHCommandRunner runner, String command, LogRecord logRecord){
return runCommandAndWait(runner, String.format("echo -e \"%s\nsave\n\" | augtool", command), logRecord);
}
public static int updateAugeasConfig(SSHCommandRunner runner, String augeusPath, String newValue){
if (newValue == null)
return runAugeasCommand(runner, String.format("rm %s", augeusPath), LogMessageUtil.action());
else
return runAugeasCommand(runner, String.format("set %s '%s'", augeusPath, newValue), LogMessageUtil.action());
}
/**
* Use the sshCommandRunner to execute the given command and verify the output
* contains an expected grep expression. Moreover, the stdout and stderr strings are
* redirected to this.stdoutFile and this.stderrFile which you can subsequently
* use for further post processing before the next call to runCommandAndAssert(...).
* @param command - command to execute with options
* @param stdoutGrepExpression - if !null, stdout is asserted to contain a match to this grep expression
* @param stderrGrepExpression - if !null, stderr is asserted to contain a match to this grep expression
* @param expectedExitCode - expected exit code from the command (usually 0 on success, non-0 on failure)
* @author jsefler
*/
public static void runCommandAndAssert(SSHCommandRunner sshCommandRunner, String command, String stdoutGrepExpression, String stderrGrepExpression, int expectedExitCode) {
//String runCommand = String.format("(%s | tee %s) 3>&1 1>&2 2>&3 | tee %s", command, stdoutFile, stderrFile); // the problem with this is that the exit code is lost
String runCommand = String.format("%s 1>%s 2>%s", command, stdoutFile, stderrFile);
int exitCode = sshCommandRunner.runCommandAndWait(runCommand);
if (exitCode!=expectedExitCode) {
sshCommandRunner.runCommandAndWait("echo 'Stdout from: "+command+"'; cat "+stdoutFile); // cheap way to log stdoutFile
sshCommandRunner.runCommandAndWait("echo 'Stderr from: "+command+"'; cat "+stderrFile); // cheap way to log stderrFile
- } Assert.assertEquals(exitCode,expectedExitCode);
+ }
+ Assert.assertEquals(exitCode,expectedExitCode);
if (stdoutGrepExpression!=null) {
sshCommandRunner.runCommandAndWait("echo 'Stdout from: "+command+"'; cat "+stdoutFile); // cheap way to log stdoutFile
Assert.assertEquals(RemoteFileTasks.grepFile(sshCommandRunner, stdoutFile, stdoutGrepExpression),0,"Stdout contains a match grepping for extended regular expression '"+stdoutGrepExpression+"' (0 means match)");
}
if (stderrGrepExpression!=null) {
sshCommandRunner.runCommandAndWait("echo 'Stderr from: "+command+"'; cat "+stderrFile); // cheap way to log stderrFile
Assert.assertEquals(RemoteFileTasks.grepFile(sshCommandRunner, stderrFile, stderrGrepExpression),0,"Stderr contains a match grepping for extended regular expression '"+stderrGrepExpression+"' (0 means match)");
}
}
}
| true | true | public static void runCommandAndAssert(SSHCommandRunner sshCommandRunner, String command, String stdoutGrepExpression, String stderrGrepExpression, int expectedExitCode) {
//String runCommand = String.format("(%s | tee %s) 3>&1 1>&2 2>&3 | tee %s", command, stdoutFile, stderrFile); // the problem with this is that the exit code is lost
String runCommand = String.format("%s 1>%s 2>%s", command, stdoutFile, stderrFile);
int exitCode = sshCommandRunner.runCommandAndWait(runCommand);
if (exitCode!=expectedExitCode) {
sshCommandRunner.runCommandAndWait("echo 'Stdout from: "+command+"'; cat "+stdoutFile); // cheap way to log stdoutFile
sshCommandRunner.runCommandAndWait("echo 'Stderr from: "+command+"'; cat "+stderrFile); // cheap way to log stderrFile
} Assert.assertEquals(exitCode,expectedExitCode);
if (stdoutGrepExpression!=null) {
sshCommandRunner.runCommandAndWait("echo 'Stdout from: "+command+"'; cat "+stdoutFile); // cheap way to log stdoutFile
Assert.assertEquals(RemoteFileTasks.grepFile(sshCommandRunner, stdoutFile, stdoutGrepExpression),0,"Stdout contains a match grepping for extended regular expression '"+stdoutGrepExpression+"' (0 means match)");
}
if (stderrGrepExpression!=null) {
sshCommandRunner.runCommandAndWait("echo 'Stderr from: "+command+"'; cat "+stderrFile); // cheap way to log stderrFile
Assert.assertEquals(RemoteFileTasks.grepFile(sshCommandRunner, stderrFile, stderrGrepExpression),0,"Stderr contains a match grepping for extended regular expression '"+stderrGrepExpression+"' (0 means match)");
}
}
| public static void runCommandAndAssert(SSHCommandRunner sshCommandRunner, String command, String stdoutGrepExpression, String stderrGrepExpression, int expectedExitCode) {
//String runCommand = String.format("(%s | tee %s) 3>&1 1>&2 2>&3 | tee %s", command, stdoutFile, stderrFile); // the problem with this is that the exit code is lost
String runCommand = String.format("%s 1>%s 2>%s", command, stdoutFile, stderrFile);
int exitCode = sshCommandRunner.runCommandAndWait(runCommand);
if (exitCode!=expectedExitCode) {
sshCommandRunner.runCommandAndWait("echo 'Stdout from: "+command+"'; cat "+stdoutFile); // cheap way to log stdoutFile
sshCommandRunner.runCommandAndWait("echo 'Stderr from: "+command+"'; cat "+stderrFile); // cheap way to log stderrFile
}
Assert.assertEquals(exitCode,expectedExitCode);
if (stdoutGrepExpression!=null) {
sshCommandRunner.runCommandAndWait("echo 'Stdout from: "+command+"'; cat "+stdoutFile); // cheap way to log stdoutFile
Assert.assertEquals(RemoteFileTasks.grepFile(sshCommandRunner, stdoutFile, stdoutGrepExpression),0,"Stdout contains a match grepping for extended regular expression '"+stdoutGrepExpression+"' (0 means match)");
}
if (stderrGrepExpression!=null) {
sshCommandRunner.runCommandAndWait("echo 'Stderr from: "+command+"'; cat "+stderrFile); // cheap way to log stderrFile
Assert.assertEquals(RemoteFileTasks.grepFile(sshCommandRunner, stderrFile, stderrGrepExpression),0,"Stderr contains a match grepping for extended regular expression '"+stderrGrepExpression+"' (0 means match)");
}
}
|
diff --git a/src/main/java/com/basho/riak/client/core/netty/RiakHttpMessageHandler.java b/src/main/java/com/basho/riak/client/core/netty/RiakHttpMessageHandler.java
index 8c5abda8..5ab2f4e7 100644
--- a/src/main/java/com/basho/riak/client/core/netty/RiakHttpMessageHandler.java
+++ b/src/main/java/com/basho/riak/client/core/netty/RiakHttpMessageHandler.java
@@ -1,85 +1,86 @@
/*
* Copyright 2013 Basho Technologies Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.basho.riak.client.core.netty;
import com.basho.riak.client.core.RiakHttpMessage;
import com.basho.riak.client.core.RiakResponseListener;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundMessageHandlerAdapter;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.LastHttpContent;
import java.util.LinkedList;
import java.util.List;
/**
*
* @author Brian Roach <roach at basho dot com>
* @since 2.0
*/
public class RiakHttpMessageHandler extends ChannelInboundMessageHandlerAdapter<Object>
{
private final RiakResponseListener listener;
private RiakHttpMessage message;
private final List<ByteBuf> chunks;
private int totalContentLength;
public RiakHttpMessageHandler(RiakResponseListener listener)
{
this.listener = listener;
this.chunks = new LinkedList<ByteBuf>();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.channel().pipeline().remove(this);
listener.onException(ctx.channel(), cause);
}
@Override
public void messageReceived(ChannelHandlerContext chc, Object msg) throws Exception
{
if (msg instanceof HttpResponse)
{
message = new RiakHttpMessage((HttpResponse)msg);
}
if (msg instanceof HttpContent)
{
chunks.add(((HttpContent)msg).data().retain());
totalContentLength += ((HttpContent)msg).data().readableBytes();
if (msg instanceof LastHttpContent)
{
byte[] bytes = new byte[totalContentLength];
int index = 0;
for (ByteBuf buffer : chunks)
{
- buffer.readBytes(bytes, index, buffer.readableBytes());
- index += buffer.readableBytes();
+ int readable = buffer.readableBytes();
+ buffer.readBytes(bytes, index, readable);
+ index += readable;
buffer.release();
}
message.setContent(bytes);
listener.onSuccess(chc.channel(), message);
chc.channel().pipeline().remove(this);
}
}
}
}
| true | true | public void messageReceived(ChannelHandlerContext chc, Object msg) throws Exception
{
if (msg instanceof HttpResponse)
{
message = new RiakHttpMessage((HttpResponse)msg);
}
if (msg instanceof HttpContent)
{
chunks.add(((HttpContent)msg).data().retain());
totalContentLength += ((HttpContent)msg).data().readableBytes();
if (msg instanceof LastHttpContent)
{
byte[] bytes = new byte[totalContentLength];
int index = 0;
for (ByteBuf buffer : chunks)
{
buffer.readBytes(bytes, index, buffer.readableBytes());
index += buffer.readableBytes();
buffer.release();
}
message.setContent(bytes);
listener.onSuccess(chc.channel(), message);
chc.channel().pipeline().remove(this);
}
}
}
| public void messageReceived(ChannelHandlerContext chc, Object msg) throws Exception
{
if (msg instanceof HttpResponse)
{
message = new RiakHttpMessage((HttpResponse)msg);
}
if (msg instanceof HttpContent)
{
chunks.add(((HttpContent)msg).data().retain());
totalContentLength += ((HttpContent)msg).data().readableBytes();
if (msg instanceof LastHttpContent)
{
byte[] bytes = new byte[totalContentLength];
int index = 0;
for (ByteBuf buffer : chunks)
{
int readable = buffer.readableBytes();
buffer.readBytes(bytes, index, readable);
index += readable;
buffer.release();
}
message.setContent(bytes);
listener.onSuccess(chc.channel(), message);
chc.channel().pipeline().remove(this);
}
}
}
|
diff --git a/src/org/bodytrack/client/DataPlot.java b/src/org/bodytrack/client/DataPlot.java
index 4781df5..dec7e96 100644
--- a/src/org/bodytrack/client/DataPlot.java
+++ b/src/org/bodytrack/client/DataPlot.java
@@ -1,1625 +1,1625 @@
package org.bodytrack.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import gwt.g2d.client.graphics.Color;
import gwt.g2d.client.math.Vector2;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Represents a single set of data, along with references to its
* associated axes.
*
* <p>Has the ability to draw itself and its axes on a
* {@link Canvas} object, and to update
* the positions of its dots based on the zoom level. Also, if the
* zoom level or position of the X-axis changes enough, this class will
* automatically fetch the data from the server via Ajax and redraw
* the data whenever it comes in from the server.</p>
*
* <p>A class that wishes to inherit this class can override
* {@link DataPlot#paintAllDataPoints}, but the easiest way to modify
* functionality it to override {@link DataPlot#paintDataPoint} and
* {@link DataPlot#paintEdgePoint(BoundedDrawingBox, double, double, PlottablePoint)}.
* These two functions are responsible for painting a single point on
* this DataPlot. This (parent) class will automatically handle
* highlighting, zooming, and the Ajax calls for pulling extra data
* from the server.</p>
*
* <p>A classes that wishes to inherit this class may also wish to
* override {@link DataPlot#getDataPoints(GrapherTile)}, which
* determines the points that {@link DataPlot#paintAllDataPoints}
* will draw, and the order in which paintAllDataPoints will draw
* them.</p>
*
* <p>Note that <strong>any</strong> class that inherits from this class
* should override {@link #getType()}, which allows consistent saving
* and restoring of views.</p>
*/
public class DataPlot implements Alertable<GrapherTile> {
/**
* The width at which a normal line is drawn.
*/
protected static final int NORMAL_STROKE_WIDTH = 1;
/**
* The width at which a highlighted line is drawn.
*/
protected static final int HIGHLIGHT_STROKE_WIDTH = 3;
/**
* Never render a point with value less than this - use anything
* less as a sentinel for "data point not present".
*
* <p>This value is intended to be used by subclasses as a sentinel
* value.</p>
*/
protected static final double MIN_DRAWABLE_VALUE = -1e300;
/**
* The preferred width in pixels of a comment popup panel. The comment panel's actual width will be the minimum of
* this value, the drawing width, and the preferred width of the comment.
*/
private static final int PREFERRED_MAX_COMMENT_WIDTH = 600;
/**
* Whenever the {@link #highlight()} method is called, we don't know
* which points on the axes should be highlighted, so we use this
* value to indicate this. As such, testing with == is OK as a test
* for this point, since we set highlightedPoint to this exact
* memory location whenever we don't know which point should be
* highlighted.
*/
protected static final PlottablePoint HIGHLIGHTED_NO_SINGLE_POINT =
new PlottablePoint(Double.MIN_VALUE, 0.0);
/**
* The radius to use when drawing a dot on the grapher.
*/
private static final double DOT_RADIUS = 0.5;
/**
* The radius to use when drawing a highlighted dot on the grapher.
*/
private static final double HIGHLIGHTED_DOT_RADIUS = 4;
/**
* We never re-request a URL with MAX_REQUESTS_PER_URL or more failures
* in a row.
*/
private static final int MAX_REQUESTS_PER_URL = 5;
/**
* Used to speed up the log2 method.
*/
private static final double LN_2 = Math.log(2);
private final GraphWidget container;
private GraphAxis xAxis;
private GraphAxis yAxis;
private final Canvas canvas;
private PopupPanel commentPanel;
private final String deviceName;
private final String channelName;
private final int minLevel;
private Color color;
private boolean shouldZoomIn;
// Values related to getting new values from the server
private final String baseUrl;
private final List<GrapherTile> currentData;
private final Set<TileDescription> pendingDescriptions;
private final Map<String, Integer> pendingUrls;
private final List<GrapherTile> pendingData;
private final Map<String, List<Integer>> loadingUrls;
// Determining whether or not we should retrieve more data from
// the server
private int currentLevel;
private int currentMinOffset;
private int currentMaxOffset;
// If highlightedPoint is null, then this should not be highlighted.
// Otherwise, this is the point to highlight on the axes
private PlottablePoint highlightedPoint;
// If publishValueOnHighlight is true, we will show our data value
// as a decimal whenever this axis is highlighted, using the
// data value publishing API in GraphWidget.
private final boolean publishValueOnHighlight;
private int publishedValueId;
/**
* Main constructor for the DataPlot object.
*
* <p>The parameter url is the trickiest to get right. This parameter
* should be the <strong>beginning</strong> (the text up to, but
* not including, the <level>.<offset>.json part of the
* URL to fetch) of the URL which will be used to get more data.
* Note that this <strong>must</strong> be a trusted BodyTrack
* URL. As described in the documentation for
* {@link GrapherTile#retrieveTile(String, int, int, List, Alertable)},
* an untrusted connection could allow
* unauthorized access to all of a user's data.</p>
*
* @param container
* the {@link GraphWidget GraphWidget} on
* which this DataPlot will draw itself and its axes
* @param xAxis
* the X-axis along which this data set will be aligned when
* drawn. Usually this is a
* {@link TimeGraphAxis TimeGraphAxis}
* @param yAxis
* the Y-axis along which this data set will be aligned when
* drawn
* @param deviceName
* the name of the device from which this channel came
* @param channelName
* the name of the channel on the device specified by deviceName
* @param url
* the beginning of the URL for fetching this data with Ajax
* calls
* @param minLevel
* the minimum level to which the user will be allowed to zoom
* @param color
* the color in which to draw these data points (note that
* this does not affect the color of the axes)
* @param publishValueOnHighlight
* <tt>true</tt> to signify that, whenever a point is highlighted
* on this <tt>DataPlot</tt>, the value should show up in the
* corner of container
* @throws NullPointerException
* if container, xAxis, yAxis, deviceName, channelName, url,
* or color is <tt>null</tt>
*/
public DataPlot(final GraphWidget container, final GraphAxis xAxis, final GraphAxis yAxis,
final String deviceName, final String channelName, final String url, final int minLevel,
final Color color, final boolean publishValueOnHighlight) {
if (container == null || xAxis == null || yAxis == null
|| deviceName == null || channelName == null
|| url == null || color == null) {
throw new NullPointerException("Cannot have a null container, "
+ "axis, device or channel name, url, or color");
}
this.container = container;
this.xAxis = xAxis;
this.yAxis = yAxis;
this.deviceName = deviceName;
this.channelName = channelName;
baseUrl = url;
shouldZoomIn = true;
this.minLevel = minLevel;
this.color = color;
this.publishValueOnHighlight = publishValueOnHighlight;
canvas = Canvas.buildCanvas(this.container);
// The data will be pulled in with the checkForFetch call
pendingData = new ArrayList<GrapherTile>();
pendingDescriptions = new HashSet<TileDescription>();
pendingUrls = new HashMap<String, Integer>();
currentData = new ArrayList<GrapherTile>();
loadingUrls = new HashMap<String, List<Integer>>();
currentLevel = Integer.MIN_VALUE;
currentMinOffset = Integer.MAX_VALUE;
currentMaxOffset = Integer.MIN_VALUE;
highlightedPoint = null;
publishedValueId = 0;
shouldZoomIn = checkForFetch();
}
/**
* Puts together the base URL for a channel, based on the URL
* specification for tiles.
*
* @param userId
* the ID of the current user
* @param deviceName
* the device for the channel we want to pull tiles from
* @param channelName
* the channel name for the channel we want to pull tiles from
* @return
* a base URL that is suitable for passing to one of the
* constructors for <tt>DataPlot</tt> or one of its subclasses
* @throws NullPointerException
* if deviceName or channelName is <tt>null</tt>
*/
public static String buildBaseUrl(final int userId, final String deviceName, final String channelName) {
if (deviceName == null || channelName == null) {
throw new NullPointerException(
"Null part of base URL not allowed");
}
if ("".equals(deviceName)) {
return "/tiles/" + userId + "/" + channelName + "/";
}
return "/tiles/" + userId + "/" + deviceName + "." + channelName + "/";
}
/**
* Combines the device and channel name to get the overall
* name for the channel.
*
* @param deviceName
* the name of the device, which may be <tt>null</tt>
* @param channelName
* the name of the channel, which may be <tt>null</tt>
* @return
* a string representing the device and channel name
* together
*/
// TODO: Rename to a more useful name
// TODO: Move this to StringPair, then refactor StringPair to have
// a different name
public static String getDeviceChanName(final String deviceName, final String channelName) {
final String cleanedDeviceName = (deviceName == null) ? "" : deviceName;
final String cleanedChannelName = (channelName == null) ? "" : channelName;
if ("".equals(cleanedDeviceName)) {
return cleanedChannelName;
}
return cleanedDeviceName + "." + cleanedChannelName;
}
/**
* Returns the type of this plot.
*
* @return
* a string representing the type of this plot. For objects
* of runtime type <tt>DataPlot</tt>, this will always be
* equal to the string "plot", although subclasses
* should override this implementation
*/
public String getType() {
return "plot";
}
/**
* Returns the device name for this plot.
*
* @return
* the device name passed to the constructor
*/
public String getDeviceName() {
return deviceName;
}
/**
* Returns the channel name for this plot.
*
* @return
* the channel name passed to the constructor
*/
public String getChannelName() {
return channelName;
}
/**
* Returns <tt>true</tt> if and only if the X-axis is allowed to
* zoom in farther, based on the zoom policy of this DataPlot.
*
* @return
* <tt>true</tt> if the X-axis should be allowed to
* zoom in more, <tt>false</tt> otherwise
*/
public boolean shouldZoomIn() {
return shouldZoomIn;
}
/**
* Returns the color at which this <tt>DataPlot</tt> is drawn.
*
* @return
* the color used to draw this <tt>DataPlot</tt>
*/
public Color getColor() {
return color;
}
/**
* Sets the color at which this <tt>DataPlot</tt> is drawn.
*
* @param newColor
* the color that should be used to draw this <tt>DataPlot</tt>
* @throws NullPointerException
* if newColor is <tt>null</tt>
*/
public void setColor(final Color newColor) {
if (newColor == null) {
throw new NullPointerException(
"Cannot use null color to draw plot");
}
color = newColor;
container.paintTwice();
}
/**
* Gives subclasses a reference to the
* {@link Canvas Canvas} object on which they
* can draw.
*
* @return
* the <tt>Canvas</tt> on which this <tt>DataPlot</tt> draws
*/
protected Canvas getCanvas() {
return canvas;
}
/**
* Gives subclasses a reference to the
* {@link GraphWidget GraphWidget} object that
* they can use for the <tt>GraphWidget</tt> API.
*
* <p>Do <em>not</em> use this method's return value for direct
* drawing - this is why the {@link #getCanvas()} method was created.
* Instead, this method's return value should be used for other
* calls that are specific to the <tt>GraphWidget</tt> class.</p>
*
* @return
* the <tt>GraphWidget</tt> on which this <tt>DataPlot</tt>
* draws
*/
protected GraphWidget getContainer() {
return container;
}
/**
* Checks for and performs a fetch for data from the server if
* necessary.
*
* @return
* <tt>true</tt> if the user should be allowed to zoom past
* this point, <tt>false</tt> if the user shouldn't be allowed
* to zoom past this point
*/
private boolean checkForFetch() {
final int correctLevel = computeCurrentLevel();
final int correctMinOffset = computeMinOffset(correctLevel);
final int correctMaxOffset = computeMaxOffset(correctLevel);
if (correctLevel != currentLevel) {
for (int i = correctMinOffset; i <= correctMaxOffset; i++) {
fetchFromServer(correctLevel, i);
}
}
else if (correctMinOffset < currentMinOffset) {
fetchFromServer(correctLevel, correctMinOffset);
}
else if (correctMaxOffset > currentMaxOffset) {
fetchFromServer(correctLevel, correctMaxOffset);
}
// This way we don't fetch the same data multiple times
currentLevel = correctLevel;
currentMinOffset = correctMinOffset;
currentMaxOffset = correctMaxOffset;
return correctLevel > minLevel;
}
/**
* Fetches the specified tile from the server.
*
* Note that this checks the pendingDescriptions instance variable
* to determine if this tile has already been requested. If so,
* does not request anything from the server.
*
* @param level
* the level of the tile to fetch
* @param offset
* the offset of the tile to fetch
*/
private void fetchFromServer(final int level, final int offset) {
final TileDescription desc = new TileDescription(level, offset);
// Ensures we don't fetch the same tile twice unnecessarily
if (pendingDescriptions.contains(desc)) {
return;
}
final String url = getTileUrl(level, offset);
GrapherTile.retrieveTile(url, level, offset, pendingData, this);
// Tell the user we are looking for information
addLoadingText(level, offset, url);
// Make sure we don't fetch this again unnecessarily
pendingDescriptions.add(desc);
pendingUrls.put(url, 0);
}
/**
* A method to generate the correct URL for a given tile.
*
* <p>This method is designed so that subclasses can override
* it and change the default behavior of tile fetching with
* little effort. For instance, a photo data plot can modify the
* "tags" and "nsfw" parameters in the request
* to the server.</p>
*
* @param level
* the level at which the tile should come
* @param offset
* the offset of the tile
* @return
* the URL to use to get the tile
*/
protected String getTileUrl(final int level, final int offset) {
return baseUrl + level + "." + offset + ".json";
}
/**
* Adds the specified loading text to container.
*
* <p>This is one of two methods to handle the loading text feature
* for DataPlot objects. The other is
* {@link #removeLoadingText(String)}. This method will create
* a loading text string and publish it to container.</p>
*
* @param level
* the level of the tile that is loading
* @param offset
* the offset of the tile that is loading
* @param url
* the URL of the tile that is loading
*/
private void addLoadingText(final int level, final int offset, final String url) {
final String msg = "Loading " + url;
// Actually add the message
final int id = container.addLoadingMessage(msg);
final List<Integer> ids = loadingUrls.containsKey(url) ?
loadingUrls.remove(url) : new ArrayList<Integer>();
ids.add(id);
loadingUrls.put(url, ids);
}
/**
* Removes the specified loading text from container.
*
* <p>This is one of two methods to handle the loading text feature
* for DataPlot objects. The other is
* {@link #addLoadingText(int, int, String)}. This method will
* remove from container the loading text string associated
* with url. Thus, it is required that this take the same
* URL that was passed to addLoadingText to create the message.</p>
*
* @param url
* the URL of the tile that is finished loading
*/
private void removeLoadingText(final String url) {
if (loadingUrls.containsKey(url)) {
// Always maintain the invariant that each value in
// loadingUrls has at least one element. Since this
// is the place where things are removed from loadingUrls,
// and since no empty lists are added to loadingUrls,
// this method is responsible for maintaining the
// invariant.
// Note that we remove from loadingUrls
final List<Integer> ids = loadingUrls.remove(url);
final int id = ids.remove(0);
if (ids.size() > 0) {
loadingUrls.put(url, ids);
}
container.removeLoadingMessage(id);
}
// Don't do anything if we don't have an ID with this URL
}
/**
* Called every time a new tile loads.
*
* @param tile
* the <tt>GrapherTile</tt> representing the tile that loaded
*/
@Override
public void onSuccess(final GrapherTile tile) {
final String url = tile.getUrl();
if (pendingUrls.containsKey(url)) {
pendingUrls.remove(url);
}
removeLoadingText(url);
// It is important to call container.paintTwice() rather than
// simply paint() here, since the loading text does
// not update unless container.paint() is called at least once
container.paintTwice();
}
/**
* Called every time a tile load fails.
*
* <p>Tries to re-request the tile.</p>
*
* @param tile
* the <tt>GrapherTile</tt> representing the tile that failed
* to load
*/
@Override
public void onFailure(final GrapherTile tile) {
final String url = tile.getUrl();
final int level = tile.getLevel();
final int offset = tile.getOffset();
if (pendingUrls.containsKey(url)) {
final int oldValue = pendingUrls.get(url);
if (oldValue > MAX_REQUESTS_PER_URL) {
// TODO: Log or alert user whenever we can't get
// a piece of data
// Perhaps use InfoPublisher API
removeLoadingText(url);
return;
}
pendingUrls.remove(url);
pendingUrls.put(url, oldValue + 1);
}
else {
pendingUrls.put(url, 1);
}
GrapherTile.retrieveTile(url, level, offset, pendingData, this);
// See the documentation in onSuccess() to see why
// container.paintTwice() is important
container.paintTwice();
}
/**
* Paints this DataPlot on the stored GraphWidget.
*
* <p>Does not draw the axes associated with this DataPlot.</p>
*
* <p>Note that it is <strong>not</strong> recommended that a subclass
* override this method. Instead, it is recommended that a subclass
* override the {@link #paintAllDataPoints} method.</p>
*/
public void paint() {
checkForNewData();
// Draw data points
canvas.getSurface().setStrokeStyle(color);
canvas.getSurface().setLineWidth(isHighlighted()
? HIGHLIGHT_STROKE_WIDTH : NORMAL_STROKE_WIDTH);
final BoundedDrawingBox drawing = getDrawingBounds();
paintAllDataPoints(drawing);
hideComment();
if (highlightedPoint != null
&& highlightedPoint != HIGHLIGHTED_NO_SINGLE_POINT) { // TODO: should this be an .equals() comparison instead?
drawing.beginClippedPath();
paintHighlightedPoint(drawing, highlightedPoint);
drawing.strokeClippedPath();
if (highlightedPoint.hasComment()) {
paintComment(drawing, highlightedPoint);
}
}
// Clean up after ourselves
canvas.getSurface().setStrokeStyle(Canvas.DEFAULT_COLOR);
canvas.getSurface().setLineWidth(NORMAL_STROKE_WIDTH);
// Make sure we shouldn't get any more info from the server
shouldZoomIn = checkForFetch();
}
/**
* Builds and returns a new {@link BoundedDrawingBox
* BoundedDrawingBox} that constrains drawing to the viewing window.
*
* @return
* a <tt>BoundedDrawingBox</tt> that will only allow drawing
* within the axes
*/
private BoundedDrawingBox getDrawingBounds() {
final double minX = xAxis.project2D(xAxis.getMin()).getX();
final double maxX = xAxis.project2D(xAxis.getMax()).getX();
// Although minY and maxY appear to be switched, this is actually
// the correct way to define these variables, since we draw the
// Y-axis from bottom to top but pixel values increase from top
// to bottom. Thus, the max Y-value is associated with the min
// axis value, and vice versa.
final double minY = yAxis.project2D(yAxis.getMax()).getY();
final double maxY = yAxis.project2D(yAxis.getMin()).getY();
return new BoundedDrawingBox(canvas, minX, minY, maxX, maxY);
}
/**
* Checks to see if we have received data from the server
*/
private void checkForNewData() {
if (pendingData.size() > 0) {
// Pull all the data out of pendingData
for (final GrapherTile tile : pendingData) {
if (tile == null) {
continue;
}
currentData.add(tile);
// Make sure we don't still mark this as pending
pendingDescriptions.remove(tile.getDescription());
}
pendingData.clear();
}
}
/**
* Renders all the salient data points in currentData.
*
* @param drawing
* the {@link BoundedDrawingBox
* BoundedDrawingBox} in which all points should be
* drawn
*/
protected void paintAllDataPoints(final BoundedDrawingBox drawing) {
// TODO: improve the algorithm for getting the best resolution tile
// Current algorithm is O(n m), where n is currentData.length()
// and m is getBestResolutionTiles().length()
// Could use a cache for the best resolution tiles, but would
// have to be careful to drop the cache if we pan or zoom too much,
// and definitely if we pull in more data
drawing.beginClippedPath();
// Putting these declarations outside the loop ensures
// that no gaps appear between lines
double prevX = -Double.MAX_VALUE;
double prevY = -Double.MAX_VALUE;
for (final GrapherTile tile : getBestResolutionTiles()) {
final List<PlottablePoint> dataPoints = getDataPoints(tile);
if (dataPoints == null) {
continue;
}
for (final PlottablePoint point : dataPoints) {
final double x = xAxis.project2D(point.getDate()).getX();
final double y = yAxis.project2D(point.getValue()).getY();
if (x < MIN_DRAWABLE_VALUE || y < MIN_DRAWABLE_VALUE
|| Double.isInfinite(x) || Double.isInfinite(y)) {
// Don't draw a boundary point
// So that we don't draw a boundary point, we (relying
// on the fact that MIN_DRAWABLE_VALUE is negative)
// set prevY to something smaller than
// MIN_DRAWABLE_VALUE, ensuring that paintEdgePoint
// will be called on the next loop iteration
prevY = MIN_DRAWABLE_VALUE * 1.01;
continue;
}
// Skip any "reverse" drawing
if (prevX > x) {
continue;
}
// Draw this part of the line
if (prevX > MIN_DRAWABLE_VALUE
&& prevY > MIN_DRAWABLE_VALUE) {
paintDataPoint(drawing, prevX, prevY, x, y, point);
}
else {
paintEdgePoint(drawing, x, y, point);
}
prevX = x;
prevY = y;
}
}
drawing.strokeClippedPath();
}
/**
* Returns the ordered list of points this DataPlot should draw
* in {@link #paintAllDataPoints}.
*
* <p>It is acceptable, and not considered an error, if this or a subclass
* implementation returns <tt>null</tt>. Such a return should simply
* be taken as a sign that the specified tile contains no data points
* that paintAllDataPoints should draw.</p>
*
* @param tile
* the {@link GrapherTile GrapherTile}
* from which to pull the data points
* @return
* a list of
* {@link PlottablePoint PlottablePoint}
* objects to be drawn by paintAllDataPoints
*/
protected List<PlottablePoint> getDataPoints(final GrapherTile tile) {
return tile.getDataPoints();
}
/**
* Paints a left edge point for a segment of the plot.
*
* <p>This method is designed to be overridden by subclasses.
* Note that this is only called for the left edge of a plot
* segment. This particular implementation draws a small dot,
* although a subclass implementation does not have to do the
* same. Note that all parameters (except drawing, of course)
* are assumed to be in terms of pixels, not logical values
* on the axes.</p>
*
* @param drawing
* the
* {@link BoundedDrawingBox}
* that should constrain the drawing. Forwarding graphics calls
* through drawing will ensure that everything draws up to the edge
* of the viewing window but no farther
* @param x
* the X-coordinate of the point to draw
* @param y
* the Y-coordinate of the point to draw
* @param rawDataPoint
* the raw {@link PlottablePoint}
*/
protected void paintEdgePoint(final BoundedDrawingBox drawing, final double x,
final double y, final PlottablePoint rawDataPoint) {
drawing.drawDot(x, y, DOT_RADIUS);
if (rawDataPoint.hasComment()) {
paintHighlightedPoint(drawing, rawDataPoint);
}
}
/**
* Draws a single data point on the graph.
*
* <p>This method is designed to be overridden by subclasses.
* Note that this method has as a precondition that
* {@code prevX < x}. Note that all parameters (except drawing and rawDataPoint,
* of course) are assumed to be in terms of pixels.</p>
*
*
* @param drawing
* the
* {@link BoundedDrawingBox BoundedDrawingBox}
* that should constrain the drawing. Forwarding graphics calls
* through drawing will ensure that everything draws up to the edge
* of the viewing window but no farther
* @param prevX
* the previous X-value, which will be greater than
* MIN_DRAWABLE_VALUE
* @param prevY
* the previous Y-value, which will be greater than
* MIN_DRAWABLE_VALUE
* @param x
* the current X-value, which will be greater than
* MIN_DRAWABLE_VALUE, and greater than or equal to
* prevX
* @param y
* the current Y-value, which will be greater than
* MIN_DRAWABLE_VALUE
* @param rawDataPoint
* the raw {@link PlottablePoint}
*
* @see #MIN_DRAWABLE_VALUE
*/
protected void paintDataPoint(final BoundedDrawingBox drawing, final double prevX,
final double prevY, final double x, final double y, final PlottablePoint rawDataPoint) {
drawing.drawLineSegment(prevX, prevY, x, y);
if (rawDataPoint.hasComment()) {
paintHighlightedPoint(drawing, rawDataPoint);
}
}
/**
* Draws a single point on the graph, in highlighted style.
*
* <p>This is designed to be overridden by subclasses. It is
* called by {@link #paint()} after all data points have been
* painted, and the parameter is the data point closest to
* the mouse. Note that this means that, by the time this
* method is called, point has already been drawn.</p>
*
* <p>This draws a larger dot at point, although of course a subclass
* implementation does not have to follow that lead.</p>
*
* @param drawing
* the
* {@link BoundedDrawingBox BoundedDrawingBox}
* that should constrain the drawing. Forwarding graphics calls
* through drawing will ensure that everything draws up to the edge
* of the viewing window but no farther
* @param point
* the data point closest to the mouse. It is guaranteed that
* point will never be <tt>null</tt> or equal to
* {@link #HIGHLIGHTED_NO_SINGLE_POINT}
*/
protected void paintHighlightedPoint(final BoundedDrawingBox drawing,
final PlottablePoint point) {
final double x = xAxis.project2D(point.getDate()).getX();
final double y = yAxis.project2D(point.getValue()).getY();
// Draw three concentric circles to look like one filled-in circle
// The real radius is the first one used: HIGHLIGHTED_DOT_RADIUS
drawing.drawDot(x, y, HIGHLIGHTED_DOT_RADIUS);
drawing.drawDot(x, y, HIGHLIGHT_STROKE_WIDTH);
drawing.drawDot(x, y, NORMAL_STROKE_WIDTH);
}
private void paintComment(final BoundedDrawingBox drawing, final PlottablePoint highlightedPoint) {
if (highlightedPoint.hasComment()) {
// compute (x,y) for the highlighted point in pixels, relative to the canvas
final int x = (int)xAxis.project2D(highlightedPoint.getDate()).getX();
final int y = (int)yAxis.project2D(highlightedPoint.getValue()).getY();
// create the panel, but display it offscreen so we can measure its preferred width
commentPanel = new PopupPanel();
commentPanel.add(new Label(highlightedPoint.getComment()));
commentPanel.setPopupPosition(-10000, -10000);
commentPanel.show();
final int preferredCommentPanelWidth = commentPanel.getOffsetWidth();
commentPanel.hide();
// compute the actual panel width by taking the minimum of the comment panel's preferred width, the width of
// the drawing region, and the PREFERRED_MAX_COMMENT_WIDTH.
final int desiredPanelWidth = (int)Math.min(preferredCommentPanelWidth, Math.min(drawing.getWidth(), PREFERRED_MAX_COMMENT_WIDTH));
// set the panel to the corrected width
final int actualPanelWidth;
if (desiredPanelWidth != preferredCommentPanelWidth) {
commentPanel.setWidth(String.valueOf(desiredPanelWidth) + "px");
commentPanel.show();
// unfortunately, setting the width doesn't take borders and such into account, so we need read the width again and
// then adjust accordingly
final int widthPlusExtra = commentPanel.getOffsetWidth();
commentPanel.hide();
commentPanel.setWidth(String.valueOf(desiredPanelWidth - (widthPlusExtra - desiredPanelWidth)) + "px");
commentPanel.show();
actualPanelWidth = commentPanel.getOffsetWidth();
} else {
actualPanelWidth = preferredCommentPanelWidth;
}
// now, if the actual panel width is less than the comment panel's preferred width, then the height must have
// changed so we need to redisplay the panel to determine its new height.
commentPanel.show();
final int actualPanelHeight = commentPanel.getOffsetHeight();
// now that we know the actual height and width of the comment panel, we can determine where to place the panel
// horizontally and vertically. The general strategy is to try to center the panel horizontally above the
// point (we favor placement above the point so that the mouse pointer doesn't occlude the comment). For
// horizontal placement, if the panel can't be centered with respect to the point, then just shift it left or
// right enough so that it fits within the bounds of the drawing region. For vertical placement, if the panel
// can't be placed above the point, then place it below.
final int actualPanelLeft;
final int desiredPanelLeft = x - actualPanelWidth / 2;
if (desiredPanelLeft < drawing.getTopLeft().getIntX()) {
actualPanelLeft = drawing.getTopLeft().getIntX();
} else if ((desiredPanelLeft + actualPanelWidth) > drawing.getBottomRight().getIntX()) {
actualPanelLeft = drawing.getBottomRight().getIntX() - actualPanelWidth;
} else {
actualPanelLeft = desiredPanelLeft;
}
final int actualPanelTop;
final int desiredPanelTop = (int)(y - actualPanelHeight - HIGHLIGHTED_DOT_RADIUS);
if (desiredPanelTop < drawing.getTopLeft().getIntY()) {
// place the panel below the point since there's not enough room to place it above
actualPanelTop = (int)(y + HIGHLIGHTED_DOT_RADIUS);
} else {
actualPanelTop = desiredPanelTop;
}
// get the top-left coords of the canvas so we can offset the panel position
final Element nativeCanvasElement = drawing.getCanvas().getNativeCanvasElement();
final int canvasLeft = nativeCanvasElement.getAbsoluteLeft();
final int canvasTop = nativeCanvasElement.getAbsoluteTop();
- // set the panel's position--these are in absolute page coordinates, so we need to offset it by the canvas's
- // absolute position and the drawing region's position with respect to the canvas.
+ // set the panel's position--these are in absolute page coordinates,
+ // so we need to offset it by the canvas's absolute position.
commentPanel.setPopupPosition(actualPanelLeft + canvasLeft, actualPanelTop + canvasTop);
// show the panel
commentPanel.show();
}
}
private void hideComment() {
if (commentPanel != null) {
commentPanel.hide();
commentPanel = null;
}
}
/**
* Returns a sorted list of all best resolution tiles available.
*
* @return
* a sorted list of all the best resolution tiles in
* currentData
*/
private List<GrapherTile> getBestResolutionTiles() {
final List<GrapherTile> best = new ArrayList<GrapherTile>();
// When minTime and maxTime are used in calculations, they are
// used to make the calculations scale-independent
final double minTime = xAxis.getMin();
final double maxTime = xAxis.getMax();
double maxCoveredTime = minTime;
final int bestLevel = computeCurrentLevel();
while (maxCoveredTime <= maxTime) {
final GrapherTile bestAtCurrTime = getBestResolutionTileAt(
maxCoveredTime + (maxTime - minTime) * 1e-3,
bestLevel);
// We need to move a little to the right of the current time
// so we don't get the same tile twice
if (bestAtCurrTime == null) {
maxCoveredTime += (maxTime - minTime) * 1e-2;
}
else {
best.add(bestAtCurrTime);
maxCoveredTime =
bestAtCurrTime.getDescription().getMaxTime();
}
}
return best;
}
/**
* Returns the best-resolution tile that covers the specified
* point.
*
* @param time
* the time which must be covered by the tile
* @param bestLevel
* the level to which we want the returned tile to be close
* @return
* the best-resolution (lowest-level) tile which has min value
* less than or equal to time, and max value greater than or
* equal to time, or <tt>null</tt> if no such tile exists
*/
private GrapherTile getBestResolutionTileAt(final double time, final int bestLevel) {
GrapherTile best = null;
TileDescription bestDesc = null;
for (final GrapherTile tile : currentData) {
final TileDescription desc = tile.getDescription();
if (desc.getMinTime() > time || desc.getMaxTime() < time) {
continue;
}
if (best == null) {
best = tile;
bestDesc = desc;
}
else if (Math.abs(desc.getLevel() - bestLevel) <
Math.abs(bestDesc.getLevel() - bestLevel)) {
best = tile;
bestDesc = desc;
}
else if (Math.abs(desc.getLevel() - bestLevel) ==
Math.abs(bestDesc.getLevel() - bestLevel)) {
if (desc.getLevel() < bestDesc.getLevel()) {
best = tile;
bestDesc = desc;
}
}
}
return best;
}
/**
* Returns the X-Axis for this DataPlot.
*
* @return
* the X-axis for this DataPlot
*/
public GraphAxis getXAxis() {
return xAxis;
}
/**
* Sets the X-axis for this <tt>DataPlot</tt>.
*
* <p>This is only intended to be used within this package.
* In almost all cases, there is no need for this method.</p>
*
* @param axis
* the new X-axis to use
* @throws NullPointerException
* if axis is <tt>null</tt>
*/
void setXAxis(final GraphAxis axis) {
if (axis == null) {
throw new NullPointerException("Cannot use null X-axis");
}
xAxis = axis;
}
/**
* Returns the Y-Axis for this DataPlot.
*
* @return
* the Y-axis for this DataPlot
*/
public GraphAxis getYAxis() {
return yAxis;
}
/**
* Sets the Y-axis for this <tt>DataPlot</tt>.
*
* <p>This is only intended to be used within this package.
* In almost all cases, there is no need for this method.</p>
*
* @param axis
* the new Y-axis to use
* @throws NullPointerException
* if axis is <tt>null</tt>
*/
void setYAxis(final GraphAxis axis) {
if (axis == null) {
throw new NullPointerException("Cannot use null Y-axis");
}
yAxis = axis;
}
/**
* Computes the value for currentLevel based on xAxis.
*
* @return
* the level at which xAxis is operating
*/
private int computeCurrentLevel() {
final double xAxisWidth = xAxis.getMax() - xAxis.getMin();
final double dataPointWidth = xAxisWidth / GrapherTile.TILE_WIDTH;
return log2(dataPointWidth);
}
/**
* Computes the floor of the log (base 2) of x.
*
* @param x
* the value for which we want to take the log
* @return
* the floor of the log (base 2) of x
*/
private static int log2(final double x) {
if (x <= 0) {
return Integer.MIN_VALUE;
}
return (int)Math.floor((Math.log(x) / LN_2));
}
/**
* Returns the offset at which the left edge of the X-axis is operating.
*
* Returns the offset of the tile in which the minimum value
* of the X-axis is found.
*
* @param level
* the level at which we assume we are operating when calculating
* offsets
* @return
* the current offset of the X-axis, based on level
* and the private variable xAxis
*/
private int computeMinOffset(final int level) {
final double min = xAxis.getMin();
final double tileWidth = getTileWidth(level);
// Tile offset computation
return (int)(min / tileWidth);
}
/**
* Returns the offset at which the right edge of the X-axis is operating.
*
* Returns the offset of the tile in which the maximum value
* of the X-axis is found.
*
* @param level
* the level at which we assume we are operating when calculating
* offsets
* @return
* the current offset of the X-axis, based on level
* and the private variable xAxis
*/
private int computeMaxOffset(final int level) {
final double max = xAxis.getMax();
final double tileWidth = getTileWidth(level);
// Tile number computation
return (int)(max / tileWidth);
}
/**
* Returns the width of a single tile.
*
* @param level
* the level of the tile for which we will find the width
* @return
* the width of a tile at the given level
*/
private static double getTileWidth(final int level) {
return (new TileDescription(level, 0)).getTileWidth();
}
/**
* Returns a PlottablePoint if and only if there is a point, part of
* this DataPlot, within threshold pixels of pos. Otherwise, returns
* <tt>null</tt>.
*
* This actually builds a square of 2 * threshold pixels on each
* side, centered at pos, and checks if there is a data point within
* that square, but that is a minor detail that should not affect
* the workings of this method.
*
* @param pos
* the mouse position from which to check proximity to a data
* point
* @param threshold
* the maximum distance pos can be from a data point to be
* considered "near" to it
* @return
* <tt>null</tt> if there is no point within threshold pixels
* of pos, or one of the points, if there is such a point
* @throws IllegalArgumentException
* if threshold is negative
*/
public PlottablePoint closest(final Vector2 pos, final double threshold) {
if (threshold < 0) {
throw new IllegalArgumentException(
"Cannot work with a negative distance");
}
final double x = pos.getX();
final double y = pos.getY();
// Build a square for checking location
final Vector2 topLeft = new Vector2(x - threshold, y - threshold);
final Vector2 bottomRight = new Vector2(x + threshold, y + threshold);
// Now convert that square into a square of times and values
final double minTime = xAxis.unproject(topLeft);
final double maxTime = xAxis.unproject(bottomRight);
final double minValue = yAxis.unproject(bottomRight);
final double maxValue = yAxis.unproject(topLeft);
final double centerTime = xAxis.unproject(pos);
final double centerValue = xAxis.unproject(pos);
// Don't even bother trying to highlight if the mouse is out of
// bounds
if (maxTime < xAxis.getMin() || minTime > xAxis.getMax()
|| maxValue < yAxis.getMin() || minValue > yAxis.getMax()) {
return null;
}
// Get the tiles to check
final int correctLevel = computeCurrentLevel();
final GrapherTile bestTileMinTime =
getBestResolutionTileAt(minTime, correctLevel);
final GrapherTile bestTileMaxTime =
getBestResolutionTileAt(maxTime, correctLevel);
final PlottablePoint closest = getClosestPoint(bestTileMinTime,
minTime, maxTime, minValue, maxValue, centerTime,
centerValue);
// pos is right on the border between two tiles
if (bestTileMinTime != bestTileMaxTime) { // TODO: should this be an .equals() comparison instead?
// This is unlikely but possible, especially if threshold
// is large
final PlottablePoint closestMaxTime = getClosestPoint(
bestTileMaxTime, minTime, maxTime, minValue,
maxValue, centerTime, centerValue);
final double distClosestSq = getDistanceSquared(closest,
centerTime, centerValue);
final double distClosestMaxTimeSq =
getDistanceSquared(closestMaxTime, centerTime,
centerValue);
if (distClosestMaxTimeSq < distClosestSq) {
return closestMaxTime;
}
}
return closest;
}
/**
* Helper method for {@link DataPlot#closest(Vector2, double)}.
*
* This method has a lot of similar parameters, which is normally
* poor style, but it is an internal helper method, so this is
* OK.
*
* @param tile
* the {@link GrapherTile GrapherTile}
* in which to search for the closest point
* @param minTime
* the minimum time at which we consider points
* @param maxTime
* the maximum time at which we consider points
* @param minValue
* the minimum value of a point for us to consider it
* @param maxValue
* the maximum value of a point at which we will consider it
* @param centerTime
* the time to which we will try to make our point close
* @param centerValue
* the value to which we will try to make our point close
* @return
* the point closest to (centerTime, centerValue)
* in getDataPoints(tile), as long as that point is within the
* square determined by (minTime, minValue) and
* (maxTime, maxValue) and visible to the user. If there is no
* such point, returns <tt>null</tt>
*/
private PlottablePoint getClosestPoint(final GrapherTile tile,
final double minTime, final double maxTime, final double minValue,
final double maxValue, final double centerTime, final double centerValue) {
if (tile == null) {
return null;
}
final List<PlottablePoint> points = getDataPoints(tile);
if (points == null) {
return null;
}
PlottablePoint closest = null;
double shortestDistanceSq = Double.MAX_VALUE;
for (final PlottablePoint point : points) {
final double time = point.getDate();
final double val = point.getValue();
// Only check for proximity to points we can see
if (time < xAxis.getMin() || time > xAxis.getMax()) {
continue;
}
if (val < yAxis.getMin() || val > yAxis.getMax()) {
continue;
}
// Only check for proximity to points within the desired
// range
if (time >= minTime && time <= maxTime
&& val >= minValue && val <= maxValue) {
// If we don't have a value for closest, any point
// in the specified range is closer
if (closest == null) {
closest = point;
continue;
}
// Compute the square of the distance to pos
final double distanceSq = getDistanceSquared(point,
centerTime, centerValue);
if (distanceSq < shortestDistanceSq) {
closest = point;
shortestDistanceSq = distanceSq;
}
}
}
return closest;
}
/**
* Returns the square of the distance from point to (time, value).
*
* @param point
* the first of the two points
* @param time
* the time for the second point
* @param value
* the distance for the second point
* @return
* the square of the distance from point to (time, value), or
* {@link Double#MAX_VALUE} if point is <tt>null</tt>
*/
private double getDistanceSquared(final PlottablePoint point,
final double time, final double value) {
if (point == null) {
return Double.MAX_VALUE;
}
final double pointTime = point.getDate();
final double pointValue = point.getValue();
return (time - pointTime) * (time - pointTime)
+ (value - pointValue) * (value - pointValue);
}
/**
* Highlights this DataPlot in future
* {@link DataPlot#paint() paint} calls.
*
* <p>Note that this does not highlight the axes associated with this
* DataPlot.</p>
*/
public void highlight() {
highlightedPoint = HIGHLIGHTED_NO_SINGLE_POINT;
}
/**
* Stops highlighting this DataPlot.
*
* <p>Note that this does not affect the highlighting status on the
* axes associated with this DataPlot.</p>
*/
public void unhighlight() {
highlightedPoint = null;
possiblyDisplayHighlightedValue();
}
/**
* Tells whether or not this DataPlot is highlighted.
*
* <p>If {@link #highlight()} has been called since the constructor
* and since the last call to {@link #unhighlight()}, returns
* <tt>true</tt>. Otherwise, returns <tt>false</tt>.</p>
*
* @return
* <tt>true</tt> if and only if this DataPlot is highlighted
*/
public boolean isHighlighted() {
return highlightedPoint != null;
}
/**
* Highlights this <tt>DataPlot</tt> if and only if it contains a
* point within threshold pixels of pos.
*
* <p>Also, if this data plot should be highlighted, this publishes
* the highlighted data plot's value to the container widget, as long
* as such a preference was indicated when this <tt>DataPlot</tt>
* was created, using the publishValueOnHighlight constructor parameter.
* On the other hand, if this data plot is currently highlighted but
* should be unhighlighted, this removes the published value. If a
* subclass would like to change the formatting of the published
* value, it should accomplish that by overriding
* {@link #getDataLabel(PlottablePoint)}.</p>
*
* <p>Note that this does <strong>not</strong> unhighlight this
* <tt>DataPlot</tt> if there is no point within threshold pixels of
* pos. A subclass may also change the measurement unit on threshold
* (the unit is pixels here), as long as that fact is clearly
* documented.</p>
*
* @param pos
* the position at which the mouse is hovering, and from which
* we want to derive our highlighting
* @param threshold
* the maximum distance the mouse can be from a point, while
* still causing the highlighting effects
* @return
* <tt>true</tt> if and only if this highlights the axes
* @throws IllegalArgumentException
* if threshold is negative
*/
public boolean highlightIfNear(final Vector2 pos, final double threshold) {
highlightedPoint = closest(pos, threshold);
possiblyDisplayHighlightedValue();
return isHighlighted();
}
/**
* Handles the value to be shown in the container as the highlighted
* value.
*
* <p>This first checks publishValueOnHighlight. If that is
* <tt>false</tt>, does nothing. Otherwise, checks highlightedPoint.
* If it is <tt>null</tt> or equal to
* {@link #HIGHLIGHTED_NO_SINGLE_POINT}, removes any messages that
* might be showing for this data plot. Otherwise, ensures that the
* current value is being shown on the parent container, with the
* value returned by {@link #getDataLabel(PlottablePoint)}.</p>
*/
private void possiblyDisplayHighlightedValue() {
if (!publishValueOnHighlight) {
return;
}
if (highlightedPoint == null
|| highlightedPoint == HIGHLIGHTED_NO_SINGLE_POINT) { // TODO: should this be an .equals() comparison instead?
// We can call this without problems because we know
// that container will ignore any invalid message IDs
container.removeValueMessage(publishedValueId);
publishedValueId = 0;
}
else if (publishedValueId == 0) // Don't add message twice
{
publishedValueId = container.addValueMessage(
getDataLabel(highlightedPoint), color);
}
}
/**
* Returns a label for the specified point.
*
* <p>This implementation takes the value of p out to three
* significant digits and returns that value. However, subclass
* implementations might behave differently.</p>
*
* <p>This is designed to be overridden by subclasses that wish
* to change the default behavior. However, there are a few
* requirements for subclass implementations, which unfortunately
* cannot be expressed in code. A subclass implementation of
* this method must always return a non-<tt>null</tt> label in
* finite (preferably very short) time, and must never throw
* an exception.</p>
*
* @param p
* the point for which to return a data label
* @return
* a data label to be displayed for p
*/
protected String getDataLabel(final PlottablePoint p) {
final double value = p.getValue();
final double absValue = Math.abs(value);
final String timeString = getTimeString(p.getDate()) + " ";
if (absValue == 0.0) // Rare, but possible
{
return timeString + "0.0";
}
if (absValue < 1e-3 || absValue > 1e7) {
return timeString
+ NumberFormat.getScientificFormat().format(value);
}
return timeString
+ NumberFormat.getFormat("###,##0.0##").format(value);
}
/**
* Returns a time string representing the specified time.
*
* <p>A caveat: time should be the number of <em>seconds</em>,
* since the epoch.
*
* @param secondsSinceEpoch
* the number of seconds since the epoch
* @return
* a string representation of time
*/
protected final String getTimeString(final double secondsSinceEpoch) {
return getTimeString((long)(secondsSinceEpoch * 1000));
}
/**
* Returns a time string representing the specified time.
*
* <p>A caveat: time should be the number of <em>milliseconds</em>,
* not seconds, since the epoch. If a caller forgets to multiply
* a time by 1000, wrong date strings (usually something
* involving January 15, 1970) will come back.</p>
*
* @param time
* the number of milliseconds since the epoch
* @return
* a string representation of time
*/
private String getTimeString(final long time) {
String formatString = "EEE MMM dd yyyy, HH:mm:ss";
final int fractionalSecondDigits = getFractionalSecondDigits();
// We know that fractionalSecondDigits will always be 0, 1, 2, or 3
switch (fractionalSecondDigits) {
case 0:
break;
case 1:
formatString += ".S";
break;
case 2:
formatString += ".SS";
break;
case 3:
formatString += ".SSS";
break;
default:
GWT.log("DataPlot.getTimeString(): Unexpected number of fractionalSecondDigits: " + fractionalSecondDigits);
}
final DateTimeFormat format = DateTimeFormat.getFormat(formatString);
return format.format(new Date(time));
}
/**
* Computes the number of fractional second digits that should
* appear in a displayed time string, based on the current level.
*
* <p>This <em>always</em> returns a nonnegative integer less than
* or equal to 3.</p>
*
* @return
* the number of fractional second digits that should appear
* in a displayed times string
*/
private int getFractionalSecondDigits() {
final int level = computeCurrentLevel();
if (level > 1) {
return 0;
}
if (level == 1) {
return 1;
}
if (level > -2) // 0 or -1
{
return 2;
}
return 3; // We can't get better than millisecond precision
}
/**
* Returns the highlighted point maintained by this <tt>DataPlot</tt>.
*
* @return
* the highlighted point this <tt>DataPlot</tt> keeps, or
* <tt>null</tt> if there is no highlighted point
*/
public PlottablePoint getHighlightedPoint() {
return highlightedPoint;
}
}
| true | true | private void paintComment(final BoundedDrawingBox drawing, final PlottablePoint highlightedPoint) {
if (highlightedPoint.hasComment()) {
// compute (x,y) for the highlighted point in pixels, relative to the canvas
final int x = (int)xAxis.project2D(highlightedPoint.getDate()).getX();
final int y = (int)yAxis.project2D(highlightedPoint.getValue()).getY();
// create the panel, but display it offscreen so we can measure its preferred width
commentPanel = new PopupPanel();
commentPanel.add(new Label(highlightedPoint.getComment()));
commentPanel.setPopupPosition(-10000, -10000);
commentPanel.show();
final int preferredCommentPanelWidth = commentPanel.getOffsetWidth();
commentPanel.hide();
// compute the actual panel width by taking the minimum of the comment panel's preferred width, the width of
// the drawing region, and the PREFERRED_MAX_COMMENT_WIDTH.
final int desiredPanelWidth = (int)Math.min(preferredCommentPanelWidth, Math.min(drawing.getWidth(), PREFERRED_MAX_COMMENT_WIDTH));
// set the panel to the corrected width
final int actualPanelWidth;
if (desiredPanelWidth != preferredCommentPanelWidth) {
commentPanel.setWidth(String.valueOf(desiredPanelWidth) + "px");
commentPanel.show();
// unfortunately, setting the width doesn't take borders and such into account, so we need read the width again and
// then adjust accordingly
final int widthPlusExtra = commentPanel.getOffsetWidth();
commentPanel.hide();
commentPanel.setWidth(String.valueOf(desiredPanelWidth - (widthPlusExtra - desiredPanelWidth)) + "px");
commentPanel.show();
actualPanelWidth = commentPanel.getOffsetWidth();
} else {
actualPanelWidth = preferredCommentPanelWidth;
}
// now, if the actual panel width is less than the comment panel's preferred width, then the height must have
// changed so we need to redisplay the panel to determine its new height.
commentPanel.show();
final int actualPanelHeight = commentPanel.getOffsetHeight();
// now that we know the actual height and width of the comment panel, we can determine where to place the panel
// horizontally and vertically. The general strategy is to try to center the panel horizontally above the
// point (we favor placement above the point so that the mouse pointer doesn't occlude the comment). For
// horizontal placement, if the panel can't be centered with respect to the point, then just shift it left or
// right enough so that it fits within the bounds of the drawing region. For vertical placement, if the panel
// can't be placed above the point, then place it below.
final int actualPanelLeft;
final int desiredPanelLeft = x - actualPanelWidth / 2;
if (desiredPanelLeft < drawing.getTopLeft().getIntX()) {
actualPanelLeft = drawing.getTopLeft().getIntX();
} else if ((desiredPanelLeft + actualPanelWidth) > drawing.getBottomRight().getIntX()) {
actualPanelLeft = drawing.getBottomRight().getIntX() - actualPanelWidth;
} else {
actualPanelLeft = desiredPanelLeft;
}
final int actualPanelTop;
final int desiredPanelTop = (int)(y - actualPanelHeight - HIGHLIGHTED_DOT_RADIUS);
if (desiredPanelTop < drawing.getTopLeft().getIntY()) {
// place the panel below the point since there's not enough room to place it above
actualPanelTop = (int)(y + HIGHLIGHTED_DOT_RADIUS);
} else {
actualPanelTop = desiredPanelTop;
}
// get the top-left coords of the canvas so we can offset the panel position
final Element nativeCanvasElement = drawing.getCanvas().getNativeCanvasElement();
final int canvasLeft = nativeCanvasElement.getAbsoluteLeft();
final int canvasTop = nativeCanvasElement.getAbsoluteTop();
// set the panel's position--these are in absolute page coordinates, so we need to offset it by the canvas's
// absolute position and the drawing region's position with respect to the canvas.
commentPanel.setPopupPosition(actualPanelLeft + canvasLeft, actualPanelTop + canvasTop);
// show the panel
commentPanel.show();
}
}
| private void paintComment(final BoundedDrawingBox drawing, final PlottablePoint highlightedPoint) {
if (highlightedPoint.hasComment()) {
// compute (x,y) for the highlighted point in pixels, relative to the canvas
final int x = (int)xAxis.project2D(highlightedPoint.getDate()).getX();
final int y = (int)yAxis.project2D(highlightedPoint.getValue()).getY();
// create the panel, but display it offscreen so we can measure its preferred width
commentPanel = new PopupPanel();
commentPanel.add(new Label(highlightedPoint.getComment()));
commentPanel.setPopupPosition(-10000, -10000);
commentPanel.show();
final int preferredCommentPanelWidth = commentPanel.getOffsetWidth();
commentPanel.hide();
// compute the actual panel width by taking the minimum of the comment panel's preferred width, the width of
// the drawing region, and the PREFERRED_MAX_COMMENT_WIDTH.
final int desiredPanelWidth = (int)Math.min(preferredCommentPanelWidth, Math.min(drawing.getWidth(), PREFERRED_MAX_COMMENT_WIDTH));
// set the panel to the corrected width
final int actualPanelWidth;
if (desiredPanelWidth != preferredCommentPanelWidth) {
commentPanel.setWidth(String.valueOf(desiredPanelWidth) + "px");
commentPanel.show();
// unfortunately, setting the width doesn't take borders and such into account, so we need read the width again and
// then adjust accordingly
final int widthPlusExtra = commentPanel.getOffsetWidth();
commentPanel.hide();
commentPanel.setWidth(String.valueOf(desiredPanelWidth - (widthPlusExtra - desiredPanelWidth)) + "px");
commentPanel.show();
actualPanelWidth = commentPanel.getOffsetWidth();
} else {
actualPanelWidth = preferredCommentPanelWidth;
}
// now, if the actual panel width is less than the comment panel's preferred width, then the height must have
// changed so we need to redisplay the panel to determine its new height.
commentPanel.show();
final int actualPanelHeight = commentPanel.getOffsetHeight();
// now that we know the actual height and width of the comment panel, we can determine where to place the panel
// horizontally and vertically. The general strategy is to try to center the panel horizontally above the
// point (we favor placement above the point so that the mouse pointer doesn't occlude the comment). For
// horizontal placement, if the panel can't be centered with respect to the point, then just shift it left or
// right enough so that it fits within the bounds of the drawing region. For vertical placement, if the panel
// can't be placed above the point, then place it below.
final int actualPanelLeft;
final int desiredPanelLeft = x - actualPanelWidth / 2;
if (desiredPanelLeft < drawing.getTopLeft().getIntX()) {
actualPanelLeft = drawing.getTopLeft().getIntX();
} else if ((desiredPanelLeft + actualPanelWidth) > drawing.getBottomRight().getIntX()) {
actualPanelLeft = drawing.getBottomRight().getIntX() - actualPanelWidth;
} else {
actualPanelLeft = desiredPanelLeft;
}
final int actualPanelTop;
final int desiredPanelTop = (int)(y - actualPanelHeight - HIGHLIGHTED_DOT_RADIUS);
if (desiredPanelTop < drawing.getTopLeft().getIntY()) {
// place the panel below the point since there's not enough room to place it above
actualPanelTop = (int)(y + HIGHLIGHTED_DOT_RADIUS);
} else {
actualPanelTop = desiredPanelTop;
}
// get the top-left coords of the canvas so we can offset the panel position
final Element nativeCanvasElement = drawing.getCanvas().getNativeCanvasElement();
final int canvasLeft = nativeCanvasElement.getAbsoluteLeft();
final int canvasTop = nativeCanvasElement.getAbsoluteTop();
// set the panel's position--these are in absolute page coordinates,
// so we need to offset it by the canvas's absolute position.
commentPanel.setPopupPosition(actualPanelLeft + canvasLeft, actualPanelTop + canvasTop);
// show the panel
commentPanel.show();
}
}
|
diff --git a/src/main/java/com/troiaTester/DataGenerator.java b/src/main/java/com/troiaTester/DataGenerator.java
index 3bff98e..1dfd66a 100644
--- a/src/main/java/com/troiaTester/DataGenerator.java
+++ b/src/main/java/com/troiaTester/DataGenerator.java
@@ -1,325 +1,325 @@
package main.com.troiaTester;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.log4j.Logger;
import troiaClient.Category;
import troiaClient.CategoryFactory;
import troiaClient.GoldLabel;
import troiaClient.Label;
import troiaClient.MisclassificationCost;
import troiaClient.MisclassificationCostFactory;
/**
* This class is used to create test data for Troia client tests.
*
* @author [email protected]
*/
public class DataGenerator {
/**
* Generate collection of test objects.
*
* @see TroiaObjectCollection
* @param objectCount
* Numbers of objects to generate
* @param categories
* Map that associates class names with probability of object
* belonging to that class ( form 0 to 1 )
* @return TestObjectCollection object.
*/
public TroiaObjectCollection generateTestObjects(int objectCount,
Map<String, Double> categories) {
Collection<Double> percentages = categories.values();
double totalPercentage = 0;
for (Double percentage : percentages) {
totalPercentage += percentage.doubleValue();
}
if (Math.abs(1 - totalPercentage) > 0.0001) {
throw new ArithmeticException("Percentage values sum up to "
+ totalPercentage + " instead of 1.");
} else {
int[] borders = new int[percentages.size()];
int index = 0;
for (Double percentage : percentages) {
- borders[index] = (int) (percentage.doubleValue() * objectCount);
+ borders[index] = (int) (percentage * objectCount);
index++;
}
Map<String, String> objects = new HashMap<String, String>();
index = 0;
int categortySwitchCounter = 0;
int categoryIndex = 0;
Collection<String> categoryNames = categories.keySet();
Iterator<String> categoryNameIterator = categoryNames.iterator();
String categoryName = categoryNameIterator.next();
for (index = 0; index < objectCount; index++) {
if (categortySwitchCounter < borders[categoryIndex]) {
if (categoryIndex < categoryNames.size()) {
categortySwitchCounter++;
}
} else {
categortySwitchCounter = 0;
categoryIndex++;
categoryName = categoryNameIterator.next();
}
String objectName = "Object-" + index;
objects.put(objectName, categoryName);
}
return new TroiaObjectCollection(objects);
}
}
/**
* Generates test object collection with auto generated categories that have
* equal distribution among the objects.
*
* @see TroiaObjectCollection
* @param objectCount
* Numbers of objects to generate
* @param categoryCount
* Number of categories to generate
* @return TestObjectCollection object
*/
public TroiaObjectCollection generateTestObjects(int objectCount,
int categoryCount) {
Collection<String> categoryNames = this
.generateCategoryNames(categoryCount);
double p = 1.0 / (double) categoryNames.size();
Double percentage = new Double(p);
Map<String, Double> categories = new HashMap<String, Double>();
for (String category : categoryNames) {
categories.put(category, percentage);
}
return this.generateTestObjects(objectCount, categories);
}
public TroiaObjectCollection generateTestObjects(int objectCount,
Collection<String> categoryNames) {
double p = 1.0 / (double) categoryNames.size();
Double percentage = new Double(p);
Map<String, Double> categories = new HashMap<String, Double>();
for (String category : categoryNames) {
categories.put(category, percentage);
}
return this.generateTestObjects(objectCount, categories);
}
/**
* Generates category names
*
* @param categoryCount
* Number of categories to generate
* @return Collection of category names.
*/
public Collection<String> generateCategoryNames(int categoryCount) {
ArrayList<String> categories = new ArrayList<String>();
for (int i = 0; i < categoryCount; i++) {
categories.add("Category-" + i);
}
return categories;
}
/**
* Creates artificial worker that will be working in environment with
* categories given as a parameter
*
* @param name
* Worker name
* @param quality
* Quality of the worker (probability that he will label object
* correctly)
* @param categories
* Categories that exist in task executed by this worker
* @return Artificial worker
*/
public ArtificialWorker generateArtificialWorker(String name,
double quality, Collection<String> categories) {
ArtificialWorker worker = new ArtificialWorker();
Map<String, Map<String, Double>> confMatrix = new HashMap<String, Map<String, Double>>();
Map<String, Double> confVector;
double wrongProb = 1 - quality;
for (String correctClass : categories) {
double restProb = wrongProb;
double prob;
confVector = new HashMap<String, Double>();
for (String labeledClass : categories) {
if (labeledClass.equalsIgnoreCase(correctClass)) {
confVector.put(labeledClass, quality);
logger.debug("Set correct label probability to " + quality);
} else {
prob = Math.random() * restProb;
restProb -= prob;
confVector.put(labeledClass, prob);
}
}
confMatrix.put(correctClass, confVector);
}
worker.setName(name);
worker.setConfusionMatrix(new ConfusionMatrix(confMatrix));
logger.debug("Generated artifical worker with quality " + quality);
return worker;
}
/**
* Creates artificial worker, with random work quality, that will be working
* in environment with categories given as a parameter
*
* @param name
* Worker name
* @param categories
* Categories that exist in task executed by this worker
* @return Artificial worker
*/
public ArtificialWorker generateArtificialWorker(String name,
Collection<String> categories) {
return this.generateArtificialWorker(name, Math.random(), categories);
}
/**
* Creates collection of workers, with qualities form given range, that will
* operate in environment that contains categories given as a parameter.
*
* @param workerCount
* Number of workers that will be generated
* @param categories
* Collection of categories that workers will be assigning
* @param minQuality
* Minimal quality of generated worker (from 0 to 1)
* @param maxQuality
* Maximal quality of generated worker (from 0 to 1)
* @return Collection of artifical workers
*/
public Collection<ArtificialWorker> generateArtificialWorkers(
int workerCount, Collection<String> categories, double minQuality,
double maxQuality) {
Collection<ArtificialWorker> workers = new ArrayList<ArtificialWorker>();
if (minQuality > maxQuality)
minQuality = 0;
double qualityRange = maxQuality - minQuality;
for (int i = 0; i < workerCount; i++) {
double quality = Math.random() * qualityRange + minQuality;
ArtificialWorker worker = this.generateArtificialWorker("Worker-"
+ i, quality, categories);
workers.add(worker);
}
return workers;
}
/**
* Generates labels assigned by artificial workers.
*
* @param workers
* Collection of artificial workers
* @param objects
* Test objects collection
* @param workersPerObject
* How many workers will assign label to same object
* @return Collection of worker assigned labels
*/
public Collection<Label> generateLabels(
Collection<ArtificialWorker> workers, TroiaObjectCollection objects,
int workersPerObject) {
Collection<Label> labels = new ArrayList<Label>();
Map<ArtificialWorker, NoisedLabelGenerator> generators = NoisedLabelGeneratorFactory
.getInstance().getRouletteGeneratorsForWorkers(workers);
Iterator<ArtificialWorker> workersIterator = workers.iterator();
for (String object : objects) {
String correctCat = objects.getCategory(object);
ArtificialWorker worker;
for (int labelsForObject = 0; labelsForObject < workersPerObject; labelsForObject++) {
String assignedLabel;
if (!workersIterator.hasNext()) {
workersIterator = workers.iterator();
}
worker = workersIterator.next();
assignedLabel = generators.get(worker).getCategoryWithNoise(
correctCat);
labels.add(new Label(worker.getName(), object, assignedLabel));
}
}
return labels;
}
/**
* Generates gold labels from collection of test objects
*
* @param objects
* Test objects
* @param goldCoverage
* Fraction of objects that will have gold label
* @return Collection of gold labels.
*/
public Collection<GoldLabel> generateGoldLabels(
TroiaObjectCollection objects, double goldCoverage) {
int goldCount = (int) (objects.size() * goldCoverage);
Collection<GoldLabel> goldLabels = new ArrayList<GoldLabel>();
Iterator<String> objectsIterator = objects.iterator();
for (int i = 0; i < goldCount; i++) {
String objectName;
if (objectsIterator.hasNext()) {
objectName = objectsIterator.next();
goldLabels.add(new GoldLabel(objectName, objects
.getCategory(objectName)));
} else {
break;
}
}
return goldLabels;
}
public Data generateTestData(String requestId, int objectCount,
int categoryCount, int workerCount, double minQuality,
double maxQuality, double goldRatio, int workersPerObject) {
Data data = new Data();
Collection<String> categoryNames = this
.generateCategoryNames(categoryCount);
Collection<Category> categories = CategoryFactory.getInstance()
.createCategories(categoryNames);
TroiaObjectCollection objects = this.generateTestObjects(objectCount,
categoryNames);
Collection<MisclassificationCost> misclassificationCost = MisclassificationCostFactory
.getInstance().getMisclassificationCosts(categories);
Collection<GoldLabel> goldLabels = this.generateGoldLabels(objects,
goldRatio);
Collection<ArtificialWorker> workers = null;
Collection<Label> labels = null;
Collection<String> workerNames = null;
if(workerCount>0) {
workers = this.generateArtificialWorkers(workerCount, categoryNames, minQuality, maxQuality);
labels = this.generateLabels(workers, objects,workersPerObject);
workerNames = new ArrayList<String>();
for (ArtificialWorker worker : workers) {
workerNames.add(worker.getName());
}
}
data.setCategories(categories);
data.setGoldLabels(goldLabels);
data.setLabels(labels);
data.setMisclassificationCost(misclassificationCost);
data.setObjectCollection(objects);
data.setRequestId(requestId);
data.setWorkers(workerNames);
data.setArtificialWorkers(workers);
return data;
}
public static DataGenerator getInstance() {
return instance;
}
private static DataGenerator instance = new DataGenerator();
private DataGenerator() {
}
/**
* Logger for this class
*/
private static Logger logger = Logger.getLogger(DataGenerator.class);
}
| true | true | public TroiaObjectCollection generateTestObjects(int objectCount,
Map<String, Double> categories) {
Collection<Double> percentages = categories.values();
double totalPercentage = 0;
for (Double percentage : percentages) {
totalPercentage += percentage.doubleValue();
}
if (Math.abs(1 - totalPercentage) > 0.0001) {
throw new ArithmeticException("Percentage values sum up to "
+ totalPercentage + " instead of 1.");
} else {
int[] borders = new int[percentages.size()];
int index = 0;
for (Double percentage : percentages) {
borders[index] = (int) (percentage.doubleValue() * objectCount);
index++;
}
Map<String, String> objects = new HashMap<String, String>();
index = 0;
int categortySwitchCounter = 0;
int categoryIndex = 0;
Collection<String> categoryNames = categories.keySet();
Iterator<String> categoryNameIterator = categoryNames.iterator();
String categoryName = categoryNameIterator.next();
for (index = 0; index < objectCount; index++) {
if (categortySwitchCounter < borders[categoryIndex]) {
if (categoryIndex < categoryNames.size()) {
categortySwitchCounter++;
}
} else {
categortySwitchCounter = 0;
categoryIndex++;
categoryName = categoryNameIterator.next();
}
String objectName = "Object-" + index;
objects.put(objectName, categoryName);
}
return new TroiaObjectCollection(objects);
}
}
| public TroiaObjectCollection generateTestObjects(int objectCount,
Map<String, Double> categories) {
Collection<Double> percentages = categories.values();
double totalPercentage = 0;
for (Double percentage : percentages) {
totalPercentage += percentage.doubleValue();
}
if (Math.abs(1 - totalPercentage) > 0.0001) {
throw new ArithmeticException("Percentage values sum up to "
+ totalPercentage + " instead of 1.");
} else {
int[] borders = new int[percentages.size()];
int index = 0;
for (Double percentage : percentages) {
borders[index] = (int) (percentage * objectCount);
index++;
}
Map<String, String> objects = new HashMap<String, String>();
index = 0;
int categortySwitchCounter = 0;
int categoryIndex = 0;
Collection<String> categoryNames = categories.keySet();
Iterator<String> categoryNameIterator = categoryNames.iterator();
String categoryName = categoryNameIterator.next();
for (index = 0; index < objectCount; index++) {
if (categortySwitchCounter < borders[categoryIndex]) {
if (categoryIndex < categoryNames.size()) {
categortySwitchCounter++;
}
} else {
categortySwitchCounter = 0;
categoryIndex++;
categoryName = categoryNameIterator.next();
}
String objectName = "Object-" + index;
objects.put(objectName, categoryName);
}
return new TroiaObjectCollection(objects);
}
}
|
diff --git a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/widgets/chatControl/ChatControl.java b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/widgets/chatControl/ChatControl.java
index 22965e71d..f81763e62 100644
--- a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/widgets/chatControl/ChatControl.java
+++ b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/widgets/chatControl/ChatControl.java
@@ -1,248 +1,249 @@
package de.fu_berlin.inf.dpp.ui.widgets.chatControl;
import java.util.Date;
import java.util.Vector;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import de.fu_berlin.inf.dpp.ui.widgets.chatControl.events.CharacterEnteredEvent;
import de.fu_berlin.inf.dpp.ui.widgets.chatControl.events.ChatClearedEvent;
import de.fu_berlin.inf.dpp.ui.widgets.chatControl.events.IChatControlListener;
import de.fu_berlin.inf.dpp.ui.widgets.chatControl.events.IChatDisplayListener;
import de.fu_berlin.inf.dpp.ui.widgets.chatControl.events.MessageEnteredEvent;
import de.fu_berlin.inf.dpp.ui.widgets.chatControl.parts.ChatDisplay;
import de.fu_berlin.inf.dpp.ui.widgets.chatControl.parts.ChatInput;
import de.fu_berlin.inf.dpp.ui.widgets.explanation.ExplanationComposite;
/**
* This composite displays a chat conversation and the possibility to enter
* text.
* <p>
* This composite does <strong>NOT</strong> handle setting the layout and adding
* sub {@link Control}s correctly.
*
* <dl>
* <dt><b>Styles:</b></dt>
* <dd>BORDER and those supported by {@link ExplanationComposite}</dd>
* <dt><b>Events:</b></dt>
* <dd>{@link MessageEnteredEvent}</dd>
* </dl>
*
* @author bkahlert
*
*/
public class ChatControl extends Composite {
protected Vector<IChatControlListener> chatControlListeners = new Vector<IChatControlListener>();
/**
* This {@link IChatDisplayListener} is used to forward events fired in the
* {@link ChatDisplay} so the user only has to add listeners on the
* {@link ChatControl} and not on all its child components.
*/
protected IChatDisplayListener chatDisplayListener = new IChatDisplayListener() {
public void chatCleared(ChatClearedEvent event) {
ChatControl.this.notifyChatCleared(event);
}
};
/**
* This {@link KeyAdapter} is used to forward events fired in the
* {@link ChatInput} so the user only has to add listeners on the
* {@link ChatControl} and not on all its child components.
*/
protected KeyAdapter chatInputListener = new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
switch (e.keyCode) {
case SWT.CR:
case SWT.KEYPAD_CR:
if (e.stateMask == 0) {
String message = ChatControl.this.getInputText().trim();
ChatControl.this.setInputText("");
if (message.length() != 0)
ChatControl.this.notifyMessageEntered(message);
/*
* We do not want the ENTER to be inserted
*/
e.doit = false;
}
break;
}
}
@Override
public void keyReleased(KeyEvent e) {
ChatControl.this.notifyCharacterEntered(e.character);
}
};
/**
* Chat layer
*/
protected SashForm sashForm;
protected ChatDisplay chatDisplay;
protected ChatInput chatInput;
public ChatControl(Composite parent, int style,
Color displayBackgroundColor, Color inputBackgroundColor,
final int minVisibleInputLines) {
super(parent, style & ~SWT.BORDER);
- int chatDisplayStyle = (style & SWT.BORDER) | SWT.V_SCROLL;
+ int chatDisplayStyle = (style & SWT.BORDER) | SWT.V_SCROLL
+ | SWT.H_SCROLL;
int chatInputStyle = (style & SWT.BORDER) | SWT.MULTI | SWT.V_SCROLL
| SWT.WRAP;
this.setLayout(new FillLayout());
this.sashForm = new SashForm(this, SWT.VERTICAL);
// ChatDisplay
this.chatDisplay = new ChatDisplay(sashForm, chatDisplayStyle,
displayBackgroundColor);
this.chatDisplay.setAlwaysShowScrollBars(true);
this.chatDisplay.addChatDisplayListener(this.chatDisplayListener);
// ChatInput
this.chatInput = new ChatInput(sashForm, chatInputStyle);
this.chatInput.addKeyListener(this.chatInputListener);
/*
* Updates SashForm weights to emulate a fixed ChatInput height
*/
this.addListener(SWT.Resize, new Listener() {
public void handleEvent(Event event) {
int fullHeight = ChatControl.this.getSize().y;
int chatInputHeight = ChatControl.this.chatInput.getSize().y;
int lineHeight = (int) Math.round(chatInput.getFont()
.getFontData()[0].getHeight() * 1.4);
int minChatInputHeight = minVisibleInputLines * lineHeight;
if (chatInputHeight < minChatInputHeight) {
chatInputHeight = minChatInputHeight;
}
int newChatDisplayHeight = fullHeight - chatInputHeight;
if (newChatDisplayHeight <= 0 || chatInputHeight <= 0)
return;
sashForm.setWeights(new int[] { newChatDisplayHeight,
chatInputHeight });
}
});
/*
* no need for dispose handling because all child controls (and
* listeners) are disposed automatically
*/
}
/**
* @see ChatDisplay#addChatLine(Object, Color, String, Date)
*/
public void addChatLine(Object sender, Color color, String message,
Date receivedOn) {
this.chatDisplay.addChatLine(sender, color, message, receivedOn);
}
/**
* Sets the chat input's text
*
* @param string
* the new text
*/
public void setInputText(String string) {
this.chatInput.setText(string);
}
/**
* Return entered text in the chat input
*
* @return the entered text
*/
public String getInputText() {
return this.chatInput.getText();
}
/**
* Adds a {@link IChatControlListener}
*
* @param chatControlListener
*/
public void addChatControlListener(IChatControlListener chatControlListener) {
this.chatControlListeners.addElement(chatControlListener);
}
/**
* Removes a {@link IChatControlListener}
*
* @param chatControlListener
*/
public void removeChatControlListener(
IChatControlListener chatControlListener) {
this.chatControlListeners.removeElement(chatControlListener);
}
/**
* Notify all {@link IChatControlListener}s about entered character
*
* @param character
* the entered character
*/
public void notifyCharacterEntered(Character character) {
for (IChatControlListener chatControlListener : this.chatControlListeners) {
chatControlListener.characterEntered(new CharacterEnteredEvent(
this, character));
}
}
/**
* Notify all {@link IChatControlListener}s about entered text
*
* @param message
* the entered text
*/
public void notifyMessageEntered(String message) {
for (IChatControlListener chatControlListener : this.chatControlListeners) {
chatControlListener.messageEntered(new MessageEnteredEvent(this,
message));
}
}
/**
* Notify all {@link IChatDisplayListener}s about a cleared chat
*/
public void notifyChatCleared(ChatClearedEvent event) {
for (IChatControlListener chatControlListener : this.chatControlListeners) {
chatControlListener.chatCleared(event);
}
}
/**
* @see ChatDisplay#clear()
*/
public void clear() {
this.chatDisplay.clear();
}
/**
* @see ChatDisplay#silentClear()
*/
public void silentClear() {
this.chatDisplay.silentClear();
}
@Override
public boolean setFocus() {
return this.chatInput.setFocus();
}
}
| true | true | public ChatControl(Composite parent, int style,
Color displayBackgroundColor, Color inputBackgroundColor,
final int minVisibleInputLines) {
super(parent, style & ~SWT.BORDER);
int chatDisplayStyle = (style & SWT.BORDER) | SWT.V_SCROLL;
int chatInputStyle = (style & SWT.BORDER) | SWT.MULTI | SWT.V_SCROLL
| SWT.WRAP;
this.setLayout(new FillLayout());
this.sashForm = new SashForm(this, SWT.VERTICAL);
// ChatDisplay
this.chatDisplay = new ChatDisplay(sashForm, chatDisplayStyle,
displayBackgroundColor);
this.chatDisplay.setAlwaysShowScrollBars(true);
this.chatDisplay.addChatDisplayListener(this.chatDisplayListener);
// ChatInput
this.chatInput = new ChatInput(sashForm, chatInputStyle);
this.chatInput.addKeyListener(this.chatInputListener);
/*
* Updates SashForm weights to emulate a fixed ChatInput height
*/
this.addListener(SWT.Resize, new Listener() {
public void handleEvent(Event event) {
int fullHeight = ChatControl.this.getSize().y;
int chatInputHeight = ChatControl.this.chatInput.getSize().y;
int lineHeight = (int) Math.round(chatInput.getFont()
.getFontData()[0].getHeight() * 1.4);
int minChatInputHeight = minVisibleInputLines * lineHeight;
if (chatInputHeight < minChatInputHeight) {
chatInputHeight = minChatInputHeight;
}
int newChatDisplayHeight = fullHeight - chatInputHeight;
if (newChatDisplayHeight <= 0 || chatInputHeight <= 0)
return;
sashForm.setWeights(new int[] { newChatDisplayHeight,
chatInputHeight });
}
});
/*
* no need for dispose handling because all child controls (and
* listeners) are disposed automatically
*/
}
| public ChatControl(Composite parent, int style,
Color displayBackgroundColor, Color inputBackgroundColor,
final int minVisibleInputLines) {
super(parent, style & ~SWT.BORDER);
int chatDisplayStyle = (style & SWT.BORDER) | SWT.V_SCROLL
| SWT.H_SCROLL;
int chatInputStyle = (style & SWT.BORDER) | SWT.MULTI | SWT.V_SCROLL
| SWT.WRAP;
this.setLayout(new FillLayout());
this.sashForm = new SashForm(this, SWT.VERTICAL);
// ChatDisplay
this.chatDisplay = new ChatDisplay(sashForm, chatDisplayStyle,
displayBackgroundColor);
this.chatDisplay.setAlwaysShowScrollBars(true);
this.chatDisplay.addChatDisplayListener(this.chatDisplayListener);
// ChatInput
this.chatInput = new ChatInput(sashForm, chatInputStyle);
this.chatInput.addKeyListener(this.chatInputListener);
/*
* Updates SashForm weights to emulate a fixed ChatInput height
*/
this.addListener(SWT.Resize, new Listener() {
public void handleEvent(Event event) {
int fullHeight = ChatControl.this.getSize().y;
int chatInputHeight = ChatControl.this.chatInput.getSize().y;
int lineHeight = (int) Math.round(chatInput.getFont()
.getFontData()[0].getHeight() * 1.4);
int minChatInputHeight = minVisibleInputLines * lineHeight;
if (chatInputHeight < minChatInputHeight) {
chatInputHeight = minChatInputHeight;
}
int newChatDisplayHeight = fullHeight - chatInputHeight;
if (newChatDisplayHeight <= 0 || chatInputHeight <= 0)
return;
sashForm.setWeights(new int[] { newChatDisplayHeight,
chatInputHeight });
}
});
/*
* no need for dispose handling because all child controls (and
* listeners) are disposed automatically
*/
}
|