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/engine/src/info/svitkine/alexei/wage/GameWindow.java b/engine/src/info/svitkine/alexei/wage/GameWindow.java index 61391c1..0abf6f2 100644 --- a/engine/src/info/svitkine/alexei/wage/GameWindow.java +++ b/engine/src/info/svitkine/alexei/wage/GameWindow.java @@ -1,395 +1,394 @@ package info.svitkine.alexei.wage; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.InvocationTargetException; import java.util.Timer; import java.util.TimerTask; 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.JScrollPane; import javax.swing.JTextArea; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; public class GameWindow extends JFrame { private World world; private Engine engine; private SceneViewer viewer; private ConsoleTextArea textArea; private JPanel panel; private Timer randomSoundTimer; public GameWindow(final World world) { this.world = world; JMenuBar menubar = new JMenuBar(); JMenu fileMenu = createFileMenu(); JMenu editMenu = createEditMenu(); final JMenu commandsMenu = createCommandsMenu(); JMenu weaponsMenu = createWeaponsMenu(); menubar.add(createAppleMenu()); menubar.add(fileMenu); menubar.add(editMenu); menubar.add(commandsMenu); menubar.add(weaponsMenu); Loader.setupCloseWindowKeyStrokes(this, getRootPane()); WindowManager wm = new WindowManager(); viewer = new SceneViewer(); textArea = createTextArea(); final JScrollPane scrollPane = wrapInScrollPane(textArea); panel = wrapInPanel(scrollPane); engine = new Engine(world, textArea.getOut(), new Engine.Callbacks() { public void setCommandsMenu(String format) { updateMenuFromString(commandsMenu, format); } }); engine.processTurn(null, null); Scene scene = world.getPlayer().getCurrentScene(); world.addMoveListener(new World.MoveListener() { public void onMove(World.MoveEvent event) { Scene currentScene = world.getPlayer().getCurrentScene(); if (event.getTo() == currentScene || event.getFrom() == currentScene) { Runnable repainter = new Runnable() { public void run() { viewer.repaint(); getContentPane().repaint(); } }; runOnEventDispatchThread(repainter); try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } - textArea.setText(""); + if (event.getWhat() == world.getPlayer()) { + textArea.setText(""); + } } } }); wm.add(viewer); wm.add(panel); updateSceneViewerForScene(viewer, scene); updateTextAreaForScene(textArea, panel, scene); updateSoundTimerForScene(scene); viewer.addMouseListener(new MouseAdapter() { @Override - public void mouseClicked(MouseEvent e) { - synchronized (engine) { - final Object target = viewer.getClickTarget(e); - if (target != null) { - Thread thread = new Thread(new Runnable() { - public void run() { + public void mouseClicked(final MouseEvent e) { + Thread thread = new Thread(new Runnable() { + public void run() { + synchronized (engine) { + final Object target = viewer.getClickTarget(e); + if (target != null) { engine.processTurn(null, target); textArea.getOut().append("\n"); processEndOfTurn(); } - }); - thread.start(); - while (true) { - try { thread.join(); break; } catch (InterruptedException e1) { } } } - } + }); + thread.start(); } }); new Thread(new Runnable() { public void run() { BufferedReader in = new BufferedReader(new InputStreamReader(textArea.getIn())); try { String line = in.readLine(); while (line != null) { doCommand(line); line = in.readLine(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); setJMenuBar(menubar); setContentPane(wm); setSize(640, 480); setLocationRelativeTo(null); setVisible(true); } private static void runOnEventDispatchThread(Runnable runnable) { if (SwingUtilities.isEventDispatchThread()) { runnable.run(); } else try { SwingUtilities.invokeAndWait(runnable); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (InvocationTargetException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } private void doCommand(String line) { if (line.equals("debug")) { for (Obj o : world.getPlayer().getCurrentScene().getObjs()) System.out.println(o.getName()); return; } line = line.trim().toLowerCase(); if (line.equals("n")) line = "north"; else if (line.equals("s")) line = "south"; else if (line.equals("w")) line = "west"; else if (line.equals("e")) line = "east"; else line = line.replaceAll("\\s+", " "); synchronized (engine) { engine.processTurn(line, null); textArea.getOut().append("\n"); processEndOfTurn(); } } private void processEndOfTurn() { final Scene scene = world.getPlayer().getCurrentScene(); SwingUtilities.invokeLater(new Runnable() { public void run() { if (scene != viewer.getScene()) { if (scene == world.getStorageScene()) { JOptionPane.showMessageDialog(GameWindow.this, "Game over!"); setVisible(false); dispose(); } else { updateSceneViewerForScene(viewer, scene); updateTextAreaForScene(textArea, panel, scene); updateSoundTimerForScene(scene); } } getContentPane().validate(); getContentPane().repaint(); textArea.postUpdateUI(); } }); } private JMenu createAppleMenu() { // TODO: extract info (such as about name), out of the MENU resource JMenu menu = new JMenu("\uF8FF"); JMenuItem menuItem = new JMenuItem("About " + world.getName() + "..."); menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String aboutMessage = world.getAboutMessage(); aboutMessage = "<html><center>" + aboutMessage.replace("\n", "<br>"); JOptionPane.showMessageDialog(GameWindow.this, new JLabel(aboutMessage)); } }); menu.add(menuItem); return menu; } private JMenu createFileMenu() { JMenu menu = new JMenu("File"); menu.add(new JMenuItem("New")); menu.add(new JMenuItem("Open...")); menu.add(new JMenuItem("Close")); menu.add(new JMenuItem("Save")); menu.add(new JMenuItem("Save As...")); menu.add(new JMenuItem("Revert")); menu.add(new JMenuItem("Quit")); return menu; } private JMenu createEditMenu() { JMenu menu = new JMenu("Edit"); menu.add(new JMenuItem("Undo")); menu.addSeparator(); menu.add(new JMenuItem("Cut")); menu.add(new JMenuItem("Copy")); menu.add(new JMenuItem("Paste")); menu.add(new JMenuItem("Clear")); return menu; } private JMenu createWeaponsMenu() { final JMenu menu = new JMenu("Weapons"); menu.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { menu.removeAll(); Chr player = world.getPlayer(); if (player.getNativeWeapon1().length() > 0) menu.add(new JMenuItem(player.getOperativeVerb1() + " " + player.getNativeWeapon1())); if (player.getNativeWeapon2().length() > 0) menu.add(new JMenuItem(player.getOperativeVerb2() + " " + player.getNativeWeapon2())); for (Obj obj : player.getInventory()) { if (obj.getType() == Obj.REGULAR_WEAPON || obj.getType() == Obj.THROW_WEAPON || obj.getType() == Obj.MAGICAL_OBJECT) { menu.add(new JMenuItem(obj.getOperativeVerb() + " " + obj.getName())); } } for (Object item : menu.getMenuComponents()) { ((JMenuItem) item).addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textArea.getOut().append(e.getActionCommand() + "\n"); doCommand(e.getActionCommand()); } }); } } public void menuCanceled(MenuEvent e) {} public void menuDeselected(MenuEvent e) {} }); return menu; } private JMenu createCommandsMenu() { JMenu menu = new JMenu("Commands"); updateMenuFromString(menu, "North/N;South/S;East/E;West/W;Up/U;Down/D;(-;Look/L;Rest/R;Status/T;Inventory/I;Search/F;(-;Open;Close"); return menu; } private void updateMenuFromString(JMenu menu, String string) { String[] items = string.split(";"); menu.removeAll(); for (String item : items) { if (item.equals("(-")) { menu.addSeparator(); } else { JMenuItem menuItem; int index = item.lastIndexOf("/"); if (index != -1) { menuItem = new JMenuItem(item.substring(0, index)); menuItem.setAccelerator(KeyStroke.getKeyStroke(item.substring(index).charAt(1), Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); } else { menuItem = new JMenuItem(item); } menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textArea.getOut().append(e.getActionCommand() + "\n"); doCommand(e.getActionCommand()); } }); menu.add(menuItem); } } } private void updateTextAreaForScene(ConsoleTextArea textArea, JPanel panel, Scene scene) { textArea.setFont(new Font(scene.getFontName(), 0, scene.getFontSize())); panel.setBounds(scene.getTextBounds()); } private void updateSceneViewerForScene(SceneViewer viewer, Scene scene) { viewer.setScene(scene); viewer.setBounds(scene.getDesignBounds()); } private static class PlaySoundTask extends TimerTask { private Sound sound; public PlaySoundTask(Sound sound) { this.sound = sound; } public void run() { sound.play(); } } private class UpdateSoundTimerTask extends TimerTask { private Scene scene; public UpdateSoundTimerTask(Scene scene) { this.scene = scene; } public void run() { synchronized (engine) { if (world.getPlayer().getCurrentScene() == scene) { updateSoundTimerForScene(scene); } } } } private void updateSoundTimerForScene(final Scene scene) { if (randomSoundTimer != null) { randomSoundTimer.cancel(); randomSoundTimer = null; } if (scene.getSoundFrequency() > 0 && scene.getSoundName() != null && scene.getSoundName().length() > 0) { final Sound sound = world.getSounds().get(scene.getSoundName().toLowerCase()); if (sound != null) { randomSoundTimer = new Timer(); switch (scene.getSoundType()) { case Scene.PERIODIC: int delay = 60000 / scene.getSoundFrequency(); randomSoundTimer.schedule(new PlaySoundTask(sound), delay); randomSoundTimer.schedule(new UpdateSoundTimerTask(scene), delay + 1); break; case Scene.RANDOM: for (int i = 0; i < scene.getSoundFrequency(); i++) randomSoundTimer.schedule(new PlaySoundTask(sound), (int) (Math.random() * 60000)); randomSoundTimer.schedule(new UpdateSoundTimerTask(scene), 60000); break; } } } } private ConsoleTextArea createTextArea() { ConsoleTextArea textArea = new ConsoleTextArea(); textArea.setColumns(0); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); return textArea; } private JScrollPane wrapInScrollPane(JTextArea textArea) { JScrollPane scrollPane = new JScrollPane(textArea); scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER); scrollPane.setBorder(null); return scrollPane; } private JPanel wrapInPanel(JScrollPane scrollPane) { JPanel text = new JPanel() { public void paint(Graphics g) { Graphics2D g2d = (Graphics2D) g; g2d.setClip(2, 2, getWidth()-4, getHeight()-4); super.paint(g); g2d.setClip(null); paintBorder(g); } }; text.setBackground(Color.WHITE); text.setLayout(new BorderLayout()); text.add(scrollPane, BorderLayout.CENTER); return text; } }
false
true
public GameWindow(final World world) { this.world = world; JMenuBar menubar = new JMenuBar(); JMenu fileMenu = createFileMenu(); JMenu editMenu = createEditMenu(); final JMenu commandsMenu = createCommandsMenu(); JMenu weaponsMenu = createWeaponsMenu(); menubar.add(createAppleMenu()); menubar.add(fileMenu); menubar.add(editMenu); menubar.add(commandsMenu); menubar.add(weaponsMenu); Loader.setupCloseWindowKeyStrokes(this, getRootPane()); WindowManager wm = new WindowManager(); viewer = new SceneViewer(); textArea = createTextArea(); final JScrollPane scrollPane = wrapInScrollPane(textArea); panel = wrapInPanel(scrollPane); engine = new Engine(world, textArea.getOut(), new Engine.Callbacks() { public void setCommandsMenu(String format) { updateMenuFromString(commandsMenu, format); } }); engine.processTurn(null, null); Scene scene = world.getPlayer().getCurrentScene(); world.addMoveListener(new World.MoveListener() { public void onMove(World.MoveEvent event) { Scene currentScene = world.getPlayer().getCurrentScene(); if (event.getTo() == currentScene || event.getFrom() == currentScene) { Runnable repainter = new Runnable() { public void run() { viewer.repaint(); getContentPane().repaint(); } }; runOnEventDispatchThread(repainter); try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } textArea.setText(""); } } }); wm.add(viewer); wm.add(panel); updateSceneViewerForScene(viewer, scene); updateTextAreaForScene(textArea, panel, scene); updateSoundTimerForScene(scene); viewer.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { synchronized (engine) { final Object target = viewer.getClickTarget(e); if (target != null) { Thread thread = new Thread(new Runnable() { public void run() { engine.processTurn(null, target); textArea.getOut().append("\n"); processEndOfTurn(); } }); thread.start(); while (true) { try { thread.join(); break; } catch (InterruptedException e1) { } } } } } }); new Thread(new Runnable() { public void run() { BufferedReader in = new BufferedReader(new InputStreamReader(textArea.getIn())); try { String line = in.readLine(); while (line != null) { doCommand(line); line = in.readLine(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); setJMenuBar(menubar); setContentPane(wm); setSize(640, 480); setLocationRelativeTo(null); setVisible(true); }
public GameWindow(final World world) { this.world = world; JMenuBar menubar = new JMenuBar(); JMenu fileMenu = createFileMenu(); JMenu editMenu = createEditMenu(); final JMenu commandsMenu = createCommandsMenu(); JMenu weaponsMenu = createWeaponsMenu(); menubar.add(createAppleMenu()); menubar.add(fileMenu); menubar.add(editMenu); menubar.add(commandsMenu); menubar.add(weaponsMenu); Loader.setupCloseWindowKeyStrokes(this, getRootPane()); WindowManager wm = new WindowManager(); viewer = new SceneViewer(); textArea = createTextArea(); final JScrollPane scrollPane = wrapInScrollPane(textArea); panel = wrapInPanel(scrollPane); engine = new Engine(world, textArea.getOut(), new Engine.Callbacks() { public void setCommandsMenu(String format) { updateMenuFromString(commandsMenu, format); } }); engine.processTurn(null, null); Scene scene = world.getPlayer().getCurrentScene(); world.addMoveListener(new World.MoveListener() { public void onMove(World.MoveEvent event) { Scene currentScene = world.getPlayer().getCurrentScene(); if (event.getTo() == currentScene || event.getFrom() == currentScene) { Runnable repainter = new Runnable() { public void run() { viewer.repaint(); getContentPane().repaint(); } }; runOnEventDispatchThread(repainter); try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (event.getWhat() == world.getPlayer()) { textArea.setText(""); } } } }); wm.add(viewer); wm.add(panel); updateSceneViewerForScene(viewer, scene); updateTextAreaForScene(textArea, panel, scene); updateSoundTimerForScene(scene); viewer.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(final MouseEvent e) { Thread thread = new Thread(new Runnable() { public void run() { synchronized (engine) { final Object target = viewer.getClickTarget(e); if (target != null) { engine.processTurn(null, target); textArea.getOut().append("\n"); processEndOfTurn(); } } } }); thread.start(); } }); new Thread(new Runnable() { public void run() { BufferedReader in = new BufferedReader(new InputStreamReader(textArea.getIn())); try { String line = in.readLine(); while (line != null) { doCommand(line); line = in.readLine(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); setJMenuBar(menubar); setContentPane(wm); setSize(640, 480); setLocationRelativeTo(null); setVisible(true); }
diff --git a/hot-deploy/purchasing/src/org/opentaps/purchasing/domain/PurchasingRepository.java b/hot-deploy/purchasing/src/org/opentaps/purchasing/domain/PurchasingRepository.java index 825b15ef5..b1485bed7 100644 --- a/hot-deploy/purchasing/src/org/opentaps/purchasing/domain/PurchasingRepository.java +++ b/hot-deploy/purchasing/src/org/opentaps/purchasing/domain/PurchasingRepository.java @@ -1,119 +1,120 @@ /* * Copyright (c) 2009 - 2009 Open Source Strategies, Inc. * * Opentaps is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Opentaps 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Opentaps. If not, see <http://www.gnu.org/licenses/>. */ package org.opentaps.purchasing.domain; import java.math.BigDecimal; import java.util.List; import org.ofbiz.base.util.Debug; import org.ofbiz.entity.GenericValue; import org.opentaps.base.entities.SupplierProduct; import org.opentaps.base.services.CreateSupplierProductService; import org.opentaps.base.services.GetSuppliersForProductService; import org.opentaps.domain.purchasing.PurchasingRepositoryInterface; import org.opentaps.foundation.repository.RepositoryException; import org.opentaps.foundation.repository.ofbiz.Repository; import org.opentaps.foundation.service.ServiceException; /** {@inheritDoc} */ public class PurchasingRepository extends Repository implements PurchasingRepositoryInterface { private static final String MODULE = PurchasingRepository.class.getName(); /** * Default constructor. */ public PurchasingRepository() { super(); } /** {@inheritDoc} */ @SuppressWarnings("unchecked") public SupplierProduct getSupplierProduct(String supplierPartyId, String productId, BigDecimal quantityToPurchase, String currencyUomId) throws RepositoryException { GenericValue supplierProduct = null; try { GetSuppliersForProductService service = new GetSuppliersForProductService(); service.setInProductId(productId); service.setInPartyId(supplierPartyId); service.setInCurrencyUomId(currencyUomId); service.setInQuantity(quantityToPurchase); service.runSync(getInfrastructure()); List<GenericValue> productSuppliers = service.getOutSupplierProducts(); if ((productSuppliers != null) && (productSuppliers.size() > 0)) { supplierProduct = productSuppliers.get(0); } } catch (ServiceException e) { Debug.logError(e.getMessage(), MODULE); } if (supplierProduct == null) { return null; } return loadFromGeneric(SupplierProduct.class, supplierProduct); } /** {@inheritDoc} */ public void createSupplierProduct(SupplierProduct supplierProduct) throws RepositoryException { CreateSupplierProductService service = new CreateSupplierProductService(); + service.setInProductId(supplierProduct.getProductId()); service.setInSupplierProductId(supplierProduct.getSupplierProductId()); // contruct parameters for call service service.setInPartyId(supplierProduct.getPartyId()); service.setInMinimumOrderQuantity(supplierProduct.getMinimumOrderQuantity()); service.setInLastPrice(supplierProduct.getLastPrice()); service.setInCurrencyUomId(supplierProduct.getCurrencyUomId()); service.setInAvailableFromDate(supplierProduct.getAvailableFromDate()); service.setInComments(supplierProduct.getComments()); if (supplierProduct.getAvailableThruDate() != null) { service.setInAvailableThruDate(supplierProduct.getAvailableThruDate()); } if (supplierProduct.getCanDropShip() != null) { service.setInCanDropShip(supplierProduct.getCanDropShip()); } if (supplierProduct.getOrderQtyIncrements() != null) { service.setInOrderQtyIncrements(supplierProduct.getOrderQtyIncrements()); } if (supplierProduct.getQuantityUomId() != null) { service.setInQuantityUomId(supplierProduct.getQuantityUomId()); } if (supplierProduct.getStandardLeadTimeDays() != null) { service.setInStandardLeadTimeDays(supplierProduct.getStandardLeadTimeDays()); } if (supplierProduct.getSupplierProductName() != null) { service.setInSupplierProductName(supplierProduct.getSupplierProductName()); } if (supplierProduct.getSupplierPrefOrderId() != null) { service.setInSupplierPrefOrderId(supplierProduct.getSupplierPrefOrderId()); } if (supplierProduct.getSupplierRatingTypeId() != null) { service.setInSupplierRatingTypeId(supplierProduct.getSupplierRatingTypeId()); } if (supplierProduct.getUnitsIncluded() != null) { service.setInUnitsIncluded(supplierProduct.getUnitsIncluded()); } service.setInUserLogin(getInfrastructure().getSystemUserLogin()); try { //call service to create supplierProduct service.runSync(getInfrastructure()); if (service.isError()) { throw new RepositoryException("can not create supplier product"); } } catch (ServiceException e) { throw new RepositoryException(e); } } }
true
true
public void createSupplierProduct(SupplierProduct supplierProduct) throws RepositoryException { CreateSupplierProductService service = new CreateSupplierProductService(); service.setInSupplierProductId(supplierProduct.getSupplierProductId()); // contruct parameters for call service service.setInPartyId(supplierProduct.getPartyId()); service.setInMinimumOrderQuantity(supplierProduct.getMinimumOrderQuantity()); service.setInLastPrice(supplierProduct.getLastPrice()); service.setInCurrencyUomId(supplierProduct.getCurrencyUomId()); service.setInAvailableFromDate(supplierProduct.getAvailableFromDate()); service.setInComments(supplierProduct.getComments()); if (supplierProduct.getAvailableThruDate() != null) { service.setInAvailableThruDate(supplierProduct.getAvailableThruDate()); } if (supplierProduct.getCanDropShip() != null) { service.setInCanDropShip(supplierProduct.getCanDropShip()); } if (supplierProduct.getOrderQtyIncrements() != null) { service.setInOrderQtyIncrements(supplierProduct.getOrderQtyIncrements()); } if (supplierProduct.getQuantityUomId() != null) { service.setInQuantityUomId(supplierProduct.getQuantityUomId()); } if (supplierProduct.getStandardLeadTimeDays() != null) { service.setInStandardLeadTimeDays(supplierProduct.getStandardLeadTimeDays()); } if (supplierProduct.getSupplierProductName() != null) { service.setInSupplierProductName(supplierProduct.getSupplierProductName()); } if (supplierProduct.getSupplierPrefOrderId() != null) { service.setInSupplierPrefOrderId(supplierProduct.getSupplierPrefOrderId()); } if (supplierProduct.getSupplierRatingTypeId() != null) { service.setInSupplierRatingTypeId(supplierProduct.getSupplierRatingTypeId()); } if (supplierProduct.getUnitsIncluded() != null) { service.setInUnitsIncluded(supplierProduct.getUnitsIncluded()); } service.setInUserLogin(getInfrastructure().getSystemUserLogin()); try { //call service to create supplierProduct service.runSync(getInfrastructure()); if (service.isError()) { throw new RepositoryException("can not create supplier product"); } } catch (ServiceException e) { throw new RepositoryException(e); } }
public void createSupplierProduct(SupplierProduct supplierProduct) throws RepositoryException { CreateSupplierProductService service = new CreateSupplierProductService(); service.setInProductId(supplierProduct.getProductId()); service.setInSupplierProductId(supplierProduct.getSupplierProductId()); // contruct parameters for call service service.setInPartyId(supplierProduct.getPartyId()); service.setInMinimumOrderQuantity(supplierProduct.getMinimumOrderQuantity()); service.setInLastPrice(supplierProduct.getLastPrice()); service.setInCurrencyUomId(supplierProduct.getCurrencyUomId()); service.setInAvailableFromDate(supplierProduct.getAvailableFromDate()); service.setInComments(supplierProduct.getComments()); if (supplierProduct.getAvailableThruDate() != null) { service.setInAvailableThruDate(supplierProduct.getAvailableThruDate()); } if (supplierProduct.getCanDropShip() != null) { service.setInCanDropShip(supplierProduct.getCanDropShip()); } if (supplierProduct.getOrderQtyIncrements() != null) { service.setInOrderQtyIncrements(supplierProduct.getOrderQtyIncrements()); } if (supplierProduct.getQuantityUomId() != null) { service.setInQuantityUomId(supplierProduct.getQuantityUomId()); } if (supplierProduct.getStandardLeadTimeDays() != null) { service.setInStandardLeadTimeDays(supplierProduct.getStandardLeadTimeDays()); } if (supplierProduct.getSupplierProductName() != null) { service.setInSupplierProductName(supplierProduct.getSupplierProductName()); } if (supplierProduct.getSupplierPrefOrderId() != null) { service.setInSupplierPrefOrderId(supplierProduct.getSupplierPrefOrderId()); } if (supplierProduct.getSupplierRatingTypeId() != null) { service.setInSupplierRatingTypeId(supplierProduct.getSupplierRatingTypeId()); } if (supplierProduct.getUnitsIncluded() != null) { service.setInUnitsIncluded(supplierProduct.getUnitsIncluded()); } service.setInUserLogin(getInfrastructure().getSystemUserLogin()); try { //call service to create supplierProduct service.runSync(getInfrastructure()); if (service.isError()) { throw new RepositoryException("can not create supplier product"); } } catch (ServiceException e) { throw new RepositoryException(e); } }
diff --git a/src/main/java/org/rsna/isn/transfercontent/Worker.java b/src/main/java/org/rsna/isn/transfercontent/Worker.java index cfddf57..91cfdd2 100644 --- a/src/main/java/org/rsna/isn/transfercontent/Worker.java +++ b/src/main/java/org/rsna/isn/transfercontent/Worker.java @@ -1,217 +1,217 @@ /* Copyright (c) <2010>, <Radiological Society of North America> * 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 the <RSNA> 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 org.rsna.isn.transfercontent; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.Map; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import org.openhealthtools.ihe.utils.IHEException; import org.rsna.isn.dao.JobDao; import org.rsna.isn.domain.DicomStudy; import org.rsna.isn.domain.Exam; import org.rsna.isn.domain.Job; import org.rsna.isn.transfercontent.dcm.KosGenerator; import org.rsna.isn.transfercontent.ihe.ClearinghouseException; import org.rsna.isn.transfercontent.ihe.Iti41; import org.rsna.isn.transfercontent.ihe.Iti8; import org.rsna.isn.util.Environment; /** * Worker thread that processes jobs. * * @author Wyatt Tellis * @version 2.1.0 */ class Worker extends Thread { private static final Logger logger = Logger.getLogger(Worker.class); private static final File dcmDir = Environment.getDcmDir(); private static final File tmpDir = Environment.getTmpDir(); private final Job job; private final Exam exam; Worker(ThreadGroup group, Job job) { super(group, "worker-" + job.getJobId()); this.job = job; this.exam = job.getExam(); } @Override public void run() { logger.info("Started worker thread for " + job); try { JobDao dao = new JobDao(); try { // // Generate KOS objects // Map<String, DicomStudy> studies = Collections.EMPTY_MAP; try { dao.updateStatus(job, Job.RSNA_STARTED_KOS_GENERATION); logger.info("Started KOS generation for " + job); KosGenerator gen = new KosGenerator(job); studies = gen.processFiles(); logger.info("Completed KOS generation for " + job); } catch (IOException ex) { logger.error("Unable to generate KOS for " + job + ". ", ex); dao.updateStatus(job, Job.RSNA_FAILED_TO_GENERATE_KOS, ex); return; } // // Register patient // try { dao.updateStatus(job, Job.RSNA_STARTED_PATIENT_REGISTRATION); logger.info("Started patient registration for " + job); Iti8 iti8 = new Iti8(job); iti8.registerPatient(); logger.info("Completed patient registration for " + job); } catch (ClearinghouseException ex) { String chMsg = ex.getMessage(); String errorMsg = "Unable to register patient for " + job + ". " + chMsg; logger.error(errorMsg); dao.updateStatus(job, Job.RSNA_FAILED_TO_REGISTER_PATIENT, chMsg); return; } catch (IHEException ex) { logger.error("Unable to register patient for " + job + ". ", ex); dao.updateStatus(job, Job.RSNA_FAILED_TO_REGISTER_PATIENT, ex); return; } // // Submit documents to registry // try { dao.updateStatus(job, Job.RSNA_STARTED_DOCUMENT_SUBMISSION); logger.info("Started document submission for " + job); File jobDir = new File(tmpDir, Integer.toString(job.getJobId())); File studiesDir = new File(jobDir, "studies"); for (DicomStudy study : studies.values()) { File studyDir = new File(studiesDir, study.getStudyUid()); File debugFile = new File(studyDir, "submission-set.xml"); Iti41 iti41 = new Iti41(study); iti41.submitDocuments(debugFile); } logger.info("Completed document submission for " + job); } catch (ClearinghouseException ex) { String chMsg = ex.getMessage(); String errorMsg = "Unable to submit documents for " + job + ". " + chMsg; logger.error(errorMsg); dao.updateStatus(job, Job.RSNA_FAILED_TO_SUBMIT_DOCUMENTS, chMsg); return; } catch (Exception ex) { logger.error("Unable to submit documents for " + job + ". ", ex); dao.updateStatus(job, Job.RSNA_FAILED_TO_SUBMIT_DOCUMENTS, ex); return; } File jobDir = new File(tmpDir, Integer.toString(job.getJobId())); FileUtils.deleteDirectory(jobDir); File jobDcmDir = new File(dcmDir, Integer.toString(job.getJobId())); FileUtils.deleteDirectory(jobDcmDir); dao.updateStatus(job, Job.RSNA_COMPLETED_TRANSFER_TO_CLEARINGHOUSE); logger.info("Successfully transferred content to clearinghouse for " + job); } - catch (Exception ex) + catch (Throwable ex) { logger.error("Uncaught exception while processing job " + job, ex); dao.updateStatus(job, Job.RSNA_FAILED_TO_TRANSFER_TO_CLEARINGHOUSE, ex); } } - catch (Exception ex) + catch (Throwable ex) { logger.error("Uncaught exception while updating job " + job, ex); } finally { logger.info("Stopped worker thread"); } } }
false
true
public void run() { logger.info("Started worker thread for " + job); try { JobDao dao = new JobDao(); try { // // Generate KOS objects // Map<String, DicomStudy> studies = Collections.EMPTY_MAP; try { dao.updateStatus(job, Job.RSNA_STARTED_KOS_GENERATION); logger.info("Started KOS generation for " + job); KosGenerator gen = new KosGenerator(job); studies = gen.processFiles(); logger.info("Completed KOS generation for " + job); } catch (IOException ex) { logger.error("Unable to generate KOS for " + job + ". ", ex); dao.updateStatus(job, Job.RSNA_FAILED_TO_GENERATE_KOS, ex); return; } // // Register patient // try { dao.updateStatus(job, Job.RSNA_STARTED_PATIENT_REGISTRATION); logger.info("Started patient registration for " + job); Iti8 iti8 = new Iti8(job); iti8.registerPatient(); logger.info("Completed patient registration for " + job); } catch (ClearinghouseException ex) { String chMsg = ex.getMessage(); String errorMsg = "Unable to register patient for " + job + ". " + chMsg; logger.error(errorMsg); dao.updateStatus(job, Job.RSNA_FAILED_TO_REGISTER_PATIENT, chMsg); return; } catch (IHEException ex) { logger.error("Unable to register patient for " + job + ". ", ex); dao.updateStatus(job, Job.RSNA_FAILED_TO_REGISTER_PATIENT, ex); return; } // // Submit documents to registry // try { dao.updateStatus(job, Job.RSNA_STARTED_DOCUMENT_SUBMISSION); logger.info("Started document submission for " + job); File jobDir = new File(tmpDir, Integer.toString(job.getJobId())); File studiesDir = new File(jobDir, "studies"); for (DicomStudy study : studies.values()) { File studyDir = new File(studiesDir, study.getStudyUid()); File debugFile = new File(studyDir, "submission-set.xml"); Iti41 iti41 = new Iti41(study); iti41.submitDocuments(debugFile); } logger.info("Completed document submission for " + job); } catch (ClearinghouseException ex) { String chMsg = ex.getMessage(); String errorMsg = "Unable to submit documents for " + job + ". " + chMsg; logger.error(errorMsg); dao.updateStatus(job, Job.RSNA_FAILED_TO_SUBMIT_DOCUMENTS, chMsg); return; } catch (Exception ex) { logger.error("Unable to submit documents for " + job + ". ", ex); dao.updateStatus(job, Job.RSNA_FAILED_TO_SUBMIT_DOCUMENTS, ex); return; } File jobDir = new File(tmpDir, Integer.toString(job.getJobId())); FileUtils.deleteDirectory(jobDir); File jobDcmDir = new File(dcmDir, Integer.toString(job.getJobId())); FileUtils.deleteDirectory(jobDcmDir); dao.updateStatus(job, Job.RSNA_COMPLETED_TRANSFER_TO_CLEARINGHOUSE); logger.info("Successfully transferred content to clearinghouse for " + job); } catch (Exception ex) { logger.error("Uncaught exception while processing job " + job, ex); dao.updateStatus(job, Job.RSNA_FAILED_TO_TRANSFER_TO_CLEARINGHOUSE, ex); } } catch (Exception ex) { logger.error("Uncaught exception while updating job " + job, ex); } finally { logger.info("Stopped worker thread"); } }
public void run() { logger.info("Started worker thread for " + job); try { JobDao dao = new JobDao(); try { // // Generate KOS objects // Map<String, DicomStudy> studies = Collections.EMPTY_MAP; try { dao.updateStatus(job, Job.RSNA_STARTED_KOS_GENERATION); logger.info("Started KOS generation for " + job); KosGenerator gen = new KosGenerator(job); studies = gen.processFiles(); logger.info("Completed KOS generation for " + job); } catch (IOException ex) { logger.error("Unable to generate KOS for " + job + ". ", ex); dao.updateStatus(job, Job.RSNA_FAILED_TO_GENERATE_KOS, ex); return; } // // Register patient // try { dao.updateStatus(job, Job.RSNA_STARTED_PATIENT_REGISTRATION); logger.info("Started patient registration for " + job); Iti8 iti8 = new Iti8(job); iti8.registerPatient(); logger.info("Completed patient registration for " + job); } catch (ClearinghouseException ex) { String chMsg = ex.getMessage(); String errorMsg = "Unable to register patient for " + job + ". " + chMsg; logger.error(errorMsg); dao.updateStatus(job, Job.RSNA_FAILED_TO_REGISTER_PATIENT, chMsg); return; } catch (IHEException ex) { logger.error("Unable to register patient for " + job + ". ", ex); dao.updateStatus(job, Job.RSNA_FAILED_TO_REGISTER_PATIENT, ex); return; } // // Submit documents to registry // try { dao.updateStatus(job, Job.RSNA_STARTED_DOCUMENT_SUBMISSION); logger.info("Started document submission for " + job); File jobDir = new File(tmpDir, Integer.toString(job.getJobId())); File studiesDir = new File(jobDir, "studies"); for (DicomStudy study : studies.values()) { File studyDir = new File(studiesDir, study.getStudyUid()); File debugFile = new File(studyDir, "submission-set.xml"); Iti41 iti41 = new Iti41(study); iti41.submitDocuments(debugFile); } logger.info("Completed document submission for " + job); } catch (ClearinghouseException ex) { String chMsg = ex.getMessage(); String errorMsg = "Unable to submit documents for " + job + ". " + chMsg; logger.error(errorMsg); dao.updateStatus(job, Job.RSNA_FAILED_TO_SUBMIT_DOCUMENTS, chMsg); return; } catch (Exception ex) { logger.error("Unable to submit documents for " + job + ". ", ex); dao.updateStatus(job, Job.RSNA_FAILED_TO_SUBMIT_DOCUMENTS, ex); return; } File jobDir = new File(tmpDir, Integer.toString(job.getJobId())); FileUtils.deleteDirectory(jobDir); File jobDcmDir = new File(dcmDir, Integer.toString(job.getJobId())); FileUtils.deleteDirectory(jobDcmDir); dao.updateStatus(job, Job.RSNA_COMPLETED_TRANSFER_TO_CLEARINGHOUSE); logger.info("Successfully transferred content to clearinghouse for " + job); } catch (Throwable ex) { logger.error("Uncaught exception while processing job " + job, ex); dao.updateStatus(job, Job.RSNA_FAILED_TO_TRANSFER_TO_CLEARINGHOUSE, ex); } } catch (Throwable ex) { logger.error("Uncaught exception while updating job " + job, ex); } finally { logger.info("Stopped worker thread"); } }
diff --git a/src/JRubyVSTPluginProxy.java b/src/JRubyVSTPluginProxy.java index 652b469..8b5e816 100644 --- a/src/JRubyVSTPluginProxy.java +++ b/src/JRubyVSTPluginProxy.java @@ -1,224 +1,225 @@ import jvst.wrapper.VSTPluginAdapter; import jvst.wrapper.valueobjects.*; import org.jruby.Ruby; import org.jruby.javasupport.JavaEmbedUtils; import org.jruby.runtime.builtin.IRubyObject; import org.jruby.demo.IRBConsole; public class JRubyVSTPluginProxy extends VSTPluginAdapter { protected VSTPluginAdapter adapter; protected Ruby runtime; public boolean useMacOSX() { String lcOSName = System.getProperty("os.name").toLowerCase(); return lcOSName.startsWith("mac os x"); } public JRubyVSTPluginProxy(long wrapper) { super(wrapper); //This creates a new ruby interpreter instance for each instance of the plug + //defaults are used, eg. out from the running java program (which is *_java_stdout.txt :-)) runtime = Ruby.newInstance(); // TODO: see if we can avoid this workaround here (move up to VSTPluginAdapter ?) String resourcesFolder = getLogBasePath(); if (useMacOSX()) // mac os x tweak :o resourcesFolder += "/../Resources"; // Construct the ini file name before parsing it with JRuby // TODO: extract this to something like VSTPluginAdapter.getIniPath() instead ? String iniFileName = getLogFileName().replaceAll("_java_stdout.txt",""); if (useMacOSX()) iniFileName += ".jnilib"; iniFileName = resourcesFolder + "/" + iniFileName + ".ini"; log("res folder=" + resourcesFolder); log("ini file=" + iniFileName); // TODO: extract all ruby code inside one clean boot-strapper - and load the boot-strapper from resources instead of hard-disk ? // Autoload opaz_plug runtime.evalScriptlet("$LOAD_PATH << '"+resourcesFolder+"'"); runtime.evalScriptlet("require 'opaz_plug'"); // Current convention: %RubyPlugin%.rb should define the %RubyPlugin% class - we may need to split this in two later on String rubyPlugin = runtime.evalScriptlet("IO.read(\'"+iniFileName+"\').grep(/RubyPlugin=(.*)/) { $1 }.first").toString(); runtime.evalScriptlet("require '"+rubyPlugin+"'"); log("Creating instance of "+rubyPlugin); //We use a separate ruby interpreter for each plugin instance //--> no need to define an array of plugin instances in ruby, a simple variable is enough Object rfj = runtime.evalScriptlet("PLUG = " + rubyPlugin + ".new(" + wrapper + ")"); //runtime.evalScriptlet("if (defined? PLUGS) then PLUGS.push " + rubyPlugin + ".new(" + wrapper + ") else PLUGS = [" + rubyPlugin + ".new(" + wrapper + ")] end"); //Object rfj = runtime.evalScriptlet("PLUGS.last"); this.adapter = (VSTPluginAdapter)JavaEmbedUtils.rubyToJava(runtime, (IRubyObject) rfj, VSTPluginAdapter.class); log("Exiting constructor..."); } //hackish init for MockVSTHost public static void _hackishInit(String dllLocation, boolean log) { _initPlugFromNative(dllLocation, log); } // mandatory overrides from here... public int canDo(String arg0) { return adapter.canDo(arg0); } public int getPlugCategory() { return adapter.getPlugCategory(); } public String getProductString() { return adapter.getProductString(); } public String getProgramNameIndexed(int arg0, int arg1) { return adapter.getProgramName(); } public String getVendorString() { return adapter.getVendorString(); } public boolean setBypass(boolean arg0) { return adapter.setBypass(arg0); } public boolean string2Parameter(int arg0, String arg1) { return adapter.string2Parameter(arg0, arg1); } public int getNumParams() { return adapter.getNumParams(); } public int getNumPrograms() { return adapter.getNumPrograms(); } public float getParameter(int arg0) { return adapter.getParameter(arg0); } public String getParameterDisplay(int arg0) { return adapter.getParameterDisplay(arg0); } public String getParameterLabel(int arg0) { return adapter.getParameterLabel(arg0); } public String getParameterName(int arg0) { return adapter.getParameterName(arg0); } public int getProgram() { return adapter.getProgram(); } public String getProgramName() { return adapter.getProgramName(); } public void processReplacing(float[][] arg0, float[][] arg1, int arg2) { adapter.processReplacing(arg0, arg1, arg2); } public void setParameter(int arg0, float arg1) { adapter.setParameter(arg0, arg1); } public void setProgram(int arg0) { adapter.setProgram(arg0); } public void setProgramName(String arg0) { adapter.setProgramName(arg0); } // optional overrides from here... (copied from VSTPluginAdapter.java) // --> forward calls to ruby plugin here in order to allow to be overwritten there (by jruby plug) //provide defaults for vst 1.0 OPTIONAL methods //******************************** public void open() { adapter.open(); } public void close() { adapter.close(); } public void suspend() { adapter.suspend(); } public void resume() { adapter.resume(); } public float getVu() {return adapter.getVu(); } public int getChunk(byte[][] data, boolean isPreset) {return adapter.getChunk(data, isPreset); } public int setChunk(byte data[], int byteSize, boolean isPreset) {return adapter.setChunk(data, byteSize, isPreset);} public void setBlockSize(int blockSize) { adapter.setBlockSize(blockSize); } public void setSampleRate(float sampleRate) { adapter.setSampleRate(sampleRate); } //provide defaults for vst 2.0 OPTIONAL methods //******************************** public String getEffectName() {return adapter.getEffectName(); } public int getVendorVersion() {return adapter.getVendorVersion(); } public boolean canParameterBeAutomated(int index) {return adapter.canParameterBeAutomated(index); } public boolean copyProgram(int destination) {return adapter.copyProgram(destination); } public int fxIdle() {return adapter.fxIdle();} public float getChannelParameter(int channel, int index) {return adapter.getChannelParameter(channel, index); } public int getNumCategories() {return adapter.getNumCategories();} public VSTPinProperties getInputProperties(int index) {return adapter.getInputProperties(index);} public VSTPinProperties getOutputProperties(int index) {return adapter.getOutputProperties(index);} public String getErrorText() {return adapter.getErrorText();} public int getGetTailSize() {return adapter.getGetTailSize();} public VSTParameterProperties getParameterProperties(int index) {return adapter.getParameterProperties(index);} public int getVstVersion () {return adapter.getVstVersion();} public void inputConnected (int index, boolean state) { adapter.inputConnected(index, state); } public void outputConnected (int index, boolean state) { adapter.outputConnected(index, state); } public boolean keysRequired () {return adapter.keysRequired();} public int processEvents (VSTEvents e) {return adapter.processEvents (e);} public boolean processVariableIo (VSTVariableIO vario) {return adapter.processVariableIo (vario);} public int reportCurrentPosition () {return adapter.reportCurrentPosition();} public float[] reportDestinationBuffer () {return adapter.reportDestinationBuffer();} public void setBlockSizeAndSampleRate(int blockSize, float sampleRate) { adapter.setBlockSizeAndSampleRate(blockSize, sampleRate); } public boolean setSpeakerArrangement (VSTSpeakerArrangement pluginInput, VSTSpeakerArrangement pluginOutput) { return adapter.setSpeakerArrangement(pluginInput, pluginOutput); } public boolean getSpeakerArrangement (VSTSpeakerArrangement pluginInput, VSTSpeakerArrangement pluginOutput) { return adapter.getSpeakerArrangement(pluginInput, pluginOutput); } //provide defaults for vst 2.1 OPTIONAL methods //******************************** public int getMidiProgramName (int channel, MidiProgramName midiProgramName) { return adapter.getMidiProgramName (channel, midiProgramName); } public int getCurrentMidiProgram(int channel, MidiProgramName currentProgram) { return adapter.getCurrentMidiProgram(channel, currentProgram); } public int getMidiProgramCategory(int channel,MidiProgramCategory category) { return adapter.getMidiProgramCategory(channel, category); } public boolean hasMidiProgramsChanged(int channel) { return adapter.hasMidiProgramsChanged(channel); } public boolean getMidiKeyName(int channel, MidiKeyName keyName) { return adapter.getMidiKeyName(channel, keyName); } public boolean beginSetProgram() { return adapter.beginSetProgram();} public boolean endSetProgram() { return adapter.endSetProgram();} //provide defaults for vst 2.3 OPTIONAL methods //******************************** public int setTotalSampleToProcess (int value) { return adapter.setTotalSampleToProcess (value); } public int getNextShellPlugin(String name) { return adapter.getNextShellPlugin(name); } public int startProcess() { return adapter.startProcess(); } public int stopProcess() { return adapter.stopProcess(); } //provide defaults for vst 2.4 OPTIONAL methods //******************************** public void processDoubleReplacing (double[][] inputs, double[][] outputs, int sampleFrames) {adapter.processDoubleReplacing (inputs, outputs, sampleFrames); } public boolean setProcessPrecision (int precision){return adapter.setProcessPrecision (precision);} public int getNumMidiInputChannels(){return adapter.getNumMidiInputChannels();} public int getNumMidiOutputChannels(){return adapter.getNumMidiOutputChannels();} }
true
true
public JRubyVSTPluginProxy(long wrapper) { super(wrapper); //This creates a new ruby interpreter instance for each instance of the plug runtime = Ruby.newInstance(); // TODO: see if we can avoid this workaround here (move up to VSTPluginAdapter ?) String resourcesFolder = getLogBasePath(); if (useMacOSX()) // mac os x tweak :o resourcesFolder += "/../Resources"; // Construct the ini file name before parsing it with JRuby // TODO: extract this to something like VSTPluginAdapter.getIniPath() instead ? String iniFileName = getLogFileName().replaceAll("_java_stdout.txt",""); if (useMacOSX()) iniFileName += ".jnilib"; iniFileName = resourcesFolder + "/" + iniFileName + ".ini"; log("res folder=" + resourcesFolder); log("ini file=" + iniFileName); // TODO: extract all ruby code inside one clean boot-strapper - and load the boot-strapper from resources instead of hard-disk ? // Autoload opaz_plug runtime.evalScriptlet("$LOAD_PATH << '"+resourcesFolder+"'"); runtime.evalScriptlet("require 'opaz_plug'"); // Current convention: %RubyPlugin%.rb should define the %RubyPlugin% class - we may need to split this in two later on String rubyPlugin = runtime.evalScriptlet("IO.read(\'"+iniFileName+"\').grep(/RubyPlugin=(.*)/) { $1 }.first").toString(); runtime.evalScriptlet("require '"+rubyPlugin+"'"); log("Creating instance of "+rubyPlugin); //We use a separate ruby interpreter for each plugin instance //--> no need to define an array of plugin instances in ruby, a simple variable is enough Object rfj = runtime.evalScriptlet("PLUG = " + rubyPlugin + ".new(" + wrapper + ")"); //runtime.evalScriptlet("if (defined? PLUGS) then PLUGS.push " + rubyPlugin + ".new(" + wrapper + ") else PLUGS = [" + rubyPlugin + ".new(" + wrapper + ")] end"); //Object rfj = runtime.evalScriptlet("PLUGS.last"); this.adapter = (VSTPluginAdapter)JavaEmbedUtils.rubyToJava(runtime, (IRubyObject) rfj, VSTPluginAdapter.class); log("Exiting constructor..."); }
public JRubyVSTPluginProxy(long wrapper) { super(wrapper); //This creates a new ruby interpreter instance for each instance of the plug //defaults are used, eg. out from the running java program (which is *_java_stdout.txt :-)) runtime = Ruby.newInstance(); // TODO: see if we can avoid this workaround here (move up to VSTPluginAdapter ?) String resourcesFolder = getLogBasePath(); if (useMacOSX()) // mac os x tweak :o resourcesFolder += "/../Resources"; // Construct the ini file name before parsing it with JRuby // TODO: extract this to something like VSTPluginAdapter.getIniPath() instead ? String iniFileName = getLogFileName().replaceAll("_java_stdout.txt",""); if (useMacOSX()) iniFileName += ".jnilib"; iniFileName = resourcesFolder + "/" + iniFileName + ".ini"; log("res folder=" + resourcesFolder); log("ini file=" + iniFileName); // TODO: extract all ruby code inside one clean boot-strapper - and load the boot-strapper from resources instead of hard-disk ? // Autoload opaz_plug runtime.evalScriptlet("$LOAD_PATH << '"+resourcesFolder+"'"); runtime.evalScriptlet("require 'opaz_plug'"); // Current convention: %RubyPlugin%.rb should define the %RubyPlugin% class - we may need to split this in two later on String rubyPlugin = runtime.evalScriptlet("IO.read(\'"+iniFileName+"\').grep(/RubyPlugin=(.*)/) { $1 }.first").toString(); runtime.evalScriptlet("require '"+rubyPlugin+"'"); log("Creating instance of "+rubyPlugin); //We use a separate ruby interpreter for each plugin instance //--> no need to define an array of plugin instances in ruby, a simple variable is enough Object rfj = runtime.evalScriptlet("PLUG = " + rubyPlugin + ".new(" + wrapper + ")"); //runtime.evalScriptlet("if (defined? PLUGS) then PLUGS.push " + rubyPlugin + ".new(" + wrapper + ") else PLUGS = [" + rubyPlugin + ".new(" + wrapper + ")] end"); //Object rfj = runtime.evalScriptlet("PLUGS.last"); this.adapter = (VSTPluginAdapter)JavaEmbedUtils.rubyToJava(runtime, (IRubyObject) rfj, VSTPluginAdapter.class); log("Exiting constructor..."); }
diff --git a/src/com/untamedears/ItemExchange/utility/ExchangeRule.java b/src/com/untamedears/ItemExchange/utility/ExchangeRule.java index 79fc5d0..600f241 100644 --- a/src/com/untamedears/ItemExchange/utility/ExchangeRule.java +++ b/src/com/untamedears/ItemExchange/utility/ExchangeRule.java @@ -1,644 +1,644 @@ package com.untamedears.ItemExchange.utility; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.lang.StringUtils; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BookMeta; import org.bukkit.inventory.meta.EnchantmentStorageMeta; import org.bukkit.inventory.meta.ItemMeta; import com.untamedears.ItemExchange.ItemExchangePlugin; import com.untamedears.ItemExchange.exceptions.ExchangeRuleParseException; import com.untamedears.ItemExchange.metadata.AdditionalMetadata; import com.untamedears.ItemExchange.metadata.BookMetadata; import com.untamedears.ItemExchange.metadata.EnchantmentStorageMetadata; import com.untamedears.citadel.Citadel; import com.untamedears.citadel.entity.Faction; /* * Contains the rules pertaining to an item which can particpate in the exchange */ /** * * @author Brian Landry */ public class ExchangeRule { public static final String hiddenRuleSpacer = "§&§&§&§&§r"; public static final String hiddenCategorySpacer = "§&§&§&§r"; public static final String hiddenSecondarySpacer = "§&§&§r"; public static final String hiddenTertiarySpacer = "§&§r"; public static final String ruleSpacer = "&&&&r"; public static final String categorySpacer = "&&&r"; public static final String secondarySpacer = "&&r"; public static final String tertiarySpacer = "&r"; private Material material; private int amount; private short durability; private Map<Enchantment, Integer> requiredEnchantments; private List<Enchantment> excludedEnchantments; private boolean unlistedEnchantmentsAllowed; private String displayName; private String[] lore; private RuleType ruleType; private AdditionalMetadata additional = null; private Faction citadelGroup = null; /* * Describes whether the Exchange Rule functions as an input or an output */ public static enum RuleType { INPUT, OUTPUT } public ExchangeRule(Material material, int amount, short durability, RuleType ruleType) { this(material, amount, durability, new HashMap<Enchantment, Integer>(), new ArrayList<Enchantment>(), false, "", new String[0], ruleType); } public ExchangeRule(Material material, int amount, short durability, Map<Enchantment, Integer> requiredEnchantments, List<Enchantment> excludedEnchantments, boolean otherEnchantmentsAllowed, String displayName, String[] lore, RuleType ruleType) { this.material = material; this.amount = amount; this.durability = durability; this.requiredEnchantments = requiredEnchantments; this.excludedEnchantments = excludedEnchantments; this.unlistedEnchantmentsAllowed = otherEnchantmentsAllowed; this.displayName = displayName; this.lore = lore; this.ruleType = ruleType; } public void setAdditionalMetadata(AdditionalMetadata meta) { this.additional = meta; } /* * Parses an ItemStack into an ExchangeRule which represents that ItemStack */ public static ExchangeRule parseItemStack(ItemStack itemStack, RuleType ruleType) { Map<Enchantment, Integer> requiredEnchantments = new HashMap<Enchantment, Integer>(); for (Enchantment enchantment : itemStack.getEnchantments().keySet()) { requiredEnchantments.put(enchantment, itemStack.getEnchantments().get(enchantment)); } String displayName = ""; String[] lore = new String[0]; AdditionalMetadata additional = null; if (itemStack.hasItemMeta()) { ItemMeta itemMeta = itemStack.getItemMeta(); if (itemMeta.hasDisplayName()) { displayName = itemMeta.getDisplayName(); } if (itemMeta.hasLore()) { lore = itemMeta.getLore().toArray(new String[itemMeta.getLore().size()]); } if(itemMeta instanceof BookMeta) { additional = new BookMetadata((BookMeta) itemMeta); } else if(itemMeta instanceof EnchantmentStorageMeta) { additional = new EnchantmentStorageMetadata((EnchantmentStorageMeta) itemMeta); } } ExchangeRule exchangeRule = new ExchangeRule(itemStack.getType(), itemStack.getAmount(), itemStack.getDurability(), requiredEnchantments, new ArrayList<Enchantment>(), false, displayName, lore, ruleType); exchangeRule.setAdditionalMetadata(additional); return exchangeRule; } public static ExchangeRule[] parseBulkRuleBlock(ItemStack ruleBlock) throws ExchangeRuleParseException { try { String[] rules = ruleBlock.getItemMeta().getLore().get(1).split(hiddenRuleSpacer); List<ExchangeRule> ruleList = new ArrayList<ExchangeRule>(); for(String rule : rules) { ruleList.add(parseRuleString(rule)); } return ruleList.toArray(new ExchangeRule[0]); } catch(Exception e) { throw new ExchangeRuleParseException("Invalid Exchange Rule"); } } /* * Parses an RuleBlock into an ExchangeRule It uses the escape character to * hide the information being stored from being visible to the character. It * also includes an easily read but not parse version of the rule for the * player. Might fail if the display name contains an &. */ public static ExchangeRule parseRuleBlock(ItemStack ruleBlock) throws ExchangeRuleParseException { try { return parseRuleString(ruleBlock.getItemMeta().getLore().get(0)); } catch(Exception e) { throw new ExchangeRuleParseException("Invalid exchange rule"); } } public static ExchangeRule parseRuleString(String ruleString) throws ExchangeRuleParseException { try { // [Type,Material // ID,Durability,Amount,RequiredEnchantments[],ExcludedEnchantments[],UnlistedEnchantments[],DisplayName,Lore] String[] compiledRule = ruleString.split(hiddenCategorySpacer); // Check length is correct if (compiledRule.length < 12) { throw new ExchangeRuleParseException("Compiled rule too short: " + String.valueOf(compiledRule.length)); } // Get Rule Type RuleType ruleType; if (showString(compiledRule[0]).equals("i")) { ruleType = RuleType.INPUT; } else if (showString(compiledRule[0]).equals("o")) { ruleType = RuleType.OUTPUT; } else { throw new ExchangeRuleParseException("Invalid rule type"); } String transactionType = showString(compiledRule[1]); if(!transactionType.equals("item")) { throw new ExchangeRuleParseException("Invalid transaction type"); } // Get Material Material material = Material.getMaterial(Integer.valueOf(showString(compiledRule[2]))); // Get Durability short durability = Short.valueOf(showString(compiledRule[3])); // Get Amount int amount = Integer.parseInt(showString(compiledRule[4])); // Get Required Enchantments Map<Enchantment, Integer> requiredEnchantments = new HashMap<Enchantment, Integer>(); for (String compiledEnchant : compiledRule[5].split(hiddenSecondarySpacer)) { if (compiledEnchant.equals("")) { continue; } Enchantment enchantment = Enchantment.getById(Integer.valueOf(showString(compiledEnchant.split(hiddenTertiarySpacer)[0]))); Integer level = Integer.valueOf(showString(compiledEnchant.split(hiddenTertiarySpacer)[1])); requiredEnchantments.put(enchantment, level); } // Get Excluded Enchantments List<Enchantment> excludedEnchantments = new ArrayList<Enchantment>(); for (String compiledEnchant : compiledRule[6].split(hiddenSecondarySpacer)) { if (compiledEnchant.equals("")) { continue; } Enchantment enchantment = Enchantment.getById(Integer.valueOf(showString(compiledEnchant))); excludedEnchantments.add(enchantment); } // Get if unlisted enchantments are allowed boolean unlistedEnchantmentsAllowed; if (showString(compiledRule[7]).equals("0")) { unlistedEnchantmentsAllowed = false; } else if (showString(compiledRule[7]).equals("1")) { unlistedEnchantmentsAllowed = true; } else { throw new ExchangeRuleParseException("Invalid Rule Type"); } // Get DisplayName String displayName = ""; if (!compiledRule[8].equals("")) { displayName = showString(compiledRule[8]); } // Get Lore String[] lore = new String[0]; if (!compiledRule[9].equals("")) { - lore = showString(compiledRule[9]).split(hiddenSecondarySpacer); + lore = showString(compiledRule[9]).split(secondarySpacer); } AdditionalMetadata additional = null; if(material == Material.WRITTEN_BOOK) { additional = BookMetadata.deserialize(showString(compiledRule[10])); } else if(material == Material.ENCHANTED_BOOK) { additional = EnchantmentStorageMetadata.deserialize(showString(compiledRule[10])); } Faction group; if(!compiledRule[11].equals("")) { group = Citadel.getGroupManager().getGroup(compiledRule[11]); } else { group = null; } ExchangeRule exchangeRule = new ExchangeRule(material, amount, durability, requiredEnchantments, excludedEnchantments, unlistedEnchantmentsAllowed, displayName, lore, ruleType); exchangeRule.setAdditionalMetadata(additional); exchangeRule.setCitadelGroup(group); return exchangeRule; } catch (Exception e) { throw new ExchangeRuleParseException("Invalid Exchange Rule"); } } /* * Removes § from string */ private static String showString(String string) { return StringUtils.join(string.split("§")); } /* * Adds a § infront of every character in a string */ private static String hideString(String string) { String hiddenString = ""; for (char character : string.toCharArray()) { hiddenString += "§" + character; } return hiddenString; } /* * Parse create command into an exchange rule */ public static ExchangeRule parseCreateCommand(String[] args) throws ExchangeRuleParseException { try { // Parse ruletype RuleType ruleType = null; if (args[0].equalsIgnoreCase("input")) { ruleType = ExchangeRule.RuleType.INPUT; } else if (args[0].equalsIgnoreCase("output")) { ruleType = ExchangeRule.RuleType.INPUT; } if (ruleType != null) { Material material = null; short durability = 0; int amount = 1; if (args.length >= 2) { if (ItemExchangePlugin.NAME_MATERIAL.containsKey(args[1].toLowerCase())) { ItemStack itemStack = ItemExchangePlugin.NAME_MATERIAL.get(args[1].toLowerCase()); material = itemStack.getType(); durability = itemStack.getDurability(); } else { String[] split = args[1].split(":"); material = Material.getMaterial(Integer.valueOf(split[0])); if (split.length > 1) { durability = Short.valueOf(split[1]); } } if (args.length == 3) { amount = Integer.valueOf(args[2]); } } return new ExchangeRule(material, amount, durability, ruleType); } else { throw new ExchangeRuleParseException("Please specify and input or output."); } } catch (Exception e) { throw new ExchangeRuleParseException("Invalid Exchange Rule"); } } public static ItemStack toBulkItemStack(Collection<ExchangeRule> rules) { ItemStack itemStack = ItemExchangePlugin.ITEM_RULE_ITEMSTACK.clone(); String ruleSpacer = "§&§&§&§&§r"; ItemMeta itemMeta = itemStack.getItemMeta(); itemMeta.setDisplayName(ChatColor.DARK_RED + "Bulk Rule Block"); List<String> newLore = new ArrayList<String>(); StringBuilder compiledRules = new StringBuilder(); Iterator<ExchangeRule> iterator = rules.iterator(); while(iterator.hasNext()) { compiledRules.append(iterator.next().compileRule()); if(iterator.hasNext()) compiledRules.append(ruleSpacer); } newLore.add("This rule block holds " + rules.size() + (rules.size() > 1 ? " exchange rules." : " exchange rule.")); newLore.add(compiledRules.toString()); itemMeta.setLore(newLore); itemStack.setItemMeta(itemMeta); return itemStack; } /* * Stores the exchange rule as an item stack */ public ItemStack toItemStack() { ItemStack itemStack = ItemExchangePlugin.ITEM_RULE_ITEMSTACK.clone(); ItemMeta itemMeta = itemStack.getItemMeta(); itemMeta.setDisplayName(displayedItemStackInfo()); List<String> newLore = new ArrayList<String>(); newLore.add(compileRule() + displayedEnchantments()); if (lore.length > 0) { newLore.add(displayedLore()); } itemMeta.setLore(newLore); itemStack.setItemMeta(itemMeta); return itemStack; } /* * Saves the exchange rule to lore in a semi-readable fashion */ public String compileRule() { String compiledRule = ""; // RuleType compiledRule += ruleType.equals(RuleType.INPUT) ? hideString("i") : hideString("o"); // Transaction type compiledRule += "item"; // Material ID compiledRule += hiddenCategorySpacer + hideString(String.valueOf(material.getId())); // Durability compiledRule += hiddenCategorySpacer + hideString(String.valueOf(durability)); // Amount compiledRule += hiddenCategorySpacer + hideString(String.valueOf(amount)); compiledRule += hiddenCategorySpacer; for (Entry<Enchantment, Integer> entry : requiredEnchantments.entrySet()) { compiledRule += hideString(String.valueOf(entry.getKey().getId())) + hiddenTertiarySpacer + hideString(entry.getValue().toString()) + hiddenSecondarySpacer; } compiledRule += hiddenCategorySpacer; for (Enchantment enchantment : excludedEnchantments) { compiledRule += hideString(String.valueOf(enchantment.getId())) + hiddenSecondarySpacer; } compiledRule += hiddenCategorySpacer + (unlistedEnchantmentsAllowed ? hideString("1") : hideString("0")); compiledRule += hiddenCategorySpacer + hideString(displayName); compiledRule += hiddenCategorySpacer; for (String line : lore) { compiledRule += hiddenSecondarySpacer + hideString(line); } compiledRule += hiddenCategorySpacer; if(additional != null) { compiledRule += hideString(additional.serialize()); } compiledRule += hiddenCategorySpacer; if(citadelGroup != null) { compiledRule += hideString(citadelGroup.getName()); } compiledRule += hiddenCategorySpacer + "§r"; return compiledRule; } public boolean followsRules(Player player) { if(this.ruleType == RuleType.INPUT) { if(citadelGroup != null) { String playerName = player.getName(); if(citadelGroup.isMember(playerName) || citadelGroup.isModerator(playerName) || citadelGroup.isFounder(playerName)) { return true; } else { return false; } } } return true; } /* * Checks if an inventory has enough items which follow the ItemRules */ public boolean followsRules(Inventory inventory) { int invAmount = 0; for (ItemStack itemStack : inventory.getContents()) { if (itemStack != null && followsRules(itemStack)) { invAmount += itemStack.getAmount(); } } return invAmount >= amount; } /* * Checks if the given ItemStack follows the ItemRules except for the amount */ public boolean followsRules(ItemStack itemStack) { // check material type and druability boolean followsRules = material.getId() == itemStack.getTypeId() && durability == itemStack.getDurability(); // Check enchantments if (itemStack.getEnchantments().size() > 0) { followsRules = followsRules && itemStack.getEnchantments().entrySet().containsAll(requiredEnchantments.entrySet()); for (Enchantment excludedEnchantment : excludedEnchantments) { followsRules = followsRules && !itemStack.getEnchantments().entrySet().contains(excludedEnchantment); } } else if (requiredEnchantments.size() > 0) { followsRules = false; } if(additional != null) followsRules = followsRules && additional.matches(itemStack); // Check displayName and Lore if (itemStack.hasItemMeta()) { ItemMeta itemMeta = itemStack.getItemMeta(); if (itemMeta.hasDisplayName()) { followsRules = followsRules && displayName.equals(itemMeta.getDisplayName()); } else { followsRules = followsRules && displayName.equals(""); } if (itemMeta.hasLore()) { for (int i = 0; i < itemMeta.getLore().size() && i < lore.length; i++) { followsRules = followsRules && lore[i].equals(itemMeta.getLore().get(i)); } followsRules = followsRules && itemMeta.getLore().size() == lore.length; } else { followsRules = followsRules && lore.length == 0; } } else { followsRules = followsRules && displayName.equals("") && lore.length == 0; } return followsRules; } public String[] display() { List<String> displayed = new ArrayList<>(); // Material type, durability and amount displayed.add(displayedItemStackInfo()); // Additional metadata (books, etc.) if(additional != null) { displayed.add(additional.getDisplayedInfo()); } // Enchantments if(ItemExchangePlugin.ENCHANTABLE_ITEMS.contains(material)) { displayed.add(displayedEnchantments()); } // Lore if (lore.length == 1) { displayed.add(ChatColor.DARK_PURPLE + lore[0]); } else if (lore.length > 1) { displayed.add(ChatColor.DARK_PURPLE + lore[0] + "..."); } // Citadel group if(citadelGroup != null) { displayed.add(ChatColor.RED + "Restricted with Citadel."); } return displayed.toArray(new String[displayed.size()]); } private String displayedItemStackInfo() { StringBuilder stringBuilder = new StringBuilder().append(ChatColor.YELLOW).append((ruleType == RuleType.INPUT ? "Input" : "Output") + ": " + ChatColor.WHITE).append(amount); if (ItemExchangePlugin.MATERIAL_NAME.containsKey(new ItemStack(material, 1, durability))) { stringBuilder.append(" " + ItemExchangePlugin.MATERIAL_NAME.get(new ItemStack(material, 1, durability))); } else { stringBuilder.append(material.name() + ":").append(durability); } stringBuilder.append(displayName.equals("") ? "" : " \"" + displayName + "\""); return stringBuilder.toString(); } private String displayedEnchantments() { if (requiredEnchantments.size() > 0 || excludedEnchantments.size() > 0) { StringBuilder stringBuilder = new StringBuilder(); for (Entry<Enchantment, Integer> entry : requiredEnchantments.entrySet()) { stringBuilder.append(ChatColor.GREEN); stringBuilder.append(ItemExchangePlugin.ENCHANTMENT_ABBRV.get(entry.getKey().getName())); stringBuilder.append(entry.getValue()); stringBuilder.append(" "); } for (Enchantment enchantment : excludedEnchantments) { stringBuilder.append(ChatColor.RED); stringBuilder.append(ItemExchangePlugin.ENCHANTMENT_ABBRV.get(enchantment.getName())); stringBuilder.append(" "); } stringBuilder.append(unlistedEnchantmentsAllowed ? ChatColor.GREEN + "Other Enchantments Allowed." : ChatColor.RED + "Other Enchantments Disallowed"); return stringBuilder.toString(); } else { return unlistedEnchantmentsAllowed ? ChatColor.GREEN + "Any enchantments allowed" : ChatColor.RED + "No enchantments allowed"; } } private String displayedLore() { if (lore.length == 0) { return ""; } else if (lore.length == 1) { return (ChatColor.DARK_PURPLE + lore[0]); } else { return ChatColor.DARK_PURPLE + lore[0] + "..."; } } public void setMaterial(Material material) { this.material = material; } public void setUnlistedEnchantmentsAllowed(boolean allowed) { this.unlistedEnchantmentsAllowed = allowed; } public boolean getUnlistedEnchantmentsAllowed() { return unlistedEnchantmentsAllowed; } public void requireEnchantment(Enchantment enchantment, Integer level) { requiredEnchantments.put(enchantment, level); } public void removeRequiredEnchantment(Enchantment enchantment) { requiredEnchantments.remove(enchantment); } public void excludeEnchantment(Enchantment enchantment) { if(!excludedEnchantments.contains(enchantment)) excludedEnchantments.add(enchantment); } public void removeExcludedEnchantment(Enchantment enchantment) { excludedEnchantments.remove(enchantment); } public void setAmount(int amount) { this.amount = amount; } public void setDurability(short durability) { this.durability = durability; } public void setDisplayName(String displayName) { this.displayName = displayName; } public void setLore(String[] lore) { this.lore = lore; } public void switchIO() { ruleType = ruleType == RuleType.INPUT ? RuleType.OUTPUT : RuleType.INPUT; } public int getAmount() { return amount; } public void setCitadelGroup(Faction group) { this.citadelGroup = group; } public Faction getCitadelGroup() { return citadelGroup; } public RuleType getType() { return ruleType; } public static boolean isRuleBlock(ItemStack item) { try { ExchangeRule.parseBulkRuleBlock(item); return true; } catch(ExchangeRuleParseException e) { try { ExchangeRule.parseRuleBlock(item); return true; } catch(ExchangeRuleParseException e2) { return false; } } } }
true
true
public static ExchangeRule parseRuleString(String ruleString) throws ExchangeRuleParseException { try { // [Type,Material // ID,Durability,Amount,RequiredEnchantments[],ExcludedEnchantments[],UnlistedEnchantments[],DisplayName,Lore] String[] compiledRule = ruleString.split(hiddenCategorySpacer); // Check length is correct if (compiledRule.length < 12) { throw new ExchangeRuleParseException("Compiled rule too short: " + String.valueOf(compiledRule.length)); } // Get Rule Type RuleType ruleType; if (showString(compiledRule[0]).equals("i")) { ruleType = RuleType.INPUT; } else if (showString(compiledRule[0]).equals("o")) { ruleType = RuleType.OUTPUT; } else { throw new ExchangeRuleParseException("Invalid rule type"); } String transactionType = showString(compiledRule[1]); if(!transactionType.equals("item")) { throw new ExchangeRuleParseException("Invalid transaction type"); } // Get Material Material material = Material.getMaterial(Integer.valueOf(showString(compiledRule[2]))); // Get Durability short durability = Short.valueOf(showString(compiledRule[3])); // Get Amount int amount = Integer.parseInt(showString(compiledRule[4])); // Get Required Enchantments Map<Enchantment, Integer> requiredEnchantments = new HashMap<Enchantment, Integer>(); for (String compiledEnchant : compiledRule[5].split(hiddenSecondarySpacer)) { if (compiledEnchant.equals("")) { continue; } Enchantment enchantment = Enchantment.getById(Integer.valueOf(showString(compiledEnchant.split(hiddenTertiarySpacer)[0]))); Integer level = Integer.valueOf(showString(compiledEnchant.split(hiddenTertiarySpacer)[1])); requiredEnchantments.put(enchantment, level); } // Get Excluded Enchantments List<Enchantment> excludedEnchantments = new ArrayList<Enchantment>(); for (String compiledEnchant : compiledRule[6].split(hiddenSecondarySpacer)) { if (compiledEnchant.equals("")) { continue; } Enchantment enchantment = Enchantment.getById(Integer.valueOf(showString(compiledEnchant))); excludedEnchantments.add(enchantment); } // Get if unlisted enchantments are allowed boolean unlistedEnchantmentsAllowed; if (showString(compiledRule[7]).equals("0")) { unlistedEnchantmentsAllowed = false; } else if (showString(compiledRule[7]).equals("1")) { unlistedEnchantmentsAllowed = true; } else { throw new ExchangeRuleParseException("Invalid Rule Type"); } // Get DisplayName String displayName = ""; if (!compiledRule[8].equals("")) { displayName = showString(compiledRule[8]); } // Get Lore String[] lore = new String[0]; if (!compiledRule[9].equals("")) { lore = showString(compiledRule[9]).split(hiddenSecondarySpacer); } AdditionalMetadata additional = null; if(material == Material.WRITTEN_BOOK) { additional = BookMetadata.deserialize(showString(compiledRule[10])); } else if(material == Material.ENCHANTED_BOOK) { additional = EnchantmentStorageMetadata.deserialize(showString(compiledRule[10])); } Faction group; if(!compiledRule[11].equals("")) { group = Citadel.getGroupManager().getGroup(compiledRule[11]); } else { group = null; } ExchangeRule exchangeRule = new ExchangeRule(material, amount, durability, requiredEnchantments, excludedEnchantments, unlistedEnchantmentsAllowed, displayName, lore, ruleType); exchangeRule.setAdditionalMetadata(additional); exchangeRule.setCitadelGroup(group); return exchangeRule; } catch (Exception e) { throw new ExchangeRuleParseException("Invalid Exchange Rule"); } }
public static ExchangeRule parseRuleString(String ruleString) throws ExchangeRuleParseException { try { // [Type,Material // ID,Durability,Amount,RequiredEnchantments[],ExcludedEnchantments[],UnlistedEnchantments[],DisplayName,Lore] String[] compiledRule = ruleString.split(hiddenCategorySpacer); // Check length is correct if (compiledRule.length < 12) { throw new ExchangeRuleParseException("Compiled rule too short: " + String.valueOf(compiledRule.length)); } // Get Rule Type RuleType ruleType; if (showString(compiledRule[0]).equals("i")) { ruleType = RuleType.INPUT; } else if (showString(compiledRule[0]).equals("o")) { ruleType = RuleType.OUTPUT; } else { throw new ExchangeRuleParseException("Invalid rule type"); } String transactionType = showString(compiledRule[1]); if(!transactionType.equals("item")) { throw new ExchangeRuleParseException("Invalid transaction type"); } // Get Material Material material = Material.getMaterial(Integer.valueOf(showString(compiledRule[2]))); // Get Durability short durability = Short.valueOf(showString(compiledRule[3])); // Get Amount int amount = Integer.parseInt(showString(compiledRule[4])); // Get Required Enchantments Map<Enchantment, Integer> requiredEnchantments = new HashMap<Enchantment, Integer>(); for (String compiledEnchant : compiledRule[5].split(hiddenSecondarySpacer)) { if (compiledEnchant.equals("")) { continue; } Enchantment enchantment = Enchantment.getById(Integer.valueOf(showString(compiledEnchant.split(hiddenTertiarySpacer)[0]))); Integer level = Integer.valueOf(showString(compiledEnchant.split(hiddenTertiarySpacer)[1])); requiredEnchantments.put(enchantment, level); } // Get Excluded Enchantments List<Enchantment> excludedEnchantments = new ArrayList<Enchantment>(); for (String compiledEnchant : compiledRule[6].split(hiddenSecondarySpacer)) { if (compiledEnchant.equals("")) { continue; } Enchantment enchantment = Enchantment.getById(Integer.valueOf(showString(compiledEnchant))); excludedEnchantments.add(enchantment); } // Get if unlisted enchantments are allowed boolean unlistedEnchantmentsAllowed; if (showString(compiledRule[7]).equals("0")) { unlistedEnchantmentsAllowed = false; } else if (showString(compiledRule[7]).equals("1")) { unlistedEnchantmentsAllowed = true; } else { throw new ExchangeRuleParseException("Invalid Rule Type"); } // Get DisplayName String displayName = ""; if (!compiledRule[8].equals("")) { displayName = showString(compiledRule[8]); } // Get Lore String[] lore = new String[0]; if (!compiledRule[9].equals("")) { lore = showString(compiledRule[9]).split(secondarySpacer); } AdditionalMetadata additional = null; if(material == Material.WRITTEN_BOOK) { additional = BookMetadata.deserialize(showString(compiledRule[10])); } else if(material == Material.ENCHANTED_BOOK) { additional = EnchantmentStorageMetadata.deserialize(showString(compiledRule[10])); } Faction group; if(!compiledRule[11].equals("")) { group = Citadel.getGroupManager().getGroup(compiledRule[11]); } else { group = null; } ExchangeRule exchangeRule = new ExchangeRule(material, amount, durability, requiredEnchantments, excludedEnchantments, unlistedEnchantmentsAllowed, displayName, lore, ruleType); exchangeRule.setAdditionalMetadata(additional); exchangeRule.setCitadelGroup(group); return exchangeRule; } catch (Exception e) { throw new ExchangeRuleParseException("Invalid Exchange Rule"); } }
diff --git a/activemq-core/src/main/java/org/apache/activemq/xbean/XBeanBrokerFactory.java b/activemq-core/src/main/java/org/apache/activemq/xbean/XBeanBrokerFactory.java index a6726b582..91a2c178e 100644 --- a/activemq-core/src/main/java/org/apache/activemq/xbean/XBeanBrokerFactory.java +++ b/activemq-core/src/main/java/org/apache/activemq/xbean/XBeanBrokerFactory.java @@ -1,69 +1,69 @@ /** * * Copyright 2005-2006 The Apache Software Foundation * * 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.apache.activemq.xbean; import java.beans.PropertyEditorManager; import java.net.URI; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerFactory.BrokerFactoryHandler; import org.springframework.beans.BeansException; import org.apache.xbean.spring.context.ClassPathXmlApplicationContext; import org.apache.xbean.spring.context.impl.URIEditor; /** * @version $Revision$ */ public class XBeanBrokerFactory implements BrokerFactoryHandler { static { PropertyEditorManager.registerEditor(URI.class, URIEditor.class); } public BrokerService createBroker(URI config) throws Exception { String uri = config.getSchemeSpecificPart(); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(uri); - XBeanBrokerService broker = null; + BrokerService broker = null; try { - broker = (XBeanBrokerService) context.getBean("broker"); + broker = (BrokerService) context.getBean("broker"); } catch (BeansException e) { } if (broker == null) { // lets try find by type String[] names = context.getBeanNamesForType(BrokerService.class); for (int i = 0; i < names.length; i++) { String name = names[i]; - broker = (XBeanBrokerService) context.getBean(name); + broker = (BrokerService) context.getBean(name); if (broker != null) { break; } } } if (broker == null) { throw new IllegalArgumentException("The configuration has no BrokerService instance for resource: " + config); } // TODO warning resources from the context may not be closed down! return broker; } }
false
true
public BrokerService createBroker(URI config) throws Exception { String uri = config.getSchemeSpecificPart(); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(uri); XBeanBrokerService broker = null; try { broker = (XBeanBrokerService) context.getBean("broker"); } catch (BeansException e) { } if (broker == null) { // lets try find by type String[] names = context.getBeanNamesForType(BrokerService.class); for (int i = 0; i < names.length; i++) { String name = names[i]; broker = (XBeanBrokerService) context.getBean(name); if (broker != null) { break; } } } if (broker == null) { throw new IllegalArgumentException("The configuration has no BrokerService instance for resource: " + config); } // TODO warning resources from the context may not be closed down! return broker; }
public BrokerService createBroker(URI config) throws Exception { String uri = config.getSchemeSpecificPart(); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(uri); BrokerService broker = null; try { broker = (BrokerService) context.getBean("broker"); } catch (BeansException e) { } if (broker == null) { // lets try find by type String[] names = context.getBeanNamesForType(BrokerService.class); for (int i = 0; i < names.length; i++) { String name = names[i]; broker = (BrokerService) context.getBean(name); if (broker != null) { break; } } } if (broker == null) { throw new IllegalArgumentException("The configuration has no BrokerService instance for resource: " + config); } // TODO warning resources from the context may not be closed down! return broker; }
diff --git a/src/com/ensifera/animosity/craftirc/CraftIRC.java b/src/com/ensifera/animosity/craftirc/CraftIRC.java index 88b9ddc..6809b5b 100644 --- a/src/com/ensifera/animosity/craftirc/CraftIRC.java +++ b/src/com/ensifera/animosity/craftirc/CraftIRC.java @@ -1,1310 +1,1310 @@ package com.ensifera.animosity.craftirc; import java.io.*; import java.lang.StringBuilder; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.milkbowl.vault.chat.Chat; import org.bukkit.ChatColor; import org.bukkit.Server; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.java.JavaPlugin; import com.ensifera.animosity.craftirc.libs.com.sk89q.util.config.Configuration; import com.ensifera.animosity.craftirc.libs.com.sk89q.util.config.ConfigurationNode; /** * @author Animosity * @author ricin * @author Protected * @author mbaxter * */ //TODO: Better handling of null method returns (try to crash the bot and then stop that from happening again) public class CraftIRC extends JavaPlugin { public static final String NAME = "CraftIRC"; public static String VERSION; static final Logger log = Logger.getLogger("Minecraft"); Configuration configuration; //Misc class attributes PluginDescriptionFile desc = null; public Server server = null; private final CraftIRCListener listener = new CraftIRCListener(this); private final ConsoleListener sayListener = new ConsoleListener(this); private ArrayList<Minebot> instances; private boolean debug; private Timer holdTimer = new Timer(); private Timer retryTimer = new Timer(); Map<HoldType, Boolean> hold; Map<String, RetryTask> retry; //Bots and channels config storage private List<ConfigurationNode> bots; private List<ConfigurationNode> colormap; private Map<Integer, ArrayList<ConfigurationNode>> channodes; private Map<Path, ConfigurationNode> paths; //Endpoints private Map<String, EndPoint> endpoints; private Map<EndPoint, String> tags; private Map<String, CommandEndPoint> irccmds; private Map<String, List<String>> taggroups; private Chat vault; //Replacement Filters private Map<String, Map<String, String>> replaceFilters; private boolean cancelChat; static void dolog(String message) { CraftIRC.log.info("[" + CraftIRC.NAME + "] " + message); } static void dowarn(String message) { CraftIRC.log.log(Level.WARNING, "[" + CraftIRC.NAME + "] " + message); } /*************************** * Bukkit stuff ***************************/ @Override public void onEnable() { try { //Checking if the configuration file exists and imports the default one from the .jar if it doesn't final File configFile = new File(this.getDataFolder(), "config.yml"); if (!configFile.exists()) { this.saveDefaultConfig(); this.autoDisable(); return; } this.configuration = new Configuration(configFile); this.configuration.load(); this.cancelChat = this.configuration.getBoolean("settings.cancel-chat", false); this.endpoints = new HashMap<String, EndPoint>(); this.tags = new HashMap<EndPoint, String>(); this.irccmds = new HashMap<String, CommandEndPoint>(); this.taggroups = new HashMap<String, List<String>>(); final PluginDescriptionFile desc = this.getDescription(); CraftIRC.VERSION = desc.getVersion(); this.server = this.getServer(); this.bots = new ArrayList<ConfigurationNode>(this.configuration.getNodeList("bots", null)); this.channodes = new HashMap<Integer, ArrayList<ConfigurationNode>>(); for (int botID = 0; botID < this.bots.size(); botID++) { this.channodes.put(botID, new ArrayList<ConfigurationNode>(this.bots.get(botID).getNodeList("channels", null))); } this.colormap = new ArrayList<ConfigurationNode>(this.configuration.getNodeList("colormap", null)); this.paths = new HashMap<Path, ConfigurationNode>(); for (final ConfigurationNode path : this.configuration.getNodeList("paths", new LinkedList<ConfigurationNode>())) { final Path identifier = new Path(path.getString("source"), path.getString("target")); if (!identifier.getSourceTag().equals(identifier.getTargetTag()) && !this.paths.containsKey(identifier)) { this.paths.put(identifier, path); } } //Replace filters this.replaceFilters = new HashMap<String, Map<String, String>>(); try { for (String key : this.configuration.getNode("filters").getKeys()) { //Map key to regex pattern, value to replacement. Map<String, String> replaceMap = new HashMap<String, String>(); this.replaceFilters.put(key, replaceMap); for (ConfigurationNode fieldNode : this.configuration.getNodeList("filters." + key, null)) { Map<String, Object> patterns = fieldNode.getAll(); if (patterns != null) for (String pattern : patterns.keySet()) replaceMap.put(pattern, patterns.get(pattern).toString()); } //Also supports non-map entries. for (String unMappedEntry : this.configuration.getStringList("filters." + key, null)) if (unMappedEntry.length() > 0 && unMappedEntry.charAt(0) != '{') //mapped toString() begins with {, but regex can't begin with {. replaceMap.put(unMappedEntry, ""); } } catch (NullPointerException e) { } //Retry timers this.retry = new HashMap<String, RetryTask>(); this.retryTimer = new Timer(); //Event listeners this.getServer().getPluginManager().registerEvents(this.listener, this); this.getServer().getPluginManager().registerEvents(this.sayListener, this); //Native endpoints! if ((this.cMinecraftTag() != null) && !this.cMinecraftTag().equals("")) { this.registerEndPoint(this.cMinecraftTag(), new MinecraftPoint(this, this.getServer())); //The minecraft server, no bells and whistles for (final String cmd : this.cCmdWordSay(null)) { this.registerCommand(this.cMinecraftTag(), cmd); } for (final String cmd : this.cCmdWordPlayers(null)) { this.registerCommand(this.cMinecraftTag(), cmd); } if (!this.cMinecraftTagGroup().equals("")) { this.groupTag(this.cMinecraftTag(), this.cMinecraftTagGroup()); } } if ((this.cCancelledTag() != null) && !this.cCancelledTag().equals("")) { this.registerEndPoint(this.cCancelledTag(), new MinecraftPoint(this, this.getServer())); //Handles cancelled chat if (!this.cMinecraftTagGroup().equals("")) { this.groupTag(this.cCancelledTag(), this.cMinecraftTagGroup()); } } if ((this.cConsoleTag() != null) && !this.cConsoleTag().equals("")) { this.registerEndPoint(this.cConsoleTag(), new ConsolePoint(this, this.getServer())); //The minecraft console for (final String cmd : this.cCmdWordCmd(null)) { this.registerCommand(this.cConsoleTag(), cmd); } if (!this.cMinecraftTagGroup().equals("")) { this.groupTag(this.cConsoleTag(), this.cMinecraftTagGroup()); } } //Create bots this.instances = new ArrayList<Minebot>(); for (int i = 0; i < this.bots.size(); i++) { this.instances.add(new Minebot(this, i, this.cDebug())); } this.loadTagGroups(); CraftIRC.dolog("Enabled."); //Hold timers this.hold = new HashMap<HoldType, Boolean>(); this.holdTimer = new Timer(); if (this.cHold("chat") > 0) { this.hold.put(HoldType.CHAT, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.CHAT), this.cHold("chat")); } else { this.hold.put(HoldType.CHAT, false); } if (this.cHold("joins") > 0) { this.hold.put(HoldType.JOINS, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.JOINS), this.cHold("joins")); } else { this.hold.put(HoldType.JOINS, false); } if (this.cHold("quits") > 0) { this.hold.put(HoldType.QUITS, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.QUITS), this.cHold("quits")); } else { this.hold.put(HoldType.QUITS, false); } if (this.cHold("kicks") > 0) { this.hold.put(HoldType.KICKS, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.KICKS), this.cHold("kicks")); } else { this.hold.put(HoldType.KICKS, false); } if (this.cHold("bans") > 0) { this.hold.put(HoldType.BANS, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.BANS), this.cHold("bans")); } else { this.hold.put(HoldType.BANS, false); } if (this.cHold("deaths") > 0) { this.hold.put(HoldType.DEATHS, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.DEATHS), this.cHold("deaths")); } else { this.hold.put(HoldType.DEATHS, false); } this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { @Override public void run() { if (CraftIRC.this.getServer().getPluginManager().isPluginEnabled("Vault")) { try { CraftIRC.this.vault = CraftIRC.this.getServer().getServicesManager().getRegistration(Chat.class).getProvider(); } catch (final Exception e) { } } } }); this.setDebug(this.cDebug()); } catch (final Exception e) { e.printStackTrace(); } try { new Metrics(this).start(); } catch (final IOException e) { //Meh. } } private void autoDisable() { CraftIRC.dolog("Auto-disabling..."); this.getServer().getPluginManager().disablePlugin(this); } @Override public void onDisable() { try { this.retryTimer.cancel(); this.holdTimer.cancel(); //Disconnect bots if (this.bots != null) { for (int i = 0; i < this.bots.size(); i++) { this.instances.get(i).disconnect(); this.instances.get(i).dispose(); } } CraftIRC.dolog("Disabled."); } catch (final Exception e) { e.printStackTrace(); } } /*************************** * Minecraft command handling ***************************/ @Override public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { final String commandName = command.getName().toLowerCase(); try { if (commandName.equals("ircsay")){ if (!sender.hasPermission("craftirc." + commandName)) { return false; } return this.cmdMsgSay(sender,args); } if (commandName.equals("ircmsg")) { if (!sender.hasPermission("craftirc." + commandName)) { return false; } return this.cmdMsgToTag(sender, args); } else if (commandName.equals("ircmsguser")) { if (!sender.hasPermission("craftirc." + commandName)) { return false; } return this.cmdMsgToUser(sender, args); } else if (commandName.equals("ircusers")) { if (!sender.hasPermission("craftirc." + commandName)) { return false; } return this.cmdGetUserList(sender, args); } else if (commandName.equals("admins!")) { if (!sender.hasPermission("craftirc.admins")) { return false; } return this.cmdNotifyIrcAdmins(sender, args); } else if (commandName.equals("ircraw")) { if (!sender.hasPermission("craftirc." + commandName)) { return false; } return this.cmdRawIrcCommand(sender, args); } else if (commandName.equals("ircreload")) { if (!sender.hasPermission("craftirc." + commandName)) { return false; } this.getServer().getPluginManager().disablePlugin(this); this.getServer().getPluginManager().enablePlugin(this); return true; } else { return false; } } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdMsgSay(CommandSender sender, String[] args) { try{ RelayedMessage msg = this.newMsg(this.getEndPoint(this.cMinecraftTag()), null, "chat"); if (msg == null) { return true; } String senderName=sender.getName(); String world=""; String prefix=""; String suffix=""; if(sender instanceof Player){ Player player = (Player) sender; senderName = player.getDisplayName(); world = player.getWorld().getName(); prefix = this.getPrefix(player); suffix = this.getSuffix(player); } msg.setField("sender", senderName); msg.setField("message", Util.combineSplit(0, args, " ")); msg.setField("world", world); msg.setField("realSender", sender.getName()); msg.setField("prefix", prefix); msg.setField("suffix", suffix); msg.doNotColor("message"); msg.post(); return true; } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdMsgToTag(CommandSender sender, String[] args) { try { if (this.isDebug()) { CraftIRC.dolog("CraftIRCListener cmdMsgToAll()"); } if (args.length < 2) { return false; } final String msgToSend = Util.combineSplit(1, args, " "); final RelayedMessage msg = this.newMsg(this.getEndPoint(this.cMinecraftTag()), this.getEndPoint(args[0]), "chat"); if (msg == null) { return true; } if (sender instanceof Player) { msg.setField("sender", ((Player) sender).getDisplayName()); } else { msg.setField("sender", sender.getName()); } msg.setField("message", msgToSend); msg.doNotColor("message"); msg.post(); sender.sendMessage("Message sent."); return true; } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdMsgToUser(CommandSender sender, String[] args) { try { if (args.length < 3) { return false; } final String msgToSend = Util.combineSplit(2, args, " "); final RelayedMessage msg = this.newMsg(this.getEndPoint(this.cMinecraftTag()), this.getEndPoint(args[0]), "private"); if (msg == null) { return true; } if (sender instanceof Player) { msg.setField("sender", ((Player) sender).getDisplayName()); } else { msg.setField("sender", sender.getName()); }; msg.setField("message", msgToSend); msg.doNotColor("message"); boolean sameEndPoint = this.getEndPoint(this.cMinecraftTag()).equals(this.getEndPoint(args[0])); //Don't actually deliver the message if the user is invisible to the sender. if (sameEndPoint && sender instanceof Player) { Player recipient = getServer().getPlayer(args[1]); if (recipient != null && recipient.isOnline() && ((Player)sender).canSee(recipient)) msg.postToUser(args[1]); } else msg.postToUser(args[1]); sender.sendMessage("Message sent."); return true; } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdGetUserList(CommandSender sender, String[] args) { try { if (args.length == 0) { return false; } sender.sendMessage("Users in " + args[0] + ":"); final List<String> userlists = this.ircUserLists(args[0]); for (final String string : userlists) { sender.sendMessage(string); } return true; } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdNotifyIrcAdmins(CommandSender sender, String[] args) { try { if (this.isDebug()) { CraftIRC.dolog("CraftIRCListener cmdNotifyIrcAdmins()"); } if ((args.length == 0) || !(sender instanceof Player)) { if (this.isDebug()) { CraftIRC.dolog("CraftIRCListener cmdNotifyIrcAdmins() - args.length == 0 or Sender != player "); } return false; } final RelayedMessage msg = this.newMsg(this.getEndPoint(this.cMinecraftTag()), null, "admin"); if (msg == null) { return true; } msg.setField("sender", ((Player) sender).getDisplayName()); msg.setField("message", Util.combineSplit(0, args, " ")); msg.setField("world", ((Player) sender).getWorld().getName()); msg.doNotColor("message"); msg.post(true); sender.sendMessage("Admin notice sent."); return true; } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdRawIrcCommand(CommandSender sender, String[] args) { try { if (this.isDebug()) { CraftIRC.dolog("cmdRawIrcCommand(sender=" + sender.toString() + ", args=" + Util.combineSplit(0, args, " ")); } if (args.length < 2) { return false; } this.sendRawToBot(Util.combineSplit(1, args, " "), Integer.parseInt(args[0])); return true; } catch (final Exception e) { e.printStackTrace(); return false; } } /*************************** * Endpoint and message interface (to be used by CraftIRC and external plugins) ***************************/ /** * Null target: Sends message through all possible paths. * * @param source * @param target * @param eventType * @return */ public RelayedMessage newMsg(EndPoint source, EndPoint target, String eventType) { if (source == null) { return null; } if ((target == null) || this.cPathExists(this.getTag(source), this.getTag(target))) { return new RelayedMessage(this, source, target, eventType); } else { if (this.isDebug()) { CraftIRC.dolog("Failed to prepare message: " + this.getTag(source) + " -> " + this.getTag(target) + " (missing path)"); } return null; } } public RelayedMessage newMsgToTag(EndPoint source, String target, String eventType) { if (source == null) { return null; } EndPoint targetpoint = null; if (target != null) { if (this.cPathExists(this.getTag(source), target)) { targetpoint = this.getEndPoint(target); if (targetpoint == null) { CraftIRC.dolog("The requested target tag '" + target + "' isn't registered."); } } else { return null; } } return new RelayedMessage(this, source, targetpoint, eventType); } public RelayedCommand newCmd(EndPoint source, String command) { if (source == null) { return null; } final CommandEndPoint target = this.irccmds.get(command); if (target == null) { return null; } if (!this.cPathExists(this.getTag(source), this.getTag(target))) { return null; } final RelayedCommand cmd = new RelayedCommand(this, source, target); cmd.setField("command", command); return cmd; } public boolean registerEndPoint(String tag, EndPoint ep) { if (this.isDebug()) { CraftIRC.dolog("Registering endpoint: " + tag); } if (tag == null) { CraftIRC.dolog("Failed to register endpoint - No tag!"); } if ((this.endpoints.get(tag) != null) || (this.tags.get(ep) != null)) { CraftIRC.dolog("Couldn't register an endpoint tagged '" + tag + "' because either the tag or the endpoint already exist."); return false; } if (tag == "*") { CraftIRC.dolog("Couldn't register an endpoint - the character * can't be used as a tag."); return false; } this.endpoints.put(tag, ep); this.tags.put(ep, tag); return true; } public boolean endPointRegistered(String tag) { return this.endpoints.get(tag) != null; } public EndPoint getEndPoint(String tag) { return this.endpoints.get(tag); } public String getTag(EndPoint ep) { return this.tags.get(ep); } public boolean registerCommand(String tag, String command) { if (this.isDebug()) { CraftIRC.dolog("Registering command: " + command + " to endpoint:" + tag); } final EndPoint ep = this.getEndPoint(tag); if (ep == null) { CraftIRC.dolog("Couldn't register the command '" + command + "' at the endpoint tagged '" + tag + "' because there is no such tag."); return false; } if (!(ep instanceof CommandEndPoint)) { CraftIRC.dolog("Couldn't register the command '" + command + "' at the endpoint tagged '" + tag + "' because it's not capable of handling commands."); return false; } if (this.irccmds.containsKey(command)) { CraftIRC.dolog("Couldn't register the command '" + command + "' at the endpoint tagged '" + tag + "' because that command is already registered."); return false; } this.irccmds.put(command, (CommandEndPoint) ep); return true; } public boolean unregisterCommand(String command) { if (!this.irccmds.containsKey(command)) { return false; } this.irccmds.remove(command); return true; } public boolean unregisterEndPoint(String tag) { final EndPoint ep = this.getEndPoint(tag); if (ep == null) { return false; } this.endpoints.remove(tag); this.tags.remove(ep); this.ungroupTag(tag); if (ep instanceof CommandEndPoint) { final CommandEndPoint cep = (CommandEndPoint) ep; for (final String cmd : this.irccmds.keySet()) { if (this.irccmds.get(cmd) == cep) { this.irccmds.remove(cmd); } } } return true; } public boolean groupTag(String tag, String group) { if (this.getEndPoint(tag) == null) { return false; } List<String> tags = this.taggroups.get(group); if (tags == null) { tags = new ArrayList<String>(); this.taggroups.put(group, tags); } tags.add(tag); return true; } public void ungroupTag(String tag) { for (final String group : this.taggroups.keySet()) { this.taggroups.get(group).remove(tag); } } public void clearGroup(String group) { this.taggroups.remove(group); } public boolean checkTagsGrouped(String tagA, String tagB) { for (final String group : this.taggroups.keySet()) { if (this.taggroups.get(group).contains(tagA) && this.taggroups.get(group).contains(tagB)) { return true; } } return false; } /*************************** * Heart of the beast! Unified method with no special cases that replaces the old sendMessage ***************************/ boolean delivery(RelayedMessage msg) { return this.delivery(msg, null, null, RelayedMessage.DeliveryMethod.STANDARD); } boolean delivery(RelayedMessage msg, List<EndPoint> destinations) { return this.delivery(msg, destinations, null, RelayedMessage.DeliveryMethod.STANDARD); } boolean delivery(RelayedMessage msg, List<EndPoint> knownDestinations, String username) { return this.delivery(msg, knownDestinations, username, RelayedMessage.DeliveryMethod.STANDARD); } /** * Only successful if all known targets (or if there is none at least one possible target) are successful! * * @param msg * @param knownDestinations * @param username * @param dm * @return */ boolean delivery(RelayedMessage msg, List<EndPoint> knownDestinations, String username, RelayedMessage.DeliveryMethod dm) { final String sourceTag = this.getTag(msg.getSource()); msg.setField("source", sourceTag); List<EndPoint> destinations; if (this.isDebug()) { CraftIRC.dolog("X->" + (knownDestinations.size() > 0 ? knownDestinations.toString() : "*") + ": " + msg.toString()); } //If we weren't explicitly given a recipient for the message, let's try to find one (or more) if (knownDestinations.size() < 1) { //Use all possible destinations (auto-targets) destinations = new LinkedList<EndPoint>(); for (final String targetTag : this.cPathsFrom(sourceTag)) { final EndPoint ep = this.getEndPoint(targetTag); if (ep == null) { continue; } if ((ep instanceof SecuredEndPoint) && SecuredEndPoint.Security.REQUIRE_TARGET.equals(((SecuredEndPoint) ep).getSecurity())) { continue; } if (!this.cPathAttribute(sourceTag, targetTag, "attributes." + msg.getEvent())) { continue; } if ((dm == RelayedMessage.DeliveryMethod.ADMINS) && !this.cPathAttribute(sourceTag, targetTag, "attributes.admin")) { continue; } destinations.add(ep); } //Default paths to unsecured destinations (auto-paths) if (this.cAutoPaths()) { for (final EndPoint ep : this.endpoints.values()) { if (ep == null) { continue; } if (msg.getSource().equals(ep) || destinations.contains(ep)) { continue; } if ((ep instanceof SecuredEndPoint) && !SecuredEndPoint.Security.UNSECURED.equals(((SecuredEndPoint) ep).getSecurity())) { continue; } final String targetTag = this.getTag(ep); if (this.checkTagsGrouped(sourceTag, targetTag)) { continue; } if (!this.cPathAttribute(sourceTag, targetTag, "attributes." + msg.getEvent())) { continue; } if ((dm == RelayedMessage.DeliveryMethod.ADMINS) && !this.cPathAttribute(sourceTag, targetTag, "attributes.admin")) { continue; } if (this.cPathAttribute(sourceTag, targetTag, "disabled")) { continue; } destinations.add(ep); } } } else { destinations = new LinkedList<EndPoint>(knownDestinations); } if (destinations.size() < 1) { return false; } //Deliver the message boolean success = true; for (final EndPoint destination : destinations) { final String targetTag = this.getTag(destination); if(targetTag.equals(this.cCancelledTag())){ continue; } msg.setField("target", targetTag); //Check against path filters if ((msg instanceof RelayedCommand) && this.matchesFilter(msg, this.cPathFilters(sourceTag, targetTag))) { if (knownDestinations != null) { success = false; } continue; } //Finally deliver! if (this.isDebug()) { CraftIRC.dolog("-->X: " + msg.toString()); } if (username != null) { success = success && destination.userMessageIn(username, msg); } else if (dm == RelayedMessage.DeliveryMethod.ADMINS) { success = destination.adminMessageIn(msg); } else if (dm == RelayedMessage.DeliveryMethod.COMMAND) { if (!(destination instanceof CommandEndPoint)) { continue; } ((CommandEndPoint) destination).commandIn((RelayedCommand) msg); } else { destination.messageIn(msg); } } return success; } boolean matchesFilter(RelayedMessage msg, List<ConfigurationNode> filters) { if (filters == null) { return false; } newFilter: for (final ConfigurationNode filter : filters) { for (final String key : filter.getKeys()) { final Pattern condition = Pattern.compile(filter.getString(key, "")); if (condition == null) { continue newFilter; } final String subject = msg.getField(key); if (subject == null) { continue newFilter; } final Matcher check = condition.matcher(subject); if (!check.find()) { continue newFilter; } } return true; } return false; } /*************************** * Auxiliary methods ***************************/ public Minebot getBot(int bot){ return this.instances.get(bot); } public void sendRawToBot(String rawMessage, int bot) { if (this.isDebug()) { CraftIRC.dolog("sendRawToBot(bot=" + bot + ", message=" + rawMessage); } final Minebot targetBot = this.instances.get(bot); targetBot.sendRawLineViaQueue(rawMessage); } public void sendMsgToTargetViaBot(String message, String target, int bot) { final Minebot targetBot = this.instances.get(bot); targetBot.sendMessage(target, message); } public List<String> ircUserLists(String tag) { return this.getEndPoint(tag).listDisplayUsers(); } void setDebug(boolean d) { this.debug = d; for (int i = 0; i < this.bots.size(); i++) { this.instances.get(i).setVerbose(d); } CraftIRC.dolog("DEBUG [" + (d ? "ON" : "OFF") + "]"); } public String getPrefix(Player p) { String result = ""; if (this.vault != null) { try { result = this.vault.getPlayerPrefix(p); } catch (final Exception e) { } } return result; } public String getSuffix(Player p) { String result = ""; if (this.vault != null) { try { result = this.vault.getPlayerSuffix(p); } catch (final Exception e) { } } return result; } public boolean isDebug() { return this.debug; } boolean checkPerms(Player pl, String path) { return pl.hasPermission(path); } boolean checkPerms(String pl, String path) { final Player pit = this.getServer().getPlayer(pl); if (pit != null) { return pit.hasPermission(path); } return false; } // TODO: Make sure this works public String colorizeName(String name) { - final Pattern color_codes = Pattern.compile(ChatColor.COLOR_CHAR + "[0-9a-f]"); + final Pattern color_codes = Pattern.compile(ChatColor.COLOR_CHAR + "[0-9a-fk-r]"); Matcher find_colors = color_codes.matcher(name); while (find_colors.find()) { name = find_colors.replaceFirst(Character.toString((char) 3) + this.cColorIrcFromGame(find_colors.group())); find_colors = color_codes.matcher(name); } return name; } protected void enqueueConsoleCommand(String cmd) { try { this.getServer().dispatchCommand(this.getServer().getConsoleSender(), cmd); } catch (final Exception e) { e.printStackTrace(); } } /** * If the channel is null it's a reconnect, otherwise a rejoin * * @param bot * @param channel */ void scheduleForRetry(Minebot bot, String channel) { this.retryTimer.schedule(new RetryTask(this, bot, channel), this.cRetryDelay()); } /*************************** * Read stuff from config ***************************/ private ConfigurationNode getChanNode(int bot, String channel) { final ArrayList<ConfigurationNode> botChans = this.channodes.get(bot); for (final ConfigurationNode chan : botChans) { if (chan.getString("name").equalsIgnoreCase(channel)) { return chan; } } return Configuration.getEmptyNode(); } public List<ConfigurationNode> cChannels(int bot) { return this.channodes.get(bot); } private ConfigurationNode getPathNode(String source, String target) { ConfigurationNode result = this.paths.get(new Path(source, target)); if (result == null) { return this.configuration.getNode("default-attributes"); } ConfigurationNode basepath; if (result.getKeys().contains("base") && ((basepath = result.getNode("base")) != null)) { final ConfigurationNode basenode = this.paths.get(new Path(basepath.getString("source", ""), basepath.getString("target", ""))); if (basenode != null) { result = basenode; } } return result; } public String cMinecraftTag() { return this.configuration.getString("settings.minecraft-tag", "minecraft"); } public String cCancelledTag() { return this.configuration.getString("settings.cancelled-tag", "cancelled"); } public String cConsoleTag() { return this.configuration.getString("settings.console-tag", "console"); } public String cMinecraftTagGroup() { return this.configuration.getString("settings.minecraft-group-name", "minecraft"); } public String cIrcTagGroup() { return this.configuration.getString("settings.irc-group-name", "irc"); } public boolean cAutoPaths() { return this.configuration.getBoolean("settings.auto-paths", false); } public boolean cCancelChat() { return cancelChat; } public boolean cDebug() { return this.configuration.getBoolean("settings.debug", false); } public ArrayList<String> cConsoleCommands() { return new ArrayList<String>(this.configuration.getStringList("settings.console-commands", null)); } public int cHold(String eventType) { return this.configuration.getInt("settings.hold-after-enable." + eventType, 0); } public String cFormatting(String eventType, RelayedMessage msg) { return this.cFormatting(eventType, msg, null); } public String cFormatting(String eventType, RelayedMessage msg, EndPoint realTarget) { final String source = this.getTag(msg.getSource()), target = this.getTag(realTarget != null ? realTarget : msg.getTarget()); if ((source == null) || (target == null)) { CraftIRC.dowarn("Attempted to obtain formatting for invalid path " + source + " -> " + target + " ."); return this.cDefaultFormatting(eventType, msg); } final ConfigurationNode pathConfig = this.paths.get(new Path(source, target)); if ((pathConfig != null) && (pathConfig.getString("formatting." + eventType, null) != null)) { return pathConfig.getString("formatting." + eventType, null); } else { return this.cDefaultFormatting(eventType, msg); } } public String cDefaultFormatting(String eventType, RelayedMessage msg) { if (msg.getSource().getType() == EndPoint.Type.MINECRAFT) { return this.configuration.getString("settings.formatting.from-game." + eventType); } if (msg.getSource().getType() == EndPoint.Type.IRC) { return this.configuration.getString("settings.formatting.from-irc." + eventType); } if (msg.getSource().getType() == EndPoint.Type.PLAIN) { return this.configuration.getString("settings.formatting.from-plain." + eventType); } return ""; } public String cColorIrcFromGame(String game) { ConfigurationNode color; final Iterator<ConfigurationNode> it = this.colormap.iterator(); while (it.hasNext()) { color = it.next(); if (color.getString("game").equals(game)) { //Forces sending two digit colour codes. return (color.getString("irc").length() == 1 ? "0" : "") + color.getString("irc", this.cColorIrcFromName("foreground")); } } return this.cColorIrcFromName("foreground"); } public String cColorIrcFromName(String name) { ConfigurationNode color; final Iterator<ConfigurationNode> it = this.colormap.iterator(); while (it.hasNext()) { color = it.next(); if (color.getString("name").equalsIgnoreCase(name) && (color.getProperty("irc") != null)) { return color.getString("irc", "01"); } } if (name.equalsIgnoreCase("foreground")) { return "01"; } else { return this.cColorIrcFromName("foreground"); } } public String cColorGameFromIrc(String irc) { //Always convert to two digits. if (irc.length() == 1) irc = "0"+irc; ConfigurationNode color; final Iterator<ConfigurationNode> it = this.colormap.iterator(); while (it.hasNext()) { color = it.next(); //Enforce two digit comparisons. if (color.getString("irc", "").equals(irc) || "0".concat(color.getString("irc", "")).equals(irc)) { return color.getString("game", this.cColorGameFromName("foreground")); } } return this.cColorGameFromName("foreground"); } public String cColorGameFromName(String name) { ConfigurationNode color; final Iterator<ConfigurationNode> it = this.colormap.iterator(); while (it.hasNext()) { color = it.next(); if (color.getString("name").equalsIgnoreCase(name) && (color.getProperty("game") != null)) { return color.getString("game", "\u00C2\u00A7f"); } } if (name.equalsIgnoreCase("foreground")) { return "\u00C2\u00A7f"; } else { return this.cColorGameFromName("foreground"); } } public String cBindLocalAddr() { return this.configuration.getString("settings.bind-address", ""); } public int cRetryDelay() { return this.configuration.getInt("settings.retry-delay", 10) * 1000; } public String cBotNickname(int bot) { return this.bots.get(bot).getString("nickname", "CraftIRCbot"); } public String cBotServer(int bot) { return this.bots.get(bot).getString("server", "irc.esper.net"); } public int cBotPort(int bot) { return this.bots.get(bot).getInt("port", 6667); } public int cBotBindPort(int bot) { return this.bots.get(bot).getInt("bind-port", 0); } public String cBotLogin(int bot) { return this.bots.get(bot).getString("userident", ""); } public String cBotPassword(int bot) { return this.bots.get(bot).getString("serverpass", ""); } public boolean cBotSsl(int bot) { return this.bots.get(bot).getBoolean("ssl", false); } public int cBotMessageDelay(int bot) { return this.bots.get(bot).getInt("message-delay", 1000); } public int cBotQueueSize(int bot) { return this.bots.get(bot).getInt("queue-size", 5); } public String cCommandPrefix(int bot) { return this.bots.get(bot).getString("command-prefix", this.configuration.getString("settings.command-prefix", ".")); } public List<String> cCmdWordCmd(Integer bot) { final List<String> init = new ArrayList<String>(); init.add("cmd"); final List<String> result = this.configuration.getStringList("settings.irc-commands.cmd", init); if (bot != null) { return this.bots.get(bot).getStringList("irc-commands.cmd", result); } return result; } public List<String> cCmdWordSay(Integer bot) { final List<String> init = new ArrayList<String>(); init.add("say"); final List<String> result = this.configuration.getStringList("settings.irc-commands.say", init); if (bot != null) { return this.bots.get(bot).getStringList("irc-commands.say", result); } return result; } public List<String> cCmdWordPlayers(Integer bot) { final List<String> init = new ArrayList<String>(); init.add("players"); final List<String> result = this.configuration.getStringList("settings.irc-commands.players", init); if (bot != null) { return this.bots.get(bot).getStringList("irc-commands.players", result); } return result; } public ArrayList<String> cBotAdminPrefixes(int bot) { return new ArrayList<String>(this.bots.get(bot).getStringList("admin-prefixes", null)); } public ArrayList<String> cBotIgnoredUsers(int bot) { return new ArrayList<String>(this.bots.get(bot).getStringList("ignored-users", null)); } public String cBotAuthMethod(int bot) { return this.bots.get(bot).getString("auth.method", "nickserv"); } public String cBotAuthUsername(int bot) { return this.bots.get(bot).getString("auth.username", ""); } public String cBotAuthPassword(int bot) { return this.bots.get(bot).getString("auth.password", ""); } public ArrayList<String> cBotOnConnect(int bot) { return new ArrayList<String>(this.bots.get(bot).getStringList("on-connect", null)); } public String cChanName(int bot, String channel) { return this.getChanNode(bot, channel).getString("name", "#changeme"); } public String cChanTag(int bot, String channel) { return this.getChanNode(bot, channel).getString("tag", String.valueOf(bot) + "_" + channel); } public String cChanPassword(int bot, String channel) { return this.getChanNode(bot, channel).getString("password", ""); } public ArrayList<String> cChanOnJoin(int bot, String channel) { return new ArrayList<String>(this.getChanNode(bot, channel).getStringList("on-join", null)); } public List<String> cPathsFrom(String source) { final List<String> results = new LinkedList<String>(); for (final Path path : this.paths.keySet()) { if (!path.getSourceTag().equals(source)) { continue; } if (this.paths.get(path).getBoolean("disable", false)) { continue; } results.add(path.getTargetTag()); } return results; } List<String> cPathsTo(String target) { final List<String> results = new LinkedList<String>(); for (final Path path : this.paths.keySet()) { if (!path.getTargetTag().equals(target)) { continue; } if (this.paths.get(path).getBoolean("disable", false)) { continue; } results.add(path.getSourceTag()); } return results; } public boolean cPathExists(String source, String target) { final ConfigurationNode pathNode = this.getPathNode(source, target); return (pathNode != null) && !pathNode.getBoolean("disabled", false); } public boolean cPathAttribute(String source, String target, String attribute) { final ConfigurationNode node = this.getPathNode(source, target); if (node.getProperty(attribute) != null) { return node.getBoolean(attribute, false); } else { return this.configuration.getNode("default-attributes").getBoolean(attribute, false); } } public List<ConfigurationNode> cPathFilters(String source, String target) { return this.getPathNode(source, target).getNodeList("filters", new ArrayList<ConfigurationNode>()); } public Map<String, Map<String, String>> cReplaceFilters() { return this.replaceFilters; } void loadTagGroups() { final List<String> groups = this.configuration.getKeys("settings.tag-groups"); if (groups == null) { return; } for (final String group : groups) { for (final String tag : this.configuration.getStringList("settings.tag-groups." + group, new ArrayList<String>())) { this.groupTag(tag, group); } } } boolean cUseMapAsWhitelist(int bot) { return this.bots.get(bot).getBoolean("use-map-as-whitelist", false); } public String cIrcDisplayName(int bot, String nickname) { return this.bots.get(bot).getString("irc-nickname-map." + nickname, nickname); } public boolean cNicknameIsInIrcMap(int bot, String nickname) { return this.bots.get(bot).getString("irc-nickname-map." + nickname) != null; } public enum HoldType { CHAT, JOINS, QUITS, KICKS, BANS, DEATHS } class RemoveHoldTask extends TimerTask { private final CraftIRC plugin; private final HoldType ht; protected RemoveHoldTask(CraftIRC plugin, HoldType ht) { super(); this.plugin = plugin; this.ht = ht; } @Override public void run() { this.plugin.hold.put(this.ht, false); } } public boolean isHeld(HoldType ht) { return this.hold.get(ht); } public List<ConfigurationNode> getColorMap() { return this.colormap; } public String processAntiHighlight(String input) { String delimiter = this.configuration.getString("settings.anti-highlight"); if (delimiter != null && !delimiter.isEmpty()) { StringBuilder builder = new StringBuilder(); for (int i=0; i < input.length(); i++) { char c = input.charAt(i); builder.append(c); if (c != '\u00A7') { builder.append(delimiter); } } return builder.toString(); } else { return input; } } }
true
true
public void onEnable() { try { //Checking if the configuration file exists and imports the default one from the .jar if it doesn't final File configFile = new File(this.getDataFolder(), "config.yml"); if (!configFile.exists()) { this.saveDefaultConfig(); this.autoDisable(); return; } this.configuration = new Configuration(configFile); this.configuration.load(); this.cancelChat = this.configuration.getBoolean("settings.cancel-chat", false); this.endpoints = new HashMap<String, EndPoint>(); this.tags = new HashMap<EndPoint, String>(); this.irccmds = new HashMap<String, CommandEndPoint>(); this.taggroups = new HashMap<String, List<String>>(); final PluginDescriptionFile desc = this.getDescription(); CraftIRC.VERSION = desc.getVersion(); this.server = this.getServer(); this.bots = new ArrayList<ConfigurationNode>(this.configuration.getNodeList("bots", null)); this.channodes = new HashMap<Integer, ArrayList<ConfigurationNode>>(); for (int botID = 0; botID < this.bots.size(); botID++) { this.channodes.put(botID, new ArrayList<ConfigurationNode>(this.bots.get(botID).getNodeList("channels", null))); } this.colormap = new ArrayList<ConfigurationNode>(this.configuration.getNodeList("colormap", null)); this.paths = new HashMap<Path, ConfigurationNode>(); for (final ConfigurationNode path : this.configuration.getNodeList("paths", new LinkedList<ConfigurationNode>())) { final Path identifier = new Path(path.getString("source"), path.getString("target")); if (!identifier.getSourceTag().equals(identifier.getTargetTag()) && !this.paths.containsKey(identifier)) { this.paths.put(identifier, path); } } //Replace filters this.replaceFilters = new HashMap<String, Map<String, String>>(); try { for (String key : this.configuration.getNode("filters").getKeys()) { //Map key to regex pattern, value to replacement. Map<String, String> replaceMap = new HashMap<String, String>(); this.replaceFilters.put(key, replaceMap); for (ConfigurationNode fieldNode : this.configuration.getNodeList("filters." + key, null)) { Map<String, Object> patterns = fieldNode.getAll(); if (patterns != null) for (String pattern : patterns.keySet()) replaceMap.put(pattern, patterns.get(pattern).toString()); } //Also supports non-map entries. for (String unMappedEntry : this.configuration.getStringList("filters." + key, null)) if (unMappedEntry.length() > 0 && unMappedEntry.charAt(0) != '{') //mapped toString() begins with {, but regex can't begin with {. replaceMap.put(unMappedEntry, ""); } } catch (NullPointerException e) { } //Retry timers this.retry = new HashMap<String, RetryTask>(); this.retryTimer = new Timer(); //Event listeners this.getServer().getPluginManager().registerEvents(this.listener, this); this.getServer().getPluginManager().registerEvents(this.sayListener, this); //Native endpoints! if ((this.cMinecraftTag() != null) && !this.cMinecraftTag().equals("")) { this.registerEndPoint(this.cMinecraftTag(), new MinecraftPoint(this, this.getServer())); //The minecraft server, no bells and whistles for (final String cmd : this.cCmdWordSay(null)) { this.registerCommand(this.cMinecraftTag(), cmd); } for (final String cmd : this.cCmdWordPlayers(null)) { this.registerCommand(this.cMinecraftTag(), cmd); } if (!this.cMinecraftTagGroup().equals("")) { this.groupTag(this.cMinecraftTag(), this.cMinecraftTagGroup()); } } if ((this.cCancelledTag() != null) && !this.cCancelledTag().equals("")) { this.registerEndPoint(this.cCancelledTag(), new MinecraftPoint(this, this.getServer())); //Handles cancelled chat if (!this.cMinecraftTagGroup().equals("")) { this.groupTag(this.cCancelledTag(), this.cMinecraftTagGroup()); } } if ((this.cConsoleTag() != null) && !this.cConsoleTag().equals("")) { this.registerEndPoint(this.cConsoleTag(), new ConsolePoint(this, this.getServer())); //The minecraft console for (final String cmd : this.cCmdWordCmd(null)) { this.registerCommand(this.cConsoleTag(), cmd); } if (!this.cMinecraftTagGroup().equals("")) { this.groupTag(this.cConsoleTag(), this.cMinecraftTagGroup()); } } //Create bots this.instances = new ArrayList<Minebot>(); for (int i = 0; i < this.bots.size(); i++) { this.instances.add(new Minebot(this, i, this.cDebug())); } this.loadTagGroups(); CraftIRC.dolog("Enabled."); //Hold timers this.hold = new HashMap<HoldType, Boolean>(); this.holdTimer = new Timer(); if (this.cHold("chat") > 0) { this.hold.put(HoldType.CHAT, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.CHAT), this.cHold("chat")); } else { this.hold.put(HoldType.CHAT, false); } if (this.cHold("joins") > 0) { this.hold.put(HoldType.JOINS, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.JOINS), this.cHold("joins")); } else { this.hold.put(HoldType.JOINS, false); } if (this.cHold("quits") > 0) { this.hold.put(HoldType.QUITS, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.QUITS), this.cHold("quits")); } else { this.hold.put(HoldType.QUITS, false); } if (this.cHold("kicks") > 0) { this.hold.put(HoldType.KICKS, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.KICKS), this.cHold("kicks")); } else { this.hold.put(HoldType.KICKS, false); } if (this.cHold("bans") > 0) { this.hold.put(HoldType.BANS, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.BANS), this.cHold("bans")); } else { this.hold.put(HoldType.BANS, false); } if (this.cHold("deaths") > 0) { this.hold.put(HoldType.DEATHS, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.DEATHS), this.cHold("deaths")); } else { this.hold.put(HoldType.DEATHS, false); } this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { @Override public void run() { if (CraftIRC.this.getServer().getPluginManager().isPluginEnabled("Vault")) { try { CraftIRC.this.vault = CraftIRC.this.getServer().getServicesManager().getRegistration(Chat.class).getProvider(); } catch (final Exception e) { } } } }); this.setDebug(this.cDebug()); } catch (final Exception e) { e.printStackTrace(); } try { new Metrics(this).start(); } catch (final IOException e) { //Meh. } } private void autoDisable() { CraftIRC.dolog("Auto-disabling..."); this.getServer().getPluginManager().disablePlugin(this); } @Override public void onDisable() { try { this.retryTimer.cancel(); this.holdTimer.cancel(); //Disconnect bots if (this.bots != null) { for (int i = 0; i < this.bots.size(); i++) { this.instances.get(i).disconnect(); this.instances.get(i).dispose(); } } CraftIRC.dolog("Disabled."); } catch (final Exception e) { e.printStackTrace(); } } /*************************** * Minecraft command handling ***************************/ @Override public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { final String commandName = command.getName().toLowerCase(); try { if (commandName.equals("ircsay")){ if (!sender.hasPermission("craftirc." + commandName)) { return false; } return this.cmdMsgSay(sender,args); } if (commandName.equals("ircmsg")) { if (!sender.hasPermission("craftirc." + commandName)) { return false; } return this.cmdMsgToTag(sender, args); } else if (commandName.equals("ircmsguser")) { if (!sender.hasPermission("craftirc." + commandName)) { return false; } return this.cmdMsgToUser(sender, args); } else if (commandName.equals("ircusers")) { if (!sender.hasPermission("craftirc." + commandName)) { return false; } return this.cmdGetUserList(sender, args); } else if (commandName.equals("admins!")) { if (!sender.hasPermission("craftirc.admins")) { return false; } return this.cmdNotifyIrcAdmins(sender, args); } else if (commandName.equals("ircraw")) { if (!sender.hasPermission("craftirc." + commandName)) { return false; } return this.cmdRawIrcCommand(sender, args); } else if (commandName.equals("ircreload")) { if (!sender.hasPermission("craftirc." + commandName)) { return false; } this.getServer().getPluginManager().disablePlugin(this); this.getServer().getPluginManager().enablePlugin(this); return true; } else { return false; } } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdMsgSay(CommandSender sender, String[] args) { try{ RelayedMessage msg = this.newMsg(this.getEndPoint(this.cMinecraftTag()), null, "chat"); if (msg == null) { return true; } String senderName=sender.getName(); String world=""; String prefix=""; String suffix=""; if(sender instanceof Player){ Player player = (Player) sender; senderName = player.getDisplayName(); world = player.getWorld().getName(); prefix = this.getPrefix(player); suffix = this.getSuffix(player); } msg.setField("sender", senderName); msg.setField("message", Util.combineSplit(0, args, " ")); msg.setField("world", world); msg.setField("realSender", sender.getName()); msg.setField("prefix", prefix); msg.setField("suffix", suffix); msg.doNotColor("message"); msg.post(); return true; } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdMsgToTag(CommandSender sender, String[] args) { try { if (this.isDebug()) { CraftIRC.dolog("CraftIRCListener cmdMsgToAll()"); } if (args.length < 2) { return false; } final String msgToSend = Util.combineSplit(1, args, " "); final RelayedMessage msg = this.newMsg(this.getEndPoint(this.cMinecraftTag()), this.getEndPoint(args[0]), "chat"); if (msg == null) { return true; } if (sender instanceof Player) { msg.setField("sender", ((Player) sender).getDisplayName()); } else { msg.setField("sender", sender.getName()); } msg.setField("message", msgToSend); msg.doNotColor("message"); msg.post(); sender.sendMessage("Message sent."); return true; } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdMsgToUser(CommandSender sender, String[] args) { try { if (args.length < 3) { return false; } final String msgToSend = Util.combineSplit(2, args, " "); final RelayedMessage msg = this.newMsg(this.getEndPoint(this.cMinecraftTag()), this.getEndPoint(args[0]), "private"); if (msg == null) { return true; } if (sender instanceof Player) { msg.setField("sender", ((Player) sender).getDisplayName()); } else { msg.setField("sender", sender.getName()); }; msg.setField("message", msgToSend); msg.doNotColor("message"); boolean sameEndPoint = this.getEndPoint(this.cMinecraftTag()).equals(this.getEndPoint(args[0])); //Don't actually deliver the message if the user is invisible to the sender. if (sameEndPoint && sender instanceof Player) { Player recipient = getServer().getPlayer(args[1]); if (recipient != null && recipient.isOnline() && ((Player)sender).canSee(recipient)) msg.postToUser(args[1]); } else msg.postToUser(args[1]); sender.sendMessage("Message sent."); return true; } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdGetUserList(CommandSender sender, String[] args) { try { if (args.length == 0) { return false; } sender.sendMessage("Users in " + args[0] + ":"); final List<String> userlists = this.ircUserLists(args[0]); for (final String string : userlists) { sender.sendMessage(string); } return true; } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdNotifyIrcAdmins(CommandSender sender, String[] args) { try { if (this.isDebug()) { CraftIRC.dolog("CraftIRCListener cmdNotifyIrcAdmins()"); } if ((args.length == 0) || !(sender instanceof Player)) { if (this.isDebug()) { CraftIRC.dolog("CraftIRCListener cmdNotifyIrcAdmins() - args.length == 0 or Sender != player "); } return false; } final RelayedMessage msg = this.newMsg(this.getEndPoint(this.cMinecraftTag()), null, "admin"); if (msg == null) { return true; } msg.setField("sender", ((Player) sender).getDisplayName()); msg.setField("message", Util.combineSplit(0, args, " ")); msg.setField("world", ((Player) sender).getWorld().getName()); msg.doNotColor("message"); msg.post(true); sender.sendMessage("Admin notice sent."); return true; } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdRawIrcCommand(CommandSender sender, String[] args) { try { if (this.isDebug()) { CraftIRC.dolog("cmdRawIrcCommand(sender=" + sender.toString() + ", args=" + Util.combineSplit(0, args, " ")); } if (args.length < 2) { return false; } this.sendRawToBot(Util.combineSplit(1, args, " "), Integer.parseInt(args[0])); return true; } catch (final Exception e) { e.printStackTrace(); return false; } } /*************************** * Endpoint and message interface (to be used by CraftIRC and external plugins) ***************************/ /** * Null target: Sends message through all possible paths. * * @param source * @param target * @param eventType * @return */ public RelayedMessage newMsg(EndPoint source, EndPoint target, String eventType) { if (source == null) { return null; } if ((target == null) || this.cPathExists(this.getTag(source), this.getTag(target))) { return new RelayedMessage(this, source, target, eventType); } else { if (this.isDebug()) { CraftIRC.dolog("Failed to prepare message: " + this.getTag(source) + " -> " + this.getTag(target) + " (missing path)"); } return null; } } public RelayedMessage newMsgToTag(EndPoint source, String target, String eventType) { if (source == null) { return null; } EndPoint targetpoint = null; if (target != null) { if (this.cPathExists(this.getTag(source), target)) { targetpoint = this.getEndPoint(target); if (targetpoint == null) { CraftIRC.dolog("The requested target tag '" + target + "' isn't registered."); } } else { return null; } } return new RelayedMessage(this, source, targetpoint, eventType); } public RelayedCommand newCmd(EndPoint source, String command) { if (source == null) { return null; } final CommandEndPoint target = this.irccmds.get(command); if (target == null) { return null; } if (!this.cPathExists(this.getTag(source), this.getTag(target))) { return null; } final RelayedCommand cmd = new RelayedCommand(this, source, target); cmd.setField("command", command); return cmd; } public boolean registerEndPoint(String tag, EndPoint ep) { if (this.isDebug()) { CraftIRC.dolog("Registering endpoint: " + tag); } if (tag == null) { CraftIRC.dolog("Failed to register endpoint - No tag!"); } if ((this.endpoints.get(tag) != null) || (this.tags.get(ep) != null)) { CraftIRC.dolog("Couldn't register an endpoint tagged '" + tag + "' because either the tag or the endpoint already exist."); return false; } if (tag == "*") { CraftIRC.dolog("Couldn't register an endpoint - the character * can't be used as a tag."); return false; } this.endpoints.put(tag, ep); this.tags.put(ep, tag); return true; } public boolean endPointRegistered(String tag) { return this.endpoints.get(tag) != null; } public EndPoint getEndPoint(String tag) { return this.endpoints.get(tag); } public String getTag(EndPoint ep) { return this.tags.get(ep); } public boolean registerCommand(String tag, String command) { if (this.isDebug()) { CraftIRC.dolog("Registering command: " + command + " to endpoint:" + tag); } final EndPoint ep = this.getEndPoint(tag); if (ep == null) { CraftIRC.dolog("Couldn't register the command '" + command + "' at the endpoint tagged '" + tag + "' because there is no such tag."); return false; } if (!(ep instanceof CommandEndPoint)) { CraftIRC.dolog("Couldn't register the command '" + command + "' at the endpoint tagged '" + tag + "' because it's not capable of handling commands."); return false; } if (this.irccmds.containsKey(command)) { CraftIRC.dolog("Couldn't register the command '" + command + "' at the endpoint tagged '" + tag + "' because that command is already registered."); return false; } this.irccmds.put(command, (CommandEndPoint) ep); return true; } public boolean unregisterCommand(String command) { if (!this.irccmds.containsKey(command)) { return false; } this.irccmds.remove(command); return true; } public boolean unregisterEndPoint(String tag) { final EndPoint ep = this.getEndPoint(tag); if (ep == null) { return false; } this.endpoints.remove(tag); this.tags.remove(ep); this.ungroupTag(tag); if (ep instanceof CommandEndPoint) { final CommandEndPoint cep = (CommandEndPoint) ep; for (final String cmd : this.irccmds.keySet()) { if (this.irccmds.get(cmd) == cep) { this.irccmds.remove(cmd); } } } return true; } public boolean groupTag(String tag, String group) { if (this.getEndPoint(tag) == null) { return false; } List<String> tags = this.taggroups.get(group); if (tags == null) { tags = new ArrayList<String>(); this.taggroups.put(group, tags); } tags.add(tag); return true; } public void ungroupTag(String tag) { for (final String group : this.taggroups.keySet()) { this.taggroups.get(group).remove(tag); } } public void clearGroup(String group) { this.taggroups.remove(group); } public boolean checkTagsGrouped(String tagA, String tagB) { for (final String group : this.taggroups.keySet()) { if (this.taggroups.get(group).contains(tagA) && this.taggroups.get(group).contains(tagB)) { return true; } } return false; } /*************************** * Heart of the beast! Unified method with no special cases that replaces the old sendMessage ***************************/ boolean delivery(RelayedMessage msg) { return this.delivery(msg, null, null, RelayedMessage.DeliveryMethod.STANDARD); } boolean delivery(RelayedMessage msg, List<EndPoint> destinations) { return this.delivery(msg, destinations, null, RelayedMessage.DeliveryMethod.STANDARD); } boolean delivery(RelayedMessage msg, List<EndPoint> knownDestinations, String username) { return this.delivery(msg, knownDestinations, username, RelayedMessage.DeliveryMethod.STANDARD); } /** * Only successful if all known targets (or if there is none at least one possible target) are successful! * * @param msg * @param knownDestinations * @param username * @param dm * @return */ boolean delivery(RelayedMessage msg, List<EndPoint> knownDestinations, String username, RelayedMessage.DeliveryMethod dm) { final String sourceTag = this.getTag(msg.getSource()); msg.setField("source", sourceTag); List<EndPoint> destinations; if (this.isDebug()) { CraftIRC.dolog("X->" + (knownDestinations.size() > 0 ? knownDestinations.toString() : "*") + ": " + msg.toString()); } //If we weren't explicitly given a recipient for the message, let's try to find one (or more) if (knownDestinations.size() < 1) { //Use all possible destinations (auto-targets) destinations = new LinkedList<EndPoint>(); for (final String targetTag : this.cPathsFrom(sourceTag)) { final EndPoint ep = this.getEndPoint(targetTag); if (ep == null) { continue; } if ((ep instanceof SecuredEndPoint) && SecuredEndPoint.Security.REQUIRE_TARGET.equals(((SecuredEndPoint) ep).getSecurity())) { continue; } if (!this.cPathAttribute(sourceTag, targetTag, "attributes." + msg.getEvent())) { continue; } if ((dm == RelayedMessage.DeliveryMethod.ADMINS) && !this.cPathAttribute(sourceTag, targetTag, "attributes.admin")) { continue; } destinations.add(ep); } //Default paths to unsecured destinations (auto-paths) if (this.cAutoPaths()) { for (final EndPoint ep : this.endpoints.values()) { if (ep == null) { continue; } if (msg.getSource().equals(ep) || destinations.contains(ep)) { continue; } if ((ep instanceof SecuredEndPoint) && !SecuredEndPoint.Security.UNSECURED.equals(((SecuredEndPoint) ep).getSecurity())) { continue; } final String targetTag = this.getTag(ep); if (this.checkTagsGrouped(sourceTag, targetTag)) { continue; } if (!this.cPathAttribute(sourceTag, targetTag, "attributes." + msg.getEvent())) { continue; } if ((dm == RelayedMessage.DeliveryMethod.ADMINS) && !this.cPathAttribute(sourceTag, targetTag, "attributes.admin")) { continue; } if (this.cPathAttribute(sourceTag, targetTag, "disabled")) { continue; } destinations.add(ep); } } } else { destinations = new LinkedList<EndPoint>(knownDestinations); } if (destinations.size() < 1) { return false; } //Deliver the message boolean success = true; for (final EndPoint destination : destinations) { final String targetTag = this.getTag(destination); if(targetTag.equals(this.cCancelledTag())){ continue; } msg.setField("target", targetTag); //Check against path filters if ((msg instanceof RelayedCommand) && this.matchesFilter(msg, this.cPathFilters(sourceTag, targetTag))) { if (knownDestinations != null) { success = false; } continue; } //Finally deliver! if (this.isDebug()) { CraftIRC.dolog("-->X: " + msg.toString()); } if (username != null) { success = success && destination.userMessageIn(username, msg); } else if (dm == RelayedMessage.DeliveryMethod.ADMINS) { success = destination.adminMessageIn(msg); } else if (dm == RelayedMessage.DeliveryMethod.COMMAND) { if (!(destination instanceof CommandEndPoint)) { continue; } ((CommandEndPoint) destination).commandIn((RelayedCommand) msg); } else { destination.messageIn(msg); } } return success; } boolean matchesFilter(RelayedMessage msg, List<ConfigurationNode> filters) { if (filters == null) { return false; } newFilter: for (final ConfigurationNode filter : filters) { for (final String key : filter.getKeys()) { final Pattern condition = Pattern.compile(filter.getString(key, "")); if (condition == null) { continue newFilter; } final String subject = msg.getField(key); if (subject == null) { continue newFilter; } final Matcher check = condition.matcher(subject); if (!check.find()) { continue newFilter; } } return true; } return false; } /*************************** * Auxiliary methods ***************************/ public Minebot getBot(int bot){ return this.instances.get(bot); } public void sendRawToBot(String rawMessage, int bot) { if (this.isDebug()) { CraftIRC.dolog("sendRawToBot(bot=" + bot + ", message=" + rawMessage); } final Minebot targetBot = this.instances.get(bot); targetBot.sendRawLineViaQueue(rawMessage); } public void sendMsgToTargetViaBot(String message, String target, int bot) { final Minebot targetBot = this.instances.get(bot); targetBot.sendMessage(target, message); } public List<String> ircUserLists(String tag) { return this.getEndPoint(tag).listDisplayUsers(); } void setDebug(boolean d) { this.debug = d; for (int i = 0; i < this.bots.size(); i++) { this.instances.get(i).setVerbose(d); } CraftIRC.dolog("DEBUG [" + (d ? "ON" : "OFF") + "]"); } public String getPrefix(Player p) { String result = ""; if (this.vault != null) { try { result = this.vault.getPlayerPrefix(p); } catch (final Exception e) { } } return result; } public String getSuffix(Player p) { String result = ""; if (this.vault != null) { try { result = this.vault.getPlayerSuffix(p); } catch (final Exception e) { } } return result; } public boolean isDebug() { return this.debug; } boolean checkPerms(Player pl, String path) { return pl.hasPermission(path); } boolean checkPerms(String pl, String path) { final Player pit = this.getServer().getPlayer(pl); if (pit != null) { return pit.hasPermission(path); } return false; } // TODO: Make sure this works public String colorizeName(String name) { final Pattern color_codes = Pattern.compile(ChatColor.COLOR_CHAR + "[0-9a-f]"); Matcher find_colors = color_codes.matcher(name); while (find_colors.find()) { name = find_colors.replaceFirst(Character.toString((char) 3) + this.cColorIrcFromGame(find_colors.group())); find_colors = color_codes.matcher(name); } return name; } protected void enqueueConsoleCommand(String cmd) { try { this.getServer().dispatchCommand(this.getServer().getConsoleSender(), cmd); } catch (final Exception e) { e.printStackTrace(); } } /** * If the channel is null it's a reconnect, otherwise a rejoin * * @param bot * @param channel */ void scheduleForRetry(Minebot bot, String channel) { this.retryTimer.schedule(new RetryTask(this, bot, channel), this.cRetryDelay()); } /*************************** * Read stuff from config ***************************/ private ConfigurationNode getChanNode(int bot, String channel) { final ArrayList<ConfigurationNode> botChans = this.channodes.get(bot); for (final ConfigurationNode chan : botChans) { if (chan.getString("name").equalsIgnoreCase(channel)) { return chan; } } return Configuration.getEmptyNode(); } public List<ConfigurationNode> cChannels(int bot) { return this.channodes.get(bot); } private ConfigurationNode getPathNode(String source, String target) { ConfigurationNode result = this.paths.get(new Path(source, target)); if (result == null) { return this.configuration.getNode("default-attributes"); } ConfigurationNode basepath; if (result.getKeys().contains("base") && ((basepath = result.getNode("base")) != null)) { final ConfigurationNode basenode = this.paths.get(new Path(basepath.getString("source", ""), basepath.getString("target", ""))); if (basenode != null) { result = basenode; } } return result; } public String cMinecraftTag() { return this.configuration.getString("settings.minecraft-tag", "minecraft"); } public String cCancelledTag() { return this.configuration.getString("settings.cancelled-tag", "cancelled"); } public String cConsoleTag() { return this.configuration.getString("settings.console-tag", "console"); } public String cMinecraftTagGroup() { return this.configuration.getString("settings.minecraft-group-name", "minecraft"); } public String cIrcTagGroup() { return this.configuration.getString("settings.irc-group-name", "irc"); } public boolean cAutoPaths() { return this.configuration.getBoolean("settings.auto-paths", false); } public boolean cCancelChat() { return cancelChat; } public boolean cDebug() { return this.configuration.getBoolean("settings.debug", false); } public ArrayList<String> cConsoleCommands() { return new ArrayList<String>(this.configuration.getStringList("settings.console-commands", null)); } public int cHold(String eventType) { return this.configuration.getInt("settings.hold-after-enable." + eventType, 0); } public String cFormatting(String eventType, RelayedMessage msg) { return this.cFormatting(eventType, msg, null); } public String cFormatting(String eventType, RelayedMessage msg, EndPoint realTarget) { final String source = this.getTag(msg.getSource()), target = this.getTag(realTarget != null ? realTarget : msg.getTarget()); if ((source == null) || (target == null)) { CraftIRC.dowarn("Attempted to obtain formatting for invalid path " + source + " -> " + target + " ."); return this.cDefaultFormatting(eventType, msg); } final ConfigurationNode pathConfig = this.paths.get(new Path(source, target)); if ((pathConfig != null) && (pathConfig.getString("formatting." + eventType, null) != null)) { return pathConfig.getString("formatting." + eventType, null); } else { return this.cDefaultFormatting(eventType, msg); } } public String cDefaultFormatting(String eventType, RelayedMessage msg) { if (msg.getSource().getType() == EndPoint.Type.MINECRAFT) { return this.configuration.getString("settings.formatting.from-game." + eventType); } if (msg.getSource().getType() == EndPoint.Type.IRC) { return this.configuration.getString("settings.formatting.from-irc." + eventType); } if (msg.getSource().getType() == EndPoint.Type.PLAIN) { return this.configuration.getString("settings.formatting.from-plain." + eventType); } return ""; } public String cColorIrcFromGame(String game) { ConfigurationNode color; final Iterator<ConfigurationNode> it = this.colormap.iterator(); while (it.hasNext()) { color = it.next(); if (color.getString("game").equals(game)) { //Forces sending two digit colour codes. return (color.getString("irc").length() == 1 ? "0" : "") + color.getString("irc", this.cColorIrcFromName("foreground")); } } return this.cColorIrcFromName("foreground"); } public String cColorIrcFromName(String name) { ConfigurationNode color; final Iterator<ConfigurationNode> it = this.colormap.iterator(); while (it.hasNext()) { color = it.next(); if (color.getString("name").equalsIgnoreCase(name) && (color.getProperty("irc") != null)) { return color.getString("irc", "01"); } } if (name.equalsIgnoreCase("foreground")) { return "01"; } else { return this.cColorIrcFromName("foreground"); } } public String cColorGameFromIrc(String irc) { //Always convert to two digits. if (irc.length() == 1) irc = "0"+irc; ConfigurationNode color; final Iterator<ConfigurationNode> it = this.colormap.iterator(); while (it.hasNext()) { color = it.next(); //Enforce two digit comparisons. if (color.getString("irc", "").equals(irc) || "0".concat(color.getString("irc", "")).equals(irc)) { return color.getString("game", this.cColorGameFromName("foreground")); } } return this.cColorGameFromName("foreground"); } public String cColorGameFromName(String name) { ConfigurationNode color; final Iterator<ConfigurationNode> it = this.colormap.iterator(); while (it.hasNext()) { color = it.next(); if (color.getString("name").equalsIgnoreCase(name) && (color.getProperty("game") != null)) { return color.getString("game", "\u00C2\u00A7f"); } } if (name.equalsIgnoreCase("foreground")) { return "\u00C2\u00A7f"; } else { return this.cColorGameFromName("foreground"); } } public String cBindLocalAddr() { return this.configuration.getString("settings.bind-address", ""); } public int cRetryDelay() { return this.configuration.getInt("settings.retry-delay", 10) * 1000; } public String cBotNickname(int bot) { return this.bots.get(bot).getString("nickname", "CraftIRCbot"); } public String cBotServer(int bot) { return this.bots.get(bot).getString("server", "irc.esper.net"); } public int cBotPort(int bot) { return this.bots.get(bot).getInt("port", 6667); } public int cBotBindPort(int bot) { return this.bots.get(bot).getInt("bind-port", 0); } public String cBotLogin(int bot) { return this.bots.get(bot).getString("userident", ""); } public String cBotPassword(int bot) { return this.bots.get(bot).getString("serverpass", ""); } public boolean cBotSsl(int bot) { return this.bots.get(bot).getBoolean("ssl", false); } public int cBotMessageDelay(int bot) { return this.bots.get(bot).getInt("message-delay", 1000); } public int cBotQueueSize(int bot) { return this.bots.get(bot).getInt("queue-size", 5); } public String cCommandPrefix(int bot) { return this.bots.get(bot).getString("command-prefix", this.configuration.getString("settings.command-prefix", ".")); } public List<String> cCmdWordCmd(Integer bot) { final List<String> init = new ArrayList<String>(); init.add("cmd"); final List<String> result = this.configuration.getStringList("settings.irc-commands.cmd", init); if (bot != null) { return this.bots.get(bot).getStringList("irc-commands.cmd", result); } return result; } public List<String> cCmdWordSay(Integer bot) { final List<String> init = new ArrayList<String>(); init.add("say"); final List<String> result = this.configuration.getStringList("settings.irc-commands.say", init); if (bot != null) { return this.bots.get(bot).getStringList("irc-commands.say", result); } return result; } public List<String> cCmdWordPlayers(Integer bot) { final List<String> init = new ArrayList<String>(); init.add("players"); final List<String> result = this.configuration.getStringList("settings.irc-commands.players", init); if (bot != null) { return this.bots.get(bot).getStringList("irc-commands.players", result); } return result; } public ArrayList<String> cBotAdminPrefixes(int bot) { return new ArrayList<String>(this.bots.get(bot).getStringList("admin-prefixes", null)); } public ArrayList<String> cBotIgnoredUsers(int bot) { return new ArrayList<String>(this.bots.get(bot).getStringList("ignored-users", null)); } public String cBotAuthMethod(int bot) { return this.bots.get(bot).getString("auth.method", "nickserv"); } public String cBotAuthUsername(int bot) { return this.bots.get(bot).getString("auth.username", ""); } public String cBotAuthPassword(int bot) { return this.bots.get(bot).getString("auth.password", ""); } public ArrayList<String> cBotOnConnect(int bot) { return new ArrayList<String>(this.bots.get(bot).getStringList("on-connect", null)); } public String cChanName(int bot, String channel) { return this.getChanNode(bot, channel).getString("name", "#changeme"); } public String cChanTag(int bot, String channel) { return this.getChanNode(bot, channel).getString("tag", String.valueOf(bot) + "_" + channel); } public String cChanPassword(int bot, String channel) { return this.getChanNode(bot, channel).getString("password", ""); } public ArrayList<String> cChanOnJoin(int bot, String channel) { return new ArrayList<String>(this.getChanNode(bot, channel).getStringList("on-join", null)); } public List<String> cPathsFrom(String source) { final List<String> results = new LinkedList<String>(); for (final Path path : this.paths.keySet()) { if (!path.getSourceTag().equals(source)) { continue; } if (this.paths.get(path).getBoolean("disable", false)) { continue; } results.add(path.getTargetTag()); } return results; } List<String> cPathsTo(String target) { final List<String> results = new LinkedList<String>(); for (final Path path : this.paths.keySet()) { if (!path.getTargetTag().equals(target)) { continue; } if (this.paths.get(path).getBoolean("disable", false)) { continue; } results.add(path.getSourceTag()); } return results; } public boolean cPathExists(String source, String target) { final ConfigurationNode pathNode = this.getPathNode(source, target); return (pathNode != null) && !pathNode.getBoolean("disabled", false); } public boolean cPathAttribute(String source, String target, String attribute) { final ConfigurationNode node = this.getPathNode(source, target); if (node.getProperty(attribute) != null) { return node.getBoolean(attribute, false); } else { return this.configuration.getNode("default-attributes").getBoolean(attribute, false); } } public List<ConfigurationNode> cPathFilters(String source, String target) { return this.getPathNode(source, target).getNodeList("filters", new ArrayList<ConfigurationNode>()); } public Map<String, Map<String, String>> cReplaceFilters() { return this.replaceFilters; } void loadTagGroups() { final List<String> groups = this.configuration.getKeys("settings.tag-groups"); if (groups == null) { return; } for (final String group : groups) { for (final String tag : this.configuration.getStringList("settings.tag-groups." + group, new ArrayList<String>())) { this.groupTag(tag, group); } } } boolean cUseMapAsWhitelist(int bot) { return this.bots.get(bot).getBoolean("use-map-as-whitelist", false); } public String cIrcDisplayName(int bot, String nickname) { return this.bots.get(bot).getString("irc-nickname-map." + nickname, nickname); } public boolean cNicknameIsInIrcMap(int bot, String nickname) { return this.bots.get(bot).getString("irc-nickname-map." + nickname) != null; } public enum HoldType { CHAT, JOINS, QUITS, KICKS, BANS, DEATHS } class RemoveHoldTask extends TimerTask { private final CraftIRC plugin; private final HoldType ht; protected RemoveHoldTask(CraftIRC plugin, HoldType ht) { super(); this.plugin = plugin; this.ht = ht; } @Override public void run() { this.plugin.hold.put(this.ht, false); } } public boolean isHeld(HoldType ht) { return this.hold.get(ht); } public List<ConfigurationNode> getColorMap() { return this.colormap; } public String processAntiHighlight(String input) { String delimiter = this.configuration.getString("settings.anti-highlight"); if (delimiter != null && !delimiter.isEmpty()) { StringBuilder builder = new StringBuilder(); for (int i=0; i < input.length(); i++) { char c = input.charAt(i); builder.append(c); if (c != '\u00A7') { builder.append(delimiter); } } return builder.toString(); } else { return input; } } }
public void onEnable() { try { //Checking if the configuration file exists and imports the default one from the .jar if it doesn't final File configFile = new File(this.getDataFolder(), "config.yml"); if (!configFile.exists()) { this.saveDefaultConfig(); this.autoDisable(); return; } this.configuration = new Configuration(configFile); this.configuration.load(); this.cancelChat = this.configuration.getBoolean("settings.cancel-chat", false); this.endpoints = new HashMap<String, EndPoint>(); this.tags = new HashMap<EndPoint, String>(); this.irccmds = new HashMap<String, CommandEndPoint>(); this.taggroups = new HashMap<String, List<String>>(); final PluginDescriptionFile desc = this.getDescription(); CraftIRC.VERSION = desc.getVersion(); this.server = this.getServer(); this.bots = new ArrayList<ConfigurationNode>(this.configuration.getNodeList("bots", null)); this.channodes = new HashMap<Integer, ArrayList<ConfigurationNode>>(); for (int botID = 0; botID < this.bots.size(); botID++) { this.channodes.put(botID, new ArrayList<ConfigurationNode>(this.bots.get(botID).getNodeList("channels", null))); } this.colormap = new ArrayList<ConfigurationNode>(this.configuration.getNodeList("colormap", null)); this.paths = new HashMap<Path, ConfigurationNode>(); for (final ConfigurationNode path : this.configuration.getNodeList("paths", new LinkedList<ConfigurationNode>())) { final Path identifier = new Path(path.getString("source"), path.getString("target")); if (!identifier.getSourceTag().equals(identifier.getTargetTag()) && !this.paths.containsKey(identifier)) { this.paths.put(identifier, path); } } //Replace filters this.replaceFilters = new HashMap<String, Map<String, String>>(); try { for (String key : this.configuration.getNode("filters").getKeys()) { //Map key to regex pattern, value to replacement. Map<String, String> replaceMap = new HashMap<String, String>(); this.replaceFilters.put(key, replaceMap); for (ConfigurationNode fieldNode : this.configuration.getNodeList("filters." + key, null)) { Map<String, Object> patterns = fieldNode.getAll(); if (patterns != null) for (String pattern : patterns.keySet()) replaceMap.put(pattern, patterns.get(pattern).toString()); } //Also supports non-map entries. for (String unMappedEntry : this.configuration.getStringList("filters." + key, null)) if (unMappedEntry.length() > 0 && unMappedEntry.charAt(0) != '{') //mapped toString() begins with {, but regex can't begin with {. replaceMap.put(unMappedEntry, ""); } } catch (NullPointerException e) { } //Retry timers this.retry = new HashMap<String, RetryTask>(); this.retryTimer = new Timer(); //Event listeners this.getServer().getPluginManager().registerEvents(this.listener, this); this.getServer().getPluginManager().registerEvents(this.sayListener, this); //Native endpoints! if ((this.cMinecraftTag() != null) && !this.cMinecraftTag().equals("")) { this.registerEndPoint(this.cMinecraftTag(), new MinecraftPoint(this, this.getServer())); //The minecraft server, no bells and whistles for (final String cmd : this.cCmdWordSay(null)) { this.registerCommand(this.cMinecraftTag(), cmd); } for (final String cmd : this.cCmdWordPlayers(null)) { this.registerCommand(this.cMinecraftTag(), cmd); } if (!this.cMinecraftTagGroup().equals("")) { this.groupTag(this.cMinecraftTag(), this.cMinecraftTagGroup()); } } if ((this.cCancelledTag() != null) && !this.cCancelledTag().equals("")) { this.registerEndPoint(this.cCancelledTag(), new MinecraftPoint(this, this.getServer())); //Handles cancelled chat if (!this.cMinecraftTagGroup().equals("")) { this.groupTag(this.cCancelledTag(), this.cMinecraftTagGroup()); } } if ((this.cConsoleTag() != null) && !this.cConsoleTag().equals("")) { this.registerEndPoint(this.cConsoleTag(), new ConsolePoint(this, this.getServer())); //The minecraft console for (final String cmd : this.cCmdWordCmd(null)) { this.registerCommand(this.cConsoleTag(), cmd); } if (!this.cMinecraftTagGroup().equals("")) { this.groupTag(this.cConsoleTag(), this.cMinecraftTagGroup()); } } //Create bots this.instances = new ArrayList<Minebot>(); for (int i = 0; i < this.bots.size(); i++) { this.instances.add(new Minebot(this, i, this.cDebug())); } this.loadTagGroups(); CraftIRC.dolog("Enabled."); //Hold timers this.hold = new HashMap<HoldType, Boolean>(); this.holdTimer = new Timer(); if (this.cHold("chat") > 0) { this.hold.put(HoldType.CHAT, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.CHAT), this.cHold("chat")); } else { this.hold.put(HoldType.CHAT, false); } if (this.cHold("joins") > 0) { this.hold.put(HoldType.JOINS, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.JOINS), this.cHold("joins")); } else { this.hold.put(HoldType.JOINS, false); } if (this.cHold("quits") > 0) { this.hold.put(HoldType.QUITS, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.QUITS), this.cHold("quits")); } else { this.hold.put(HoldType.QUITS, false); } if (this.cHold("kicks") > 0) { this.hold.put(HoldType.KICKS, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.KICKS), this.cHold("kicks")); } else { this.hold.put(HoldType.KICKS, false); } if (this.cHold("bans") > 0) { this.hold.put(HoldType.BANS, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.BANS), this.cHold("bans")); } else { this.hold.put(HoldType.BANS, false); } if (this.cHold("deaths") > 0) { this.hold.put(HoldType.DEATHS, true); this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.DEATHS), this.cHold("deaths")); } else { this.hold.put(HoldType.DEATHS, false); } this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { @Override public void run() { if (CraftIRC.this.getServer().getPluginManager().isPluginEnabled("Vault")) { try { CraftIRC.this.vault = CraftIRC.this.getServer().getServicesManager().getRegistration(Chat.class).getProvider(); } catch (final Exception e) { } } } }); this.setDebug(this.cDebug()); } catch (final Exception e) { e.printStackTrace(); } try { new Metrics(this).start(); } catch (final IOException e) { //Meh. } } private void autoDisable() { CraftIRC.dolog("Auto-disabling..."); this.getServer().getPluginManager().disablePlugin(this); } @Override public void onDisable() { try { this.retryTimer.cancel(); this.holdTimer.cancel(); //Disconnect bots if (this.bots != null) { for (int i = 0; i < this.bots.size(); i++) { this.instances.get(i).disconnect(); this.instances.get(i).dispose(); } } CraftIRC.dolog("Disabled."); } catch (final Exception e) { e.printStackTrace(); } } /*************************** * Minecraft command handling ***************************/ @Override public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { final String commandName = command.getName().toLowerCase(); try { if (commandName.equals("ircsay")){ if (!sender.hasPermission("craftirc." + commandName)) { return false; } return this.cmdMsgSay(sender,args); } if (commandName.equals("ircmsg")) { if (!sender.hasPermission("craftirc." + commandName)) { return false; } return this.cmdMsgToTag(sender, args); } else if (commandName.equals("ircmsguser")) { if (!sender.hasPermission("craftirc." + commandName)) { return false; } return this.cmdMsgToUser(sender, args); } else if (commandName.equals("ircusers")) { if (!sender.hasPermission("craftirc." + commandName)) { return false; } return this.cmdGetUserList(sender, args); } else if (commandName.equals("admins!")) { if (!sender.hasPermission("craftirc.admins")) { return false; } return this.cmdNotifyIrcAdmins(sender, args); } else if (commandName.equals("ircraw")) { if (!sender.hasPermission("craftirc." + commandName)) { return false; } return this.cmdRawIrcCommand(sender, args); } else if (commandName.equals("ircreload")) { if (!sender.hasPermission("craftirc." + commandName)) { return false; } this.getServer().getPluginManager().disablePlugin(this); this.getServer().getPluginManager().enablePlugin(this); return true; } else { return false; } } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdMsgSay(CommandSender sender, String[] args) { try{ RelayedMessage msg = this.newMsg(this.getEndPoint(this.cMinecraftTag()), null, "chat"); if (msg == null) { return true; } String senderName=sender.getName(); String world=""; String prefix=""; String suffix=""; if(sender instanceof Player){ Player player = (Player) sender; senderName = player.getDisplayName(); world = player.getWorld().getName(); prefix = this.getPrefix(player); suffix = this.getSuffix(player); } msg.setField("sender", senderName); msg.setField("message", Util.combineSplit(0, args, " ")); msg.setField("world", world); msg.setField("realSender", sender.getName()); msg.setField("prefix", prefix); msg.setField("suffix", suffix); msg.doNotColor("message"); msg.post(); return true; } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdMsgToTag(CommandSender sender, String[] args) { try { if (this.isDebug()) { CraftIRC.dolog("CraftIRCListener cmdMsgToAll()"); } if (args.length < 2) { return false; } final String msgToSend = Util.combineSplit(1, args, " "); final RelayedMessage msg = this.newMsg(this.getEndPoint(this.cMinecraftTag()), this.getEndPoint(args[0]), "chat"); if (msg == null) { return true; } if (sender instanceof Player) { msg.setField("sender", ((Player) sender).getDisplayName()); } else { msg.setField("sender", sender.getName()); } msg.setField("message", msgToSend); msg.doNotColor("message"); msg.post(); sender.sendMessage("Message sent."); return true; } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdMsgToUser(CommandSender sender, String[] args) { try { if (args.length < 3) { return false; } final String msgToSend = Util.combineSplit(2, args, " "); final RelayedMessage msg = this.newMsg(this.getEndPoint(this.cMinecraftTag()), this.getEndPoint(args[0]), "private"); if (msg == null) { return true; } if (sender instanceof Player) { msg.setField("sender", ((Player) sender).getDisplayName()); } else { msg.setField("sender", sender.getName()); }; msg.setField("message", msgToSend); msg.doNotColor("message"); boolean sameEndPoint = this.getEndPoint(this.cMinecraftTag()).equals(this.getEndPoint(args[0])); //Don't actually deliver the message if the user is invisible to the sender. if (sameEndPoint && sender instanceof Player) { Player recipient = getServer().getPlayer(args[1]); if (recipient != null && recipient.isOnline() && ((Player)sender).canSee(recipient)) msg.postToUser(args[1]); } else msg.postToUser(args[1]); sender.sendMessage("Message sent."); return true; } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdGetUserList(CommandSender sender, String[] args) { try { if (args.length == 0) { return false; } sender.sendMessage("Users in " + args[0] + ":"); final List<String> userlists = this.ircUserLists(args[0]); for (final String string : userlists) { sender.sendMessage(string); } return true; } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdNotifyIrcAdmins(CommandSender sender, String[] args) { try { if (this.isDebug()) { CraftIRC.dolog("CraftIRCListener cmdNotifyIrcAdmins()"); } if ((args.length == 0) || !(sender instanceof Player)) { if (this.isDebug()) { CraftIRC.dolog("CraftIRCListener cmdNotifyIrcAdmins() - args.length == 0 or Sender != player "); } return false; } final RelayedMessage msg = this.newMsg(this.getEndPoint(this.cMinecraftTag()), null, "admin"); if (msg == null) { return true; } msg.setField("sender", ((Player) sender).getDisplayName()); msg.setField("message", Util.combineSplit(0, args, " ")); msg.setField("world", ((Player) sender).getWorld().getName()); msg.doNotColor("message"); msg.post(true); sender.sendMessage("Admin notice sent."); return true; } catch (final Exception e) { e.printStackTrace(); return false; } } private boolean cmdRawIrcCommand(CommandSender sender, String[] args) { try { if (this.isDebug()) { CraftIRC.dolog("cmdRawIrcCommand(sender=" + sender.toString() + ", args=" + Util.combineSplit(0, args, " ")); } if (args.length < 2) { return false; } this.sendRawToBot(Util.combineSplit(1, args, " "), Integer.parseInt(args[0])); return true; } catch (final Exception e) { e.printStackTrace(); return false; } } /*************************** * Endpoint and message interface (to be used by CraftIRC and external plugins) ***************************/ /** * Null target: Sends message through all possible paths. * * @param source * @param target * @param eventType * @return */ public RelayedMessage newMsg(EndPoint source, EndPoint target, String eventType) { if (source == null) { return null; } if ((target == null) || this.cPathExists(this.getTag(source), this.getTag(target))) { return new RelayedMessage(this, source, target, eventType); } else { if (this.isDebug()) { CraftIRC.dolog("Failed to prepare message: " + this.getTag(source) + " -> " + this.getTag(target) + " (missing path)"); } return null; } } public RelayedMessage newMsgToTag(EndPoint source, String target, String eventType) { if (source == null) { return null; } EndPoint targetpoint = null; if (target != null) { if (this.cPathExists(this.getTag(source), target)) { targetpoint = this.getEndPoint(target); if (targetpoint == null) { CraftIRC.dolog("The requested target tag '" + target + "' isn't registered."); } } else { return null; } } return new RelayedMessage(this, source, targetpoint, eventType); } public RelayedCommand newCmd(EndPoint source, String command) { if (source == null) { return null; } final CommandEndPoint target = this.irccmds.get(command); if (target == null) { return null; } if (!this.cPathExists(this.getTag(source), this.getTag(target))) { return null; } final RelayedCommand cmd = new RelayedCommand(this, source, target); cmd.setField("command", command); return cmd; } public boolean registerEndPoint(String tag, EndPoint ep) { if (this.isDebug()) { CraftIRC.dolog("Registering endpoint: " + tag); } if (tag == null) { CraftIRC.dolog("Failed to register endpoint - No tag!"); } if ((this.endpoints.get(tag) != null) || (this.tags.get(ep) != null)) { CraftIRC.dolog("Couldn't register an endpoint tagged '" + tag + "' because either the tag or the endpoint already exist."); return false; } if (tag == "*") { CraftIRC.dolog("Couldn't register an endpoint - the character * can't be used as a tag."); return false; } this.endpoints.put(tag, ep); this.tags.put(ep, tag); return true; } public boolean endPointRegistered(String tag) { return this.endpoints.get(tag) != null; } public EndPoint getEndPoint(String tag) { return this.endpoints.get(tag); } public String getTag(EndPoint ep) { return this.tags.get(ep); } public boolean registerCommand(String tag, String command) { if (this.isDebug()) { CraftIRC.dolog("Registering command: " + command + " to endpoint:" + tag); } final EndPoint ep = this.getEndPoint(tag); if (ep == null) { CraftIRC.dolog("Couldn't register the command '" + command + "' at the endpoint tagged '" + tag + "' because there is no such tag."); return false; } if (!(ep instanceof CommandEndPoint)) { CraftIRC.dolog("Couldn't register the command '" + command + "' at the endpoint tagged '" + tag + "' because it's not capable of handling commands."); return false; } if (this.irccmds.containsKey(command)) { CraftIRC.dolog("Couldn't register the command '" + command + "' at the endpoint tagged '" + tag + "' because that command is already registered."); return false; } this.irccmds.put(command, (CommandEndPoint) ep); return true; } public boolean unregisterCommand(String command) { if (!this.irccmds.containsKey(command)) { return false; } this.irccmds.remove(command); return true; } public boolean unregisterEndPoint(String tag) { final EndPoint ep = this.getEndPoint(tag); if (ep == null) { return false; } this.endpoints.remove(tag); this.tags.remove(ep); this.ungroupTag(tag); if (ep instanceof CommandEndPoint) { final CommandEndPoint cep = (CommandEndPoint) ep; for (final String cmd : this.irccmds.keySet()) { if (this.irccmds.get(cmd) == cep) { this.irccmds.remove(cmd); } } } return true; } public boolean groupTag(String tag, String group) { if (this.getEndPoint(tag) == null) { return false; } List<String> tags = this.taggroups.get(group); if (tags == null) { tags = new ArrayList<String>(); this.taggroups.put(group, tags); } tags.add(tag); return true; } public void ungroupTag(String tag) { for (final String group : this.taggroups.keySet()) { this.taggroups.get(group).remove(tag); } } public void clearGroup(String group) { this.taggroups.remove(group); } public boolean checkTagsGrouped(String tagA, String tagB) { for (final String group : this.taggroups.keySet()) { if (this.taggroups.get(group).contains(tagA) && this.taggroups.get(group).contains(tagB)) { return true; } } return false; } /*************************** * Heart of the beast! Unified method with no special cases that replaces the old sendMessage ***************************/ boolean delivery(RelayedMessage msg) { return this.delivery(msg, null, null, RelayedMessage.DeliveryMethod.STANDARD); } boolean delivery(RelayedMessage msg, List<EndPoint> destinations) { return this.delivery(msg, destinations, null, RelayedMessage.DeliveryMethod.STANDARD); } boolean delivery(RelayedMessage msg, List<EndPoint> knownDestinations, String username) { return this.delivery(msg, knownDestinations, username, RelayedMessage.DeliveryMethod.STANDARD); } /** * Only successful if all known targets (or if there is none at least one possible target) are successful! * * @param msg * @param knownDestinations * @param username * @param dm * @return */ boolean delivery(RelayedMessage msg, List<EndPoint> knownDestinations, String username, RelayedMessage.DeliveryMethod dm) { final String sourceTag = this.getTag(msg.getSource()); msg.setField("source", sourceTag); List<EndPoint> destinations; if (this.isDebug()) { CraftIRC.dolog("X->" + (knownDestinations.size() > 0 ? knownDestinations.toString() : "*") + ": " + msg.toString()); } //If we weren't explicitly given a recipient for the message, let's try to find one (or more) if (knownDestinations.size() < 1) { //Use all possible destinations (auto-targets) destinations = new LinkedList<EndPoint>(); for (final String targetTag : this.cPathsFrom(sourceTag)) { final EndPoint ep = this.getEndPoint(targetTag); if (ep == null) { continue; } if ((ep instanceof SecuredEndPoint) && SecuredEndPoint.Security.REQUIRE_TARGET.equals(((SecuredEndPoint) ep).getSecurity())) { continue; } if (!this.cPathAttribute(sourceTag, targetTag, "attributes." + msg.getEvent())) { continue; } if ((dm == RelayedMessage.DeliveryMethod.ADMINS) && !this.cPathAttribute(sourceTag, targetTag, "attributes.admin")) { continue; } destinations.add(ep); } //Default paths to unsecured destinations (auto-paths) if (this.cAutoPaths()) { for (final EndPoint ep : this.endpoints.values()) { if (ep == null) { continue; } if (msg.getSource().equals(ep) || destinations.contains(ep)) { continue; } if ((ep instanceof SecuredEndPoint) && !SecuredEndPoint.Security.UNSECURED.equals(((SecuredEndPoint) ep).getSecurity())) { continue; } final String targetTag = this.getTag(ep); if (this.checkTagsGrouped(sourceTag, targetTag)) { continue; } if (!this.cPathAttribute(sourceTag, targetTag, "attributes." + msg.getEvent())) { continue; } if ((dm == RelayedMessage.DeliveryMethod.ADMINS) && !this.cPathAttribute(sourceTag, targetTag, "attributes.admin")) { continue; } if (this.cPathAttribute(sourceTag, targetTag, "disabled")) { continue; } destinations.add(ep); } } } else { destinations = new LinkedList<EndPoint>(knownDestinations); } if (destinations.size() < 1) { return false; } //Deliver the message boolean success = true; for (final EndPoint destination : destinations) { final String targetTag = this.getTag(destination); if(targetTag.equals(this.cCancelledTag())){ continue; } msg.setField("target", targetTag); //Check against path filters if ((msg instanceof RelayedCommand) && this.matchesFilter(msg, this.cPathFilters(sourceTag, targetTag))) { if (knownDestinations != null) { success = false; } continue; } //Finally deliver! if (this.isDebug()) { CraftIRC.dolog("-->X: " + msg.toString()); } if (username != null) { success = success && destination.userMessageIn(username, msg); } else if (dm == RelayedMessage.DeliveryMethod.ADMINS) { success = destination.adminMessageIn(msg); } else if (dm == RelayedMessage.DeliveryMethod.COMMAND) { if (!(destination instanceof CommandEndPoint)) { continue; } ((CommandEndPoint) destination).commandIn((RelayedCommand) msg); } else { destination.messageIn(msg); } } return success; } boolean matchesFilter(RelayedMessage msg, List<ConfigurationNode> filters) { if (filters == null) { return false; } newFilter: for (final ConfigurationNode filter : filters) { for (final String key : filter.getKeys()) { final Pattern condition = Pattern.compile(filter.getString(key, "")); if (condition == null) { continue newFilter; } final String subject = msg.getField(key); if (subject == null) { continue newFilter; } final Matcher check = condition.matcher(subject); if (!check.find()) { continue newFilter; } } return true; } return false; } /*************************** * Auxiliary methods ***************************/ public Minebot getBot(int bot){ return this.instances.get(bot); } public void sendRawToBot(String rawMessage, int bot) { if (this.isDebug()) { CraftIRC.dolog("sendRawToBot(bot=" + bot + ", message=" + rawMessage); } final Minebot targetBot = this.instances.get(bot); targetBot.sendRawLineViaQueue(rawMessage); } public void sendMsgToTargetViaBot(String message, String target, int bot) { final Minebot targetBot = this.instances.get(bot); targetBot.sendMessage(target, message); } public List<String> ircUserLists(String tag) { return this.getEndPoint(tag).listDisplayUsers(); } void setDebug(boolean d) { this.debug = d; for (int i = 0; i < this.bots.size(); i++) { this.instances.get(i).setVerbose(d); } CraftIRC.dolog("DEBUG [" + (d ? "ON" : "OFF") + "]"); } public String getPrefix(Player p) { String result = ""; if (this.vault != null) { try { result = this.vault.getPlayerPrefix(p); } catch (final Exception e) { } } return result; } public String getSuffix(Player p) { String result = ""; if (this.vault != null) { try { result = this.vault.getPlayerSuffix(p); } catch (final Exception e) { } } return result; } public boolean isDebug() { return this.debug; } boolean checkPerms(Player pl, String path) { return pl.hasPermission(path); } boolean checkPerms(String pl, String path) { final Player pit = this.getServer().getPlayer(pl); if (pit != null) { return pit.hasPermission(path); } return false; } // TODO: Make sure this works public String colorizeName(String name) { final Pattern color_codes = Pattern.compile(ChatColor.COLOR_CHAR + "[0-9a-fk-r]"); Matcher find_colors = color_codes.matcher(name); while (find_colors.find()) { name = find_colors.replaceFirst(Character.toString((char) 3) + this.cColorIrcFromGame(find_colors.group())); find_colors = color_codes.matcher(name); } return name; } protected void enqueueConsoleCommand(String cmd) { try { this.getServer().dispatchCommand(this.getServer().getConsoleSender(), cmd); } catch (final Exception e) { e.printStackTrace(); } } /** * If the channel is null it's a reconnect, otherwise a rejoin * * @param bot * @param channel */ void scheduleForRetry(Minebot bot, String channel) { this.retryTimer.schedule(new RetryTask(this, bot, channel), this.cRetryDelay()); } /*************************** * Read stuff from config ***************************/ private ConfigurationNode getChanNode(int bot, String channel) { final ArrayList<ConfigurationNode> botChans = this.channodes.get(bot); for (final ConfigurationNode chan : botChans) { if (chan.getString("name").equalsIgnoreCase(channel)) { return chan; } } return Configuration.getEmptyNode(); } public List<ConfigurationNode> cChannels(int bot) { return this.channodes.get(bot); } private ConfigurationNode getPathNode(String source, String target) { ConfigurationNode result = this.paths.get(new Path(source, target)); if (result == null) { return this.configuration.getNode("default-attributes"); } ConfigurationNode basepath; if (result.getKeys().contains("base") && ((basepath = result.getNode("base")) != null)) { final ConfigurationNode basenode = this.paths.get(new Path(basepath.getString("source", ""), basepath.getString("target", ""))); if (basenode != null) { result = basenode; } } return result; } public String cMinecraftTag() { return this.configuration.getString("settings.minecraft-tag", "minecraft"); } public String cCancelledTag() { return this.configuration.getString("settings.cancelled-tag", "cancelled"); } public String cConsoleTag() { return this.configuration.getString("settings.console-tag", "console"); } public String cMinecraftTagGroup() { return this.configuration.getString("settings.minecraft-group-name", "minecraft"); } public String cIrcTagGroup() { return this.configuration.getString("settings.irc-group-name", "irc"); } public boolean cAutoPaths() { return this.configuration.getBoolean("settings.auto-paths", false); } public boolean cCancelChat() { return cancelChat; } public boolean cDebug() { return this.configuration.getBoolean("settings.debug", false); } public ArrayList<String> cConsoleCommands() { return new ArrayList<String>(this.configuration.getStringList("settings.console-commands", null)); } public int cHold(String eventType) { return this.configuration.getInt("settings.hold-after-enable." + eventType, 0); } public String cFormatting(String eventType, RelayedMessage msg) { return this.cFormatting(eventType, msg, null); } public String cFormatting(String eventType, RelayedMessage msg, EndPoint realTarget) { final String source = this.getTag(msg.getSource()), target = this.getTag(realTarget != null ? realTarget : msg.getTarget()); if ((source == null) || (target == null)) { CraftIRC.dowarn("Attempted to obtain formatting for invalid path " + source + " -> " + target + " ."); return this.cDefaultFormatting(eventType, msg); } final ConfigurationNode pathConfig = this.paths.get(new Path(source, target)); if ((pathConfig != null) && (pathConfig.getString("formatting." + eventType, null) != null)) { return pathConfig.getString("formatting." + eventType, null); } else { return this.cDefaultFormatting(eventType, msg); } } public String cDefaultFormatting(String eventType, RelayedMessage msg) { if (msg.getSource().getType() == EndPoint.Type.MINECRAFT) { return this.configuration.getString("settings.formatting.from-game." + eventType); } if (msg.getSource().getType() == EndPoint.Type.IRC) { return this.configuration.getString("settings.formatting.from-irc." + eventType); } if (msg.getSource().getType() == EndPoint.Type.PLAIN) { return this.configuration.getString("settings.formatting.from-plain." + eventType); } return ""; } public String cColorIrcFromGame(String game) { ConfigurationNode color; final Iterator<ConfigurationNode> it = this.colormap.iterator(); while (it.hasNext()) { color = it.next(); if (color.getString("game").equals(game)) { //Forces sending two digit colour codes. return (color.getString("irc").length() == 1 ? "0" : "") + color.getString("irc", this.cColorIrcFromName("foreground")); } } return this.cColorIrcFromName("foreground"); } public String cColorIrcFromName(String name) { ConfigurationNode color; final Iterator<ConfigurationNode> it = this.colormap.iterator(); while (it.hasNext()) { color = it.next(); if (color.getString("name").equalsIgnoreCase(name) && (color.getProperty("irc") != null)) { return color.getString("irc", "01"); } } if (name.equalsIgnoreCase("foreground")) { return "01"; } else { return this.cColorIrcFromName("foreground"); } } public String cColorGameFromIrc(String irc) { //Always convert to two digits. if (irc.length() == 1) irc = "0"+irc; ConfigurationNode color; final Iterator<ConfigurationNode> it = this.colormap.iterator(); while (it.hasNext()) { color = it.next(); //Enforce two digit comparisons. if (color.getString("irc", "").equals(irc) || "0".concat(color.getString("irc", "")).equals(irc)) { return color.getString("game", this.cColorGameFromName("foreground")); } } return this.cColorGameFromName("foreground"); } public String cColorGameFromName(String name) { ConfigurationNode color; final Iterator<ConfigurationNode> it = this.colormap.iterator(); while (it.hasNext()) { color = it.next(); if (color.getString("name").equalsIgnoreCase(name) && (color.getProperty("game") != null)) { return color.getString("game", "\u00C2\u00A7f"); } } if (name.equalsIgnoreCase("foreground")) { return "\u00C2\u00A7f"; } else { return this.cColorGameFromName("foreground"); } } public String cBindLocalAddr() { return this.configuration.getString("settings.bind-address", ""); } public int cRetryDelay() { return this.configuration.getInt("settings.retry-delay", 10) * 1000; } public String cBotNickname(int bot) { return this.bots.get(bot).getString("nickname", "CraftIRCbot"); } public String cBotServer(int bot) { return this.bots.get(bot).getString("server", "irc.esper.net"); } public int cBotPort(int bot) { return this.bots.get(bot).getInt("port", 6667); } public int cBotBindPort(int bot) { return this.bots.get(bot).getInt("bind-port", 0); } public String cBotLogin(int bot) { return this.bots.get(bot).getString("userident", ""); } public String cBotPassword(int bot) { return this.bots.get(bot).getString("serverpass", ""); } public boolean cBotSsl(int bot) { return this.bots.get(bot).getBoolean("ssl", false); } public int cBotMessageDelay(int bot) { return this.bots.get(bot).getInt("message-delay", 1000); } public int cBotQueueSize(int bot) { return this.bots.get(bot).getInt("queue-size", 5); } public String cCommandPrefix(int bot) { return this.bots.get(bot).getString("command-prefix", this.configuration.getString("settings.command-prefix", ".")); } public List<String> cCmdWordCmd(Integer bot) { final List<String> init = new ArrayList<String>(); init.add("cmd"); final List<String> result = this.configuration.getStringList("settings.irc-commands.cmd", init); if (bot != null) { return this.bots.get(bot).getStringList("irc-commands.cmd", result); } return result; } public List<String> cCmdWordSay(Integer bot) { final List<String> init = new ArrayList<String>(); init.add("say"); final List<String> result = this.configuration.getStringList("settings.irc-commands.say", init); if (bot != null) { return this.bots.get(bot).getStringList("irc-commands.say", result); } return result; } public List<String> cCmdWordPlayers(Integer bot) { final List<String> init = new ArrayList<String>(); init.add("players"); final List<String> result = this.configuration.getStringList("settings.irc-commands.players", init); if (bot != null) { return this.bots.get(bot).getStringList("irc-commands.players", result); } return result; } public ArrayList<String> cBotAdminPrefixes(int bot) { return new ArrayList<String>(this.bots.get(bot).getStringList("admin-prefixes", null)); } public ArrayList<String> cBotIgnoredUsers(int bot) { return new ArrayList<String>(this.bots.get(bot).getStringList("ignored-users", null)); } public String cBotAuthMethod(int bot) { return this.bots.get(bot).getString("auth.method", "nickserv"); } public String cBotAuthUsername(int bot) { return this.bots.get(bot).getString("auth.username", ""); } public String cBotAuthPassword(int bot) { return this.bots.get(bot).getString("auth.password", ""); } public ArrayList<String> cBotOnConnect(int bot) { return new ArrayList<String>(this.bots.get(bot).getStringList("on-connect", null)); } public String cChanName(int bot, String channel) { return this.getChanNode(bot, channel).getString("name", "#changeme"); } public String cChanTag(int bot, String channel) { return this.getChanNode(bot, channel).getString("tag", String.valueOf(bot) + "_" + channel); } public String cChanPassword(int bot, String channel) { return this.getChanNode(bot, channel).getString("password", ""); } public ArrayList<String> cChanOnJoin(int bot, String channel) { return new ArrayList<String>(this.getChanNode(bot, channel).getStringList("on-join", null)); } public List<String> cPathsFrom(String source) { final List<String> results = new LinkedList<String>(); for (final Path path : this.paths.keySet()) { if (!path.getSourceTag().equals(source)) { continue; } if (this.paths.get(path).getBoolean("disable", false)) { continue; } results.add(path.getTargetTag()); } return results; } List<String> cPathsTo(String target) { final List<String> results = new LinkedList<String>(); for (final Path path : this.paths.keySet()) { if (!path.getTargetTag().equals(target)) { continue; } if (this.paths.get(path).getBoolean("disable", false)) { continue; } results.add(path.getSourceTag()); } return results; } public boolean cPathExists(String source, String target) { final ConfigurationNode pathNode = this.getPathNode(source, target); return (pathNode != null) && !pathNode.getBoolean("disabled", false); } public boolean cPathAttribute(String source, String target, String attribute) { final ConfigurationNode node = this.getPathNode(source, target); if (node.getProperty(attribute) != null) { return node.getBoolean(attribute, false); } else { return this.configuration.getNode("default-attributes").getBoolean(attribute, false); } } public List<ConfigurationNode> cPathFilters(String source, String target) { return this.getPathNode(source, target).getNodeList("filters", new ArrayList<ConfigurationNode>()); } public Map<String, Map<String, String>> cReplaceFilters() { return this.replaceFilters; } void loadTagGroups() { final List<String> groups = this.configuration.getKeys("settings.tag-groups"); if (groups == null) { return; } for (final String group : groups) { for (final String tag : this.configuration.getStringList("settings.tag-groups." + group, new ArrayList<String>())) { this.groupTag(tag, group); } } } boolean cUseMapAsWhitelist(int bot) { return this.bots.get(bot).getBoolean("use-map-as-whitelist", false); } public String cIrcDisplayName(int bot, String nickname) { return this.bots.get(bot).getString("irc-nickname-map." + nickname, nickname); } public boolean cNicknameIsInIrcMap(int bot, String nickname) { return this.bots.get(bot).getString("irc-nickname-map." + nickname) != null; } public enum HoldType { CHAT, JOINS, QUITS, KICKS, BANS, DEATHS } class RemoveHoldTask extends TimerTask { private final CraftIRC plugin; private final HoldType ht; protected RemoveHoldTask(CraftIRC plugin, HoldType ht) { super(); this.plugin = plugin; this.ht = ht; } @Override public void run() { this.plugin.hold.put(this.ht, false); } } public boolean isHeld(HoldType ht) { return this.hold.get(ht); } public List<ConfigurationNode> getColorMap() { return this.colormap; } public String processAntiHighlight(String input) { String delimiter = this.configuration.getString("settings.anti-highlight"); if (delimiter != null && !delimiter.isEmpty()) { StringBuilder builder = new StringBuilder(); for (int i=0; i < input.length(); i++) { char c = input.charAt(i); builder.append(c); if (c != '\u00A7') { builder.append(delimiter); } } return builder.toString(); } else { return input; } } }
diff --git a/core-providers/src/java/org/sakaiproject/entitybroker/providers/UserEntityProvider.java b/core-providers/src/java/org/sakaiproject/entitybroker/providers/UserEntityProvider.java index d75ce14b..781bd032 100644 --- a/core-providers/src/java/org/sakaiproject/entitybroker/providers/UserEntityProvider.java +++ b/core-providers/src/java/org/sakaiproject/entitybroker/providers/UserEntityProvider.java @@ -1,683 +1,678 @@ /** * $Id: UserEntityProvider.java 51727 2008-09-03 09:00:03Z [email protected] $ * $URL: https://source.sakaiproject.org/svn/entitybroker/trunk/impl/src/java/org/sakaiproject/entitybroker/providers/UserEntityProvider.java $ * UserEntityProvider.java - entity-broker - Jun 28, 2008 2:59:57 PM - azeckoski ************************************************************************** * Copyright (c) 2008, 2009 The Sakai Foundation * * Licensed under the Educational Community 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.osedu.org/licenses/ECL-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.sakaiproject.entitybroker.providers; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.azeckoski.reflectutils.FieldUtils; import org.azeckoski.reflectutils.ReflectUtils; import org.sakaiproject.component.api.ServerConfigurationService; import org.sakaiproject.entity.api.ResourcePropertiesEdit; import org.sakaiproject.entitybroker.DeveloperHelperService; import org.sakaiproject.entitybroker.EntityReference; import org.sakaiproject.entitybroker.EntityView; import org.sakaiproject.entitybroker.entityprovider.CoreEntityProvider; import org.sakaiproject.entitybroker.entityprovider.annotations.EntityCustomAction; import org.sakaiproject.entitybroker.entityprovider.capabilities.Describeable; import org.sakaiproject.entitybroker.entityprovider.capabilities.RESTful; import org.sakaiproject.entitybroker.entityprovider.extension.Formats; import org.sakaiproject.entitybroker.entityprovider.search.Restriction; import org.sakaiproject.entitybroker.entityprovider.search.Search; import org.sakaiproject.entitybroker.providers.model.EntityUser; import org.sakaiproject.entitybroker.util.AbstractEntityProvider; import org.sakaiproject.user.api.User; import org.sakaiproject.user.api.UserAlreadyDefinedException; import org.sakaiproject.user.api.UserDirectoryService; import org.sakaiproject.user.api.UserEdit; import org.sakaiproject.user.api.UserIdInvalidException; import org.sakaiproject.user.api.UserLockedException; import org.sakaiproject.user.api.UserNotDefinedException; import org.sakaiproject.user.api.UserPermissionException; /** * Entity Provider for users * * @author Aaron Zeckoski (azeckoski @ gmail.com) */ public class UserEntityProvider extends AbstractEntityProvider implements CoreEntityProvider, RESTful, Describeable { private static Log log = LogFactory.getLog(UserEntityProvider.class); private UserDirectoryService userDirectoryService; public void setUserDirectoryService(UserDirectoryService userDirectoryService) { this.userDirectoryService = userDirectoryService; } private DeveloperHelperService developerHelperService; public void setDeveloperHelperService( DeveloperHelperService developerHelperService) { this.developerHelperService = developerHelperService; } private ServerConfigurationService serverConfigurationService; public void setServerConfigurationService( ServerConfigurationService serverConfigurationService) { this.serverConfigurationService = serverConfigurationService; } public static String PREFIX = "user"; public String getEntityPrefix() { return PREFIX; } @EntityCustomAction(action="current",viewKey=EntityView.VIEW_LIST) public EntityUser getCurrentUser(EntityView view) { EntityUser eu = new EntityUser(userDirectoryService.getCurrentUser()); return eu; } @EntityCustomAction(action="exists", viewKey=EntityView.VIEW_SHOW) public boolean checkUserExists(EntityView view) { String userId = view.getEntityReference().getId(); userId = findAndCheckUserId(userId, null); boolean exists = (userId != null); return exists; } public boolean entityExists(String id) { if (id == null) { return false; } if ("".equals(id)) { return true; } String userId = findAndCheckUserId(id, null); if (userId != null) { return true; } return false; } public String createEntity(EntityReference ref, Object entity, Map<String, Object> params) { String userId = null; if (ref.getId() != null && ref.getId().length() > 0) { userId = ref.getId(); } if (entity.getClass().isAssignableFrom(User.class)) { // if someone passes in a user or useredit User user = (User) entity; if (userId == null && user.getId() != null) { userId = user.getId(); } //check if this user can add an account of this type if (!canAddAccountType(user.getType())) { throw new SecurityException("User can't add an account of type: " + user.getType()); } // NOTE: must assign empty password if user is created this way.... it sucks -AZ try { User newUser = userDirectoryService.addUser(userId, user.getEid(), user.getFirstName(), user.getLastName(), user.getEmail(), "", user.getType(), user.getProperties()); userId = newUser.getId(); } catch (UserIdInvalidException e) { throw new IllegalArgumentException("User ID is invalid, id=" + user.getId() + ", eid="+user.getEid(), e); } catch (UserAlreadyDefinedException e) { throw new IllegalArgumentException("Cannot create user, user already exists: " + ref, e); } catch (UserPermissionException e) { throw new SecurityException("Could not create user, permission denied: " + ref, e); } } else if (entity.getClass().isAssignableFrom(EntityUser.class)) { // if they instead pass in the EntityUser object EntityUser user = (EntityUser) entity; if (userId == null && user.getId() != null) { userId = user.getId(); } //check if this user can add an account of this type if (!canAddAccountType(user.getType())) { throw new SecurityException("User can't add an account of type: " + user.getType()); } try { UserEdit edit = userDirectoryService.addUser(userId, user.getEid()); edit.setEmail(user.getEmail()); edit.setFirstName(user.getFirstName()); edit.setLastName(user.getLastName()); edit.setPassword(user.getPassword()); edit.setType(user.getType()); // put in properties ResourcePropertiesEdit rpe = edit.getPropertiesEdit(); for (String key : user.getProps().keySet()) { String value = user.getProps().get(key); rpe.addProperty(key, value); } userDirectoryService.commitEdit(edit); userId = edit.getId(); } catch (UserIdInvalidException e) { throw new IllegalArgumentException("User ID is invalid: " + user.getId(), e); } catch (UserAlreadyDefinedException e) { throw new IllegalArgumentException("Cannot create user, user already exists: " + ref, e); } catch (UserPermissionException e) { throw new SecurityException("Could not create user, permission denied: " + ref, e); } } else { throw new IllegalArgumentException("Invalid entity for creation, must be User or EntityUser object"); } return userId; } public Object getSampleEntity() { return new EntityUser(); } public void updateEntity(EntityReference ref, Object entity, Map<String, Object> params) { String userId = ref.getId(); if (userId == null || "".equals(userId)) { throw new IllegalArgumentException("Cannot update, No userId in provided reference: " + ref); } User user = getUserByIdEid(userId); UserEdit edit = null; try { edit = userDirectoryService.editUser(user.getId()); } catch (UserNotDefinedException e) { throw new IllegalArgumentException("Invalid user: " + ref + ":" + e.getMessage()); } catch (UserPermissionException e) { throw new SecurityException("Permission denied: User cannot be updated: " + ref); } catch (UserLockedException e) { throw new RuntimeException("Something strange has failed with Sakai: " + e.getMessage()); } if (entity.getClass().isAssignableFrom(User.class)) { // if someone passes in a user or useredit User u = (User) entity; edit.setEmail(u.getEmail()); edit.setFirstName(u.getFirstName()); edit.setLastName(u.getLastName()); edit.setType(u.getType()); // put in properties ResourcePropertiesEdit rpe = edit.getPropertiesEdit(); rpe.set(u.getProperties()); } else if (entity.getClass().isAssignableFrom(EntityUser.class)) { // if they instead pass in the myuser object EntityUser u = (EntityUser) entity; edit.setEmail(u.getEmail()); edit.setFirstName(u.getFirstName()); edit.setLastName(u.getLastName()); edit.setPassword(u.getPassword()); edit.setType(u.getType()); // put in properties ResourcePropertiesEdit rpe = edit.getPropertiesEdit(); for (String key : u.getProps().keySet()) { String value = u.getProps().get(key); rpe.addProperty(key, value); } } else { throw new IllegalArgumentException("Invalid entity for update, must be User or EntityUser object"); } try { userDirectoryService.commitEdit(edit); } catch (UserAlreadyDefinedException e) { throw new RuntimeException(ref + ": This exception should not be possible: " + e.getMessage(), e); } } public void deleteEntity(EntityReference ref, Map<String, Object> params) { String userId = ref.getId(); if (userId == null || "".equals(userId)) { throw new IllegalArgumentException("Cannot delete, No userId in provided reference: " + ref); } User user = getUserByIdEid(userId); if (user != null) { try { UserEdit edit = userDirectoryService.editUser(user.getId()); userDirectoryService.removeUser(edit); } catch (UserNotDefinedException e) { throw new IllegalArgumentException("Invalid user: " + ref + ":" + e.getMessage()); } catch (UserPermissionException e) { throw new SecurityException("Permission denied: User cannot be removed: " + ref); } catch (UserLockedException e) { throw new RuntimeException("Something strange has failed with Sakai: " + e.getMessage()); } } } public Object getEntity(EntityReference ref) { if (ref.getId() == null) { return new EntityUser(); } String userId = ref.getId(); User user = getUserByIdEid(userId); if (developerHelperService.isEntityRequestInternal(ref.toString())) { // internal lookups are allowed to get everything } else { // external lookups require auth boolean allowed = false; String currentUserRef = developerHelperService.getCurrentUserReference(); if (currentUserRef != null) { String currentUserId = developerHelperService.getUserIdFromRef(currentUserRef); if (developerHelperService.isUserAdmin(currentUserId) || currentUserId.equals(user.getId())) { // allowed to access the user data allowed = true; } } if (! allowed) { throw new SecurityException("Current user ("+currentUserRef+") cannot access information about user: " + ref); } } // convert EntityUser eu = convertUser(user); return eu; } /** * WARNING: The search results may be drawn from different populations depending on the * search parameters specified. A straight listing with no filtering, or a search on "search" * or "criteria", will only retrieve matches from the Sakai-maintained user records. A search * on "email" may also check the records maintained by the user directory provider. */ public List<?> getEntities(EntityReference ref, Search search) { Collection<User> users = new ArrayList<User>(); if (developerHelperService.getConfigurationSetting("entity.users.viewall", false)) { // setting bypasses all checks } else if (developerHelperService.isEntityRequestInternal(ref.toString())) { // internal lookups are allowed to get everything } else { // external lookups require auth boolean allowed = false; String currentUserRef = developerHelperService.getCurrentUserReference(); if (currentUserRef != null) { String currentUserId = developerHelperService.getUserIdFromRef(currentUserRef); if ( developerHelperService.isUserAdmin(currentUserId) ) { // allowed to access the user data allowed = true; } } if (! allowed) { throw new SecurityException("Only admin can access multiple users, current user ("+currentUserRef+") cannot access ref: " + ref); } } // fix up the search limits if (search.getLimit() > 50 || search.getLimit() == 0) { search.setLimit(50); } if (search.getStart() == 0 || search.getStart() > 49) { search.setStart(1); } // get the search restrictions out Restriction restrict = search.getRestrictionByProperty("email"); if (restrict != null) { // search users by email users = userDirectoryService.findUsersByEmail(restrict.value.toString()); } if (restrict == null) { restrict = search.getRestrictionByProperty("eid"); if (restrict == null) { restrict = search.getRestrictionByProperty("search"); } if (restrict == null) { restrict = search.getRestrictionByProperty("criteria"); } if (restrict != null) { // search users but match users = userDirectoryService.searchUsers(restrict.value + "", (int) search.getStart(), (int) search.getLimit()); } } if (restrict == null) { users = userDirectoryService.getUsers((int) search.getStart(), (int) search.getLimit()); } // convert these into EntityUser objects List<EntityUser> entityUsers = new ArrayList<EntityUser>(); for (User user : users) { entityUsers.add( convertUser(user) ); } return entityUsers; } public String[] getHandledInputFormats() { return new String[] { Formats.HTML, Formats.XML, Formats.JSON }; } public String[] getHandledOutputFormats() { return new String[] { Formats.XML, Formats.JSON, Formats.FORM }; } /** * Allows for easy retrieval of the user object * @param userId a user Id (can be eid) * @return the user object * @throws IllegalArgumentException if the user Id is invalid */ public EntityUser getUserById(String userId) { userId = findAndCheckUserId(userId, null); //we could have been passed a Id that no longer referes to a user if (userId == null) { return null; } EntityReference ref = new EntityReference("user", userId); EntityUser eu = (EntityUser) getEntity(ref); return eu; } /* * This ugliness is needed because of the edge case where people are using identical ID/EIDs, * this is a really really bad hack to attempt to get the server to tell us if the eid==id for users */ private Boolean usesSeparateIdEid = null; private boolean isUsingSameIdEid() { if (usesSeparateIdEid == null) { String config = developerHelperService.getConfigurationSetting("[email protected]", (String)null); if (config != null) { try { usesSeparateIdEid = ReflectUtils.getInstance().convert(config, Boolean.class); } catch (UnsupportedOperationException e) { // oh well usesSeparateIdEid = null; } } if (usesSeparateIdEid == null) { // could not get the stupid setting so attempt to check the service itself try { usesSeparateIdEid = FieldUtils.getInstance().getFieldValue(userDirectoryService, "m_separateIdEid", Boolean.class); } catch (RuntimeException e) { // no luck here usesSeparateIdEid = null; } } if (usesSeparateIdEid == null) usesSeparateIdEid = Boolean.FALSE; } return ! usesSeparateIdEid.booleanValue(); } /** * Will check that a userId/eid is valid and will produce a valid userId from the check * @param currentUserId user id (can be eid) * @param currentUserEid user eid (can be id) * @return a valid user id OR null if not valid */ public String findAndCheckUserId(String currentUserId, String currentUserEid) { if (currentUserId == null && currentUserEid == null) { throw new IllegalArgumentException("Cannot get user from a null userId and eid, ensure at least userId or userEid are set"); } String userId = null; // can use the efficient methods to check if the user Id is valid if (currentUserId == null) { + // We should assume we will resolve by EID if (log.isDebugEnabled()) log.debug("currentUserId is null, currentUserEid=" + currentUserEid, new Exception()); // try to get userId from eid if (currentUserEid.startsWith("/user/")) { // assume the form of "/user/userId" (the UDS method is protected) currentUserEid = new EntityReference(currentUserEid).getId(); } if (isUsingSameIdEid()) { // have to actually fetch the user User u; try { u = getUserByIdEid(currentUserEid); if (u != null) { userId = u.getId(); } } catch (IllegalArgumentException e) { userId = null; } } else { if (userIdExplicitOnly()) { // only check ID or EID if (currentUserEid.length() > 3 && currentUserEid.startsWith("id=") ) { // strip the id marker out currentUserEid = currentUserEid.substring(3); // check ID, do not attempt to check by EID as well try { userId = userDirectoryService.getUserId(currentUserEid); } catch (UserNotDefinedException e2) { userId = null; } } else { // check by EID try { userDirectoryService.getUserEid(currentUserEid); // simply here to throw an exception or not userId = currentUserEid; } catch (UserNotDefinedException e2) { userId = null; } } } else { // check for EID and then ID try { userId = userDirectoryService.getUserId(currentUserEid); } catch (UserNotDefinedException e) { try { userDirectoryService.getUserEid(currentUserEid); // simply here to throw an exception or not userId = currentUserEid; } catch (UserNotDefinedException e2) { userId = null; } } } } } else { + // Assume we will resolve by ID // get the id out of a ref if (currentUserId.startsWith("/user/")) { // assume the form of "/user/userId" (the UDS method is protected) currentUserId = new EntityReference(currentUserId).getId(); } // verify the userId is valid if (isUsingSameIdEid()) { // have to actually fetch the user try { User u = getUserByIdEid(currentUserId); if (u != null) { userId = u.getId(); } } catch (IllegalArgumentException e) { userId = null; } } else { if (userIdExplicitOnly()) { if (currentUserId.length() > 3 && currentUserId.startsWith("id=") ) { // strip the id marker out currentUserId = currentUserId.substring(3); - // check ID, do not attempt to check by EID as well - try { - userDirectoryService.getUserEid(currentUserId); // simply here to throw an exception or not - userId = currentUserId; - } catch (UserNotDefinedException e2) { - userId = null; - } - } else { - // check EID only - try { - userId = userDirectoryService.getUserId(currentUserId); - } catch (UserNotDefinedException e2) { - userId = null; - } + } + // check ID, do not attempt to check by EID as well + try { + userDirectoryService.getUserEid(currentUserId); // simply here to throw an exception or not + userId = currentUserId; + } catch (UserNotDefinedException e2) { + userId = null; } } else { // check for ID and then EID try { userDirectoryService.getUserEid(currentUserId); // simply here to throw an exception or not userId = currentUserId; } catch (UserNotDefinedException e) { try { userId = userDirectoryService.getUserId(currentUserId); } catch (UserNotDefinedException e2) { userId = null; } } } } } return userId; } /** * @param userSearchValue either a user ID, a user EID, or a user email address * @return the first matching user, or null if no search method worked */ public EntityUser findUserFromSearchValue(String userSearchValue) { EntityUser entityUser; User user; try { user = userDirectoryService.getUser(userSearchValue); } catch (UserNotDefinedException e) { try { user = userDirectoryService.getUserByEid(userSearchValue); } catch (UserNotDefinedException e1) { user = null; } } if (user == null) { Collection<User> users = userDirectoryService.findUsersByEmail(userSearchValue); if ((users != null) && (users.size() > 0)) { user = users.iterator().next(); if (users.size() > 1) { if (log.isWarnEnabled()) log.warn("Found multiple users with email " + userSearchValue); } } } if (user != null) { entityUser = convertUser(user); } else { entityUser = null; } return entityUser; } public EntityUser convertUser(User user) { EntityUser eu = new EntityUser(user); return eu; } /** * Attempt to get a user by EID or ID (if that fails) * * NOTE: can force this to only attempt the ID lookups if prefixed with "id=" using "user.explicit.id.only=true" * * @param userEid the user EID (could also be the ID) * @return the populated User object */ private User getUserByIdEid(String userEid) { User user = null; if (userEid != null) { boolean doCheckForId = false; boolean doCheckForEid = true; String userId = userEid; // check if the incoming param says this is explicitly an id if (userId.length() > 3 && userId.startsWith("id=") ) { // strip the id marker out userId = userEid.substring(3); doCheckForEid = false; // skip the EID check entirely doCheckForId = true; } // attempt checking both with failover by default (override by property "user.id.failover.check=false") if (doCheckForEid) { try { user = userDirectoryService.getUserByEid(userEid); } catch (UserNotDefinedException e) { user = null; String msg = "Could not find user with eid="+userEid; if (!userIdExplicitOnly()) { msg += " (attempting check using user id="+userId+")"; doCheckForId = true; } msg += " :: " + e.getMessage(); log.warn(msg); } } if (doCheckForId) { try { user = userDirectoryService.getUser(userId); } catch (UserNotDefinedException e) { user = null; String msg = "Could not find user with id="+userId+" :: " + e.getMessage(); log.warn(msg); } } if (user == null) { throw new IllegalArgumentException("Could not find user with eid="+userEid+" or id="+userId); } } return user; } /** * Can the current user add an account of this type see KNL-357 * @param type * @return */ private boolean canAddAccountType(String type) { log.debug("canAddAccountType(" + type + ")"); //admin can always add users if (developerHelperService.isUserAdmin(developerHelperService.getCurrentUserReference())) { log.debug("Admin user is allowed!"); return true; } String currentSessionUserId = developerHelperService.getCurrentUserId(); log.debug("checking if " + currentSessionUserId + " can add account of type: " + type); //this may be an anonymous session registering if (currentSessionUserId == null) { String regAccountTypes = serverConfigurationService.getString("user.registrationTypes", "registered"); List<String> regTypes = Arrays.asList(regAccountTypes.split(",")); if (! regTypes.contains(type)) { log.warn("Anonamous user can't create an account of type: " + type + ", allowed types: " + regAccountTypes); return false; } } else { //this is a authenticated non-admin user String newAccountTypes = serverConfigurationService.getString("user.nonAdminTypes", "guest"); List<String> newTypes = Arrays.asList(newAccountTypes.split(",")); if (! newTypes.contains(type)) { log.warn("User " + currentSessionUserId + " can't create an account of type: " + type +" with eid , allowed types: " + newAccountTypes); return false; } } return true; } /** * Checks the sakai.properties setting for: "user.explicit.id.only", * set this to true to disable id/eid failover checks (this means lookups will only attempt to use * id or eid as per the exact params which are passed or as per the endpoint API) * * In other words, the user id must be prefixed with "id=", otherwise it will be treated like an eid * * @return true if user ID must be passed explicitly (no id/eid failover checks are allowed), default: false */ private boolean userIdExplicitOnly() { boolean allowed = developerHelperService.getConfigurationSetting("user.explicit.id.only", false); return allowed; } }
false
true
public String findAndCheckUserId(String currentUserId, String currentUserEid) { if (currentUserId == null && currentUserEid == null) { throw new IllegalArgumentException("Cannot get user from a null userId and eid, ensure at least userId or userEid are set"); } String userId = null; // can use the efficient methods to check if the user Id is valid if (currentUserId == null) { if (log.isDebugEnabled()) log.debug("currentUserId is null, currentUserEid=" + currentUserEid, new Exception()); // try to get userId from eid if (currentUserEid.startsWith("/user/")) { // assume the form of "/user/userId" (the UDS method is protected) currentUserEid = new EntityReference(currentUserEid).getId(); } if (isUsingSameIdEid()) { // have to actually fetch the user User u; try { u = getUserByIdEid(currentUserEid); if (u != null) { userId = u.getId(); } } catch (IllegalArgumentException e) { userId = null; } } else { if (userIdExplicitOnly()) { // only check ID or EID if (currentUserEid.length() > 3 && currentUserEid.startsWith("id=") ) { // strip the id marker out currentUserEid = currentUserEid.substring(3); // check ID, do not attempt to check by EID as well try { userId = userDirectoryService.getUserId(currentUserEid); } catch (UserNotDefinedException e2) { userId = null; } } else { // check by EID try { userDirectoryService.getUserEid(currentUserEid); // simply here to throw an exception or not userId = currentUserEid; } catch (UserNotDefinedException e2) { userId = null; } } } else { // check for EID and then ID try { userId = userDirectoryService.getUserId(currentUserEid); } catch (UserNotDefinedException e) { try { userDirectoryService.getUserEid(currentUserEid); // simply here to throw an exception or not userId = currentUserEid; } catch (UserNotDefinedException e2) { userId = null; } } } } } else { // get the id out of a ref if (currentUserId.startsWith("/user/")) { // assume the form of "/user/userId" (the UDS method is protected) currentUserId = new EntityReference(currentUserId).getId(); } // verify the userId is valid if (isUsingSameIdEid()) { // have to actually fetch the user try { User u = getUserByIdEid(currentUserId); if (u != null) { userId = u.getId(); } } catch (IllegalArgumentException e) { userId = null; } } else { if (userIdExplicitOnly()) { if (currentUserId.length() > 3 && currentUserId.startsWith("id=") ) { // strip the id marker out currentUserId = currentUserId.substring(3); // check ID, do not attempt to check by EID as well try { userDirectoryService.getUserEid(currentUserId); // simply here to throw an exception or not userId = currentUserId; } catch (UserNotDefinedException e2) { userId = null; } } else { // check EID only try { userId = userDirectoryService.getUserId(currentUserId); } catch (UserNotDefinedException e2) { userId = null; } } } else { // check for ID and then EID try { userDirectoryService.getUserEid(currentUserId); // simply here to throw an exception or not userId = currentUserId; } catch (UserNotDefinedException e) { try { userId = userDirectoryService.getUserId(currentUserId); } catch (UserNotDefinedException e2) { userId = null; } } } } } return userId; }
public String findAndCheckUserId(String currentUserId, String currentUserEid) { if (currentUserId == null && currentUserEid == null) { throw new IllegalArgumentException("Cannot get user from a null userId and eid, ensure at least userId or userEid are set"); } String userId = null; // can use the efficient methods to check if the user Id is valid if (currentUserId == null) { // We should assume we will resolve by EID if (log.isDebugEnabled()) log.debug("currentUserId is null, currentUserEid=" + currentUserEid, new Exception()); // try to get userId from eid if (currentUserEid.startsWith("/user/")) { // assume the form of "/user/userId" (the UDS method is protected) currentUserEid = new EntityReference(currentUserEid).getId(); } if (isUsingSameIdEid()) { // have to actually fetch the user User u; try { u = getUserByIdEid(currentUserEid); if (u != null) { userId = u.getId(); } } catch (IllegalArgumentException e) { userId = null; } } else { if (userIdExplicitOnly()) { // only check ID or EID if (currentUserEid.length() > 3 && currentUserEid.startsWith("id=") ) { // strip the id marker out currentUserEid = currentUserEid.substring(3); // check ID, do not attempt to check by EID as well try { userId = userDirectoryService.getUserId(currentUserEid); } catch (UserNotDefinedException e2) { userId = null; } } else { // check by EID try { userDirectoryService.getUserEid(currentUserEid); // simply here to throw an exception or not userId = currentUserEid; } catch (UserNotDefinedException e2) { userId = null; } } } else { // check for EID and then ID try { userId = userDirectoryService.getUserId(currentUserEid); } catch (UserNotDefinedException e) { try { userDirectoryService.getUserEid(currentUserEid); // simply here to throw an exception or not userId = currentUserEid; } catch (UserNotDefinedException e2) { userId = null; } } } } } else { // Assume we will resolve by ID // get the id out of a ref if (currentUserId.startsWith("/user/")) { // assume the form of "/user/userId" (the UDS method is protected) currentUserId = new EntityReference(currentUserId).getId(); } // verify the userId is valid if (isUsingSameIdEid()) { // have to actually fetch the user try { User u = getUserByIdEid(currentUserId); if (u != null) { userId = u.getId(); } } catch (IllegalArgumentException e) { userId = null; } } else { if (userIdExplicitOnly()) { if (currentUserId.length() > 3 && currentUserId.startsWith("id=") ) { // strip the id marker out currentUserId = currentUserId.substring(3); } // check ID, do not attempt to check by EID as well try { userDirectoryService.getUserEid(currentUserId); // simply here to throw an exception or not userId = currentUserId; } catch (UserNotDefinedException e2) { userId = null; } } else { // check for ID and then EID try { userDirectoryService.getUserEid(currentUserId); // simply here to throw an exception or not userId = currentUserId; } catch (UserNotDefinedException e) { try { userId = userDirectoryService.getUserId(currentUserId); } catch (UserNotDefinedException e2) { userId = null; } } } } } return userId; }
diff --git a/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java b/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java index 9135f7b..4d50a4a 100644 --- a/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java +++ b/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java @@ -1,318 +1,319 @@ /* * Copyright 2008, 2009, 2010, 2011: * Tobias Fleig (tfg[AT]online[DOT]de), * Michael Haas (mekhar[AT]gmx[DOT]de), * Johannes Kattinger (johanneskattinger[AT]gmx[DOT]de) * * - All rights reserved - * * * This file is part of Centuries of Rage. * * Centuries of Rage 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. * * Centuries of Rage 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 Centuries of Rage. If not, see <http://www.gnu.org/licenses/>. * */ package de._13ducks.cor.game.server.movement; import de._13ducks.cor.game.FloatingPointPosition; import de._13ducks.cor.game.GameObject; import de._13ducks.cor.game.Moveable; import de._13ducks.cor.game.SimplePosition; import de._13ducks.cor.networks.server.behaviour.ServerBehaviour; import de._13ducks.cor.game.server.ServerCore; /** * Lowlevel-Movemanagement * * Verwaltet die reine Bewegung einer einzelnen Einheit. * Kümmert sich nicht weiter um Formationen/Kampf oder ähnliches. * Erhält vom übergeordneten MidLevelManager einen Richtungsvektor und eine Zielkoordinate. * Läuft dann dort hin. Tut sonst nichts. * Hat exklusive Kontrolle über die Einheitenposition. * Weigert sich, sich schneller als die maximale Einheitengeschwindigkeit zu bewegen. * Dadurch werden Sprünge verhindert. * * Wenn eine Kollision festgestellt wird, wird der überliegende GroupManager gefragt was zu tun ist. * Der GroupManager entscheidet dann über die Ausweichroute oder lässt uns warten. */ public class ServerBehaviourMove extends ServerBehaviour { private Moveable caster2; private SimplePosition target; private double speed; private boolean stopUnit = false; private long lastTick; private Vector lastVec; private MovementMap moveMap; /** * Die Systemzeit zu dem Zeitpunkt, an dem mit dem Warten begonnen wurde */ private long waitStartTime; /** * Gibt an, ob gerade gewartet wird * (z.B. wenn etwas im WEg steht und man wartet bis es den WEg freimacht) */ private boolean wait; /** * Die Zeit, die gewartet wird */ private static long waitTime = 1000; public ServerBehaviourMove(ServerCore.InnerServer newinner, GameObject caster1, Moveable caster2, MovementMap moveMap) { super(newinner, caster1, 1, 20, true); this.caster2 = caster2; this.moveMap = moveMap; } @Override public void activate() { active = true; trigger(); } @Override public void deactivate() { active = false; } @Override public synchronized void execute() { // Auto-Ende: if (target == null || speed <= 0) { deactivate(); return; } // Wir laufen also. // Aktuelle Position berechnen: FloatingPointPosition oldPos = caster2.getPrecisePosition(); Vector vec = target.toFPP().subtract(oldPos).toVector(); vec.normalizeMe(); long ticktime = System.currentTimeMillis(); vec.multiplyMe((ticktime - lastTick) / 1000.0 * speed); FloatingPointPosition newpos = vec.toFPP().add(oldPos); // Wir sind im Warten-Modus. Jetzt also testen, ob wir zur nächsten Position können if (wait) { // Testen, ob wir schon weiterlaufen können: // Echtzeitkollision: boolean stillColliding = false; for (Moveable m : this.caster2.moversAroundMe(4 * this.caster2.getRadius())) { if (m.getPrecisePosition().getDistance(newpos) < (m.getRadius() + this.caster2.getRadius())) { stillColliding = true; break; } } if (stillColliding) { // Immer noch Kollision if (System.currentTimeMillis() - waitStartTime < waitTime) { // Das ist ok, einfach weiter warten + lastTick = System.currentTimeMillis(); return; } else { wait = false; // Diese Bewegung richtig abbrechen stopUnit = true; } } else { // Nichtmehr weiter warten - Bewegung wieder starten wait = false; // Ticktime manipulieren. lastTick = System.currentTimeMillis(); trigger(); return; } } if (!vec.equals(lastVec) && !stopUnit) { // An Client senden rgi.netctrl.broadcastMoveVec(caster2.getNetID(), target.toFPP(), speed); lastVec = new Vector(vec.getX(), vec.getY()); } if (!stopUnit) { // Echtzeitkollision: for (Moveable m : this.caster2.moversAroundMe(4 * this.caster2.getRadius())) { if (m.getPrecisePosition().getDistance(newpos) < (m.getRadius() + this.caster2.getRadius())) { wait = this.caster2.getMidLevelManager().collisionDetected(this.caster2, m); FloatingPointPosition nextnewpos = m.getPrecisePosition().add(m.getPrecisePosition().subtract(this.caster2.getPrecisePosition()).toVector().normalize().getInverted().multiply(this.caster2.getRadius() + m.getRadius()).toFPP()); if (nextnewpos.toVector().isValid()) { newpos = nextnewpos; } else { System.out.println("WARNING: Ugly back-stop!"); newpos = oldPos.toFPP(); } if (wait) { waitStartTime = System.currentTimeMillis(); // Spezielle Stopfunktion: (hält den Client in einem Pseudozustand) // Der Client muss das auch mitbekommen rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY()))); caster2.setMainPosition(newpos); System.out.println("WAIT-COLLISION " + caster2 + " with " + m); return; // Nicht weiter ausführen! } else { // Bricht die Bewegung vollständig ab. System.out.println("STOP-COLLISION " + caster2 + " with " + m); stopUnit = true; } break; } } } // Ziel schon erreicht? Vector nextVec = target.toFPP().subtract(newpos).toVector(); if (vec.isOpposite(nextVec) && !stopUnit) { // Zielvektor erreicht // Wir sind warscheinlich drüber - egal einfach auf dem Ziel halten. caster2.setMainPosition(target.toFPP()); SimplePosition oldTar = target; // Neuen Wegpunkt anfordern: if (!stopUnit && !caster2.getMidLevelManager().reachedTarget(caster2)) { // Wenn das false gibt, gibts keine weiteren, dann hier halten. target = null; stopUnit = false; // Es ist wohl besser auf dem Ziel zu stoppen als kurz dahinter! deactivate(); } else { // Herausfinden, ob der Sektor gewechselt wurde SimplePosition newTar = target; if (newTar instanceof Node && oldTar instanceof Node) { // Nur in diesem Fall kommt ein Sektorwechsel in Frage FreePolygon sector = commonSector((Node) newTar, (Node) oldTar); // Sektor geändert? if (!sector.equals(caster2.getMyPoly())) { caster2.setMyPoly(sector); } } } } else { // Sofort stoppen? if (stopUnit) { // Der Client muss das auch mitbekommen rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY()))); caster2.setMainPosition(newpos); target = null; stopUnit = false; deactivate(); } else { // Weiterlaufen caster2.setMainPosition(newpos); lastTick = System.currentTimeMillis(); } } } @Override public void gotSignal(byte[] packet) { } @Override public void pause() { caster2.pause(); } @Override public void unpause() { caster2.unpause(); } /** * Setzt den Zielvektor für diese Einheit. * Es wird nicht untersucht, ob das Ziel in irgendeiner Weise ok ist, die Einheit beginnt sofort loszulaufen. * In der Regel sollte noch eine Geschwindigkeit angegeben werden. * Wehrt sich gegen nicht existente Ziele. * @param pos die Zielposition, wird auf direktem Weg angesteuert. */ public synchronized void setTargetVector(SimplePosition pos) { if (pos == null) { throw new IllegalArgumentException("Cannot send " + caster2 + " to null"); } if (!pos.toVector().isValid()) { throw new IllegalArgumentException("Cannot send " + caster2 + " to invalid position"); } target = pos; lastTick = System.currentTimeMillis(); lastVec = Vector.ZERO; activate(); } /** * Setzt den Zielvektor und die Geschwindigkeit und startet die Bewegung sofort. * @param pos die Zielposition * @param speed die Geschwindigkeit */ public synchronized void setTargetVector(SimplePosition pos, double speed) { changeSpeed(speed); setTargetVector(pos); } /** * Ändert die Geschwindigkeit während des Laufens. * Speed wird verkleinert, wenn der Wert über dem Einheiten-Maximum liegen würde * @param speed Die Einheitengeschwindigkeit */ public synchronized void changeSpeed(double speed) { if (speed > 0 && speed <= caster2.getSpeed()) { this.speed = speed; } trigger(); } public boolean isMoving() { return target != null; } /** * Stoppt die Einheit innerhalb eines Ticks. */ public synchronized void stopImmediately() { stopUnit = true; trigger(); } /** * Findet einen Sektor, den beide Knoten gemeinsam haben * @param n1 Knoten 1 * @param n2 Knoten 2 */ private FreePolygon commonSector(Node n1, Node n2) { for (FreePolygon poly : n1.getPolygons()) { if (n2.getPolygons().contains(poly)) { return poly; } } return null; } /** * Berechnet den Winkel zwischen zwei Vektoren * @param vector_1 * @param vector_2 * @return */ public double getAngle(FloatingPointPosition vector_1, FloatingPointPosition vector_2) { double scalar = ((vector_1.getfX() * vector_2.getfX()) + (vector_1.getfY() * vector_2.getfY())); double vector_1_lenght = Math.sqrt((vector_1.getfX() * vector_1.getfX()) + vector_2.getfY() * vector_1.getfY()); double vector_2_lenght = Math.sqrt((vector_2.getfX() * vector_2.getfX()) + vector_2.getfY() * vector_2.getfY()); double lenght = vector_1_lenght * vector_2_lenght; double angle = Math.acos((scalar / lenght)); return angle; } }
true
true
public synchronized void execute() { // Auto-Ende: if (target == null || speed <= 0) { deactivate(); return; } // Wir laufen also. // Aktuelle Position berechnen: FloatingPointPosition oldPos = caster2.getPrecisePosition(); Vector vec = target.toFPP().subtract(oldPos).toVector(); vec.normalizeMe(); long ticktime = System.currentTimeMillis(); vec.multiplyMe((ticktime - lastTick) / 1000.0 * speed); FloatingPointPosition newpos = vec.toFPP().add(oldPos); // Wir sind im Warten-Modus. Jetzt also testen, ob wir zur nächsten Position können if (wait) { // Testen, ob wir schon weiterlaufen können: // Echtzeitkollision: boolean stillColliding = false; for (Moveable m : this.caster2.moversAroundMe(4 * this.caster2.getRadius())) { if (m.getPrecisePosition().getDistance(newpos) < (m.getRadius() + this.caster2.getRadius())) { stillColliding = true; break; } } if (stillColliding) { // Immer noch Kollision if (System.currentTimeMillis() - waitStartTime < waitTime) { // Das ist ok, einfach weiter warten return; } else { wait = false; // Diese Bewegung richtig abbrechen stopUnit = true; } } else { // Nichtmehr weiter warten - Bewegung wieder starten wait = false; // Ticktime manipulieren. lastTick = System.currentTimeMillis(); trigger(); return; } } if (!vec.equals(lastVec) && !stopUnit) { // An Client senden rgi.netctrl.broadcastMoveVec(caster2.getNetID(), target.toFPP(), speed); lastVec = new Vector(vec.getX(), vec.getY()); } if (!stopUnit) { // Echtzeitkollision: for (Moveable m : this.caster2.moversAroundMe(4 * this.caster2.getRadius())) { if (m.getPrecisePosition().getDistance(newpos) < (m.getRadius() + this.caster2.getRadius())) { wait = this.caster2.getMidLevelManager().collisionDetected(this.caster2, m); FloatingPointPosition nextnewpos = m.getPrecisePosition().add(m.getPrecisePosition().subtract(this.caster2.getPrecisePosition()).toVector().normalize().getInverted().multiply(this.caster2.getRadius() + m.getRadius()).toFPP()); if (nextnewpos.toVector().isValid()) { newpos = nextnewpos; } else { System.out.println("WARNING: Ugly back-stop!"); newpos = oldPos.toFPP(); } if (wait) { waitStartTime = System.currentTimeMillis(); // Spezielle Stopfunktion: (hält den Client in einem Pseudozustand) // Der Client muss das auch mitbekommen rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY()))); caster2.setMainPosition(newpos); System.out.println("WAIT-COLLISION " + caster2 + " with " + m); return; // Nicht weiter ausführen! } else { // Bricht die Bewegung vollständig ab. System.out.println("STOP-COLLISION " + caster2 + " with " + m); stopUnit = true; } break; } } } // Ziel schon erreicht? Vector nextVec = target.toFPP().subtract(newpos).toVector(); if (vec.isOpposite(nextVec) && !stopUnit) { // Zielvektor erreicht // Wir sind warscheinlich drüber - egal einfach auf dem Ziel halten. caster2.setMainPosition(target.toFPP()); SimplePosition oldTar = target; // Neuen Wegpunkt anfordern: if (!stopUnit && !caster2.getMidLevelManager().reachedTarget(caster2)) { // Wenn das false gibt, gibts keine weiteren, dann hier halten. target = null; stopUnit = false; // Es ist wohl besser auf dem Ziel zu stoppen als kurz dahinter! deactivate(); } else { // Herausfinden, ob der Sektor gewechselt wurde SimplePosition newTar = target; if (newTar instanceof Node && oldTar instanceof Node) { // Nur in diesem Fall kommt ein Sektorwechsel in Frage FreePolygon sector = commonSector((Node) newTar, (Node) oldTar); // Sektor geändert? if (!sector.equals(caster2.getMyPoly())) { caster2.setMyPoly(sector); } } } } else { // Sofort stoppen? if (stopUnit) { // Der Client muss das auch mitbekommen rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY()))); caster2.setMainPosition(newpos); target = null; stopUnit = false; deactivate(); } else { // Weiterlaufen caster2.setMainPosition(newpos); lastTick = System.currentTimeMillis(); } } }
public synchronized void execute() { // Auto-Ende: if (target == null || speed <= 0) { deactivate(); return; } // Wir laufen also. // Aktuelle Position berechnen: FloatingPointPosition oldPos = caster2.getPrecisePosition(); Vector vec = target.toFPP().subtract(oldPos).toVector(); vec.normalizeMe(); long ticktime = System.currentTimeMillis(); vec.multiplyMe((ticktime - lastTick) / 1000.0 * speed); FloatingPointPosition newpos = vec.toFPP().add(oldPos); // Wir sind im Warten-Modus. Jetzt also testen, ob wir zur nächsten Position können if (wait) { // Testen, ob wir schon weiterlaufen können: // Echtzeitkollision: boolean stillColliding = false; for (Moveable m : this.caster2.moversAroundMe(4 * this.caster2.getRadius())) { if (m.getPrecisePosition().getDistance(newpos) < (m.getRadius() + this.caster2.getRadius())) { stillColliding = true; break; } } if (stillColliding) { // Immer noch Kollision if (System.currentTimeMillis() - waitStartTime < waitTime) { // Das ist ok, einfach weiter warten lastTick = System.currentTimeMillis(); return; } else { wait = false; // Diese Bewegung richtig abbrechen stopUnit = true; } } else { // Nichtmehr weiter warten - Bewegung wieder starten wait = false; // Ticktime manipulieren. lastTick = System.currentTimeMillis(); trigger(); return; } } if (!vec.equals(lastVec) && !stopUnit) { // An Client senden rgi.netctrl.broadcastMoveVec(caster2.getNetID(), target.toFPP(), speed); lastVec = new Vector(vec.getX(), vec.getY()); } if (!stopUnit) { // Echtzeitkollision: for (Moveable m : this.caster2.moversAroundMe(4 * this.caster2.getRadius())) { if (m.getPrecisePosition().getDistance(newpos) < (m.getRadius() + this.caster2.getRadius())) { wait = this.caster2.getMidLevelManager().collisionDetected(this.caster2, m); FloatingPointPosition nextnewpos = m.getPrecisePosition().add(m.getPrecisePosition().subtract(this.caster2.getPrecisePosition()).toVector().normalize().getInverted().multiply(this.caster2.getRadius() + m.getRadius()).toFPP()); if (nextnewpos.toVector().isValid()) { newpos = nextnewpos; } else { System.out.println("WARNING: Ugly back-stop!"); newpos = oldPos.toFPP(); } if (wait) { waitStartTime = System.currentTimeMillis(); // Spezielle Stopfunktion: (hält den Client in einem Pseudozustand) // Der Client muss das auch mitbekommen rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY()))); caster2.setMainPosition(newpos); System.out.println("WAIT-COLLISION " + caster2 + " with " + m); return; // Nicht weiter ausführen! } else { // Bricht die Bewegung vollständig ab. System.out.println("STOP-COLLISION " + caster2 + " with " + m); stopUnit = true; } break; } } } // Ziel schon erreicht? Vector nextVec = target.toFPP().subtract(newpos).toVector(); if (vec.isOpposite(nextVec) && !stopUnit) { // Zielvektor erreicht // Wir sind warscheinlich drüber - egal einfach auf dem Ziel halten. caster2.setMainPosition(target.toFPP()); SimplePosition oldTar = target; // Neuen Wegpunkt anfordern: if (!stopUnit && !caster2.getMidLevelManager().reachedTarget(caster2)) { // Wenn das false gibt, gibts keine weiteren, dann hier halten. target = null; stopUnit = false; // Es ist wohl besser auf dem Ziel zu stoppen als kurz dahinter! deactivate(); } else { // Herausfinden, ob der Sektor gewechselt wurde SimplePosition newTar = target; if (newTar instanceof Node && oldTar instanceof Node) { // Nur in diesem Fall kommt ein Sektorwechsel in Frage FreePolygon sector = commonSector((Node) newTar, (Node) oldTar); // Sektor geändert? if (!sector.equals(caster2.getMyPoly())) { caster2.setMyPoly(sector); } } } } else { // Sofort stoppen? if (stopUnit) { // Der Client muss das auch mitbekommen rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY()))); caster2.setMainPosition(newpos); target = null; stopUnit = false; deactivate(); } else { // Weiterlaufen caster2.setMainPosition(newpos); lastTick = System.currentTimeMillis(); } } }
diff --git a/src/app/Session.java b/src/app/Session.java index 8f09953..0cb5824 100644 --- a/src/app/Session.java +++ b/src/app/Session.java @@ -1,45 +1,45 @@ package app; import org.neo4j.graphdb.Transaction; import java.util.Date; import java.util.Calendar; public class Session { // Reference account public final User user; public final Date validUntil; public static Session createFromLogin( String email, String password ) { Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.HOUR_OF_DAY, 1); Session s; try(Transaction tx = GraphDatabase.get().beginTx()) { //TODO: query DB using email & password - s = new Session(new User(email)); + s = new Session(new User(email), cal.getTime()); if( s.user.getPassword() == null || s.user.getPassword() != password ) { return null; } tx.success(); } return s; } public Session(User user, Date validUntil) { if(user == null || validUntil == null) { throw new IllegalArgumentException(); } this.user = user; this.validUntil = validUntil; } public boolean isValid() { Date now = new Date(); //test if validUntil is equal to now or now is < 0 (before validUntil) return (now.compareTo(validUntil) <= 0); } }
true
true
public static Session createFromLogin( String email, String password ) { Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.HOUR_OF_DAY, 1); Session s; try(Transaction tx = GraphDatabase.get().beginTx()) { //TODO: query DB using email & password s = new Session(new User(email)); if( s.user.getPassword() == null || s.user.getPassword() != password ) { return null; } tx.success(); } return s; }
public static Session createFromLogin( String email, String password ) { Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.HOUR_OF_DAY, 1); Session s; try(Transaction tx = GraphDatabase.get().beginTx()) { //TODO: query DB using email & password s = new Session(new User(email), cal.getTime()); if( s.user.getPassword() == null || s.user.getPassword() != password ) { return null; } tx.success(); } return s; }
diff --git a/src/blur-thrift/src/main/java/com/nearinfinity/blur/thrift/BlurClientManager.java b/src/blur-thrift/src/main/java/com/nearinfinity/blur/thrift/BlurClientManager.java index cbe5b5a5..6e3cb5d4 100644 --- a/src/blur-thrift/src/main/java/com/nearinfinity/blur/thrift/BlurClientManager.java +++ b/src/blur-thrift/src/main/java/com/nearinfinity/blur/thrift/BlurClientManager.java @@ -1,327 +1,329 @@ /* * Copyright (C) 2011 Near Infinity Corporation * * 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.nearinfinity.blur.thrift; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.Proxy.Type; import java.net.Socket; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TFramedTransport; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransportException; import com.nearinfinity.blur.log.Log; import com.nearinfinity.blur.log.LogFactory; import com.nearinfinity.blur.thrift.generated.Blur; import com.nearinfinity.blur.thrift.generated.Blur.Client; import com.nearinfinity.blur.thrift.generated.BlurException; public class BlurClientManager { private static final Object NULL = new Object(); private static final Log LOG = LogFactory.getLog(BlurClientManager.class); private static final int MAX_RETRIES = 5; private static final long BACK_OFF_TIME = TimeUnit.MILLISECONDS.toMillis(250); private static final long MAX_BACK_OFF_TIME = TimeUnit.SECONDS.toMillis(10); private static final long ONE_SECOND = TimeUnit.SECONDS.toMillis(1); private static Map<Connection, BlockingQueue<Client>> clientPool = new ConcurrentHashMap<Connection, BlockingQueue<Client>>(); private static Thread daemon; private static AtomicBoolean running = new AtomicBoolean(true); private static Map<Connection,Object> badConnections = new ConcurrentHashMap<Connection, Object>(); static { startDaemon(); } private static void startDaemon() { daemon = new Thread(new Runnable() { private Set<Connection> good = new HashSet<Connection>(); @Override public void run() { while (running.get()) { good.clear(); Set<Connection> badConns = badConnections.keySet(); for (Connection connection : badConns) { if (isConnectionGood(connection)) { good.add(connection); } } for (Connection connection : good) { badConnections.remove(connection); } try { Thread.sleep(ONE_SECOND); } catch (InterruptedException e) { return; } } } }); daemon.setDaemon(true); daemon.setName("Blur-Client-Manager-Connection-Checker"); daemon.start(); } protected static boolean isConnectionGood(Connection connection) { try { returnClient(connection, getClient(connection)); return true; } catch (TTransportException e) { LOG.debug("Connection [{0}] is still bad.", connection); } catch (IOException e) { LOG.debug("Connection [{0}] is still bad.", connection); } return false; } public static <CLIENT, T> T execute(Connection connection, AbstractCommand<CLIENT, T> command) throws BlurException, TException, IOException { return execute(connection, command, MAX_RETRIES, BACK_OFF_TIME, MAX_BACK_OFF_TIME); } public static <CLIENT, T> T execute(Connection connection, AbstractCommand<CLIENT, T> command, int maxRetries, long backOffTime, long maxBackOffTime) throws BlurException, TException, IOException { return execute(Arrays.asList(connection), command, maxRetries, backOffTime, maxBackOffTime); } public static <CLIENT, T> T execute(List<Connection> connections, AbstractCommand<CLIENT, T> command) throws BlurException, TException, IOException { return execute(connections, command, MAX_RETRIES, BACK_OFF_TIME, MAX_BACK_OFF_TIME); } private static class LocalResources { AtomicInteger retries = new AtomicInteger(); AtomicReference<Blur.Client> client = new AtomicReference<Client>(); List<Connection> shuffledConnections = new ArrayList<Connection>(); Random random = new Random(); } // private static ThreadLocal<LocalResources> resources = new ThreadLocal<BlurClientManager.LocalResources>() { // @Override // protected LocalResources initialValue() { // return new LocalResources(); // } // }; @SuppressWarnings("unchecked") public static <CLIENT, T> T execute(List<Connection> connections, AbstractCommand<CLIENT, T> command, int maxRetries, long backOffTime, long maxBackOffTime) throws BlurException, TException, IOException { // LocalResources localResources = resources.get(); LocalResources localResources = null; try { if (localResources == null) { localResources = new LocalResources(); } // resources.set(null); AtomicReference<Client> client = localResources.client; Random random = localResources.random; AtomicInteger retries = localResources.retries; List<Connection> shuffledConnections = localResources.shuffledConnections; retries.set(0); shuffledConnections.addAll(connections); Collections.shuffle(shuffledConnections, random); while (true) { for (Connection connection : shuffledConnections) { if (isBadConnection(connection)) { continue; } client.set(null); try { client.set(getClient(connection)); } catch (IOException e) { if (handleError(connection,client,retries,command,e,maxRetries,backOffTime,maxBackOffTime)) { throw e; } else { markBadConnection(connection); continue; } } try { return command.call((CLIENT) client.get()); } catch (RuntimeException e) { Throwable cause = e.getCause(); if (cause instanceof TTransportException) { TTransportException t = (TTransportException) cause; if (handleError(connection,client,retries,command,t,maxRetries,backOffTime,maxBackOffTime)) { throw t; } + } else { + throw e; } } catch (TTransportException e) { if (handleError(connection,client,retries,command,e,maxRetries,backOffTime,maxBackOffTime)) { throw e; } } finally { if (client.get() != null) { returnClient(connection, client); } } } } } finally { // resources.set(localResources); } } private static void markBadConnection(Connection connection) { LOG.info("Marking bad connection [{0}]",connection); badConnections.put(connection, NULL); } private static boolean isBadConnection(Connection connection) { return badConnections.containsKey(connection); } private static <CLIENT,T> boolean handleError(Connection connection, AtomicReference<Blur.Client> client, AtomicInteger retries, AbstractCommand<CLIENT, T> command, Exception e, int maxRetries, long backOffTime, long maxBackOffTime) { if (client.get() != null) { trashConnections(connection,client); markBadConnection(connection); client.set(null); } if (retries.get() > maxRetries) { LOG.error("No more retries [{0}] out of [{1}]", retries, maxRetries); return true; } LOG.error("Retrying call [{0}] retry [{1}] out of [{2}] message [{3}]", command, retries.get(), maxRetries, e.getMessage()); sleep(backOffTime,maxBackOffTime,retries.get(),maxRetries); retries.incrementAndGet(); return false; } public static void sleep(long backOffTime, long maxBackOffTime, int retry, int maxRetries) { long extra = (maxBackOffTime - backOffTime) / maxRetries; long sleep = backOffTime + (extra * retry); LOG.info("Backing off call for [{0} ms]",sleep); try { Thread.sleep(sleep); } catch (InterruptedException e) { throw new RuntimeException(e); } } public static <CLIENT, T> T execute(String connectionStr, AbstractCommand<CLIENT, T> command, int maxRetries, long backOffTime, long maxBackOffTime) throws BlurException, TException, IOException { return execute(getCommands(connectionStr),command,maxRetries,backOffTime,maxBackOffTime); } private static List<Connection> getCommands(String connectionStr) { int start = 0; int index = connectionStr.indexOf(','); if (index >= 0) { List<Connection> connections = new ArrayList<Connection>(); while (index >= 0) { connections.add(new Connection(connectionStr.substring(start, index))); start = index + 1; index = connectionStr.indexOf(',', start); } connections.add(new Connection(connectionStr.substring(start))); return connections; } return Arrays.asList(new Connection(connectionStr)); } public static <CLIENT, T> T execute(String connectionStr, AbstractCommand<CLIENT, T> command) throws BlurException, TException, IOException { return execute(getCommands(connectionStr),command); } private static void returnClient(Connection connection, AtomicReference<Blur.Client> client) { returnClient(connection, client.get()); } private static void returnClient(Connection connection, Blur.Client client) { try { clientPool.get(connection).put(client); } catch (InterruptedException e) { throw new RuntimeException(e); } } private static void trashConnections(Connection connection, AtomicReference<Client> c) { BlockingQueue<Client> blockingQueue; synchronized (clientPool) { blockingQueue = clientPool.put(connection,new LinkedBlockingQueue<Client>()); try { blockingQueue.put(c.get()); } catch (InterruptedException e) { throw new RuntimeException(e); } } LOG.info("Trashing client for connections [{0}]",connection); for (Client client : blockingQueue) { client.getInputProtocol().getTransport().close(); client.getOutputProtocol().getTransport().close(); } } private static Client getClient(Connection connection) throws TTransportException, IOException { BlockingQueue<Client> blockingQueue; synchronized (clientPool) { blockingQueue = clientPool.get(connection); if (blockingQueue == null) { blockingQueue = new LinkedBlockingQueue<Client>(); clientPool.put(connection, blockingQueue); } } if (blockingQueue.isEmpty()) { return newClient(connection); } try { return blockingQueue.take(); } catch (InterruptedException e) { throw new RuntimeException(e); } } private static Client newClient(Connection connection) throws TTransportException, IOException { String host = connection.getHost(); int port = connection.getPort(); TSocket trans; Socket socket; if (connection.isProxy()) { Proxy proxy = new Proxy(Type.SOCKS, new InetSocketAddress(connection.getProxyHost(),connection.getProxyPort())); socket = new Socket(proxy); } else { socket = new Socket(); } socket.connect(new InetSocketAddress(host, port)); trans = new TSocket(socket); TProtocol proto = new TBinaryProtocol(new TFramedTransport(trans)); Client client = new Client(proto); return client; } }
true
true
public static <CLIENT, T> T execute(List<Connection> connections, AbstractCommand<CLIENT, T> command, int maxRetries, long backOffTime, long maxBackOffTime) throws BlurException, TException, IOException { // LocalResources localResources = resources.get(); LocalResources localResources = null; try { if (localResources == null) { localResources = new LocalResources(); } // resources.set(null); AtomicReference<Client> client = localResources.client; Random random = localResources.random; AtomicInteger retries = localResources.retries; List<Connection> shuffledConnections = localResources.shuffledConnections; retries.set(0); shuffledConnections.addAll(connections); Collections.shuffle(shuffledConnections, random); while (true) { for (Connection connection : shuffledConnections) { if (isBadConnection(connection)) { continue; } client.set(null); try { client.set(getClient(connection)); } catch (IOException e) { if (handleError(connection,client,retries,command,e,maxRetries,backOffTime,maxBackOffTime)) { throw e; } else { markBadConnection(connection); continue; } } try { return command.call((CLIENT) client.get()); } catch (RuntimeException e) { Throwable cause = e.getCause(); if (cause instanceof TTransportException) { TTransportException t = (TTransportException) cause; if (handleError(connection,client,retries,command,t,maxRetries,backOffTime,maxBackOffTime)) { throw t; } } } catch (TTransportException e) { if (handleError(connection,client,retries,command,e,maxRetries,backOffTime,maxBackOffTime)) { throw e; } } finally { if (client.get() != null) { returnClient(connection, client); } } } } } finally { // resources.set(localResources); } }
public static <CLIENT, T> T execute(List<Connection> connections, AbstractCommand<CLIENT, T> command, int maxRetries, long backOffTime, long maxBackOffTime) throws BlurException, TException, IOException { // LocalResources localResources = resources.get(); LocalResources localResources = null; try { if (localResources == null) { localResources = new LocalResources(); } // resources.set(null); AtomicReference<Client> client = localResources.client; Random random = localResources.random; AtomicInteger retries = localResources.retries; List<Connection> shuffledConnections = localResources.shuffledConnections; retries.set(0); shuffledConnections.addAll(connections); Collections.shuffle(shuffledConnections, random); while (true) { for (Connection connection : shuffledConnections) { if (isBadConnection(connection)) { continue; } client.set(null); try { client.set(getClient(connection)); } catch (IOException e) { if (handleError(connection,client,retries,command,e,maxRetries,backOffTime,maxBackOffTime)) { throw e; } else { markBadConnection(connection); continue; } } try { return command.call((CLIENT) client.get()); } catch (RuntimeException e) { Throwable cause = e.getCause(); if (cause instanceof TTransportException) { TTransportException t = (TTransportException) cause; if (handleError(connection,client,retries,command,t,maxRetries,backOffTime,maxBackOffTime)) { throw t; } } else { throw e; } } catch (TTransportException e) { if (handleError(connection,client,retries,command,e,maxRetries,backOffTime,maxBackOffTime)) { throw e; } } finally { if (client.get() != null) { returnClient(connection, client); } } } } } finally { // resources.set(localResources); } }
diff --git a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/history/command/ShowVersionsHandler.java b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/history/command/ShowVersionsHandler.java index 8a9ce037..2fdb9974 100644 --- a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/history/command/ShowVersionsHandler.java +++ b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/history/command/ShowVersionsHandler.java @@ -1,183 +1,183 @@ /******************************************************************************* * Copyright (C) 2010, Mathias Kinzler <[email protected]> * * 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 *******************************************************************************/ package org.eclipse.egit.ui.internal.history.command; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.compare.ITypedElement; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.egit.core.project.RepositoryMapping; import org.eclipse.egit.ui.Activator; import org.eclipse.egit.ui.UIText; import org.eclipse.egit.ui.internal.CompareUtils; import org.eclipse.egit.ui.internal.EgitUiEditorUtils; import org.eclipse.egit.ui.internal.GitCompareFileRevisionEditorInput; import org.eclipse.egit.ui.internal.history.GitHistoryPage; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.osgi.util.NLS; import org.eclipse.team.core.history.IFileRevision; import org.eclipse.team.ui.synchronize.SaveableCompareEditorInput; /** * Show versions/open. * <p> * If a single version is selected, open it, otherwise open several versions of * the file content. */ public class ShowVersionsHandler extends AbstractHistoryCommanndHandler { public Object execute(ExecutionEvent event) throws ExecutionException { boolean compareMode = Boolean.TRUE.toString().equals( event.getParameter(HistoryViewCommands.COMPARE_MODE_PARAM)); IStructuredSelection selection = getSelection(getPage()); if (selection.size() < 1) return null; Object input = getPage().getInputInternal().getSingleFile(); if (input == null) return null; boolean errorOccured = false; List<ObjectId> ids = new ArrayList<ObjectId>(); String gitPath = null; if (input instanceof IFile) { IFile resource = (IFile) input; final RepositoryMapping map = RepositoryMapping .getMapping(resource); gitPath = map.getRepoRelativePath(resource); Iterator<?> it = selection.iterator(); while (it.hasNext()) { RevCommit commit = (RevCommit) it.next(); IFileRevision rev = null; try { rev = CompareUtils.getFileRevision(gitPath, commit, map .getRepository(), null); } catch (IOException e) { Activator.logError(NLS.bind( UIText.GitHistoryPage_errorLookingUpPath, gitPath, commit.getId()), e); errorOccured = true; } if (rev != null) { if (compareMode) { ITypedElement right = CompareUtils .getFileRevisionTypedElement(gitPath, commit, map.getRepository()); final GitCompareFileRevisionEditorInput in = new GitCompareFileRevisionEditorInput( SaveableCompareEditorInput .createFileElement(resource), right, null); try { openInCompare(event, in); } catch (Exception e) { errorOccured = true; } } else { try { EgitUiEditorUtils.openEditor(getPart(event) .getSite().getPage(), rev, new NullProgressMonitor()); } catch (CoreException e) { Activator.logError( UIText.GitHistoryPage_openFailed, e); errorOccured = true; } } } else { ids.add(commit.getId()); } } } if (input instanceof File) { File fileInput = (File) input; Repository repo = getRepository(event); gitPath = getRepoRelativePath(repo, fileInput); Iterator<?> it = selection.iterator(); while (it.hasNext()) { RevCommit commit = (RevCommit) it.next(); IFileRevision rev = null; try { rev = CompareUtils.getFileRevision(gitPath, commit, repo, null); } catch (IOException e) { Activator.logError(NLS.bind( UIText.GitHistoryPage_errorLookingUpPath, gitPath, commit.getId()), e); errorOccured = true; } if (rev != null) { if (compareMode) { try { ITypedElement left = CompareUtils .getFileRevisionTypedElement(gitPath, new RevWalk(repo).parseCommit(repo .resolve(Constants.HEAD)), repo); ITypedElement right = CompareUtils .getFileRevisionTypedElement(gitPath, commit, repo); final GitCompareFileRevisionEditorInput in = new GitCompareFileRevisionEditorInput( left, right, null); openInCompare(event, in); - } catch (Exception e) { + } catch (IOException e) { errorOccured = true; } } else { try { EgitUiEditorUtils.openEditor(getPart(event) .getSite().getPage(), rev, new NullProgressMonitor()); } catch (CoreException e) { Activator.logError( UIText.GitHistoryPage_openFailed, e); errorOccured = true; } } } else { ids.add(commit.getId()); } } } if (errorOccured) Activator.showError(UIText.GitHistoryPage_openFailed, null); if (ids.size() > 0) { String idList = ""; //$NON-NLS-1$ for (ObjectId objectId : ids) { idList += objectId.getName() + " "; //$NON-NLS-1$ } MessageDialog.openError(getPart(event).getSite().getShell(), UIText.GitHistoryPage_fileNotFound, NLS.bind( UIText.GitHistoryPage_notContainedInCommits, gitPath, idList)); } return null; } @Override public boolean isEnabled() { GitHistoryPage page = getPage(); if (page == null) return false; int size = getSelection(page).size(); if (size == 0) return false; return page.getInputInternal().isSingleFile(); } }
true
true
public Object execute(ExecutionEvent event) throws ExecutionException { boolean compareMode = Boolean.TRUE.toString().equals( event.getParameter(HistoryViewCommands.COMPARE_MODE_PARAM)); IStructuredSelection selection = getSelection(getPage()); if (selection.size() < 1) return null; Object input = getPage().getInputInternal().getSingleFile(); if (input == null) return null; boolean errorOccured = false; List<ObjectId> ids = new ArrayList<ObjectId>(); String gitPath = null; if (input instanceof IFile) { IFile resource = (IFile) input; final RepositoryMapping map = RepositoryMapping .getMapping(resource); gitPath = map.getRepoRelativePath(resource); Iterator<?> it = selection.iterator(); while (it.hasNext()) { RevCommit commit = (RevCommit) it.next(); IFileRevision rev = null; try { rev = CompareUtils.getFileRevision(gitPath, commit, map .getRepository(), null); } catch (IOException e) { Activator.logError(NLS.bind( UIText.GitHistoryPage_errorLookingUpPath, gitPath, commit.getId()), e); errorOccured = true; } if (rev != null) { if (compareMode) { ITypedElement right = CompareUtils .getFileRevisionTypedElement(gitPath, commit, map.getRepository()); final GitCompareFileRevisionEditorInput in = new GitCompareFileRevisionEditorInput( SaveableCompareEditorInput .createFileElement(resource), right, null); try { openInCompare(event, in); } catch (Exception e) { errorOccured = true; } } else { try { EgitUiEditorUtils.openEditor(getPart(event) .getSite().getPage(), rev, new NullProgressMonitor()); } catch (CoreException e) { Activator.logError( UIText.GitHistoryPage_openFailed, e); errorOccured = true; } } } else { ids.add(commit.getId()); } } } if (input instanceof File) { File fileInput = (File) input; Repository repo = getRepository(event); gitPath = getRepoRelativePath(repo, fileInput); Iterator<?> it = selection.iterator(); while (it.hasNext()) { RevCommit commit = (RevCommit) it.next(); IFileRevision rev = null; try { rev = CompareUtils.getFileRevision(gitPath, commit, repo, null); } catch (IOException e) { Activator.logError(NLS.bind( UIText.GitHistoryPage_errorLookingUpPath, gitPath, commit.getId()), e); errorOccured = true; } if (rev != null) { if (compareMode) { try { ITypedElement left = CompareUtils .getFileRevisionTypedElement(gitPath, new RevWalk(repo).parseCommit(repo .resolve(Constants.HEAD)), repo); ITypedElement right = CompareUtils .getFileRevisionTypedElement(gitPath, commit, repo); final GitCompareFileRevisionEditorInput in = new GitCompareFileRevisionEditorInput( left, right, null); openInCompare(event, in); } catch (Exception e) { errorOccured = true; } } else { try { EgitUiEditorUtils.openEditor(getPart(event) .getSite().getPage(), rev, new NullProgressMonitor()); } catch (CoreException e) { Activator.logError( UIText.GitHistoryPage_openFailed, e); errorOccured = true; } } } else { ids.add(commit.getId()); } } } if (errorOccured) Activator.showError(UIText.GitHistoryPage_openFailed, null); if (ids.size() > 0) { String idList = ""; //$NON-NLS-1$ for (ObjectId objectId : ids) { idList += objectId.getName() + " "; //$NON-NLS-1$ } MessageDialog.openError(getPart(event).getSite().getShell(), UIText.GitHistoryPage_fileNotFound, NLS.bind( UIText.GitHistoryPage_notContainedInCommits, gitPath, idList)); } return null; }
public Object execute(ExecutionEvent event) throws ExecutionException { boolean compareMode = Boolean.TRUE.toString().equals( event.getParameter(HistoryViewCommands.COMPARE_MODE_PARAM)); IStructuredSelection selection = getSelection(getPage()); if (selection.size() < 1) return null; Object input = getPage().getInputInternal().getSingleFile(); if (input == null) return null; boolean errorOccured = false; List<ObjectId> ids = new ArrayList<ObjectId>(); String gitPath = null; if (input instanceof IFile) { IFile resource = (IFile) input; final RepositoryMapping map = RepositoryMapping .getMapping(resource); gitPath = map.getRepoRelativePath(resource); Iterator<?> it = selection.iterator(); while (it.hasNext()) { RevCommit commit = (RevCommit) it.next(); IFileRevision rev = null; try { rev = CompareUtils.getFileRevision(gitPath, commit, map .getRepository(), null); } catch (IOException e) { Activator.logError(NLS.bind( UIText.GitHistoryPage_errorLookingUpPath, gitPath, commit.getId()), e); errorOccured = true; } if (rev != null) { if (compareMode) { ITypedElement right = CompareUtils .getFileRevisionTypedElement(gitPath, commit, map.getRepository()); final GitCompareFileRevisionEditorInput in = new GitCompareFileRevisionEditorInput( SaveableCompareEditorInput .createFileElement(resource), right, null); try { openInCompare(event, in); } catch (Exception e) { errorOccured = true; } } else { try { EgitUiEditorUtils.openEditor(getPart(event) .getSite().getPage(), rev, new NullProgressMonitor()); } catch (CoreException e) { Activator.logError( UIText.GitHistoryPage_openFailed, e); errorOccured = true; } } } else { ids.add(commit.getId()); } } } if (input instanceof File) { File fileInput = (File) input; Repository repo = getRepository(event); gitPath = getRepoRelativePath(repo, fileInput); Iterator<?> it = selection.iterator(); while (it.hasNext()) { RevCommit commit = (RevCommit) it.next(); IFileRevision rev = null; try { rev = CompareUtils.getFileRevision(gitPath, commit, repo, null); } catch (IOException e) { Activator.logError(NLS.bind( UIText.GitHistoryPage_errorLookingUpPath, gitPath, commit.getId()), e); errorOccured = true; } if (rev != null) { if (compareMode) { try { ITypedElement left = CompareUtils .getFileRevisionTypedElement(gitPath, new RevWalk(repo).parseCommit(repo .resolve(Constants.HEAD)), repo); ITypedElement right = CompareUtils .getFileRevisionTypedElement(gitPath, commit, repo); final GitCompareFileRevisionEditorInput in = new GitCompareFileRevisionEditorInput( left, right, null); openInCompare(event, in); } catch (IOException e) { errorOccured = true; } } else { try { EgitUiEditorUtils.openEditor(getPart(event) .getSite().getPage(), rev, new NullProgressMonitor()); } catch (CoreException e) { Activator.logError( UIText.GitHistoryPage_openFailed, e); errorOccured = true; } } } else { ids.add(commit.getId()); } } } if (errorOccured) Activator.showError(UIText.GitHistoryPage_openFailed, null); if (ids.size() > 0) { String idList = ""; //$NON-NLS-1$ for (ObjectId objectId : ids) { idList += objectId.getName() + " "; //$NON-NLS-1$ } MessageDialog.openError(getPart(event).getSite().getShell(), UIText.GitHistoryPage_fileNotFound, NLS.bind( UIText.GitHistoryPage_notContainedInCommits, gitPath, idList)); } return null; }
diff --git a/src/com/tactfactory/harmony/plateforme/SqliteAdapter.java b/src/com/tactfactory/harmony/plateforme/SqliteAdapter.java index 5b249129..34cd7b94 100644 --- a/src/com/tactfactory/harmony/plateforme/SqliteAdapter.java +++ b/src/com/tactfactory/harmony/plateforme/SqliteAdapter.java @@ -1,400 +1,401 @@ /** * This file is part of the Harmony package. * * (c) Mickael Gaillard <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ package com.tactfactory.harmony.plateforme; import java.lang.reflect.Field; import java.util.ArrayList; import com.google.common.base.Strings; import com.tactfactory.harmony.annotation.Column; import com.tactfactory.harmony.annotation.Column.Type; import com.tactfactory.harmony.annotation.InheritanceType.InheritanceMode; import com.tactfactory.harmony.meta.ApplicationMetadata; import com.tactfactory.harmony.meta.EntityMetadata; import com.tactfactory.harmony.meta.EnumMetadata; import com.tactfactory.harmony.meta.FieldMetadata; import com.tactfactory.harmony.utils.ConsoleUtils; /** * SQliteAdapter. */ public abstract class SqliteAdapter { /** Prefix for column name generation. */ private static final String PREFIX = "COL_"; /** Suffix for column name generation. */ private static final String SUFFIX = "_ID"; /** * Generate field's structure for database creation schema. * @param fm The field * @return The field's structure */ public static String generateStructure(final FieldMetadata fm) { final StringBuilder builder = new StringBuilder(20); builder.append(' '); builder.append(fm.getColumnDefinition()); if (fm.isId()) { builder.append(" PRIMARY KEY"); if (fm.getColumnDefinition().equalsIgnoreCase("INTEGER")) { builder.append(" AUTOINCREMENT"); } } else { // Set Length final Type fieldType = Type.fromName(fm.getType()); if (fieldType != null) { if (fm.getLength() != null && fm.getLength() != fieldType.getLength()) { builder.append('('); builder.append(fm.getLength()); builder.append(')'); } else if (fm.getPrecision() != null && fm.getPrecision() != fieldType.getPrecision()) { builder.append('('); builder.append(fm.getPrecision()); if (fm.getScale() != null && fm.getScale() != fieldType.getScale()) { builder.append(','); builder.append(fm.getScale()); } builder.append(')'); } } // Set Unique /*if (fm.isUnique() != null && fm.isUnique()) { builder.append(" UNIQUE"); }*/ boolean isSingleTabInherited = fm.getOwner().getInheritance() != null && fm.getOwner().getInheritance().getType() == InheritanceMode.SINGLE_TAB && fm.getOwner().getInheritance().getSuperclass() != null; // Set Nullable if ((fm.isNullable() == null || !fm.isNullable()) && !isSingleTabInherited) { builder.append(" NOT NULL"); } if (fm.getDefaultValue() != null) { builder.append(" DEFAULT '" + fm.getDefaultValue() + "'"); } } return builder.toString(); } /** * Generate the column type for a given harmony type. * @param field The harmony type of a field. * @return The columnType for SQLite */ public static String generateColumnType(final FieldMetadata field) { String type; if (!Strings.isNullOrEmpty(field.getHarmonyType())) { if (field.getHarmonyType().equals(Column.Type.ENUM.getValue())) { EnumMetadata enumMeta = ApplicationMetadata.INSTANCE.getEnums().get( field.getType()); type = enumMeta.getType(); } else { type = field.getHarmonyType(); } } else { if (field.getRelation() != null) { EntityMetadata relatedEntity = field.getRelation().getEntityRef(); ArrayList<FieldMetadata> ids = new ArrayList<FieldMetadata>( relatedEntity.getIds().values()); if (ids.size() > 0) { type = SqliteAdapter.generateColumnType(ids.get(0)); } else { StringBuilder warning = new StringBuilder(); warning.append("Erroneous relation between "); warning.append(field.getOwner().getName()); warning.append("."); warning.append(field.getName()); warning.append(" AND "); warning.append(relatedEntity.getName()); warning.append(". Entity "); warning.append(relatedEntity.getName()); warning.append(" must be an entity and declare an @Id."); ConsoleUtils.displayWarning(warning.toString()); field.getOwner().removeField(field); type = "BLOB"; - return type; } } else { type = field.getType(); } } if (type.equalsIgnoreCase(Column.Type.STRING.getValue()) || type.equalsIgnoreCase(Column.Type.TEXT.getValue()) || type.equalsIgnoreCase(Column.Type.LOGIN.getValue()) || type.equalsIgnoreCase(Column.Type.PHONE.getValue()) || type.equalsIgnoreCase(Column.Type.PASSWORD.getValue()) || type.equalsIgnoreCase(Column.Type.EMAIL.getValue()) || type.equalsIgnoreCase(Column.Type.CITY.getValue()) || type.equalsIgnoreCase(Column.Type.ZIPCODE.getValue()) || type.equalsIgnoreCase(Column.Type.COUNTRY.getValue())) { type = "VARCHAR"; } else if (type.equalsIgnoreCase(Column.Type.DATETIME.getValue())) { type = "DATETIME"; } else if (type.equalsIgnoreCase(Column.Type.DATE.getValue())) { type = "DATE"; } else if (type.equalsIgnoreCase(Column.Type.TIME.getValue())) { type = "DATETIME"; } else if (type.equalsIgnoreCase(Column.Type.BOOLEAN.getValue())) { type = "BOOLEAN"; } else if (type.equalsIgnoreCase(Column.Type.INTEGER.getValue()) || type.equalsIgnoreCase(Column.Type.INT.getValue()) || type.equalsIgnoreCase(Column.Type.BC_EAN.getValue())) { type = "INTEGER"; } else if (type.equalsIgnoreCase(Column.Type.FLOAT.getValue())) { type = "FLOAT"; } else if (type.equalsIgnoreCase(Column.Type.DOUBLE.getValue())) { type = "DOUBLE"; } else if (type.equalsIgnoreCase(Column.Type.SHORT.getValue())) { type = "SHORT"; } else if (type.equalsIgnoreCase(Column.Type.LONG.getValue())) { type = "LONG"; } else if (type.equalsIgnoreCase(Column.Type.CHAR.getValue())) { type = "STRING"; } else if (type.equalsIgnoreCase(Column.Type.BYTE.getValue())) { type = "STRING"; } else if (type.equalsIgnoreCase(Column.Type.CHARACTER.getValue())) { type = "STRING"; } else { - ConsoleUtils.displayWarning("No type found for " + type - + " in entity " + field.getOwner().getName()); + if (field.getOwner() != null) { + ConsoleUtils.displayWarning("No type found for " + type + + " in entity " + field.getOwner().getName()); + } type = "BLOB"; } return type; } /** * Generate a column name. * @param fieldName The original field's name * @return the generated column name */ public static String generateColumnName(final String fieldName) { return PREFIX + fieldName.toUpperCase(); } /** * Generate a relation column name. * @param fieldName The original field's name * @return the generated column name */ public static String generateRelationColumnName(final String fieldName) { return PREFIX + fieldName.toUpperCase() + SUFFIX; } /** * Generate a column definition. * @param type The original field's type * @return the generated column definition */ public static String generateColumnDefinition(final String type) { String ret = type; if (type.equalsIgnoreCase("int")) { ret = "integer"; } return ret; } /** * SQLite Reserved keywords. */ public static enum Keywords { // CHECKSTYLE:OFF ABORT, ACTION, ADD, AFTER, ALL, ALTER, ANALYZE, AND, AS, ASC, ATTACH, AUTOINCREMENT, BEFORE, BEGIN, BETWEEN, BY, CASCADE, CASE, CAST, CHECK, COLLATE, COLUMN, COMMIT, CONFLICT, CONSTRAINT, CREATE, CROSS, CURRENT_DATE, CURRENT_TIME, CURRENT_TIMESTAMP, DATABASE, DEFAULT, DEFERRABLE, DEFERRED, DELETE, DESC, DETACH, DISTINCT, DROP, EACH, ELSE, END, ESCAPE, EXCEPT, EXCLUSIVE, EXISTS, EXPLAIN, FAIL, FOR, FOREIGN, FROM, FULL, GLOB, GROUP, HAVING, IF, IGNORE, IMMEDIATE, IN, INDEX, INDEXED, INITIALLY, INNER, INSERT, INSTEAD, INTERSECT, INTO, IS, ISNULL, JOIN, KEY, LEFT, LIKE, LIMIT, MATCH, NATURAL, NO, NOT, NOTNULL, NULL, OF, OFFSET, ON, OR, ORDER, OUTER, PLAN, PRAGMA, PRIMARY, QUERY, RAISE, REFERENCES, REGEXP, REINDEX, RELEASE, RENAME, REPLACE, RESTRICT, RIGHT, ROLLBACK, ROW, SAVEPOINT, SELECT, SET, TABLE, TEMP, TEMPORARY, THEN, TO, TRANSACTION, TRIGGER, UNION, UNIQUE, UPDATE, USING, VACUUM, VALUES, VIEW, VIRTUAL, WHEN, WHERE; // CHECKSTYLE:ON /** * Tests if the given String is a reserverd SQLite keyword. * @param name The string * @return True if it is */ public static boolean exists(final String name) { boolean exists = false; try { final Field field = Keywords.class.getField(name.toUpperCase()); if (field.isEnumConstant()) { ConsoleUtils.displayWarning( name + " is a reserved SQLite keyword." + " You may have problems with" + " your database schema."); exists = true; } else { exists = false; } } catch (final NoSuchFieldException e) { exists = false; } return exists; } } }
false
true
public static String generateColumnType(final FieldMetadata field) { String type; if (!Strings.isNullOrEmpty(field.getHarmonyType())) { if (field.getHarmonyType().equals(Column.Type.ENUM.getValue())) { EnumMetadata enumMeta = ApplicationMetadata.INSTANCE.getEnums().get( field.getType()); type = enumMeta.getType(); } else { type = field.getHarmonyType(); } } else { if (field.getRelation() != null) { EntityMetadata relatedEntity = field.getRelation().getEntityRef(); ArrayList<FieldMetadata> ids = new ArrayList<FieldMetadata>( relatedEntity.getIds().values()); if (ids.size() > 0) { type = SqliteAdapter.generateColumnType(ids.get(0)); } else { StringBuilder warning = new StringBuilder(); warning.append("Erroneous relation between "); warning.append(field.getOwner().getName()); warning.append("."); warning.append(field.getName()); warning.append(" AND "); warning.append(relatedEntity.getName()); warning.append(". Entity "); warning.append(relatedEntity.getName()); warning.append(" must be an entity and declare an @Id."); ConsoleUtils.displayWarning(warning.toString()); field.getOwner().removeField(field); type = "BLOB"; return type; } } else { type = field.getType(); } } if (type.equalsIgnoreCase(Column.Type.STRING.getValue()) || type.equalsIgnoreCase(Column.Type.TEXT.getValue()) || type.equalsIgnoreCase(Column.Type.LOGIN.getValue()) || type.equalsIgnoreCase(Column.Type.PHONE.getValue()) || type.equalsIgnoreCase(Column.Type.PASSWORD.getValue()) || type.equalsIgnoreCase(Column.Type.EMAIL.getValue()) || type.equalsIgnoreCase(Column.Type.CITY.getValue()) || type.equalsIgnoreCase(Column.Type.ZIPCODE.getValue()) || type.equalsIgnoreCase(Column.Type.COUNTRY.getValue())) { type = "VARCHAR"; } else if (type.equalsIgnoreCase(Column.Type.DATETIME.getValue())) { type = "DATETIME"; } else if (type.equalsIgnoreCase(Column.Type.DATE.getValue())) { type = "DATE"; } else if (type.equalsIgnoreCase(Column.Type.TIME.getValue())) { type = "DATETIME"; } else if (type.equalsIgnoreCase(Column.Type.BOOLEAN.getValue())) { type = "BOOLEAN"; } else if (type.equalsIgnoreCase(Column.Type.INTEGER.getValue()) || type.equalsIgnoreCase(Column.Type.INT.getValue()) || type.equalsIgnoreCase(Column.Type.BC_EAN.getValue())) { type = "INTEGER"; } else if (type.equalsIgnoreCase(Column.Type.FLOAT.getValue())) { type = "FLOAT"; } else if (type.equalsIgnoreCase(Column.Type.DOUBLE.getValue())) { type = "DOUBLE"; } else if (type.equalsIgnoreCase(Column.Type.SHORT.getValue())) { type = "SHORT"; } else if (type.equalsIgnoreCase(Column.Type.LONG.getValue())) { type = "LONG"; } else if (type.equalsIgnoreCase(Column.Type.CHAR.getValue())) { type = "STRING"; } else if (type.equalsIgnoreCase(Column.Type.BYTE.getValue())) { type = "STRING"; } else if (type.equalsIgnoreCase(Column.Type.CHARACTER.getValue())) { type = "STRING"; } else { ConsoleUtils.displayWarning("No type found for " + type + " in entity " + field.getOwner().getName()); type = "BLOB"; } return type; }
public static String generateColumnType(final FieldMetadata field) { String type; if (!Strings.isNullOrEmpty(field.getHarmonyType())) { if (field.getHarmonyType().equals(Column.Type.ENUM.getValue())) { EnumMetadata enumMeta = ApplicationMetadata.INSTANCE.getEnums().get( field.getType()); type = enumMeta.getType(); } else { type = field.getHarmonyType(); } } else { if (field.getRelation() != null) { EntityMetadata relatedEntity = field.getRelation().getEntityRef(); ArrayList<FieldMetadata> ids = new ArrayList<FieldMetadata>( relatedEntity.getIds().values()); if (ids.size() > 0) { type = SqliteAdapter.generateColumnType(ids.get(0)); } else { StringBuilder warning = new StringBuilder(); warning.append("Erroneous relation between "); warning.append(field.getOwner().getName()); warning.append("."); warning.append(field.getName()); warning.append(" AND "); warning.append(relatedEntity.getName()); warning.append(". Entity "); warning.append(relatedEntity.getName()); warning.append(" must be an entity and declare an @Id."); ConsoleUtils.displayWarning(warning.toString()); field.getOwner().removeField(field); type = "BLOB"; } } else { type = field.getType(); } } if (type.equalsIgnoreCase(Column.Type.STRING.getValue()) || type.equalsIgnoreCase(Column.Type.TEXT.getValue()) || type.equalsIgnoreCase(Column.Type.LOGIN.getValue()) || type.equalsIgnoreCase(Column.Type.PHONE.getValue()) || type.equalsIgnoreCase(Column.Type.PASSWORD.getValue()) || type.equalsIgnoreCase(Column.Type.EMAIL.getValue()) || type.equalsIgnoreCase(Column.Type.CITY.getValue()) || type.equalsIgnoreCase(Column.Type.ZIPCODE.getValue()) || type.equalsIgnoreCase(Column.Type.COUNTRY.getValue())) { type = "VARCHAR"; } else if (type.equalsIgnoreCase(Column.Type.DATETIME.getValue())) { type = "DATETIME"; } else if (type.equalsIgnoreCase(Column.Type.DATE.getValue())) { type = "DATE"; } else if (type.equalsIgnoreCase(Column.Type.TIME.getValue())) { type = "DATETIME"; } else if (type.equalsIgnoreCase(Column.Type.BOOLEAN.getValue())) { type = "BOOLEAN"; } else if (type.equalsIgnoreCase(Column.Type.INTEGER.getValue()) || type.equalsIgnoreCase(Column.Type.INT.getValue()) || type.equalsIgnoreCase(Column.Type.BC_EAN.getValue())) { type = "INTEGER"; } else if (type.equalsIgnoreCase(Column.Type.FLOAT.getValue())) { type = "FLOAT"; } else if (type.equalsIgnoreCase(Column.Type.DOUBLE.getValue())) { type = "DOUBLE"; } else if (type.equalsIgnoreCase(Column.Type.SHORT.getValue())) { type = "SHORT"; } else if (type.equalsIgnoreCase(Column.Type.LONG.getValue())) { type = "LONG"; } else if (type.equalsIgnoreCase(Column.Type.CHAR.getValue())) { type = "STRING"; } else if (type.equalsIgnoreCase(Column.Type.BYTE.getValue())) { type = "STRING"; } else if (type.equalsIgnoreCase(Column.Type.CHARACTER.getValue())) { type = "STRING"; } else { if (field.getOwner() != null) { ConsoleUtils.displayWarning("No type found for " + type + " in entity " + field.getOwner().getName()); } type = "BLOB"; } return type; }
diff --git a/DeliveryPerformance/src/com/sff/report_performance/ExcelDocumentCreator.java b/DeliveryPerformance/src/com/sff/report_performance/ExcelDocumentCreator.java index 9b4dcc6..90562a0 100644 --- a/DeliveryPerformance/src/com/sff/report_performance/ExcelDocumentCreator.java +++ b/DeliveryPerformance/src/com/sff/report_performance/ExcelDocumentCreator.java @@ -1,256 +1,256 @@ package com.sff.report_performance; import java.awt.Desktop; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.swing.JTextField; import javax.swing.SwingWorker; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.DataFormat; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import com.borland.dx.dataset.VariantException; import com.borland.dx.sql.dataset.Database; import com.borland.dx.sql.dataset.QueryDataSet; import com.borland.dx.sql.dataset.QueryDescriptor; /* * This class creates the excel document in another thread, using a swing worker * to publish the process progress. */ @SuppressWarnings("rawtypes") public class ExcelDocumentCreator extends SwingWorker<String, Integer> { private XSSFWorkbook workbook; private File output; private InputStream template; private XSSFSheet sheetTable; private XSSFSheet sheetProject; private List<List> customerData; private List<List> projectData; private List<List> statusData; private JTextField publishedOutput; private JTextField progressField; private FileOutputStream out; public ExcelDocumentCreator(List<List> customerData, List<List> projectData, List<List> statusData, JTextField publishedOutput, JTextField progressField, FileOutputStream out, File output){ try { this.customerData = customerData; this.projectData = projectData; this.statusData = statusData; this.publishedOutput = publishedOutput; this.progressField = progressField; this.out = out; this.output = output; //TODO: relative path template = new FileInputStream("C:/Users/hbs/workspace/SelectionGUI/DeliveryPerformance/template/template.xlsx"); workbook = (XSSFWorkbook) WorkbookFactory.create(template); sheetTable = workbook.getSheet("Table"); sheetTable.setZoom(70); sheetProject = workbook.getSheet("Project"); } catch (IOException | InvalidFormatException e) { e.printStackTrace(); } } private void saveWorkbook() { try { workbook.setActiveSheet(0); workbook.write(out); out.close(); Desktop.getDesktop().open(output); } catch (IOException e) { e.printStackTrace(); } } @Override protected String doInBackground() { try{ boolean allCustSelected = customerData.size()==0 ? true : false; boolean allProjSelected = projectData.size()==0 ? true : false; boolean allStatSelected = statusData.size()==0 ? true : false; StringBuilder query = generateQuery(allCustSelected,allProjSelected, allStatSelected, customerData, projectData, statusData); Database db = DatabaseConnection.getDatabase(); QueryDataSet dataSet = new QueryDataSet(); dataSet.setQuery(new QueryDescriptor(db, query.toString())); dataSet.open(); int rowCount = dataSet.getRowCount(); int processed = 0; CellStyle decimalStyle = workbook.createCellStyle(); CellStyle sixDigitStyle = workbook.createCellStyle(); DataFormat format = workbook.createDataFormat(); decimalStyle.setDataFormat(format.getFormat("##00.00")); sixDigitStyle.setDataFormat(format.getFormat("000000")); publishedOutput.setText("Generating Excel Document"); while(!isCancelled()){ Set<String> currencySet = new HashSet<String>(); while(dataSet.next()){ setProgress(100 * processed++ / rowCount); progressField.setText("Adding row: " + processed); sheetTable.createRow(dataSet.getRow()); for(int column = 0; column < dataSet.getColumnCount(); column++){ Cell cell = sheetTable.getRow(dataSet.getRow()).createCell(column); if(dataSet.getColumn(column).equals(dataSet.getColumn("Unit Price"))){ cell.setCellStyle(decimalStyle); } if(dataSet.getColumn(column).equals(dataSet.getColumn("Vendor nr."))){ cell.setCellStyle(sixDigitStyle); } if(dataSet.getColumn(column).equals(dataSet.getColumn("currency"))){ currencySet.add(dataSet.getString(column)); } try{ String s = dataSet.getString(column); cell.setCellValue(s); }catch(VariantException e){ try{ Double d = dataSet.getDouble(column); cell.setCellValue(d); }catch(VariantException v){ int i = dataSet.getInt(column); cell.setCellValue(i); } } } } // TODO: Does not account for the currency exchange rates. int last = sheetTable.getLastRowNum() + 1; int rowPosition = 4; CellStyle cellStyle = sheetProject.getRow(5).getCell(1).getCellStyle(); - sheetProject.shiftRows(4, 8, currencySet.size()); // TODO: if empty report this crashes, fix + if(currencySet.size()!=0)sheetProject.shiftRows(4, 8, currencySet.size()); for(String currency : currencySet){ Row row = sheetProject.createRow(rowPosition++); Cell description = row.createCell(0); description.setCellValue("Total Value [" + currency + "]:"); description.setCellStyle(cellStyle); Cell sum = row.createCell(1); sum.setCellFormula("SUMIF(Table!$N$2:$N$" + last + ",\""+ currency + "\"," + "Table!$M$2:$M$" + last + ")"); sum.setCellStyle(cellStyle); } publishedOutput.setText("Opening Excel Document"); saveWorkbook(); dataSet.close(); cancel(true); } }catch(Exception e){ e.printStackTrace(); } return null; } private StringBuilder generateQuery(boolean allCustSelected, boolean allProjSelected, boolean allStatSelected, List<List> temp_cust, List<List> temp_proj, List<List> temp_stat) { /* * The base statement is used no matter the user selection */ StringBuilder query = new StringBuilder(5000); String basicStatement = "select \"Project\" = Project.pr_name," + " \"Client\" = customerList.assoc_name," + " \"Client Ref.\" = Tr_hdr.assoc_ref," + " \"Order Nr.\" = Tr_hdr.tr_no, " + " \"Order Registration Date\" = convert(varchar(20), Tr_hdr.reg_date, 104)," + " \"Item nr.\" = clientItemList.item_no," + " \"Client Art. code\" = clientItemList.local_id," + " \"Vendor nr.\" = clientItemList.vnd_no, " + " \"Description\" = clientItemList.description," + " \"Supplier\" = supplierList.assoc_name ," + " \"QTY\" = clientItemList.qnt," + " \"Unit Price\" = clientItemList.price," + " \"Total Price\" = clientItemList.qnt*clientItemList.price," + " \"currency\" = Exchange.curr_name," + " \"CDD\" = convert(varchar(20), clientItemList.contract_date, 104)," + " \"EDD\" = convert(varchar(20), clientItemList.estimate_date, 104)," + " \"RFI\" = convert(varchar(20), clientItemList.rfi_date, 104)," + " \"CCD\" = convert(varchar(20), supplierItemList.contract_date, 104)," + " \"ECD\" = convert(varchar(20), supplierItemList.estimate_date, 104)," + " \"Item Status\" = Tr_dtl_status.tr_dtl_stname" + " from vendor.dbo.Tr_hdr," + " vendor.dbo.Tr_dtl clientItemList left join vendor.dbo.Tr_dtl supplierItemList" + " on (clientItemList.vnd_no = supplierItemList.vnd_no" + " and clientItemList.item_no = supplierItemList.item_no" + " and clientItemList.suppl_tr_id = supplierItemList.tr_no" + " and supplierItemList.tr_dtl_status>0" + " and supplierItemList.vnd_no > 1" + " )," + " vendor.dbo.Assoc customerList," + " vendor.dbo.Assoc supplierList," + " vendor.dbo.Project," + " vendor.dbo.Exchange," + " vendor.dbo.Tr_dtl_status" + " where Tr_hdr.tr_status = 2" + " and Tr_hdr.tr_no = clientItemList.tr_no" + " and Tr_hdr.assoc_id = customerList.assoc_id" + " and Tr_hdr.active_id = Project.project_id" + " and clientItemList.suppl_id = supplierList.assoc_id" + " and clientItemList.currency_id = Exchange.currency_id" + " and clientItemList.tr_dtl_status = Tr_dtl_status.tr_dtl_status"; /* * If the user have NOT selected all items in the list the method will * specify the search to only include the selected items. */ query.append(basicStatement); if(!allCustSelected){ query.append(" and customerList.assoc_id in ("); for(List l : temp_cust){ int id = (int) l.get(1); query.append(id + ", "); } query.delete(query.length()-2, query.length()); query.append(")"); } if(!allProjSelected){ query.append(" and Project.pr_name in ("); for(List l : temp_proj){ String name = (String) l.get(1); query.append("'" + name + "', "); } query.delete(query.length()-2, query.length()); query.append(")"); } if(!allStatSelected){ query.append(" and Tr_dtl_status.tr_dtl_stname in ("); for(List l : temp_stat){ String status = (String) l.get(1); query.append("'" + status + "', "); } query.delete(query.length()-2, query.length()); query.append(")"); } return query; } }
true
true
protected String doInBackground() { try{ boolean allCustSelected = customerData.size()==0 ? true : false; boolean allProjSelected = projectData.size()==0 ? true : false; boolean allStatSelected = statusData.size()==0 ? true : false; StringBuilder query = generateQuery(allCustSelected,allProjSelected, allStatSelected, customerData, projectData, statusData); Database db = DatabaseConnection.getDatabase(); QueryDataSet dataSet = new QueryDataSet(); dataSet.setQuery(new QueryDescriptor(db, query.toString())); dataSet.open(); int rowCount = dataSet.getRowCount(); int processed = 0; CellStyle decimalStyle = workbook.createCellStyle(); CellStyle sixDigitStyle = workbook.createCellStyle(); DataFormat format = workbook.createDataFormat(); decimalStyle.setDataFormat(format.getFormat("##00.00")); sixDigitStyle.setDataFormat(format.getFormat("000000")); publishedOutput.setText("Generating Excel Document"); while(!isCancelled()){ Set<String> currencySet = new HashSet<String>(); while(dataSet.next()){ setProgress(100 * processed++ / rowCount); progressField.setText("Adding row: " + processed); sheetTable.createRow(dataSet.getRow()); for(int column = 0; column < dataSet.getColumnCount(); column++){ Cell cell = sheetTable.getRow(dataSet.getRow()).createCell(column); if(dataSet.getColumn(column).equals(dataSet.getColumn("Unit Price"))){ cell.setCellStyle(decimalStyle); } if(dataSet.getColumn(column).equals(dataSet.getColumn("Vendor nr."))){ cell.setCellStyle(sixDigitStyle); } if(dataSet.getColumn(column).equals(dataSet.getColumn("currency"))){ currencySet.add(dataSet.getString(column)); } try{ String s = dataSet.getString(column); cell.setCellValue(s); }catch(VariantException e){ try{ Double d = dataSet.getDouble(column); cell.setCellValue(d); }catch(VariantException v){ int i = dataSet.getInt(column); cell.setCellValue(i); } } } } // TODO: Does not account for the currency exchange rates. int last = sheetTable.getLastRowNum() + 1; int rowPosition = 4; CellStyle cellStyle = sheetProject.getRow(5).getCell(1).getCellStyle(); sheetProject.shiftRows(4, 8, currencySet.size()); // TODO: if empty report this crashes, fix for(String currency : currencySet){ Row row = sheetProject.createRow(rowPosition++); Cell description = row.createCell(0); description.setCellValue("Total Value [" + currency + "]:"); description.setCellStyle(cellStyle); Cell sum = row.createCell(1); sum.setCellFormula("SUMIF(Table!$N$2:$N$" + last + ",\""+ currency + "\"," + "Table!$M$2:$M$" + last + ")"); sum.setCellStyle(cellStyle); } publishedOutput.setText("Opening Excel Document"); saveWorkbook(); dataSet.close(); cancel(true); } }catch(Exception e){ e.printStackTrace(); } return null; }
protected String doInBackground() { try{ boolean allCustSelected = customerData.size()==0 ? true : false; boolean allProjSelected = projectData.size()==0 ? true : false; boolean allStatSelected = statusData.size()==0 ? true : false; StringBuilder query = generateQuery(allCustSelected,allProjSelected, allStatSelected, customerData, projectData, statusData); Database db = DatabaseConnection.getDatabase(); QueryDataSet dataSet = new QueryDataSet(); dataSet.setQuery(new QueryDescriptor(db, query.toString())); dataSet.open(); int rowCount = dataSet.getRowCount(); int processed = 0; CellStyle decimalStyle = workbook.createCellStyle(); CellStyle sixDigitStyle = workbook.createCellStyle(); DataFormat format = workbook.createDataFormat(); decimalStyle.setDataFormat(format.getFormat("##00.00")); sixDigitStyle.setDataFormat(format.getFormat("000000")); publishedOutput.setText("Generating Excel Document"); while(!isCancelled()){ Set<String> currencySet = new HashSet<String>(); while(dataSet.next()){ setProgress(100 * processed++ / rowCount); progressField.setText("Adding row: " + processed); sheetTable.createRow(dataSet.getRow()); for(int column = 0; column < dataSet.getColumnCount(); column++){ Cell cell = sheetTable.getRow(dataSet.getRow()).createCell(column); if(dataSet.getColumn(column).equals(dataSet.getColumn("Unit Price"))){ cell.setCellStyle(decimalStyle); } if(dataSet.getColumn(column).equals(dataSet.getColumn("Vendor nr."))){ cell.setCellStyle(sixDigitStyle); } if(dataSet.getColumn(column).equals(dataSet.getColumn("currency"))){ currencySet.add(dataSet.getString(column)); } try{ String s = dataSet.getString(column); cell.setCellValue(s); }catch(VariantException e){ try{ Double d = dataSet.getDouble(column); cell.setCellValue(d); }catch(VariantException v){ int i = dataSet.getInt(column); cell.setCellValue(i); } } } } // TODO: Does not account for the currency exchange rates. int last = sheetTable.getLastRowNum() + 1; int rowPosition = 4; CellStyle cellStyle = sheetProject.getRow(5).getCell(1).getCellStyle(); if(currencySet.size()!=0)sheetProject.shiftRows(4, 8, currencySet.size()); for(String currency : currencySet){ Row row = sheetProject.createRow(rowPosition++); Cell description = row.createCell(0); description.setCellValue("Total Value [" + currency + "]:"); description.setCellStyle(cellStyle); Cell sum = row.createCell(1); sum.setCellFormula("SUMIF(Table!$N$2:$N$" + last + ",\""+ currency + "\"," + "Table!$M$2:$M$" + last + ")"); sum.setCellStyle(cellStyle); } publishedOutput.setText("Opening Excel Document"); saveWorkbook(); dataSet.close(); cancel(true); } }catch(Exception e){ e.printStackTrace(); } return null; }
diff --git a/modules/core/src/main/java/org/torquebox/core/injection/analysis/RuntimeInjectionAnalyzer.java b/modules/core/src/main/java/org/torquebox/core/injection/analysis/RuntimeInjectionAnalyzer.java index d7820d2ae..cef32efda 100644 --- a/modules/core/src/main/java/org/torquebox/core/injection/analysis/RuntimeInjectionAnalyzer.java +++ b/modules/core/src/main/java/org/torquebox/core/injection/analysis/RuntimeInjectionAnalyzer.java @@ -1,59 +1,59 @@ package org.torquebox.core.injection.analysis; import java.util.Set; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceRegistry; import org.jboss.msc.service.ServiceTarget; import org.jruby.RubyProc; import org.torquebox.core.component.InjectionRegistry; public class RuntimeInjectionAnalyzer { public RuntimeInjectionAnalyzer(ServiceRegistry serviceRegistry, ServiceTarget serviceTarget, DeploymentUnit deploymentUnit, InjectionAnalyzer analyzer) { this.serviceRegistry = serviceRegistry; this.serviceTarget = serviceTarget; this.deploymentUnit = deploymentUnit; this.analyzer = analyzer; } public Object analyzeAndInject(Object arg) throws Exception { System.err.println( "Analyzing: " + arg.getClass() ); if (arg instanceof RubyProc) { RubyProc proc = (RubyProc) arg; InjectionRubyByteCodeVisitor visitor = new InjectionRubyByteCodeVisitor( this.analyzer ); visitor.assumeMarkerSeen(); this.analyzer.analyze( proc, visitor ); Set<Injectable> injectables = visitor.getInjectables(); InjectionRegistry registry = new InjectionRegistry(); for (Injectable each : injectables) { ServiceName eachName = each.getServiceName( this.serviceTarget, this.deploymentUnit ); System.err.println( "SERVICE_NAME: " + eachName ); ServiceController<?> controller = this.serviceRegistry.getRequiredService( eachName ); System.err.println( "SERVICE_CONTROLLER: " + controller ); Object injectedValue = null; ClassLoader originalCl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( proc.getRuntime().getJRubyClassLoader().getParent() ); injectedValue = controller.getValue(); + System.err.println( "SERVICE_VALUE: " + injectedValue ); + System.err.println( "KEY: " + each.getKey() ); + registry.getInjector( each.getKey() ).inject( injectedValue ); } finally { Thread.currentThread().setContextClassLoader( originalCl ); } - System.err.println( "SERVICE_VALUE: " + injectedValue ); - System.err.println( "KEY: " + each.getKey() ); - registry.getInjector( each.getKey() ).inject( injectedValue ); } registry.merge( proc.getRuntime() ); } return null; } private ServiceRegistry serviceRegistry; private ServiceTarget serviceTarget; private DeploymentUnit deploymentUnit; private InjectionAnalyzer analyzer; }
false
true
public Object analyzeAndInject(Object arg) throws Exception { System.err.println( "Analyzing: " + arg.getClass() ); if (arg instanceof RubyProc) { RubyProc proc = (RubyProc) arg; InjectionRubyByteCodeVisitor visitor = new InjectionRubyByteCodeVisitor( this.analyzer ); visitor.assumeMarkerSeen(); this.analyzer.analyze( proc, visitor ); Set<Injectable> injectables = visitor.getInjectables(); InjectionRegistry registry = new InjectionRegistry(); for (Injectable each : injectables) { ServiceName eachName = each.getServiceName( this.serviceTarget, this.deploymentUnit ); System.err.println( "SERVICE_NAME: " + eachName ); ServiceController<?> controller = this.serviceRegistry.getRequiredService( eachName ); System.err.println( "SERVICE_CONTROLLER: " + controller ); Object injectedValue = null; ClassLoader originalCl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( proc.getRuntime().getJRubyClassLoader().getParent() ); injectedValue = controller.getValue(); } finally { Thread.currentThread().setContextClassLoader( originalCl ); } System.err.println( "SERVICE_VALUE: " + injectedValue ); System.err.println( "KEY: " + each.getKey() ); registry.getInjector( each.getKey() ).inject( injectedValue ); } registry.merge( proc.getRuntime() ); } return null; }
public Object analyzeAndInject(Object arg) throws Exception { System.err.println( "Analyzing: " + arg.getClass() ); if (arg instanceof RubyProc) { RubyProc proc = (RubyProc) arg; InjectionRubyByteCodeVisitor visitor = new InjectionRubyByteCodeVisitor( this.analyzer ); visitor.assumeMarkerSeen(); this.analyzer.analyze( proc, visitor ); Set<Injectable> injectables = visitor.getInjectables(); InjectionRegistry registry = new InjectionRegistry(); for (Injectable each : injectables) { ServiceName eachName = each.getServiceName( this.serviceTarget, this.deploymentUnit ); System.err.println( "SERVICE_NAME: " + eachName ); ServiceController<?> controller = this.serviceRegistry.getRequiredService( eachName ); System.err.println( "SERVICE_CONTROLLER: " + controller ); Object injectedValue = null; ClassLoader originalCl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( proc.getRuntime().getJRubyClassLoader().getParent() ); injectedValue = controller.getValue(); System.err.println( "SERVICE_VALUE: " + injectedValue ); System.err.println( "KEY: " + each.getKey() ); registry.getInjector( each.getKey() ).inject( injectedValue ); } finally { Thread.currentThread().setContextClassLoader( originalCl ); } } registry.merge( proc.getRuntime() ); } return null; }
diff --git a/src/net/sf/freecol/common/networking/SetDestinationMessage.java b/src/net/sf/freecol/common/networking/SetDestinationMessage.java index 9b34a21b4..abcd23fed 100644 --- a/src/net/sf/freecol/common/networking/SetDestinationMessage.java +++ b/src/net/sf/freecol/common/networking/SetDestinationMessage.java @@ -1,128 +1,128 @@ /** * Copyright (C) 2002-2007 The FreeCol Team * * This file is part of FreeCol. * * FreeCol 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 2 of the License, or * (at your option) any later version. * * FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.freecol.common.networking; import net.sf.freecol.common.model.Game; import net.sf.freecol.common.model.Location; import net.sf.freecol.common.model.Player; import net.sf.freecol.common.model.Unit; import net.sf.freecol.server.FreeColServer; import net.sf.freecol.server.model.ServerPlayer; import org.w3c.dom.Element; /** * The message sent when the client requests setting a unit destination. */ public class SetDestinationMessage extends Message { /** * The ID of the unit whose destination is to be set. **/ String unitId; /** * The ID of the unit destination or null. */ String destinationId; /** * Create a new <code>SetDestinationMessage</code> with the supplied unit * and destination. * * @param unit The <code>Unit</code> whose destination is to be set * @param destination The destination to set (may be null) */ public SetDestinationMessage(Unit unit, Location destination) { this.unitId = unit.getId(); this.destinationId = (destination == null) ? null : destination.getId(); } /** * Create a new <code>SetDestinationMessage</code> from a supplied element. * * @param game The <code>Game</code> this message belongs to. * @param element The <code>Element</code> to use to create the message. */ public SetDestinationMessage(Game game, Element element) { this.unitId = element.getAttribute("unit"); this.destinationId = element.getAttribute("destination"); } /** * Handle a "setDestination"-message. * * @param server The <code>FreeColServer</code> handling the message. * @param connection The <code>Connection</code> the message is from. * * @return An update containing the unit with the new destination, * or an error <code>Element</code> on failure. */ public Element handle(FreeColServer server, Connection connection) { ServerPlayer serverPlayer = server.getPlayer(connection); Game game = serverPlayer.getGame(); Unit unit; try { unit = server.getUnitSafely(unitId, serverPlayer); } catch (Exception e) { return Message.clientError(e.getMessage()); } - if (unit.getTile() == null) { + if (unit.getTile() == null && !unit.isBetweenEuropeAndNewWorld()) { return Message.clientError("Unit is not on the map: " + unitId); } Location destination; if (destinationId == null || destinationId.length() == 0) { destination = null; } else if (!(game.getFreeColGameObject(destinationId) instanceof Location)) { return Message.clientError("Not a location ID: " + destinationId); } else { destination = (Location) game.getFreeColGameObject(destinationId); } // Set destination return server.getInGameController() .setDestination(serverPlayer, unit, destination); } /** * Convert this SetDestinationMessage to XML. * * @return The XML representation of this message. */ public Element toXMLElement() { Element result = createNewRootElement(getXMLElementTagName()); result.setAttribute("unit", unitId); if (destinationId != null) { result.setAttribute("destination", destinationId); } return result; } /** * The tag name of the root element representing this object. * * @return "setDestination". */ public static String getXMLElementTagName() { return "setDestination"; } }
true
true
public Element handle(FreeColServer server, Connection connection) { ServerPlayer serverPlayer = server.getPlayer(connection); Game game = serverPlayer.getGame(); Unit unit; try { unit = server.getUnitSafely(unitId, serverPlayer); } catch (Exception e) { return Message.clientError(e.getMessage()); } if (unit.getTile() == null) { return Message.clientError("Unit is not on the map: " + unitId); } Location destination; if (destinationId == null || destinationId.length() == 0) { destination = null; } else if (!(game.getFreeColGameObject(destinationId) instanceof Location)) { return Message.clientError("Not a location ID: " + destinationId); } else { destination = (Location) game.getFreeColGameObject(destinationId); } // Set destination return server.getInGameController() .setDestination(serverPlayer, unit, destination); }
public Element handle(FreeColServer server, Connection connection) { ServerPlayer serverPlayer = server.getPlayer(connection); Game game = serverPlayer.getGame(); Unit unit; try { unit = server.getUnitSafely(unitId, serverPlayer); } catch (Exception e) { return Message.clientError(e.getMessage()); } if (unit.getTile() == null && !unit.isBetweenEuropeAndNewWorld()) { return Message.clientError("Unit is not on the map: " + unitId); } Location destination; if (destinationId == null || destinationId.length() == 0) { destination = null; } else if (!(game.getFreeColGameObject(destinationId) instanceof Location)) { return Message.clientError("Not a location ID: " + destinationId); } else { destination = (Location) game.getFreeColGameObject(destinationId); } // Set destination return server.getInGameController() .setDestination(serverPlayer, unit, destination); }
diff --git a/org.dawnsci.slicing.api/src/org/dawnsci/slicing/api/util/SliceUtils.java b/org.dawnsci.slicing.api/src/org/dawnsci/slicing/api/util/SliceUtils.java index 25241b7fe..dd40f8276 100644 --- a/org.dawnsci.slicing.api/src/org/dawnsci/slicing/api/util/SliceUtils.java +++ b/org.dawnsci.slicing.api/src/org/dawnsci/slicing/api/util/SliceUtils.java @@ -1,597 +1,604 @@ /* * Copyright (c) 2012 European Synchrotron Radiation Facility, * Diamond Light Source Ltd. * * 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 */ package org.dawnsci.slicing.api.util; import java.io.File; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import ncsa.hdf.object.Group; import org.dawb.common.services.ILoaderService; import org.dawb.common.services.ServiceManager; import org.dawb.hdf5.HierarchicalDataFactory; import org.dawb.hdf5.IHierarchicalDataFile; import org.dawnsci.doe.DOEUtils; import org.dawnsci.plotting.api.IPlottingSystem; import org.dawnsci.plotting.api.PlotType; import org.dawnsci.plotting.api.trace.IImageTrace; import org.dawnsci.plotting.api.trace.ITrace; import org.dawnsci.slicing.api.system.DimsData; import org.dawnsci.slicing.api.system.DimsDataList; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.swt.widgets.Display; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.diamond.scisoft.analysis.IAnalysisService; import uk.ac.diamond.scisoft.analysis.dataset.IDataset; import uk.ac.diamond.scisoft.analysis.dataset.ILazyDataset; import uk.ac.diamond.scisoft.analysis.io.IDataHolder; import uk.ac.diamond.scisoft.analysis.io.SliceObject; public class SliceUtils { private static Logger logger = LoggerFactory.getLogger(SliceUtils.class); private static NumberFormat format = DecimalFormat.getNumberInstance(); /** * Generates a list of slice information for a given set of dimensional data. * * The data may have fields which use DOE annotations and hence can be expanded. * This allows slices to be ranges in one or more dimensions which is a simple * form of summing sub-sets of data. * * @param dimsDataHolder * @param dataShape * @param sliceObject * @return a list of slices * @throws Exception */ public static SliceObject createSliceObject(final DimsDataList dimsDataHolder, final int[] dataShape, final SliceObject sliceObject) throws Exception { if (dimsDataHolder.size()!=dataShape.length) throw new RuntimeException("The dims data and the data shape are not equal!"); final SliceObject currentSlice = sliceObject!=null ? sliceObject.clone() : new SliceObject(); // This ugly code results from the ugly API to the slicing. final int[] start = new int[dimsDataHolder.size()]; final int[] stop = new int[dimsDataHolder.size()]; final int[] step = new int[dimsDataHolder.size()]; IDataset x = null; IDataset y = null; final StringBuilder buf = new StringBuilder(); //buf.append("\n"); // New graphing can deal with long titles. for (int i = 0; i < dimsDataHolder.size(); i++) { final DimsData dimsData = dimsDataHolder.getDimsData(i); start[i] = getStart(dimsData); stop[i] = getStop(dimsData,dataShape[i]); step[i] = getStep(dimsData); if (dimsData.getPlotAxis()<0) { String nexusAxisName = getNexusAxisName(currentSlice, dimsData, " (Dim "+(dimsData.getDimension()+1)); String formatValue = String.valueOf(dimsData.getSlice()); try { formatValue = format.format(getNexusAxisValue(sliceObject, dimsData, dimsData.getSlice(), null)); } catch (Throwable ne) { formatValue = String.valueOf(dimsData.getSlice()); } buf.append("("+nexusAxisName+" = "+(dimsData.getSliceRange()!=null?dimsData.getSliceRange():formatValue)+")"); } final IAnalysisService service = (IAnalysisService)ServiceManager.getService(IAnalysisService.class); if (dimsData.getPlotAxis()==0) { x = service.arange(dataShape[i], IAnalysisService.INT); x.setName("Dimension "+(dimsData.getDimension()+1)); currentSlice.setX(dimsData.getDimension()); } if (dimsData.getPlotAxis()==1) { y = service.arange(dataShape[i], IAnalysisService.INT); y.setName("Dimension "+(dimsData.getDimension()+1)); currentSlice.setY(dimsData.getDimension()); } if (dimsData.getSliceRange()!=null&&dimsData.getPlotAxis()<0) { currentSlice.setRange(true); } } if (x==null || x.getSize()<2) { // Nothing to plot logger.debug("Cannot slice into an image because one of the dimensions is size of 1"); return null; } if (y!=null) { currentSlice.setSlicedShape(new int[]{x.getSize(),y.getSize()}); currentSlice.setAxes(Arrays.asList(new IDataset[]{x,y})); } else { currentSlice.setSlicedShape(new int[]{x.getSize()}); currentSlice.setAxes(Arrays.asList(new IDataset[]{x})); } currentSlice.setSliceStart(start); currentSlice.setSliceStop(stop); currentSlice.setSliceStep(step); currentSlice.setShapeMessage(buf.toString()); return currentSlice; } /** * * @param sliceObject * @param data * @return * @throws Exception */ public static String getNexusAxisName(SliceObject sliceObject, DimsData data) { return getNexusAxisName(sliceObject, data, "indices"); } /** * * @param sliceObject * @param data * @return * @throws Exception */ public static String getNexusAxisName(SliceObject sliceObject, DimsData data, String alternateName) { try { Map<Integer,String> dims = sliceObject.getNexusAxes(); String axisName = dims.get(data.getDimension()+1); // The data used for this axis if (axisName==null || "".equals(axisName)) return alternateName; return axisName; } catch (Throwable ne) { return alternateName; } } /** * * @param sliceObject * @param data * @param value * @param monitor * @return the nexus axis value or the index if no nexus axis can be found. * @throws Throwable */ public static Number getNexusAxisValue(SliceObject sliceObject, DimsData data, int value, IProgressMonitor monitor) throws Throwable { IDataset axis = null; try { final String axisName = getNexusAxisName(sliceObject, data); axis = SliceUtils.getNexusAxis(sliceObject, axisName, false, monitor); } catch (Exception ne) { axis = null; } try { return axis!=null ? axis.getDouble(value) : value; } catch (Throwable ne) { return value; } } private static int getStart(DimsData dimsData) { if (dimsData.getPlotAxis()>-1) { return 0; } else if (dimsData.getSliceRange()!=null) { final double[] exp = DOEUtils.getRange(dimsData.getSliceRange(), null); return (int)exp[0]; } return dimsData.getSlice(); } private static int getStop(DimsData dimsData, final int size) { if (dimsData.getPlotAxis()>-1) { return size; } else if (dimsData.getSliceRange()!=null) { final double[] exp = DOEUtils.getRange(dimsData.getSliceRange(), null); return (int)exp[1]; } return dimsData.getSlice()+1; } private static int getStep(DimsData dimsData) { if (dimsData.getPlotAxis()>-1) { return 1; } else if (dimsData.getSliceRange()!=null) { final double[] exp = DOEUtils.getRange(dimsData.getSliceRange(), null); return (int)exp[2]; } return 1; } /** * Thread safe and time consuming part of the slice. * @param currentSlice * @param dataShape * @param type * @param plottingSystem - may be null, but if so no plotting will happen. * @param monitor * @throws Exception */ public static void plotSlice(final ILazyDataset lazySet, final SliceObject currentSlice, final int[] dataShape, final PlotType type, final IPlottingSystem plottingSystem, final IProgressMonitor monitor) throws Exception { if (plottingSystem==null) return; if (monitor!=null) monitor.worked(1); if (monitor!=null&&monitor.isCanceled()) return; currentSlice.setFullShape(dataShape); - final IDataset slice; + IDataset slice; final int[] slicedShape = currentSlice.getSlicedShape(); if (lazySet instanceof IDataset && Arrays.equals(slicedShape, lazySet.getShape())) { slice = (IDataset)lazySet; - } else { + if (currentSlice.getX() > currentSlice.getY() && slice.getShape().length==2) { + final IAnalysisService service = (IAnalysisService)ServiceManager.getService(IAnalysisService.class); + // transpose clobbers name + final String name = slice.getName(); + slice = service.transpose(slice); + if (name!=null) slice.setName(name); + } + } else { slice = getSlice(lazySet, currentSlice,monitor); } if (slice==null) return; // DO NOT CANCEL the monitor now, we have done the hard part the slice. // We may as well plot it or the plot will look very slow. if (monitor!=null) monitor.worked(1); boolean requireScale = plottingSystem.isRescale() || type!=plottingSystem.getPlotType(); if (type==PlotType.XY) { plottingSystem.clear(); final IDataset x = getNexusAxis(currentSlice, slice.getShape()[0], currentSlice.getX()+1, true, monitor); plottingSystem.setXFirst(true); plottingSystem.setPlotType(type); plottingSystem.createPlot1D(x, Arrays.asList((IDataset)slice), slice.getName(), monitor); Display.getDefault().syncExec(new Runnable() { public void run() { plottingSystem.getSelectedXAxis().setTitle(x.getName()); plottingSystem.getSelectedYAxis().setTitle(""); } }); } else if (type==PlotType.XY_STACKED || type==PlotType.XY_STACKED_3D) { final IDataset xAxis = getNexusAxis(currentSlice, slice.getShape()[0], currentSlice.getX()+1, true, monitor); plottingSystem.clear(); // We separate the 2D image into several 1d plots final int[] shape = slice.getShape(); final List<double[]> sets = new ArrayList<double[]>(shape[1]); for (int x = 0; x < shape[0]; x++) { for (int y = 0; y < shape[1]; y++) { if (y > (sets.size()-1)) sets.add(new double[shape[0]]); double[] data = sets.get(y); data[x] = slice.getDouble(x,y); } } final List<IDataset> ys = new ArrayList<IDataset>(shape[1]); int index = 0; final IAnalysisService service = (IAnalysisService)ServiceManager.getService(IAnalysisService.class); for (double[] da : sets) { final IDataset dds = service.createDoubleDataset(da, da.length); dds.setName(String.valueOf(index)); ys.add(dds); ++index; } plottingSystem.setXFirst(true); plottingSystem.setPlotType(type); plottingSystem.createPlot1D(xAxis, ys, monitor); Display.getDefault().syncExec(new Runnable() { public void run() { plottingSystem.getSelectedXAxis().setTitle(xAxis.getName()); plottingSystem.getSelectedYAxis().setTitle(""); } }); } else if (type==PlotType.IMAGE || type==PlotType.SURFACE){ plottingSystem.setPlotType(type); IDataset y = getNexusAxis(currentSlice, slice.getShape()[0], currentSlice.getX()+1, true, monitor); IDataset x = getNexusAxis(currentSlice, slice.getShape()[1], currentSlice.getY()+1, true, monitor); // Nullify user objects because the ImageHistoryTool uses // user objects to know if the image came from it. Since we // use update here, we update (as its faster) but we also // nullify the user object. final IImageTrace trace = getImageTrace(plottingSystem); if (trace!=null) trace.setUserObject(null); plottingSystem.updatePlot2D(slice, Arrays.asList(x,y), monitor); } plottingSystem.repaint(requireScale); } /** * this method gives access to the image trace plotted in the * main plotter or null if one is not plotted. * @return */ private static IImageTrace getImageTrace(IPlottingSystem plotting) { if (plotting == null) return null; final Collection<ITrace> traces = plotting.getTraces(IImageTrace.class); if (traces==null || traces.size()==0) return null; final ITrace trace = traces.iterator().next(); return trace instanceof IImageTrace ? (IImageTrace)trace : null; } /** * * @param currentSlice * @param length of axis * @param inexusAxis nexus dimension (starting with 1) * @param requireIndicesOnError * @param monitor * @return * @throws Exception */ public static IDataset getNexusAxis(SliceObject currentSlice, int length, int inexusAxis, boolean requireIndicesOnError, final IProgressMonitor monitor) throws Exception { String axisName = currentSlice.getNexusAxis(inexusAxis); final IAnalysisService service = (IAnalysisService)ServiceManager.getService(IAnalysisService.class); if ("indices".equals(axisName) || axisName==null) { IDataset indices = service.arange(length, IAnalysisService.INT); // Save time indices.setName(""); return indices; } if (axisName.endsWith("[Expression]")) { final IDataset set = currentSlice.getExpressionAxis(axisName); return service.convertToAbstractDataset(set); } try { return getNexusAxis(currentSlice, axisName, true, monitor); } catch (Throwable ne) { logger.error("Cannot get nexus axis during slice!", ne); if (requireIndicesOnError) { IDataset indices = service.arange(length, IAnalysisService.INT); // Save time indices.setName(""); return indices; } else { return null; } } } /** * * @param currentSlice * @param axisName, full path and then optionally a : and the dimension which the axis is for. * @param requireUnit - if true will get unit but will be slower. * @param requireIndicesOnError * @param monitor * @return */ public static IDataset getNexusAxis(final SliceObject currentSlice, String origName, final boolean requireUnit, final IProgressMonitor monitor) throws Throwable { int dimension = -1; String axisName = origName; if (axisName.contains(":")) { final String[] sa = axisName.split(":"); axisName = sa[0]; dimension = Integer.parseInt(sa[1])-1; } IDataset axis = null; if (axisName.endsWith("[Expression]")) { final IDataset set = currentSlice.getExpressionAxis(axisName); final IAnalysisService service = (IAnalysisService)ServiceManager.getService(IAnalysisService.class); return service.convertToAbstractDataset(set); } if (requireUnit) { // Slower IHierarchicalDataFile file = null; try { file = HierarchicalDataFactory.getReader(currentSlice.getPath()); final Group group = file.getParent(currentSlice.getName()); final String fullName = group.getFullName()+"/"+axisName; final ILoaderService service = (ILoaderService)ServiceManager.getService(ILoaderService.class); axis = service.getDataset(currentSlice.getPath(), fullName, monitor); if (axis == null) return null; axis = axis.squeeze(); final String unit = file.getAttributeValue(fullName+"@unit"); if (unit!=null) origName = origName+" "+unit; } finally { if (file!=null) file.close(); } } else { // Faster final String dataPath = currentSlice.getName(); final File file = new File(dataPath); final String fullName = file.getParent().replace('\\','/')+"/"+axisName; final ILoaderService service = (ILoaderService)ServiceManager.getService(ILoaderService.class); axis = service.getDataset(currentSlice.getPath(), fullName, monitor); if (axis == null) return null; axis = axis.squeeze(); } // TODO Should really be averaging not using first index. if (dimension>-1) { final int[] shape = axis.getShape(); final int[] start = new int[shape.length]; final int[] stop = new int[shape.length]; final int[] step = new int[shape.length]; for (int i = 0; i < shape.length; i++) { start[i] = 0; step[i] = 1; if (i==dimension) { stop[i] = shape[i]; } else { stop[i] = 1; } } axis = axis.getSlice(start, stop, step); if (axis == null) return null; axis = axis.squeeze(); } axis.setName(origName); return axis; } public static IDataset getSlice(final ILazyDataset ld, final SliceObject currentSlice, final IProgressMonitor monitor) throws Exception { final int[] dataShape = currentSlice.getFullShape(); if (monitor!=null&&monitor.isCanceled()) return null; // This is the bit that takes the time. // *DO NOT CANCEL MONITOR* if we get this far IDataset slice = (IDataset)ld.getSlice(currentSlice.getSliceStart(), currentSlice.getSliceStop(), currentSlice.getSliceStep()); slice.setName("Slice of "+currentSlice.getName()+" "+currentSlice.getShapeMessage()); final IAnalysisService service = (IAnalysisService)ServiceManager.getService(IAnalysisService.class); if (currentSlice.isRange()) { // We sum the data in the dimensions that are not axes IDataset sum = slice; final int len = dataShape.length; for (int i = len-1; i >= 0; i--) { if (!currentSlice.isAxis(i) && dataShape[i]>1) sum = service.sum(sum, i); } if (currentSlice.getX() > currentSlice.getY()) sum = service.transpose(sum); sum.setName(slice.getName()); sum = sum.squeeze(); slice = sum; } else { slice = slice.squeeze(); if (currentSlice.getX() > currentSlice.getY() && slice.getShape().length==2) { // transpose clobbers name final String name = slice.getName(); slice = service.transpose(slice); if (name!=null) slice.setName(name); } } return slice; } /** * Transforms a SliceComponent defined slice into an expanded set * of slice objects so that the data can be sliced out of the h5 file. * * @param fullShape * @param dimsDataList * @return * @throws Exception */ public static List<SliceObject> getExpandedSlices(final int[] fullShape, final Object dimsDataList) throws Exception { final DimsDataList ddl = (DimsDataList)dimsDataList; final List<SliceObject> obs = new ArrayList<SliceObject>(89); createExpandedSlices(fullShape, ddl, 0, new ArrayList<DimsData>(ddl.size()), obs); return obs; } private static void createExpandedSlices(final int[] fullShape, final DimsDataList ddl, final int index, final List<DimsData> chunk, final List<SliceObject> obs) throws Exception { final DimsData dat = ddl.getDimsData(index); final List<DimsData> exp = dat.expand(fullShape[index]); for (DimsData d : exp) { chunk.add(d); if (index==ddl.size()-1) { // Reached end SliceObject ob = new SliceObject(); ob.setFullShape(fullShape); ob = SliceUtils.createSliceObject(new DimsDataList(chunk), fullShape, ob); obs.add(ob); chunk.clear(); } else { createExpandedSlices(fullShape, ddl, index+1, chunk, obs); } } } /** * Deals with loaders which provide data names of size 1 * * * @param meta * @return */ public static final Collection<String> getSlicableNames(IDataHolder holder) { Collection<String> names = Arrays.asList(holder.getNames()); if (names==null||names.isEmpty()) return null; Collection<String> ret = new ArrayList<String>(names.size()); for (String name : names) { ILazyDataset ls = holder.getLazyDataset(name); int[] shape = ls!=null ? ls.getShape() : null; if (shape==null) continue; boolean foundDims = false; for (int i = 0; i < shape.length; i++) { if (shape[i]>1) { foundDims = true; break; } } if (!foundDims) continue; ret.add(name); } return ret; } }
false
true
public static void plotSlice(final ILazyDataset lazySet, final SliceObject currentSlice, final int[] dataShape, final PlotType type, final IPlottingSystem plottingSystem, final IProgressMonitor monitor) throws Exception { if (plottingSystem==null) return; if (monitor!=null) monitor.worked(1); if (monitor!=null&&monitor.isCanceled()) return; currentSlice.setFullShape(dataShape); final IDataset slice; final int[] slicedShape = currentSlice.getSlicedShape(); if (lazySet instanceof IDataset && Arrays.equals(slicedShape, lazySet.getShape())) { slice = (IDataset)lazySet; } else { slice = getSlice(lazySet, currentSlice,monitor); } if (slice==null) return; // DO NOT CANCEL the monitor now, we have done the hard part the slice. // We may as well plot it or the plot will look very slow. if (monitor!=null) monitor.worked(1); boolean requireScale = plottingSystem.isRescale() || type!=plottingSystem.getPlotType(); if (type==PlotType.XY) { plottingSystem.clear(); final IDataset x = getNexusAxis(currentSlice, slice.getShape()[0], currentSlice.getX()+1, true, monitor); plottingSystem.setXFirst(true); plottingSystem.setPlotType(type); plottingSystem.createPlot1D(x, Arrays.asList((IDataset)slice), slice.getName(), monitor); Display.getDefault().syncExec(new Runnable() { public void run() { plottingSystem.getSelectedXAxis().setTitle(x.getName()); plottingSystem.getSelectedYAxis().setTitle(""); } }); } else if (type==PlotType.XY_STACKED || type==PlotType.XY_STACKED_3D) { final IDataset xAxis = getNexusAxis(currentSlice, slice.getShape()[0], currentSlice.getX()+1, true, monitor); plottingSystem.clear(); // We separate the 2D image into several 1d plots final int[] shape = slice.getShape(); final List<double[]> sets = new ArrayList<double[]>(shape[1]); for (int x = 0; x < shape[0]; x++) { for (int y = 0; y < shape[1]; y++) { if (y > (sets.size()-1)) sets.add(new double[shape[0]]); double[] data = sets.get(y); data[x] = slice.getDouble(x,y); } } final List<IDataset> ys = new ArrayList<IDataset>(shape[1]); int index = 0; final IAnalysisService service = (IAnalysisService)ServiceManager.getService(IAnalysisService.class); for (double[] da : sets) { final IDataset dds = service.createDoubleDataset(da, da.length); dds.setName(String.valueOf(index)); ys.add(dds); ++index; } plottingSystem.setXFirst(true); plottingSystem.setPlotType(type); plottingSystem.createPlot1D(xAxis, ys, monitor); Display.getDefault().syncExec(new Runnable() { public void run() { plottingSystem.getSelectedXAxis().setTitle(xAxis.getName()); plottingSystem.getSelectedYAxis().setTitle(""); } }); } else if (type==PlotType.IMAGE || type==PlotType.SURFACE){ plottingSystem.setPlotType(type); IDataset y = getNexusAxis(currentSlice, slice.getShape()[0], currentSlice.getX()+1, true, monitor); IDataset x = getNexusAxis(currentSlice, slice.getShape()[1], currentSlice.getY()+1, true, monitor); // Nullify user objects because the ImageHistoryTool uses // user objects to know if the image came from it. Since we // use update here, we update (as its faster) but we also // nullify the user object. final IImageTrace trace = getImageTrace(plottingSystem); if (trace!=null) trace.setUserObject(null); plottingSystem.updatePlot2D(slice, Arrays.asList(x,y), monitor); } plottingSystem.repaint(requireScale); }
public static void plotSlice(final ILazyDataset lazySet, final SliceObject currentSlice, final int[] dataShape, final PlotType type, final IPlottingSystem plottingSystem, final IProgressMonitor monitor) throws Exception { if (plottingSystem==null) return; if (monitor!=null) monitor.worked(1); if (monitor!=null&&monitor.isCanceled()) return; currentSlice.setFullShape(dataShape); IDataset slice; final int[] slicedShape = currentSlice.getSlicedShape(); if (lazySet instanceof IDataset && Arrays.equals(slicedShape, lazySet.getShape())) { slice = (IDataset)lazySet; if (currentSlice.getX() > currentSlice.getY() && slice.getShape().length==2) { final IAnalysisService service = (IAnalysisService)ServiceManager.getService(IAnalysisService.class); // transpose clobbers name final String name = slice.getName(); slice = service.transpose(slice); if (name!=null) slice.setName(name); } } else { slice = getSlice(lazySet, currentSlice,monitor); } if (slice==null) return; // DO NOT CANCEL the monitor now, we have done the hard part the slice. // We may as well plot it or the plot will look very slow. if (monitor!=null) monitor.worked(1); boolean requireScale = plottingSystem.isRescale() || type!=plottingSystem.getPlotType(); if (type==PlotType.XY) { plottingSystem.clear(); final IDataset x = getNexusAxis(currentSlice, slice.getShape()[0], currentSlice.getX()+1, true, monitor); plottingSystem.setXFirst(true); plottingSystem.setPlotType(type); plottingSystem.createPlot1D(x, Arrays.asList((IDataset)slice), slice.getName(), monitor); Display.getDefault().syncExec(new Runnable() { public void run() { plottingSystem.getSelectedXAxis().setTitle(x.getName()); plottingSystem.getSelectedYAxis().setTitle(""); } }); } else if (type==PlotType.XY_STACKED || type==PlotType.XY_STACKED_3D) { final IDataset xAxis = getNexusAxis(currentSlice, slice.getShape()[0], currentSlice.getX()+1, true, monitor); plottingSystem.clear(); // We separate the 2D image into several 1d plots final int[] shape = slice.getShape(); final List<double[]> sets = new ArrayList<double[]>(shape[1]); for (int x = 0; x < shape[0]; x++) { for (int y = 0; y < shape[1]; y++) { if (y > (sets.size()-1)) sets.add(new double[shape[0]]); double[] data = sets.get(y); data[x] = slice.getDouble(x,y); } } final List<IDataset> ys = new ArrayList<IDataset>(shape[1]); int index = 0; final IAnalysisService service = (IAnalysisService)ServiceManager.getService(IAnalysisService.class); for (double[] da : sets) { final IDataset dds = service.createDoubleDataset(da, da.length); dds.setName(String.valueOf(index)); ys.add(dds); ++index; } plottingSystem.setXFirst(true); plottingSystem.setPlotType(type); plottingSystem.createPlot1D(xAxis, ys, monitor); Display.getDefault().syncExec(new Runnable() { public void run() { plottingSystem.getSelectedXAxis().setTitle(xAxis.getName()); plottingSystem.getSelectedYAxis().setTitle(""); } }); } else if (type==PlotType.IMAGE || type==PlotType.SURFACE){ plottingSystem.setPlotType(type); IDataset y = getNexusAxis(currentSlice, slice.getShape()[0], currentSlice.getX()+1, true, monitor); IDataset x = getNexusAxis(currentSlice, slice.getShape()[1], currentSlice.getY()+1, true, monitor); // Nullify user objects because the ImageHistoryTool uses // user objects to know if the image came from it. Since we // use update here, we update (as its faster) but we also // nullify the user object. final IImageTrace trace = getImageTrace(plottingSystem); if (trace!=null) trace.setUserObject(null); plottingSystem.updatePlot2D(slice, Arrays.asList(x,y), monitor); } plottingSystem.repaint(requireScale); }
diff --git a/WEB-INF/src/com/astrider/sfc/src/model/RegisterModel.java b/WEB-INF/src/com/astrider/sfc/src/model/RegisterModel.java index 33d3f95..59d7121 100644 --- a/WEB-INF/src/com/astrider/sfc/src/model/RegisterModel.java +++ b/WEB-INF/src/com/astrider/sfc/src/model/RegisterModel.java @@ -1,158 +1,158 @@ package com.astrider.sfc.src.model; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import com.astrider.sfc.app.lib.BaseModel; import com.astrider.sfc.app.lib.Mailer; import com.astrider.sfc.app.lib.Mapper; import com.astrider.sfc.app.lib.Validator; import com.astrider.sfc.app.lib.FlashMessage.Type; import com.astrider.sfc.app.lib.util.AuthUtils; import com.astrider.sfc.app.lib.util.StringUtils; import com.astrider.sfc.src.model.dao.UserDao; import com.astrider.sfc.src.model.dao.UserStatsDao; import com.astrider.sfc.src.model.vo.db.UserStatsVo; import com.astrider.sfc.src.model.vo.db.UserVo; import com.astrider.sfc.src.model.vo.form.ConfirmEmailVo; import com.astrider.sfc.src.model.vo.form.RegisterFormVo; import static com.astrider.sfc.ApplicationContext.*; /** * ユーザー登録関連Model. * @author astrider * */ public class RegisterModel extends BaseModel { /** * ユーザー新規登録. * @param request * @return */ public boolean registerUser(HttpServletRequest request) { // フォーム情報取得 Mapper<RegisterFormVo> m = new Mapper<RegisterFormVo>(); RegisterFormVo registerForm = (RegisterFormVo) m.fromHttpRequest(request); HttpSession session = request.getSession(); session.setAttribute(SESSION_REGISTER_FORM, registerForm); // 汎用バリデーション Validator<RegisterFormVo> validator = new Validator<RegisterFormVo>(registerForm); if (!validator.valid()) { flashMessage.addMessage(validator.getFlashMessage()); return false; } // パスワード一致 if (!registerForm.getPassword().equals(registerForm.getPasswordConfirm())) { flashMessage.addMessage("パスワードが一致しません"); return false; } // DBにユーザーを追加 UserVo user = new UserVo(registerForm); user.setAuthToken(AuthUtils.encrypt(registerForm.getPassword())); user.setEmailToken(StringUtils.getEmailToken(registerForm.getEmail())); UserDao userDao = new UserDao(); boolean succeed = userDao.insert(user, false); if (!succeed) { flashMessage.addMessage("仮登録に失敗しました。お客様のメールアドレスは既に登録されている可能性があります。"); userDao.rollback(); userDao.close(); return false; } // 仮登録メール 本文作成 String to = user.getEmail(); - String subject = "仮登録メール"; + String subject = "【sante】仮登録完了"; String body = ""; try { StringBuilder sb = new StringBuilder(); sb.append(user.getUserName() + "様\n\n"); sb.append("この度はsanteに仮登録いただきありがとうございます。\n"); sb.append("以下のURLをクリックすることによって本登録が完了いたします。\n"); sb.append("https://" + request.getServerName() + request.getContextPath() + PAGE_REGISTER_CONFIRMEMAIL); sb.append("?email=" + URLEncoder.encode(user.getEmail(), "UTF-8")); sb.append("&token=" + URLEncoder.encode(user.getEmailToken(), "UTF-8")); body = sb.toString(); } catch (UnsupportedEncodingException e) { flashMessage.addMessage("仮登録完了のメール本文の作成に失敗しました"); userDao.rollback(); userDao.close(); return false; } // 仮登録メール送信 Mailer mailer = new Mailer(to, subject, body); if (!mailer.send()) { flashMessage.addMessage("仮登録完了のメール送信に失敗しました"); userDao.rollback(); userDao.close(); return false; } userDao.commit(); userDao.close(); flashMessage.addMessage("お客様のメールアドレスに仮登録完了メールが送信されました。メール記載のリンクから本登録手続きを完了してください。"); flashMessage.setMessageType(Type.INFO); session.removeAttribute(SESSION_REGISTER_FORM); return true; } /** * メールアドレス確認. * @param request * @return */ public boolean confirmMail(HttpServletRequest request) { // 引数取得 Mapper<ConfirmEmailVo> mapper = new Mapper<ConfirmEmailVo>(); ConfirmEmailVo vo = mapper.fromHttpRequest(request); // 引数の整合性確認 Validator<ConfirmEmailVo> validator = new Validator<ConfirmEmailVo>(vo); if (!validator.valid()) { flashMessage.addMessage(validator.getFlashMessage()); return false; } // 認証トークン確認 UserDao userDao = new UserDao(); UserVo user = userDao.selectByEmailToken(vo); if (user == null) { flashMessage.addMessage("トークンが確認できませんでした。"); userDao.close(); return false; } // ユーザーを認証済みに user.setAvailable(true); user.setConfirmed(true); if (!userDao.update(user)) { flashMessage.addMessage("不明なエラー"); userDao.close(); return false; } userDao.close(); // userStatsテーブルにレコードを追加 UserStatsDao userStatsDao = new UserStatsDao(); UserStatsVo userStats = new UserStatsVo(); userStats.setUserId(user.getUserId()); userStatsDao.insert(userStats); userStatsDao.close(); // sessionをログイン済みに HttpSession session = request.getSession(); session.setAttribute(SESSION_USER, user); return true; } }
true
true
public boolean registerUser(HttpServletRequest request) { // フォーム情報取得 Mapper<RegisterFormVo> m = new Mapper<RegisterFormVo>(); RegisterFormVo registerForm = (RegisterFormVo) m.fromHttpRequest(request); HttpSession session = request.getSession(); session.setAttribute(SESSION_REGISTER_FORM, registerForm); // 汎用バリデーション Validator<RegisterFormVo> validator = new Validator<RegisterFormVo>(registerForm); if (!validator.valid()) { flashMessage.addMessage(validator.getFlashMessage()); return false; } // パスワード一致 if (!registerForm.getPassword().equals(registerForm.getPasswordConfirm())) { flashMessage.addMessage("パスワードが一致しません"); return false; } // DBにユーザーを追加 UserVo user = new UserVo(registerForm); user.setAuthToken(AuthUtils.encrypt(registerForm.getPassword())); user.setEmailToken(StringUtils.getEmailToken(registerForm.getEmail())); UserDao userDao = new UserDao(); boolean succeed = userDao.insert(user, false); if (!succeed) { flashMessage.addMessage("仮登録に失敗しました。お客様のメールアドレスは既に登録されている可能性があります。"); userDao.rollback(); userDao.close(); return false; } // 仮登録メール 本文作成 String to = user.getEmail(); String subject = "仮登録メール"; String body = ""; try { StringBuilder sb = new StringBuilder(); sb.append(user.getUserName() + "様\n\n"); sb.append("この度はsanteに仮登録いただきありがとうございます。\n"); sb.append("以下のURLをクリックすることによって本登録が完了いたします。\n"); sb.append("https://" + request.getServerName() + request.getContextPath() + PAGE_REGISTER_CONFIRMEMAIL); sb.append("?email=" + URLEncoder.encode(user.getEmail(), "UTF-8")); sb.append("&token=" + URLEncoder.encode(user.getEmailToken(), "UTF-8")); body = sb.toString(); } catch (UnsupportedEncodingException e) { flashMessage.addMessage("仮登録完了のメール本文の作成に失敗しました"); userDao.rollback(); userDao.close(); return false; } // 仮登録メール送信 Mailer mailer = new Mailer(to, subject, body); if (!mailer.send()) { flashMessage.addMessage("仮登録完了のメール送信に失敗しました"); userDao.rollback(); userDao.close(); return false; } userDao.commit(); userDao.close(); flashMessage.addMessage("お客様のメールアドレスに仮登録完了メールが送信されました。メール記載のリンクから本登録手続きを完了してください。"); flashMessage.setMessageType(Type.INFO); session.removeAttribute(SESSION_REGISTER_FORM); return true; }
public boolean registerUser(HttpServletRequest request) { // フォーム情報取得 Mapper<RegisterFormVo> m = new Mapper<RegisterFormVo>(); RegisterFormVo registerForm = (RegisterFormVo) m.fromHttpRequest(request); HttpSession session = request.getSession(); session.setAttribute(SESSION_REGISTER_FORM, registerForm); // 汎用バリデーション Validator<RegisterFormVo> validator = new Validator<RegisterFormVo>(registerForm); if (!validator.valid()) { flashMessage.addMessage(validator.getFlashMessage()); return false; } // パスワード一致 if (!registerForm.getPassword().equals(registerForm.getPasswordConfirm())) { flashMessage.addMessage("パスワードが一致しません"); return false; } // DBにユーザーを追加 UserVo user = new UserVo(registerForm); user.setAuthToken(AuthUtils.encrypt(registerForm.getPassword())); user.setEmailToken(StringUtils.getEmailToken(registerForm.getEmail())); UserDao userDao = new UserDao(); boolean succeed = userDao.insert(user, false); if (!succeed) { flashMessage.addMessage("仮登録に失敗しました。お客様のメールアドレスは既に登録されている可能性があります。"); userDao.rollback(); userDao.close(); return false; } // 仮登録メール 本文作成 String to = user.getEmail(); String subject = "【sante】仮登録完了"; String body = ""; try { StringBuilder sb = new StringBuilder(); sb.append(user.getUserName() + "様\n\n"); sb.append("この度はsanteに仮登録いただきありがとうございます。\n"); sb.append("以下のURLをクリックすることによって本登録が完了いたします。\n"); sb.append("https://" + request.getServerName() + request.getContextPath() + PAGE_REGISTER_CONFIRMEMAIL); sb.append("?email=" + URLEncoder.encode(user.getEmail(), "UTF-8")); sb.append("&token=" + URLEncoder.encode(user.getEmailToken(), "UTF-8")); body = sb.toString(); } catch (UnsupportedEncodingException e) { flashMessage.addMessage("仮登録完了のメール本文の作成に失敗しました"); userDao.rollback(); userDao.close(); return false; } // 仮登録メール送信 Mailer mailer = new Mailer(to, subject, body); if (!mailer.send()) { flashMessage.addMessage("仮登録完了のメール送信に失敗しました"); userDao.rollback(); userDao.close(); return false; } userDao.commit(); userDao.close(); flashMessage.addMessage("お客様のメールアドレスに仮登録完了メールが送信されました。メール記載のリンクから本登録手続きを完了してください。"); flashMessage.setMessageType(Type.INFO); session.removeAttribute(SESSION_REGISTER_FORM); return true; }
diff --git a/test/de/schildbach/pte/live/TlswProviderLiveTest.java b/test/de/schildbach/pte/live/TlswProviderLiveTest.java index 5006052..71b6da4 100644 --- a/test/de/schildbach/pte/live/TlswProviderLiveTest.java +++ b/test/de/schildbach/pte/live/TlswProviderLiveTest.java @@ -1,90 +1,90 @@ /* * Copyright 2010, 2011 the original author or authors. * * 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 de.schildbach.pte.live; import java.util.Date; import java.util.List; import org.junit.Test; import de.schildbach.pte.TlswProvider; import de.schildbach.pte.NetworkProvider.WalkSpeed; import de.schildbach.pte.dto.Location; import de.schildbach.pte.dto.LocationType; import de.schildbach.pte.dto.NearbyStationsResult; import de.schildbach.pte.dto.QueryConnectionsResult; import de.schildbach.pte.dto.QueryDeparturesResult; /** * @author Andreas Schildbach */ public class TlswProviderLiveTest { private final TlswProvider provider = new TlswProvider(); private static final String ALL_PRODUCTS = "IRSUTBFC"; @Test public void nearbyStations() throws Exception { final NearbyStationsResult result = provider.queryNearbyStations(new Location(LocationType.STATION, 247616), 0, 0); System.out.println(result.stations.size() + " " + result.stations); } @Test public void nearbyStationsByCoordinate() throws Exception { final NearbyStationsResult result = provider.queryNearbyStations(new Location(LocationType.ADDRESS, 51507161, -0127144), 0, 0); System.out.println(result.stations.size() + " " + result.stations); } @Test public void queryDepartures() throws Exception { final QueryDeparturesResult result = provider.queryDepartures(247616, 0, false); System.out.println(result.stationDepartures); } @Test public void autocompleteIncomplete() throws Exception { final List<Location> autocompletes = provider.autocompleteStations("Kur"); list(autocompletes); } private void list(final List<Location> autocompletes) { System.out.print(autocompletes.size() + " "); for (final Location autocomplete : autocompletes) System.out.print(autocomplete.toDebugString() + " "); System.out.println(); } @Test public void shortConnection() throws Exception { - final QueryConnectionsResult result = provider.queryConnections(new Location(LocationType.STATION, 0, null, "Hauptwache"), null, - new Location(LocationType.STATION, 0, null, "Südbahnhof"), new Date(), true, ALL_PRODUCTS, WalkSpeed.NORMAL); + final QueryConnectionsResult result = provider.queryConnections(new Location(LocationType.STATION, 0, null, "70003023"), null, new Location( + LocationType.STATION, 0, null, "70003025"), new Date(), true, ALL_PRODUCTS, WalkSpeed.NORMAL); System.out.println(result); final QueryConnectionsResult moreResult = provider.queryMoreConnections(result.context); System.out.println(moreResult); } }
true
true
public void shortConnection() throws Exception { final QueryConnectionsResult result = provider.queryConnections(new Location(LocationType.STATION, 0, null, "Hauptwache"), null, new Location(LocationType.STATION, 0, null, "Südbahnhof"), new Date(), true, ALL_PRODUCTS, WalkSpeed.NORMAL); System.out.println(result); final QueryConnectionsResult moreResult = provider.queryMoreConnections(result.context); System.out.println(moreResult); }
public void shortConnection() throws Exception { final QueryConnectionsResult result = provider.queryConnections(new Location(LocationType.STATION, 0, null, "70003023"), null, new Location( LocationType.STATION, 0, null, "70003025"), new Date(), true, ALL_PRODUCTS, WalkSpeed.NORMAL); System.out.println(result); final QueryConnectionsResult moreResult = provider.queryMoreConnections(result.context); System.out.println(moreResult); }
diff --git a/modules/cpr/src/main/java/org/atmosphere/container/Jetty7CometSupport.java b/modules/cpr/src/main/java/org/atmosphere/container/Jetty7CometSupport.java index 8b68024d9..9585df8cf 100644 --- a/modules/cpr/src/main/java/org/atmosphere/container/Jetty7CometSupport.java +++ b/modules/cpr/src/main/java/org/atmosphere/container/Jetty7CometSupport.java @@ -1,166 +1,167 @@ /* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2007-2008 Sun Microsystems, Inc. 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.html * or glassfish/bootstrap/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 glassfish/bootstrap/legal/LICENSE.txt. * Sun designates this particular file as subject to the "Classpath" exception * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * Header, with the fields enclosed by brackets [] replaced by your own * identifying information: "Portions Copyrighted [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.atmosphere.container; import org.atmosphere.cpr.ApplicationConfig; import org.atmosphere.cpr.AsynchronousProcessor; import org.atmosphere.cpr.AtmosphereHandler; import org.atmosphere.cpr.AtmosphereResourceImpl; import org.atmosphere.cpr.AtmosphereServlet.Action; import org.atmosphere.cpr.AtmosphereServlet.AtmosphereConfig; import org.atmosphere.cpr.FrameworkConfig; import org.eclipse.jetty.continuation.Continuation; import org.eclipse.jetty.continuation.ContinuationSupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.concurrent.ConcurrentLinkedQueue; /** * Comet Portable Runtime implementation on top of Jetty's Continuation. * * @author Jeanfrancois Arcand */ public class Jetty7CometSupport extends AsynchronousProcessor { private static final Logger logger = LoggerFactory.getLogger(Jetty7CometSupport.class); public Jetty7CometSupport(AtmosphereConfig config) { super(config); } /** * {@inheritDoc} */ public Action service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { Action action = null; Continuation c = (Continuation) req.getAttribute(Continuation.class.getName()); if (c == null || c.isInitial()) { action = suspended(req, res); if (action.type == Action.TYPE.SUSPEND && req.getAttribute(FrameworkConfig.CANCEL_SUSPEND_OPERATION) == null) { logger.debug("Suspending {}", res); c = ContinuationSupport.getContinuation(req); req.setAttribute(Continuation.class.getName(), c); // Do nothing except setting the times out if (action.timeout != -1) { c.setTimeout(action.timeout); } else { // Jetty 7 does something really weird if you set it to // Long.MAX_VALUE, which is to resume automatically. c.setTimeout(Integer.MAX_VALUE); } c.suspend(); } else if (action.type == Action.TYPE.RESUME) { // If resume occurs during a suspend operation, stop processing. Boolean resumeOnBroadcast = (Boolean) req.getAttribute(ApplicationConfig.RESUME_ON_BROADCAST); if (resumeOnBroadcast != null && resumeOnBroadcast) { return action; } + c = ContinuationSupport.getContinuation(req); logger.debug("Resume {}", res); if (c.isSuspended()) { try { c.complete(); } catch (IllegalStateException ex) { logger.trace("Continuation.complete()", ex); } finally { resumed(req, res); } } } } else if (!c.isInitial() && c.isExpired()) { timedout(req, res); } return action; } @Override public Action resumed(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { logger.debug("(resumed) invoked:\n HttpServletRequest: {}\n HttpServletResponse: {}", request, response); AtmosphereResourceImpl r = (AtmosphereResourceImpl) request.getAttribute(FrameworkConfig.ATMOSPHERE_RESOURCE); AtmosphereHandler<HttpServletRequest, HttpServletResponse> atmosphereHandler = (AtmosphereHandler<HttpServletRequest, HttpServletResponse>) request.getAttribute(FrameworkConfig.ATMOSPHERE_HANDLER); synchronized (r) { atmosphereHandler.onStateChange(r.getAtmosphereResourceEvent()); r.setIsInScope(false); } return new Action(Action.TYPE.RESUME); } /** * {@inheritDoc} */ @Override public void action(AtmosphereResourceImpl r) { super.action(r); if (r.isInScope() && r.action().type == Action.TYPE.RESUME && (config.getInitParameter(ApplicationConfig.RESUME_AND_KEEPALIVE) == null || config.getInitParameter(ApplicationConfig.RESUME_AND_KEEPALIVE).equalsIgnoreCase("false"))) { Continuation c = ContinuationSupport.getContinuation(r.getRequest()); if (c != null) { try { if (!c.isInitial()) { c.complete(); } else { r.getRequest().setAttribute(FrameworkConfig.CANCEL_SUSPEND_OPERATION, true); } } catch (IllegalStateException ex) { r.getRequest().setAttribute(FrameworkConfig.CANCEL_SUSPEND_OPERATION, true); logger.error("Continuation.complete() failed", ex); } } } else { try { r.getResponse(false).flushBuffer(); } catch (IOException e) { } } } }
true
true
public Action service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { Action action = null; Continuation c = (Continuation) req.getAttribute(Continuation.class.getName()); if (c == null || c.isInitial()) { action = suspended(req, res); if (action.type == Action.TYPE.SUSPEND && req.getAttribute(FrameworkConfig.CANCEL_SUSPEND_OPERATION) == null) { logger.debug("Suspending {}", res); c = ContinuationSupport.getContinuation(req); req.setAttribute(Continuation.class.getName(), c); // Do nothing except setting the times out if (action.timeout != -1) { c.setTimeout(action.timeout); } else { // Jetty 7 does something really weird if you set it to // Long.MAX_VALUE, which is to resume automatically. c.setTimeout(Integer.MAX_VALUE); } c.suspend(); } else if (action.type == Action.TYPE.RESUME) { // If resume occurs during a suspend operation, stop processing. Boolean resumeOnBroadcast = (Boolean) req.getAttribute(ApplicationConfig.RESUME_ON_BROADCAST); if (resumeOnBroadcast != null && resumeOnBroadcast) { return action; } logger.debug("Resume {}", res); if (c.isSuspended()) { try { c.complete(); } catch (IllegalStateException ex) { logger.trace("Continuation.complete()", ex); } finally { resumed(req, res); } } } } else if (!c.isInitial() && c.isExpired()) { timedout(req, res); } return action; }
public Action service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { Action action = null; Continuation c = (Continuation) req.getAttribute(Continuation.class.getName()); if (c == null || c.isInitial()) { action = suspended(req, res); if (action.type == Action.TYPE.SUSPEND && req.getAttribute(FrameworkConfig.CANCEL_SUSPEND_OPERATION) == null) { logger.debug("Suspending {}", res); c = ContinuationSupport.getContinuation(req); req.setAttribute(Continuation.class.getName(), c); // Do nothing except setting the times out if (action.timeout != -1) { c.setTimeout(action.timeout); } else { // Jetty 7 does something really weird if you set it to // Long.MAX_VALUE, which is to resume automatically. c.setTimeout(Integer.MAX_VALUE); } c.suspend(); } else if (action.type == Action.TYPE.RESUME) { // If resume occurs during a suspend operation, stop processing. Boolean resumeOnBroadcast = (Boolean) req.getAttribute(ApplicationConfig.RESUME_ON_BROADCAST); if (resumeOnBroadcast != null && resumeOnBroadcast) { return action; } c = ContinuationSupport.getContinuation(req); logger.debug("Resume {}", res); if (c.isSuspended()) { try { c.complete(); } catch (IllegalStateException ex) { logger.trace("Continuation.complete()", ex); } finally { resumed(req, res); } } } } else if (!c.isInitial() && c.isExpired()) { timedout(req, res); } return action; }
diff --git a/Laputa/src/main/java/HandicapProcessing/HandicapProcessor.java b/Laputa/src/main/java/HandicapProcessing/HandicapProcessor.java index 0e39f8f..b759490 100644 --- a/Laputa/src/main/java/HandicapProcessing/HandicapProcessor.java +++ b/Laputa/src/main/java/HandicapProcessing/HandicapProcessor.java @@ -1,29 +1,29 @@ package HandicapProcessing; /** * Created with IntelliJ IDEA. * User: snowhyzhang * Date: 13-1-10 * Time: 上午1:41 * To change this template use File | Settings | File Templates. */ public class HandicapProcessor { private iHandicapProcessing hp = new HandicapProcessing(); public static void main(String args[]){ HandicapProcessor handicapProcessor = new HandicapProcessor(); - handicapProcessor.betOneMatch(1.53, 4, 4.8, -1, 0.875, 0.925, "snow001", "8", "8"); + handicapProcessor.betOneMatch(1.45, 3.8, 6, 1.25, 0.75, 1.05, "snow001", "8", "8"); // System.out.println("=========="); // handicapProcessor.betOneMatch(1.36, 4.75, 8.0, 1, 0.7, 1.23, "snow001", "8", "8"); // System.out.println("=========="); // handicapProcessor.betOneMatch(1.36, 4.75, 8.0, 1.5, 1.29, 0.69, "snow001", "8", "8"); } public void betOneMatch(double win, double push, double lose, double handicap, double winRate, double loseRate, String matchId, String clientId, String cid){ hp.setMatch(win, push, lose, handicap, winRate, loseRate, matchId, clientId, cid, "A", "B", 4); hp.getResult(true); } }
true
true
public static void main(String args[]){ HandicapProcessor handicapProcessor = new HandicapProcessor(); handicapProcessor.betOneMatch(1.53, 4, 4.8, -1, 0.875, 0.925, "snow001", "8", "8"); // System.out.println("=========="); // handicapProcessor.betOneMatch(1.36, 4.75, 8.0, 1, 0.7, 1.23, "snow001", "8", "8"); // System.out.println("=========="); // handicapProcessor.betOneMatch(1.36, 4.75, 8.0, 1.5, 1.29, 0.69, "snow001", "8", "8"); }
public static void main(String args[]){ HandicapProcessor handicapProcessor = new HandicapProcessor(); handicapProcessor.betOneMatch(1.45, 3.8, 6, 1.25, 0.75, 1.05, "snow001", "8", "8"); // System.out.println("=========="); // handicapProcessor.betOneMatch(1.36, 4.75, 8.0, 1, 0.7, 1.23, "snow001", "8", "8"); // System.out.println("=========="); // handicapProcessor.betOneMatch(1.36, 4.75, 8.0, 1.5, 1.29, 0.69, "snow001", "8", "8"); }
diff --git a/src/line/tracker/Preview.java b/src/line/tracker/Preview.java index 4da8757..81e2f95 100644 --- a/src/line/tracker/Preview.java +++ b/src/line/tracker/Preview.java @@ -1,88 +1,88 @@ package line.tracker; import java.io.IOException; import android.content.Context; import android.graphics.Bitmap; import android.hardware.Camera; import android.hardware.Camera.PreviewCallback; import android.view.SurfaceHolder; import android.view.SurfaceView; import line.tracker.DrawOnTop; public class Preview extends SurfaceView implements SurfaceHolder.Callback { SurfaceHolder mHolder; Camera mCamera; DrawOnTop mDrawOnTop; boolean mFinished; Preview(Context context, DrawOnTop drawOnTop) { super(context); mDrawOnTop = drawOnTop; mFinished = false; // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed. mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } public void surfaceCreated(SurfaceHolder holder) { - mCamera = Camera.open(); + mCamera = Camera.open(0); try { mCamera.setPreviewDisplay(holder); // Preview callback used whenever new viewfinder frame is available mCamera.setPreviewCallback(new PreviewCallback() { public void onPreviewFrame(byte[] data, Camera camera) { if ( (mDrawOnTop == null) || mFinished ) return; if (mDrawOnTop.mBitmap == null) { // Initialize the draw-on-top companion Camera.Parameters params = camera.getParameters(); mDrawOnTop.mImageWidth = params.getPreviewSize().width; mDrawOnTop.mImageHeight = params.getPreviewSize().height; mDrawOnTop.mBitmap = Bitmap.createBitmap(mDrawOnTop.mImageWidth, mDrawOnTop.mImageHeight, Bitmap.Config.RGB_565); mDrawOnTop.mRGBData = new int[mDrawOnTop.mImageWidth * mDrawOnTop.mImageHeight]; mDrawOnTop.mYUVData = new byte[data.length]; } // Pass YUV data to draw-on-top companion System.arraycopy(data, 0, mDrawOnTop.mYUVData, 0, data.length); mDrawOnTop.invalidate(); } }); } catch (IOException exception) { mCamera.release(); mCamera = null; } } public void surfaceDestroyed(SurfaceHolder holder) { // Surface will be destroyed when we return, so stop the preview. // Because the CameraDevice object is not a shared resource, it's very // important to release it when the activity is paused. mFinished = true; mCamera.setPreviewCallback(null); mCamera.stopPreview(); mCamera.release(); mCamera = null; } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // Now that the size is known, set up the camera parameters and begin the preview. Camera.Parameters parameters = mCamera.getParameters(); parameters.setPreviewSize(160, 120); parameters.setPreviewFrameRate(30); parameters.setSceneMode(Camera.Parameters.SCENE_MODE_NIGHT); parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO); mCamera.setParameters(parameters); mCamera.startPreview(); } }
true
true
public void surfaceCreated(SurfaceHolder holder) { mCamera = Camera.open(); try { mCamera.setPreviewDisplay(holder); // Preview callback used whenever new viewfinder frame is available mCamera.setPreviewCallback(new PreviewCallback() { public void onPreviewFrame(byte[] data, Camera camera) { if ( (mDrawOnTop == null) || mFinished ) return; if (mDrawOnTop.mBitmap == null) { // Initialize the draw-on-top companion Camera.Parameters params = camera.getParameters(); mDrawOnTop.mImageWidth = params.getPreviewSize().width; mDrawOnTop.mImageHeight = params.getPreviewSize().height; mDrawOnTop.mBitmap = Bitmap.createBitmap(mDrawOnTop.mImageWidth, mDrawOnTop.mImageHeight, Bitmap.Config.RGB_565); mDrawOnTop.mRGBData = new int[mDrawOnTop.mImageWidth * mDrawOnTop.mImageHeight]; mDrawOnTop.mYUVData = new byte[data.length]; } // Pass YUV data to draw-on-top companion System.arraycopy(data, 0, mDrawOnTop.mYUVData, 0, data.length); mDrawOnTop.invalidate(); } }); } catch (IOException exception) { mCamera.release(); mCamera = null; } }
public void surfaceCreated(SurfaceHolder holder) { mCamera = Camera.open(0); try { mCamera.setPreviewDisplay(holder); // Preview callback used whenever new viewfinder frame is available mCamera.setPreviewCallback(new PreviewCallback() { public void onPreviewFrame(byte[] data, Camera camera) { if ( (mDrawOnTop == null) || mFinished ) return; if (mDrawOnTop.mBitmap == null) { // Initialize the draw-on-top companion Camera.Parameters params = camera.getParameters(); mDrawOnTop.mImageWidth = params.getPreviewSize().width; mDrawOnTop.mImageHeight = params.getPreviewSize().height; mDrawOnTop.mBitmap = Bitmap.createBitmap(mDrawOnTop.mImageWidth, mDrawOnTop.mImageHeight, Bitmap.Config.RGB_565); mDrawOnTop.mRGBData = new int[mDrawOnTop.mImageWidth * mDrawOnTop.mImageHeight]; mDrawOnTop.mYUVData = new byte[data.length]; } // Pass YUV data to draw-on-top companion System.arraycopy(data, 0, mDrawOnTop.mYUVData, 0, data.length); mDrawOnTop.invalidate(); } }); } catch (IOException exception) { mCamera.release(); mCamera = null; } }
diff --git a/src/main/java/eel/seprphase2/Simulator/PhysicalModel/PhysicalModel.java b/src/main/java/eel/seprphase2/Simulator/PhysicalModel/PhysicalModel.java index 300d108..52a81a2 100644 --- a/src/main/java/eel/seprphase2/Simulator/PhysicalModel/PhysicalModel.java +++ b/src/main/java/eel/seprphase2/Simulator/PhysicalModel/PhysicalModel.java @@ -1,334 +1,333 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package eel.seprphase2.Simulator.PhysicalModel; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import eel.seprphase2.Simulator.FailureModel.CannotControlException; import eel.seprphase2.Simulator.FailureModel.CannotRepairException; import eel.seprphase2.Simulator.FailureModel.FailableComponent; import eel.seprphase2.Simulator.FailureModel.FailureState; import eel.seprphase2.Utilities.Energy; import eel.seprphase2.Utilities.Percentage; import eel.seprphase2.Utilities.Pressure; import eel.seprphase2.Utilities.Temperature; import static eel.seprphase2.Utilities.Units.*; import java.util.ArrayList; import eel.seprphase2.Simulator.KeyNotFoundException; import eel.seprphase2.Simulator.PlantController; import eel.seprphase2.Simulator.PlantStatus; import eel.seprphase2.Utilities.Mass; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * * @author Yazidi */ public class PhysicalModel implements PlantController, PlantStatus { @JsonProperty private Reactor reactor = new Reactor(); @JsonProperty private Turbine turbine = new Turbine(); @JsonProperty private Condenser condenser = new Condenser(); @JsonProperty private Energy energyGenerated = joules(0); @JsonProperty private Connection reactorToTurbine; @JsonProperty private Connection turbineToCondenser; @JsonProperty private Pump condenserToReactor; @JsonProperty private Pump reactorToCondenser; @JsonProperty private Pump heatsinkToCondenser; @JsonProperty private String username; @JsonProperty private HashMap<Integer,Pump> allPumps; @JsonProperty private HashMap<Integer,Connection> allConnections; @JsonProperty private HeatSink heatSink; /** * */ public PhysicalModel() { heatSink = new HeatSink(); allPumps = new HashMap<Integer, Pump>(); allConnections = new HashMap<Integer, Connection>(); reactorToTurbine = new Connection(reactor.outputPort(), turbine.inputPort(), 0.05); turbineToCondenser = new Connection(turbine.outputPort(), condenser.inputPort(), 0.05); condenserToReactor = new Pump(condenser.outputPort(), reactor.inputPort()); reactorToCondenser = new Pump(reactor.outputPort(), condenser.inputPort()); heatsinkToCondenser = new Pump(heatSink.outputPort(), condenser.coolantInputPort()); reactorToCondenser.setStatus(false); allConnections.put(1,reactorToTurbine); allConnections.put(2,turbineToCondenser); allPumps.put(1, reactorToCondenser); allPumps.put(2, condenserToReactor); allPumps.put(3, heatsinkToCondenser); } public String[] listFailedComponents() { ArrayList<String> out = new ArrayList<String>(); /* * Iterate through all pumps to get their IDs */ Iterator pumpIterator = allPumps.entrySet().iterator(); while (pumpIterator.hasNext()) { Map.Entry pump = (Map.Entry)pumpIterator.next(); if(((Pump)pump.getValue()).hasFailed()) { out.add("Pump " + pump.getKey()); } - pumpIterator.remove(); } /* * Check if reactor failed */ if(reactor.hasFailed()) { out.add("Reactor"); } /* * Check if turbine failed */ if(turbine.hasFailed()) { out.add("Turbine"); } /* * Check if condenser failed */ if(condenser.hasFailed()) { out.add("Condenser"); } return out.toArray(new String[out.size()]); } /** * * @param steps */ public void step(int steps) { for (int i = 0; i < steps; i++) { reactor.step(); turbine.step(); condenser.step(); energyGenerated = joules(energyGenerated.inJoules() + turbine.outputPower()); reactorToTurbine.step(); turbineToCondenser.step(); condenserToReactor.step(); reactorToCondenser.step(); heatsinkToCondenser.step(); //System.out.println("Turbine Fail State: " + turbine.getFailureState()); //System.out.println("Condenser Fail State: " + condenser.getFailureState()); } } /** * * @param percent */ @Override public void moveControlRods(Percentage percent) { reactor.moveControlRods(percent); } /** * * @return */ @Override public Temperature reactorTemperature() { return reactor.temperature(); } public Mass reactorMinimumWaterMass() { return reactor.minimumWaterMass(); } public Mass reactorMaximumWaterMass() { return reactor.maximumWaterMass(); } @Override public Percentage reactorMinimumWaterLevel() { return reactor.minimumWaterLevel(); } public void failReactor() { reactor.fail(); } public void failCondenser() { condenser.fail(); } /** * * @return */ @Override public Energy energyGenerated() { return energyGenerated; } /** * * @return */ @Override public Percentage controlRodPosition() { return reactor.controlRodPosition(); } /** * * @return */ @Override public Pressure reactorPressure() { return reactor.pressure(); } /** * * @return */ @Override public Percentage reactorWaterLevel() { return reactor.waterLevel(); } /** * * @param open */ @Override public void setReactorToTurbine(boolean open){ reactorToTurbine.setOpen(open); } /** * * @return */ @Override public boolean getReactorToTurbine(){ return reactorToTurbine.getOpen(); } public ArrayList<FailableComponent> components() { ArrayList<FailableComponent> c = new ArrayList<FailableComponent>(); c.add(0, turbine); c.add(1, reactor); c.add(2, condenser); return c; } @Override public void changeValveState(int valveNumber, boolean isOpen) throws KeyNotFoundException { if(allConnections.containsKey(valveNumber)) { allConnections.get(valveNumber).setOpen(isOpen); } else { throw new KeyNotFoundException("Valve "+valveNumber+ " does not exist"); } } @Override public void changePumpState(int pumpNumber, boolean isPumping) throws CannotControlException, KeyNotFoundException { if (!allPumps.containsKey(pumpNumber)) { throw new KeyNotFoundException("Pump " + pumpNumber + " does not exist"); } if (allPumps.get(pumpNumber).hasFailed()) { throw new CannotControlException("Pump " + pumpNumber + " is failed"); } allPumps.get(pumpNumber).setStatus(isPumping); } @Override public void repairPump(int pumpNumber) throws KeyNotFoundException, CannotRepairException{ if(allPumps.containsKey(pumpNumber)) { allPumps.get(pumpNumber).repair(); //These shouldn't need to be changed //allPumps.get(pumpNumber).setStatus(true); //allPumps.get(pumpNumber).setCapacity(kilograms(3)); //allPumps.get(pumpNumber).setWear(new Percentage(0)); } else { throw new KeyNotFoundException("Pump "+pumpNumber+ " does not exist"); } } @Override public void repairCondenser() throws CannotRepairException { condenser.repair(); } @Override public void repairTurbine() throws CannotRepairException { turbine.repair(); } @Override public Temperature condenserTemperature() { return condenser.getTemperature(); } @Override public Pressure condenserPressure() { return condenser.getPressure(); } @Override public Percentage condenserWaterLevel() { return condenser.getWaterLevel(); } public boolean turbineHasFailed() { return turbine.hasFailed(); } }
true
true
public String[] listFailedComponents() { ArrayList<String> out = new ArrayList<String>(); /* * Iterate through all pumps to get their IDs */ Iterator pumpIterator = allPumps.entrySet().iterator(); while (pumpIterator.hasNext()) { Map.Entry pump = (Map.Entry)pumpIterator.next(); if(((Pump)pump.getValue()).hasFailed()) { out.add("Pump " + pump.getKey()); } pumpIterator.remove(); } /* * Check if reactor failed */ if(reactor.hasFailed()) { out.add("Reactor"); } /* * Check if turbine failed */ if(turbine.hasFailed()) { out.add("Turbine"); } /* * Check if condenser failed */ if(condenser.hasFailed()) { out.add("Condenser"); } return out.toArray(new String[out.size()]); }
public String[] listFailedComponents() { ArrayList<String> out = new ArrayList<String>(); /* * Iterate through all pumps to get their IDs */ Iterator pumpIterator = allPumps.entrySet().iterator(); while (pumpIterator.hasNext()) { Map.Entry pump = (Map.Entry)pumpIterator.next(); if(((Pump)pump.getValue()).hasFailed()) { out.add("Pump " + pump.getKey()); } } /* * Check if reactor failed */ if(reactor.hasFailed()) { out.add("Reactor"); } /* * Check if turbine failed */ if(turbine.hasFailed()) { out.add("Turbine"); } /* * Check if condenser failed */ if(condenser.hasFailed()) { out.add("Condenser"); } return out.toArray(new String[out.size()]); }
diff --git a/WebAlbums3-Bootstrap/src/net/wazari/bootstrap/GF.java b/WebAlbums3-Bootstrap/src/net/wazari/bootstrap/GF.java index bbaee6f4..95aac748 100644 --- a/WebAlbums3-Bootstrap/src/net/wazari/bootstrap/GF.java +++ b/WebAlbums3-Bootstrap/src/net/wazari/bootstrap/GF.java @@ -1,369 +1,372 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.wazari.bootstrap; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.Field; import java.net.BindException; import java.net.ServerSocket; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import net.wazari.bootstrap.GF.Config.User; import org.glassfish.api.admin.ParameterMap; import org.glassfish.embeddable.CommandResult; import org.glassfish.embeddable.Deployer; import org.glassfish.embeddable.GlassFish; import org.glassfish.embeddable.GlassFishException; import org.glassfish.embeddable.GlassFishProperties; import org.glassfish.embeddable.GlassFishRuntime; import org.glassfish.internal.embedded.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author pk033 */ public class GF { private static final Logger log = LoggerFactory.getLogger(GF.class.getName()); public static final String DEFAULT_CONFIG_PATH = "conf/config.xml"; private static final String SHUTDOWN_PORT_PPT = "SHUTDOWN_PORT"; /** * @param args the command line arguments */ public static void main(String[] args) { try { GF glassfish = new GF(); glassfish.start(); GF.waitForPortStop(cfg.port + 1); glassfish.terminate(); } catch (Throwable e) { e.printStackTrace(); } } public static Config cfg; static { try { log.debug("Load configuration from '"+DEFAULT_CONFIG_PATH+"'."); cfg = Config.load(DEFAULT_CONFIG_PATH); } catch (Exception ex) { throw new RuntimeException("Couldn't load the configuration file: " + ex.getMessage()); } } public GlassFish server = null; public Deployer deployer = null; public String appName = null; public File keyfile = new File("keyfile"); public void start() throws Throwable { long timeStart = System.currentTimeMillis(); log.warn("Starting WebAlbums GF bootstrap"); log.info(cfg.print()); if (keyfile.exists()) { log.warn("delete ./keyfile "); keyfile.delete(); } File earfile = new File(cfg.webAlbumsEAR); log.warn("Using EAR: {}", earfile); if (!earfile.exists()) { log.warn("The earFile {} doesn't exist ...", earfile.getAbsolutePath()); return; } try { new ServerSocket(cfg.port).close(); } catch (BindException e) { log.warn("Port {} already in use", new Object[]{cfg.port}); return; } File installDirGF = new File("./glassfish").getCanonicalFile(); EmbeddedFileSystem.Builder efsb = new EmbeddedFileSystem.Builder(); efsb.autoDelete(false); efsb.installRoot(installDirGF, true); /* EAR not recognized with domain ...*/ //File instanceGF = new File(cfg.glassfishDIR+"/domains/domain1"); //efsb.instanceRoot(instanceGF) ; EmbeddedFileSystem efs = efsb.build(); server = startServer(cfg.port, "./glassfish"); for (User usr : cfg.user) { createUsers(server, usr); } createJDBC_add_Resources(server, cfg.sunResourcesXML); deployer = server.getDeployer(); + if (!cfg.root_path.endsWith("/")) { + cfg.root_path += "/" ; + } log.info("Setting root path: {}", cfg.root_path); System.setProperty("root.path", cfg.root_path); log.info("Setting java library path: {}", cfg.libJnetFs); addToJavaLibraryPath(new File(cfg.libJnetFs)); log.info("Deploying EAR: {}", cfg.webAlbumsEAR); appName = deployer.deploy(new File(cfg.webAlbumsEAR)); if (appName == null) { log.info("Couldn't deploy ..."); throw new GlassFishException("Couldn't deploy ..."); } log.info("Deployed {}", appName); long loadingTime = System.currentTimeMillis(); float time = ((float) (loadingTime - timeStart) / 1000); log.info("Ready to server at http://localhost:{}/WebAlbums3.5-dev after {}s", new Object[]{Integer.toString(cfg.port), time}); } public void terminate() throws GlassFishException { if (deployer != null && appName != null) { deployer.undeploy(appName); } if (server != null) { server.stop(); } if (keyfile.exists()) { log.warn("delete ./keyfile "); keyfile.delete(); } } public static void waitForPortStop(int stopPort) throws IOException { System.setProperty(SHUTDOWN_PORT_PPT, Integer.toString(stopPort)); log.info("Connect to http://localhost:{} to shutdown the server", Integer.toString(stopPort)); ServerSocket servSocker = new ServerSocket(stopPort); servSocker.accept().close(); servSocker.close(); } private static GlassFish startServer(int port, String glassfishDIR) throws LifecycleException, IOException, GlassFishException { /** * Create and start GlassFish which listens at 8080 http port */ GlassFishProperties gfProps = new GlassFishProperties(); gfProps.setPort("http-listener", port); // refer JavaDocs for the details of this API. System.setProperty("java.security.auth.login.config", glassfishDIR + "/config/login.conf"); GlassFish glassfish = GlassFishRuntime.bootstrap().newGlassFish(gfProps); glassfish.start(); return glassfish; } private static void asAdmin(GlassFish server, String command, ParameterMap params) throws Throwable { org.glassfish.embeddable.CommandRunner runner = server.getCommandRunner(); log.info("Invoke {} {}", new Object[]{command, params}); log.info("command \"{}\" invoked", command); ArrayList<String> paramLst = new ArrayList<String>(); if (params != null) { for (String key : params.keySet()) { for (String value : params.get(key)) { if (key.length() != 0) { paramLst.add("--" + key); } paramLst.add(value); } } } String[] paramArray = paramLst.toArray(new String[0]); CommandResult result = runner.run(command, paramArray); log.info("command finished with {}", result.getExitStatus()); if (result.getFailureCause() != null) { throw result.getFailureCause(); } //log.info("--> {}", result.getOutput()); } private static void createUsers(GlassFish server, User usr) throws Throwable { ParameterMap params = new ParameterMap(); File tmp = File.createTempFile("embGF-", "-Webalbums"); { tmp.createNewFile(); Writer out = new OutputStreamWriter(new FileOutputStream(tmp)); out.append("AS_ADMIN_USERPASSWORD=" + usr.password); out.close(); } params.add("passwordfile", tmp.getAbsolutePath()); params.add("groups", usr.groups); params.add("", usr.name); asAdmin(server, "create-file-user", params); tmp.delete(); } private static void createJDBC_add_Resources(GlassFish server, String path) throws Throwable { if (!new File(path).exists()) { throw new IllegalArgumentException(path + " doesn't exists"); } ParameterMap params = new ParameterMap(); params.add("", path); asAdmin(server, "add-resources", params); } @XmlRootElement static class Config { public static Config loadDefault(String cfgFilePath) throws Exception { Config cfg = new Config(); cfg.sunResourcesXML = "./conf/sun-resources.xml"; cfg.libJnetFs = "./lib/libJnetFS.so"; cfg.webAlbumsEAR = "./bin/WebAlbums3-ea.ear"; cfg.root_path = "./"; cfg.port = 8080; cfg.user = new LinkedList<User>(); cfg.webAlbumsFS = "./WebAlbums3-FS"; User usr = new User(); usr.name = "kevin"; usr.password = ""; usr.groups = "Admin:Manager"; cfg.user.add(usr); cfg.save(cfgFilePath); return cfg; } public static Config load(String path) throws Exception { File file = new File(path); if (!file.isFile()) { log.info("Path '"+file.getCanonicalPath()+"' is not a file ..."); return loadDefault(path); } //Create JAXB Context JAXBContext jc = JAXBContext.newInstance(Config.class); Unmarshaller um = jc.createUnmarshaller(); Config cfg = (Config) um.unmarshal(file); return cfg; } public String print() throws JAXBException { //Create JAXB Context JAXBContext jc = JAXBContext.newInstance(Config.class); //Create marshaller Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); StringWriter writer = new StringWriter(); marshaller.marshal(this, writer); return writer.toString(); } public void save(String path) throws Exception { //Create JAXB Context JAXBContext jc = JAXBContext.newInstance(Config.class); //Create marshaller Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); File file = new File(path); file.getParentFile().mkdirs(); marshaller.marshal(this, file); log.info("Configuration saved into '"+file.getCanonicalPath()+"'."); } @XmlAttribute int port; @XmlElement String sunResourcesXML; @XmlElement String webAlbumsEAR; @XmlElement String webAlbumsFS; @XmlElement String libJnetFs; @XmlElement String root_path; @XmlElementWrapper(name = "users") List<User> user; static class User { @XmlAttribute String name; @XmlAttribute String password; @XmlAttribute String groups; } } /** * Ajoute un nouveau répertoire dans le java.library.path. * @param dir Le nouveau répertoire à ajouter. */ public static void addToJavaLibraryPath(File dir) { final String LIBRARY_PATH = "java.library.path"; if (!dir.isDirectory()) { throw new IllegalArgumentException(dir + " is not a directory."); } String javaLibraryPath = System.getProperty(LIBRARY_PATH); System.setProperty(LIBRARY_PATH, javaLibraryPath + File.pathSeparatorChar + dir.getAbsolutePath()); resetJavaLibraryPath(); } /** * Supprime le cache du "java.library.path". * Cela forcera le classloader à revérifier sa valeur lors du prochaine chargement de librairie. * * Attention : ceci est spécifique à la JVM de Sun et pourrait ne pas fonctionner * sur une autre JVM... */ public static void resetJavaLibraryPath() { synchronized(Runtime.getRuntime()) { try { Field field = ClassLoader.class.getDeclaredField("usr_paths"); field.setAccessible(true); field.set(null, null); field = ClassLoader.class.getDeclaredField("sys_paths"); field.setAccessible(true); field.set(null, null); } catch (NoSuchFieldException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } } }
true
true
public void start() throws Throwable { long timeStart = System.currentTimeMillis(); log.warn("Starting WebAlbums GF bootstrap"); log.info(cfg.print()); if (keyfile.exists()) { log.warn("delete ./keyfile "); keyfile.delete(); } File earfile = new File(cfg.webAlbumsEAR); log.warn("Using EAR: {}", earfile); if (!earfile.exists()) { log.warn("The earFile {} doesn't exist ...", earfile.getAbsolutePath()); return; } try { new ServerSocket(cfg.port).close(); } catch (BindException e) { log.warn("Port {} already in use", new Object[]{cfg.port}); return; } File installDirGF = new File("./glassfish").getCanonicalFile(); EmbeddedFileSystem.Builder efsb = new EmbeddedFileSystem.Builder(); efsb.autoDelete(false); efsb.installRoot(installDirGF, true); /* EAR not recognized with domain ...*/ //File instanceGF = new File(cfg.glassfishDIR+"/domains/domain1"); //efsb.instanceRoot(instanceGF) ; EmbeddedFileSystem efs = efsb.build(); server = startServer(cfg.port, "./glassfish"); for (User usr : cfg.user) { createUsers(server, usr); } createJDBC_add_Resources(server, cfg.sunResourcesXML); deployer = server.getDeployer(); log.info("Setting root path: {}", cfg.root_path); System.setProperty("root.path", cfg.root_path); log.info("Setting java library path: {}", cfg.libJnetFs); addToJavaLibraryPath(new File(cfg.libJnetFs)); log.info("Deploying EAR: {}", cfg.webAlbumsEAR); appName = deployer.deploy(new File(cfg.webAlbumsEAR)); if (appName == null) { log.info("Couldn't deploy ..."); throw new GlassFishException("Couldn't deploy ..."); } log.info("Deployed {}", appName); long loadingTime = System.currentTimeMillis(); float time = ((float) (loadingTime - timeStart) / 1000); log.info("Ready to server at http://localhost:{}/WebAlbums3.5-dev after {}s", new Object[]{Integer.toString(cfg.port), time}); }
public void start() throws Throwable { long timeStart = System.currentTimeMillis(); log.warn("Starting WebAlbums GF bootstrap"); log.info(cfg.print()); if (keyfile.exists()) { log.warn("delete ./keyfile "); keyfile.delete(); } File earfile = new File(cfg.webAlbumsEAR); log.warn("Using EAR: {}", earfile); if (!earfile.exists()) { log.warn("The earFile {} doesn't exist ...", earfile.getAbsolutePath()); return; } try { new ServerSocket(cfg.port).close(); } catch (BindException e) { log.warn("Port {} already in use", new Object[]{cfg.port}); return; } File installDirGF = new File("./glassfish").getCanonicalFile(); EmbeddedFileSystem.Builder efsb = new EmbeddedFileSystem.Builder(); efsb.autoDelete(false); efsb.installRoot(installDirGF, true); /* EAR not recognized with domain ...*/ //File instanceGF = new File(cfg.glassfishDIR+"/domains/domain1"); //efsb.instanceRoot(instanceGF) ; EmbeddedFileSystem efs = efsb.build(); server = startServer(cfg.port, "./glassfish"); for (User usr : cfg.user) { createUsers(server, usr); } createJDBC_add_Resources(server, cfg.sunResourcesXML); deployer = server.getDeployer(); if (!cfg.root_path.endsWith("/")) { cfg.root_path += "/" ; } log.info("Setting root path: {}", cfg.root_path); System.setProperty("root.path", cfg.root_path); log.info("Setting java library path: {}", cfg.libJnetFs); addToJavaLibraryPath(new File(cfg.libJnetFs)); log.info("Deploying EAR: {}", cfg.webAlbumsEAR); appName = deployer.deploy(new File(cfg.webAlbumsEAR)); if (appName == null) { log.info("Couldn't deploy ..."); throw new GlassFishException("Couldn't deploy ..."); } log.info("Deployed {}", appName); long loadingTime = System.currentTimeMillis(); float time = ((float) (loadingTime - timeStart) / 1000); log.info("Ready to server at http://localhost:{}/WebAlbums3.5-dev after {}s", new Object[]{Integer.toString(cfg.port), time}); }
diff --git a/src/com/herocraftonline/dev/heroes/command/commands/CooldownCommand.java b/src/com/herocraftonline/dev/heroes/command/commands/CooldownCommand.java index 636025e9..4766f66e 100644 --- a/src/com/herocraftonline/dev/heroes/command/commands/CooldownCommand.java +++ b/src/com/herocraftonline/dev/heroes/command/commands/CooldownCommand.java @@ -1,53 +1,53 @@ package com.herocraftonline.dev.heroes.command.commands; import java.util.Map; import java.util.Map.Entry; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.herocraftonline.dev.heroes.Heroes; import com.herocraftonline.dev.heroes.command.BasicCommand; import com.herocraftonline.dev.heroes.persistence.Hero; import com.herocraftonline.dev.heroes.skill.Skill; import com.herocraftonline.dev.heroes.util.Messaging; public class CooldownCommand extends BasicCommand { private Heroes plugin; public CooldownCommand(Heroes plugin) { super("Cooldowns"); this.plugin = plugin; setDescription("Displays your cooldowns"); setUsage("/cd"); setArgumentRange(0, 0); setIdentifiers(new String[] { "cooldowns", "cd" }); } @Override public boolean execute(CommandSender sender, String identifier, String[] args) { if (!(sender instanceof Player)) return false; Player player = (Player) sender; Hero hero = plugin.getHeroManager().getHero(player); if (hero.getCooldowns().isEmpty()) { Messaging.send(hero.getPlayer(), "You have no skills on cooldown!"); return true; } long time = System.currentTimeMillis(); Map<String, Skill> skillMap = plugin.getSkillMap(); for (Entry<String, Long> entry : hero.getCooldowns().entrySet()) { Skill skill = skillMap.get(entry.getKey()); - long timeLeft = time - entry.getValue(); + long timeLeft = entry.getValue() - time; if (timeLeft <= 0) continue; Messaging.send(hero.getPlayer(), "$1 has $2 seconds left on cooldown!", skill.getName(), timeLeft / 1000); } return true; } }
true
true
public boolean execute(CommandSender sender, String identifier, String[] args) { if (!(sender instanceof Player)) return false; Player player = (Player) sender; Hero hero = plugin.getHeroManager().getHero(player); if (hero.getCooldowns().isEmpty()) { Messaging.send(hero.getPlayer(), "You have no skills on cooldown!"); return true; } long time = System.currentTimeMillis(); Map<String, Skill> skillMap = plugin.getSkillMap(); for (Entry<String, Long> entry : hero.getCooldowns().entrySet()) { Skill skill = skillMap.get(entry.getKey()); long timeLeft = time - entry.getValue(); if (timeLeft <= 0) continue; Messaging.send(hero.getPlayer(), "$1 has $2 seconds left on cooldown!", skill.getName(), timeLeft / 1000); } return true; }
public boolean execute(CommandSender sender, String identifier, String[] args) { if (!(sender instanceof Player)) return false; Player player = (Player) sender; Hero hero = plugin.getHeroManager().getHero(player); if (hero.getCooldowns().isEmpty()) { Messaging.send(hero.getPlayer(), "You have no skills on cooldown!"); return true; } long time = System.currentTimeMillis(); Map<String, Skill> skillMap = plugin.getSkillMap(); for (Entry<String, Long> entry : hero.getCooldowns().entrySet()) { Skill skill = skillMap.get(entry.getKey()); long timeLeft = entry.getValue() - time; if (timeLeft <= 0) continue; Messaging.send(hero.getPlayer(), "$1 has $2 seconds left on cooldown!", skill.getName(), timeLeft / 1000); } return true; }
diff --git a/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/KnowledgeStoreServiceImpl.java b/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/KnowledgeStoreServiceImpl.java index 02cd409adc..3343babc7b 100644 --- a/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/KnowledgeStoreServiceImpl.java +++ b/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/KnowledgeStoreServiceImpl.java @@ -1,192 +1,192 @@ package org.drools.persistence.jpa; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Properties; import org.drools.KnowledgeBase; import org.drools.SessionConfiguration; import org.drools.command.CommandService; import org.drools.command.impl.CommandBasedStatefulKnowledgeSession; import org.drools.persistence.SingleSessionCommandService; import org.drools.persistence.jpa.KnowledgeStoreService; import org.drools.persistence.jpa.processinstance.JPAWorkItemManagerFactory; import org.drools.process.instance.WorkItemManagerFactory; import org.drools.runtime.CommandExecutor; import org.drools.runtime.Environment; import org.drools.runtime.KnowledgeSessionConfiguration; import org.drools.runtime.StatefulKnowledgeSession; import org.drools.time.TimerService; public class KnowledgeStoreServiceImpl implements KnowledgeStoreService { private Class< ? extends CommandExecutor> commandServiceClass; private Class< ? extends WorkItemManagerFactory> workItemManagerFactoryClass; private Class< ? extends TimerService> timerServiceClass; private Properties configProps = new Properties(); public KnowledgeStoreServiceImpl() { setDefaultImplementations(); } protected void setDefaultImplementations() { setCommandServiceClass( SingleSessionCommandService.class ); setProcessInstanceManagerFactoryClass( "org.jbpm.persistence.processinstance.JPAProcessInstanceManagerFactory" ); setWorkItemManagerFactoryClass( JPAWorkItemManagerFactory.class ); setProcessSignalManagerFactoryClass( "org.jbpm.persistence.processinstance.JPASignalManagerFactory" ); setTimerServiceClass( JpaJDKTimerService.class ); } public StatefulKnowledgeSession newStatefulKnowledgeSession(KnowledgeBase kbase, KnowledgeSessionConfiguration configuration, Environment environment) { if ( configuration == null ) { configuration = new SessionConfiguration(); } if ( environment == null ) { throw new IllegalArgumentException( "Environment cannot be null" ); } return new CommandBasedStatefulKnowledgeSession( (CommandService) buildCommanService( kbase, mergeConfig( configuration ), environment ) ); } public StatefulKnowledgeSession loadStatefulKnowledgeSession(long id, KnowledgeBase kbase, KnowledgeSessionConfiguration configuration, Environment environment) { if ( configuration == null ) { configuration = new SessionConfiguration(); } if ( environment == null ) { throw new IllegalArgumentException( "Environment cannot be null" ); } return new CommandBasedStatefulKnowledgeSession( (CommandService) buildCommanService( id, kbase, mergeConfig( configuration ), environment ) ); } private CommandExecutor buildCommanService(long sessionId, KnowledgeBase kbase, KnowledgeSessionConfiguration conf, Environment env) { try { Class< ? extends CommandExecutor> serviceClass = getCommandServiceClass(); - Constructor< ? extends CommandExecutor> constructor = serviceClass.getConstructor( int.class, + Constructor< ? extends CommandExecutor> constructor = serviceClass.getConstructor( long.class, KnowledgeBase.class, KnowledgeSessionConfiguration.class, Environment.class ); return constructor.newInstance( sessionId, kbase, conf, env ); } catch ( SecurityException e ) { throw new IllegalStateException( e ); } catch ( NoSuchMethodException e ) { throw new IllegalStateException( e ); } catch ( IllegalArgumentException e ) { throw new IllegalStateException( e ); } catch ( InstantiationException e ) { throw new IllegalStateException( e ); } catch ( IllegalAccessException e ) { throw new IllegalStateException( e ); } catch ( InvocationTargetException e ) { throw new IllegalStateException( e ); } } private CommandExecutor buildCommanService(KnowledgeBase kbase, KnowledgeSessionConfiguration conf, Environment env) { Class< ? extends CommandExecutor> serviceClass = getCommandServiceClass(); try { Constructor< ? extends CommandExecutor> constructor = serviceClass.getConstructor( KnowledgeBase.class, KnowledgeSessionConfiguration.class, Environment.class ); return constructor.newInstance( kbase, conf, env ); } catch ( SecurityException e ) { throw new IllegalStateException( e ); } catch ( NoSuchMethodException e ) { throw new IllegalStateException( e ); } catch ( IllegalArgumentException e ) { throw new IllegalStateException( e ); } catch ( InstantiationException e ) { throw new IllegalStateException( e ); } catch ( IllegalAccessException e ) { throw new IllegalStateException( e ); } catch ( InvocationTargetException e ) { throw new IllegalStateException( e ); } } private KnowledgeSessionConfiguration mergeConfig(KnowledgeSessionConfiguration configuration) { ((SessionConfiguration) configuration).addProperties( configProps ); return configuration; } public long getStatefulKnowledgeSessionId(StatefulKnowledgeSession ksession) { if ( ksession instanceof CommandBasedStatefulKnowledgeSession ) { SingleSessionCommandService commandService = (SingleSessionCommandService) ((CommandBasedStatefulKnowledgeSession) ksession).getCommandService(); return commandService.getSessionId(); } throw new IllegalArgumentException( "StatefulKnowledgeSession must be an a CommandBasedStatefulKnowledgeSession" ); } public void setCommandServiceClass(Class< ? extends CommandExecutor> commandServiceClass) { if ( commandServiceClass != null ) { this.commandServiceClass = commandServiceClass; configProps.put( "drools.commandService", commandServiceClass.getName() ); } } public Class< ? extends CommandExecutor> getCommandServiceClass() { return commandServiceClass; } public void setTimerServiceClass(Class< ? extends TimerService> timerServiceClass) { if ( timerServiceClass != null ) { this.timerServiceClass = timerServiceClass; configProps.put( "drools.timerService", timerServiceClass.getName() ); } } public Class< ? extends TimerService> getTimerServiceClass() { return timerServiceClass; } public void setProcessInstanceManagerFactoryClass(String processInstanceManagerFactoryClass) { configProps.put( "drools.processInstanceManagerFactory", processInstanceManagerFactoryClass ); } public void setWorkItemManagerFactoryClass(Class< ? extends WorkItemManagerFactory> workItemManagerFactoryClass) { if ( workItemManagerFactoryClass != null ) { this.workItemManagerFactoryClass = workItemManagerFactoryClass; configProps.put( "drools.workItemManagerFactory", workItemManagerFactoryClass.getName() ); } } public Class< ? extends WorkItemManagerFactory> getWorkItemManagerFactoryClass() { return workItemManagerFactoryClass; } public void setProcessSignalManagerFactoryClass(String processSignalManagerFactoryClass) { configProps.put( "drools.processSignalManagerFactory", processSignalManagerFactoryClass ); } }
true
true
private CommandExecutor buildCommanService(long sessionId, KnowledgeBase kbase, KnowledgeSessionConfiguration conf, Environment env) { try { Class< ? extends CommandExecutor> serviceClass = getCommandServiceClass(); Constructor< ? extends CommandExecutor> constructor = serviceClass.getConstructor( int.class, KnowledgeBase.class, KnowledgeSessionConfiguration.class, Environment.class ); return constructor.newInstance( sessionId, kbase, conf, env ); } catch ( SecurityException e ) { throw new IllegalStateException( e ); } catch ( NoSuchMethodException e ) { throw new IllegalStateException( e ); } catch ( IllegalArgumentException e ) { throw new IllegalStateException( e ); } catch ( InstantiationException e ) { throw new IllegalStateException( e ); } catch ( IllegalAccessException e ) { throw new IllegalStateException( e ); } catch ( InvocationTargetException e ) { throw new IllegalStateException( e ); } }
private CommandExecutor buildCommanService(long sessionId, KnowledgeBase kbase, KnowledgeSessionConfiguration conf, Environment env) { try { Class< ? extends CommandExecutor> serviceClass = getCommandServiceClass(); Constructor< ? extends CommandExecutor> constructor = serviceClass.getConstructor( long.class, KnowledgeBase.class, KnowledgeSessionConfiguration.class, Environment.class ); return constructor.newInstance( sessionId, kbase, conf, env ); } catch ( SecurityException e ) { throw new IllegalStateException( e ); } catch ( NoSuchMethodException e ) { throw new IllegalStateException( e ); } catch ( IllegalArgumentException e ) { throw new IllegalStateException( e ); } catch ( InstantiationException e ) { throw new IllegalStateException( e ); } catch ( IllegalAccessException e ) { throw new IllegalStateException( e ); } catch ( InvocationTargetException e ) { throw new IllegalStateException( e ); } }
diff --git a/el/src/main/java/org/apache/strutsel/taglib/html/ELFormTagBeanInfo.java b/el/src/main/java/org/apache/strutsel/taglib/html/ELFormTagBeanInfo.java index 752cb0733..99bd057dc 100644 --- a/el/src/main/java/org/apache/strutsel/taglib/html/ELFormTagBeanInfo.java +++ b/el/src/main/java/org/apache/strutsel/taglib/html/ELFormTagBeanInfo.java @@ -1,163 +1,163 @@ /* * $Id$ * * 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.strutsel.taglib.html; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.beans.SimpleBeanInfo; import java.util.ArrayList; /** * This is the <code>BeanInfo</code> descriptor for the * <code>org.apache.strutsel.taglib.html.ELFormTag</code> class. It is needed * to override the default mapping of custom tag attribute names to class * attribute names. */ public class ELFormTagBeanInfo extends SimpleBeanInfo { public PropertyDescriptor[] getPropertyDescriptors() { ArrayList proplist = new ArrayList(); try { proplist.add(new PropertyDescriptor("action", ELFormTag.class, null, "setActionExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("dir", ELFormTag.class, null, "setDirExpr")); } catch (IntrospectionException ex) { } try { - proplist.add(new PropertyDescriptor("disabled", ELTextTag.class, + proplist.add(new PropertyDescriptor("disabled", ELFormTag.class, null, "setDisabledExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("enctype", ELFormTag.class, null, "setEnctypeExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("focus", ELFormTag.class, null, "setFocusExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("focusIndex", ELFormTag.class, null, "setFocusIndexExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("lang", ELFormTag.class, null, "setLangExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("method", ELFormTag.class, null, "setMethodExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("name", ELFormTag.class, null, "setNameExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("onreset", ELFormTag.class, null, "setOnresetExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("onsubmit", ELFormTag.class, null, "setOnsubmitExpr")); } catch (IntrospectionException ex) { } try { - proplist.add(new PropertyDescriptor("readonly", ELTextTag.class, + proplist.add(new PropertyDescriptor("readonly", ELFormTag.class, null, "setReadonlyExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("scope", ELFormTag.class, null, "setScopeExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("scriptLanguage", ELFormTag.class, null, "setScriptLanguageExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("style", ELFormTag.class, null, "setStyleExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("styleClass", ELFormTag.class, null, "setStyleClassExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("styleId", ELFormTag.class, null, "setStyleIdExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("target", ELFormTag.class, null, "setTargetExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("type", ELFormTag.class, null, "setTypeExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("acceptCharset", ELFormTag.class, null, "setAcceptCharsetExpr")); } catch (IntrospectionException ex) { } PropertyDescriptor[] result = new PropertyDescriptor[proplist.size()]; return ((PropertyDescriptor[]) proplist.toArray(result)); } }
false
true
public PropertyDescriptor[] getPropertyDescriptors() { ArrayList proplist = new ArrayList(); try { proplist.add(new PropertyDescriptor("action", ELFormTag.class, null, "setActionExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("dir", ELFormTag.class, null, "setDirExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("disabled", ELTextTag.class, null, "setDisabledExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("enctype", ELFormTag.class, null, "setEnctypeExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("focus", ELFormTag.class, null, "setFocusExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("focusIndex", ELFormTag.class, null, "setFocusIndexExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("lang", ELFormTag.class, null, "setLangExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("method", ELFormTag.class, null, "setMethodExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("name", ELFormTag.class, null, "setNameExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("onreset", ELFormTag.class, null, "setOnresetExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("onsubmit", ELFormTag.class, null, "setOnsubmitExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("readonly", ELTextTag.class, null, "setReadonlyExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("scope", ELFormTag.class, null, "setScopeExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("scriptLanguage", ELFormTag.class, null, "setScriptLanguageExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("style", ELFormTag.class, null, "setStyleExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("styleClass", ELFormTag.class, null, "setStyleClassExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("styleId", ELFormTag.class, null, "setStyleIdExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("target", ELFormTag.class, null, "setTargetExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("type", ELFormTag.class, null, "setTypeExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("acceptCharset", ELFormTag.class, null, "setAcceptCharsetExpr")); } catch (IntrospectionException ex) { } PropertyDescriptor[] result = new PropertyDescriptor[proplist.size()]; return ((PropertyDescriptor[]) proplist.toArray(result)); }
public PropertyDescriptor[] getPropertyDescriptors() { ArrayList proplist = new ArrayList(); try { proplist.add(new PropertyDescriptor("action", ELFormTag.class, null, "setActionExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("dir", ELFormTag.class, null, "setDirExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("disabled", ELFormTag.class, null, "setDisabledExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("enctype", ELFormTag.class, null, "setEnctypeExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("focus", ELFormTag.class, null, "setFocusExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("focusIndex", ELFormTag.class, null, "setFocusIndexExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("lang", ELFormTag.class, null, "setLangExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("method", ELFormTag.class, null, "setMethodExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("name", ELFormTag.class, null, "setNameExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("onreset", ELFormTag.class, null, "setOnresetExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("onsubmit", ELFormTag.class, null, "setOnsubmitExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("readonly", ELFormTag.class, null, "setReadonlyExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("scope", ELFormTag.class, null, "setScopeExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("scriptLanguage", ELFormTag.class, null, "setScriptLanguageExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("style", ELFormTag.class, null, "setStyleExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("styleClass", ELFormTag.class, null, "setStyleClassExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("styleId", ELFormTag.class, null, "setStyleIdExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("target", ELFormTag.class, null, "setTargetExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("type", ELFormTag.class, null, "setTypeExpr")); } catch (IntrospectionException ex) { } try { proplist.add(new PropertyDescriptor("acceptCharset", ELFormTag.class, null, "setAcceptCharsetExpr")); } catch (IntrospectionException ex) { } PropertyDescriptor[] result = new PropertyDescriptor[proplist.size()]; return ((PropertyDescriptor[]) proplist.toArray(result)); }
diff --git a/src/com/zarcode/data/maint/GeoRSSWrite.java b/src/com/zarcode/data/maint/GeoRSSWrite.java index 9f56014..08a3b3f 100644 --- a/src/com/zarcode/data/maint/GeoRSSWrite.java +++ b/src/com/zarcode/data/maint/GeoRSSWrite.java @@ -1,341 +1,338 @@ package com.zarcode.data.maint; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.logging.Logger; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.w3c.dom.CharacterData; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import ch.hsr.geohash.WGS84Point; import com.google.appengine.api.blobstore.BlobKey; import com.google.appengine.api.blobstore.BlobstoreService; import com.google.appengine.api.blobstore.BlobstoreServiceFactory; import com.google.appengine.api.datastore.DatastoreFailureException; import com.zarcode.app.GeoRssUtil; import com.zarcode.common.EmailHelper; import com.zarcode.common.PlatformCommon; import com.zarcode.data.dao.WaterResourceDao; import com.zarcode.data.exception.WebCrawlException; import com.zarcode.data.model.WaterResourceDO; /** * This is a web GeoRSS Webcrawler for accessing Google Maps feeds. * * @author Administrator */ public class GeoRSSWrite extends HttpServlet { private Logger logger = Logger.getLogger(GeoRSSWrite.class.getName()); private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService(); private StringBuilder report = null; private String rssTitle = null; private String rssLink = null; private String rssDesc = null; public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { int i = 0; int j = 0; int k = 0; String msg = null; String urlStr = null; - String rssLink = null; - String rssTitle = null; - String rssDesc = null; String temp = null; int itemCount = 0; int memberCount = 0; Node itemNode = null; WaterResourceDO res = null; HashMap props = null; List<WGS84Point> polygon = null; OutputStream os = null; Document doc = null; int MAX_TIME_THREHOLD = 50; String[] targetList = null; report = new StringBuilder(); WaterResourceDao dao = new WaterResourceDao(); Date startTimestamp = new Date(); Node n = null; Date now = null; int startingIndex = 0; String blobKeyParam = req.getParameter("blobKey"); BlobKey blobKey = new BlobKey(blobKeyParam); byte[] rawDoc = blobstoreService.fetchData(blobKey, 0, blobstoreService.MAX_BLOB_FETCH_SIZE-1); try { doc = PlatformCommon.bytesToXml(rawDoc); } catch (Exception e) { logger.severe("EXCEPTION :: " + e.getMessage()); } /////////////////////////////////////////////////////////////////////////////// // // Process actual data in the Geo RSS feed // /////////////////////////////////////////////////////////////////////////////// logger.info("Start process GeoRSS header ..."); processGeoRSSHeader(doc); logger.info("GeoRSS header Done."); int resAdded = 0; try { if (doc != null) { NodeList lakeItemList = doc.getElementsByTagName("item"); if (lakeItemList != null && lakeItemList.getLength() > 0) { itemCount = lakeItemList.getLength(); for (i=startingIndex; i<itemCount; i++) { /** * check if we are about to hit the Google Timeout Threshold */ now = new Date(); long durationInSecs = (now.getTime() - startTimestamp.getTime())/1000; if (durationInSecs > MAX_TIME_THREHOLD) { logger.warning("Hitting ending of processing time -- Queuing task to handle late!"); /* Queue queue = QueueFactory.getDefaultQueue(); String nextIndex = "" + i; queue.add(TaskOptions.Builder.withUrl("/georssload").param("url", urlParam).param("start", nextIndex).param("delete", "false")); */ return; } else { logger.info(i + ") Time is still good ---> " + durationInSecs); } itemNode = lakeItemList.item(i); /////////////////////////////////////////////////////////////////////// // // Process each lake item data item // /////////////////////////////////////////////////////////////////////// if (itemNode != null) { // create water resource res = new WaterResourceDO(); res.setLastUpdate(new Date()); res.setRegion(rssTitle); NodeList itemMembers = itemNode.getChildNodes(); memberCount = itemMembers.getLength(); for (j=0; j<memberCount; j++) { n = itemMembers.item(j); if (n != null) { if ("guid".equalsIgnoreCase(n.getNodeName())) { temp = n.getFirstChild().getNodeValue(); logger.info("Found guid=" + temp); res.setGuid(temp); } else if ("title".equalsIgnoreCase(n.getNodeName())) { temp = n.getFirstChild().getNodeValue(); logger.info("Found title=" + temp); res.setName(temp); res.setContent(temp); } else if ("author".equalsIgnoreCase(n.getNodeName())) { temp = n.getFirstChild().getNodeValue(); logger.info("Found author=" + temp); } else if ("description".equalsIgnoreCase(n.getNodeName())) { String descData = getCharacterDataFromElement((Element)n); props = convertKVString2HashMap(descData); if (props != null && props.containsKey("reportKey")) { res.setReportKey((String)props.get("reportKey")); } else { logger.warning("reportKey not found for resource=" + res.getName()); } } else if ("gml:Polygon".equalsIgnoreCase(n.getNodeName())) { List<String> textList = new ArrayList<String>(); GeoRssUtil.findMatchingNodes(n, Node.TEXT_NODE, textList); if (textList != null && textList.size() > 0) { String polygonStr = textList.get(0); polygonStr = polygonStr.trim(); polygon = convertGMLPosList2Polygon(polygonStr); logger.info("Converted incoming polygonStr into " + polygon.size() + " object(s)."); res.setPolygon(polygon); } } } } // // add water resource to model // logger.info("Inserting resource into model!"); dao.insertResource(res); report.append("Adding resource :: "); report.append(res.getName()); report.append(" [ Region: "); report.append(res.getRegion()); report.append("]\n"); resAdded++; } } report.append("\n\nTOTAL ADDED: " + resAdded); logger.info("Processing is done on index=" + i); EmailHelper.sendAppAlert("Docked" + ": GeoRSSFeed Status", report.toString() , "Docked"); } } else { logger.warning("Document is NULL -- Write FAILED"); } } catch (DatastoreFailureException e) { logger.severe("EXCEPTION :: " + e.getMessage()); } } /** * Process the header of the Geo RSS from Google Maps. * * @param doc */ private void processGeoRSSHeader(Document doc) { int j = 0; Node n = null; String nodeName = null; Date now = null; NodeList channelList = doc.getElementsByTagName("channel"); if (channelList != null && channelList.getLength() > 0) { logger.info("Found channel node --> " + channelList.getLength()); Node header = channelList.item(0); NodeList headerChildren = header.getChildNodes(); logger.info("# of children in <channel> node: " + headerChildren.getLength()); for (j=0; j<headerChildren.getLength(); j++) { n = headerChildren.item(j); logger.info("Found <channel> children node: " + n.getNodeName()); nodeName = n.getNodeName(); if (nodeName != null) { nodeName = nodeName.trim(); } if ("link".equalsIgnoreCase(nodeName)) { rssLink = n.getFirstChild().getNodeValue(); logger.info("Saving header value for link: " + rssLink); report.append("RSSLINK: " + rssLink + "\n"); } else if ("title".equalsIgnoreCase(nodeName)) { rssTitle = n.getFirstChild().getNodeValue(); logger.info("Saving header value for title: " + rssTitle); report.append("RSSTITLE: " + rssTitle + "\n"); } else if ("description".equalsIgnoreCase(nodeName)) { rssDesc = getCharacterDataFromElement((Element)n); logger.info("Saving header value for description: " + rssDesc); report.append("DESC: " + rssDesc + "\n"); break; } } } } public String getCharacterDataFromElement(Element elem) { Node child = elem.getFirstChild(); if (child instanceof CharacterData) { CharacterData cd = (CharacterData) child; String str = cd.getData(); // take of html str = str.substring(15); str = str.substring(0, str.length()-6); str = str.trim(); logger.info("Data --> " + str); return str; } logger.warning("First child is not instanceof 'CharacterData'"); return ""; } private List<WGS84Point> convertGMLPosList2Polygon(String dataStr) { int i = 0; List<WGS84Point> res = null; String latLngStr = null; double lat = 0; double lng = 0; WGS84Point pt = null; int numOfPoints = 0; if (dataStr != null) { res = new ArrayList<WGS84Point>(); dataStr = dataStr.trim(); String[] pointList = dataStr.split("\n"); if (pointList != null && pointList.length > 0) { // // GeoRSS is returning starting pt as the last pt as well. // numOfPoints = pointList.length - 1; for (i=0; i<numOfPoints; i++) { latLngStr = pointList[i]; latLngStr = latLngStr.trim(); String[] latLngList = latLngStr.split(" "); // should have individual points here if (latLngList != null && latLngList.length == 2) { lat = Double.parseDouble(latLngList[0]); lng = Double.parseDouble(latLngList[1]); pt = new WGS84Point(lat, lng); res.add(pt); } else { logger.warning("LatLng format is not as expected --> " + latLngStr); } } } else { logger.warning("LatLng List format is not as expected --> " + dataStr); } } return res; } private HashMap<String, String> convertKVString2HashMap(String dataStr) { int i = 0; String nvPair = null; HashMap<String, String> map = null; if (dataStr != null) { map = new HashMap<String, String>(); String[] nameValueList = dataStr.split("\n"); if (nameValueList != null && nameValueList.length > 0) { for (i=0; i<nameValueList.length; i++) { nvPair = nameValueList[i]; String[] keyValue = nvPair.split("="); if (keyValue != null && keyValue.length == 2) { logger.info("Adding key=" + keyValue[0] + " val=" + keyValue[1]); map.put(keyValue[0], keyValue[1]); } } } } return map; } }
true
true
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { int i = 0; int j = 0; int k = 0; String msg = null; String urlStr = null; String rssLink = null; String rssTitle = null; String rssDesc = null; String temp = null; int itemCount = 0; int memberCount = 0; Node itemNode = null; WaterResourceDO res = null; HashMap props = null; List<WGS84Point> polygon = null; OutputStream os = null; Document doc = null; int MAX_TIME_THREHOLD = 50; String[] targetList = null; report = new StringBuilder(); WaterResourceDao dao = new WaterResourceDao(); Date startTimestamp = new Date(); Node n = null; Date now = null; int startingIndex = 0; String blobKeyParam = req.getParameter("blobKey"); BlobKey blobKey = new BlobKey(blobKeyParam); byte[] rawDoc = blobstoreService.fetchData(blobKey, 0, blobstoreService.MAX_BLOB_FETCH_SIZE-1); try { doc = PlatformCommon.bytesToXml(rawDoc); } catch (Exception e) { logger.severe("EXCEPTION :: " + e.getMessage()); } /////////////////////////////////////////////////////////////////////////////// // // Process actual data in the Geo RSS feed // /////////////////////////////////////////////////////////////////////////////// logger.info("Start process GeoRSS header ..."); processGeoRSSHeader(doc); logger.info("GeoRSS header Done."); int resAdded = 0; try { if (doc != null) { NodeList lakeItemList = doc.getElementsByTagName("item"); if (lakeItemList != null && lakeItemList.getLength() > 0) { itemCount = lakeItemList.getLength(); for (i=startingIndex; i<itemCount; i++) { /** * check if we are about to hit the Google Timeout Threshold */ now = new Date(); long durationInSecs = (now.getTime() - startTimestamp.getTime())/1000; if (durationInSecs > MAX_TIME_THREHOLD) { logger.warning("Hitting ending of processing time -- Queuing task to handle late!"); /* Queue queue = QueueFactory.getDefaultQueue(); String nextIndex = "" + i; queue.add(TaskOptions.Builder.withUrl("/georssload").param("url", urlParam).param("start", nextIndex).param("delete", "false")); */ return; } else { logger.info(i + ") Time is still good ---> " + durationInSecs); } itemNode = lakeItemList.item(i); /////////////////////////////////////////////////////////////////////// // // Process each lake item data item // /////////////////////////////////////////////////////////////////////// if (itemNode != null) { // create water resource res = new WaterResourceDO(); res.setLastUpdate(new Date()); res.setRegion(rssTitle); NodeList itemMembers = itemNode.getChildNodes(); memberCount = itemMembers.getLength(); for (j=0; j<memberCount; j++) { n = itemMembers.item(j); if (n != null) { if ("guid".equalsIgnoreCase(n.getNodeName())) { temp = n.getFirstChild().getNodeValue(); logger.info("Found guid=" + temp); res.setGuid(temp); } else if ("title".equalsIgnoreCase(n.getNodeName())) { temp = n.getFirstChild().getNodeValue(); logger.info("Found title=" + temp); res.setName(temp); res.setContent(temp); } else if ("author".equalsIgnoreCase(n.getNodeName())) { temp = n.getFirstChild().getNodeValue(); logger.info("Found author=" + temp); } else if ("description".equalsIgnoreCase(n.getNodeName())) { String descData = getCharacterDataFromElement((Element)n); props = convertKVString2HashMap(descData); if (props != null && props.containsKey("reportKey")) { res.setReportKey((String)props.get("reportKey")); } else { logger.warning("reportKey not found for resource=" + res.getName()); } } else if ("gml:Polygon".equalsIgnoreCase(n.getNodeName())) { List<String> textList = new ArrayList<String>(); GeoRssUtil.findMatchingNodes(n, Node.TEXT_NODE, textList); if (textList != null && textList.size() > 0) { String polygonStr = textList.get(0); polygonStr = polygonStr.trim(); polygon = convertGMLPosList2Polygon(polygonStr); logger.info("Converted incoming polygonStr into " + polygon.size() + " object(s)."); res.setPolygon(polygon); } } } } // // add water resource to model // logger.info("Inserting resource into model!"); dao.insertResource(res); report.append("Adding resource :: "); report.append(res.getName()); report.append(" [ Region: "); report.append(res.getRegion()); report.append("]\n"); resAdded++; } } report.append("\n\nTOTAL ADDED: " + resAdded); logger.info("Processing is done on index=" + i); EmailHelper.sendAppAlert("Docked" + ": GeoRSSFeed Status", report.toString() , "Docked"); } } else { logger.warning("Document is NULL -- Write FAILED"); } } catch (DatastoreFailureException e) { logger.severe("EXCEPTION :: " + e.getMessage()); } }
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { int i = 0; int j = 0; int k = 0; String msg = null; String urlStr = null; String temp = null; int itemCount = 0; int memberCount = 0; Node itemNode = null; WaterResourceDO res = null; HashMap props = null; List<WGS84Point> polygon = null; OutputStream os = null; Document doc = null; int MAX_TIME_THREHOLD = 50; String[] targetList = null; report = new StringBuilder(); WaterResourceDao dao = new WaterResourceDao(); Date startTimestamp = new Date(); Node n = null; Date now = null; int startingIndex = 0; String blobKeyParam = req.getParameter("blobKey"); BlobKey blobKey = new BlobKey(blobKeyParam); byte[] rawDoc = blobstoreService.fetchData(blobKey, 0, blobstoreService.MAX_BLOB_FETCH_SIZE-1); try { doc = PlatformCommon.bytesToXml(rawDoc); } catch (Exception e) { logger.severe("EXCEPTION :: " + e.getMessage()); } /////////////////////////////////////////////////////////////////////////////// // // Process actual data in the Geo RSS feed // /////////////////////////////////////////////////////////////////////////////// logger.info("Start process GeoRSS header ..."); processGeoRSSHeader(doc); logger.info("GeoRSS header Done."); int resAdded = 0; try { if (doc != null) { NodeList lakeItemList = doc.getElementsByTagName("item"); if (lakeItemList != null && lakeItemList.getLength() > 0) { itemCount = lakeItemList.getLength(); for (i=startingIndex; i<itemCount; i++) { /** * check if we are about to hit the Google Timeout Threshold */ now = new Date(); long durationInSecs = (now.getTime() - startTimestamp.getTime())/1000; if (durationInSecs > MAX_TIME_THREHOLD) { logger.warning("Hitting ending of processing time -- Queuing task to handle late!"); /* Queue queue = QueueFactory.getDefaultQueue(); String nextIndex = "" + i; queue.add(TaskOptions.Builder.withUrl("/georssload").param("url", urlParam).param("start", nextIndex).param("delete", "false")); */ return; } else { logger.info(i + ") Time is still good ---> " + durationInSecs); } itemNode = lakeItemList.item(i); /////////////////////////////////////////////////////////////////////// // // Process each lake item data item // /////////////////////////////////////////////////////////////////////// if (itemNode != null) { // create water resource res = new WaterResourceDO(); res.setLastUpdate(new Date()); res.setRegion(rssTitle); NodeList itemMembers = itemNode.getChildNodes(); memberCount = itemMembers.getLength(); for (j=0; j<memberCount; j++) { n = itemMembers.item(j); if (n != null) { if ("guid".equalsIgnoreCase(n.getNodeName())) { temp = n.getFirstChild().getNodeValue(); logger.info("Found guid=" + temp); res.setGuid(temp); } else if ("title".equalsIgnoreCase(n.getNodeName())) { temp = n.getFirstChild().getNodeValue(); logger.info("Found title=" + temp); res.setName(temp); res.setContent(temp); } else if ("author".equalsIgnoreCase(n.getNodeName())) { temp = n.getFirstChild().getNodeValue(); logger.info("Found author=" + temp); } else if ("description".equalsIgnoreCase(n.getNodeName())) { String descData = getCharacterDataFromElement((Element)n); props = convertKVString2HashMap(descData); if (props != null && props.containsKey("reportKey")) { res.setReportKey((String)props.get("reportKey")); } else { logger.warning("reportKey not found for resource=" + res.getName()); } } else if ("gml:Polygon".equalsIgnoreCase(n.getNodeName())) { List<String> textList = new ArrayList<String>(); GeoRssUtil.findMatchingNodes(n, Node.TEXT_NODE, textList); if (textList != null && textList.size() > 0) { String polygonStr = textList.get(0); polygonStr = polygonStr.trim(); polygon = convertGMLPosList2Polygon(polygonStr); logger.info("Converted incoming polygonStr into " + polygon.size() + " object(s)."); res.setPolygon(polygon); } } } } // // add water resource to model // logger.info("Inserting resource into model!"); dao.insertResource(res); report.append("Adding resource :: "); report.append(res.getName()); report.append(" [ Region: "); report.append(res.getRegion()); report.append("]\n"); resAdded++; } } report.append("\n\nTOTAL ADDED: " + resAdded); logger.info("Processing is done on index=" + i); EmailHelper.sendAppAlert("Docked" + ": GeoRSSFeed Status", report.toString() , "Docked"); } } else { logger.warning("Document is NULL -- Write FAILED"); } } catch (DatastoreFailureException e) { logger.severe("EXCEPTION :: " + e.getMessage()); } }
diff --git a/src/main/java/org/vanbest/xmltv/Horizon.java b/src/main/java/org/vanbest/xmltv/Horizon.java index 8dec8ff..a1c2b80 100644 --- a/src/main/java/org/vanbest/xmltv/Horizon.java +++ b/src/main/java/org/vanbest/xmltv/Horizon.java @@ -1,361 +1,363 @@ package org.vanbest.xmltv; /* Copyright (c) 2013 Jan-Pascal van Best <[email protected]> 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 2 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. The full license text can be found in the LICENSE file. */ import java.io.BufferedReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import net.sf.json.JSON; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class Horizon extends AbstractEPGSource implements EPGSource { static String channels_url = "https://www.horizon.tv/oesp/api/NL/nld/web/channels/"; static String listings_url = "https://www.horizon.tv/oesp/api/NL/nld/web/listings"; private static final int MAX_DAYS_AHEAD_SUPPORTED_BY_HORIZON = 7; public static String NAME = "horizon.tv"; static Logger logger = Logger.getLogger(Horizon.class); public Horizon(int sourceId, Config config) { super(sourceId, config); } public String getName() { return NAME; } public static URL programmeUrl(Channel channel, int day) throws Exception { StringBuilder s = new StringBuilder(listings_url); s.append("?byStationId="); s.append(channel.id); s.append("&sort=startTime&range=1-100"); Calendar startTime=Calendar.getInstance(); startTime.set(Calendar.HOUR_OF_DAY, 0); startTime.set(Calendar.MINUTE, 0); startTime.set(Calendar.SECOND, 0); startTime.set(Calendar.MILLISECOND, 0); startTime.add(Calendar.DAY_OF_MONTH, day); Calendar endTime = (Calendar) startTime.clone(); endTime.add(Calendar.DAY_OF_MONTH, 1); s.append("&byStartTime="); s.append(startTime.getTimeInMillis()); s.append("~"); s.append(endTime.getTimeInMillis()); return new URL(s.toString()); } /* * (non-Javadoc) * * @see org.vanbest.xmltv.EPGSource#getChannels() */ @Override public List<Channel> getChannels() { List<Channel> result = new ArrayList<Channel>(10); URL url = null; try { url = new URL(channels_url); } catch (MalformedURLException e) { logger.error("Exception creating horizon channel list url", e); } JSONObject channels; try { channels = fetchJSON(url); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); return result; } logger.debug("horizon channels json: " + channels.toString()); int numChannels = Integer.parseInt(channels.getString("totalResults")); JSONArray jsonArray = channels.getJSONArray("channels"); for (int i = 0; i < jsonArray.size(); i++) { JSONObject zender = jsonArray.getJSONObject(i); // System.out.println( "id: " + zender.getString("id")); // System.out.println( "name: " + zender.getString("name")); JSONArray stationSchedules=zender.getJSONArray("stationSchedules"); assert(1 == stationSchedules.size()); JSONObject firstSchedule = stationSchedules.getJSONObject(0); JSONObject station = firstSchedule.getJSONObject("station"); logger.debug("firstschedule: " + firstSchedule.toString()); long horizonId = station.getLong("id"); String name = station.getString("title"); // Use the largest available station logo as icon JSONArray images = station.getJSONArray("images"); String icon = ""; int maxSize = 0; for( int j=0; j<images.size(); j++) { JSONObject image = images.getJSONObject(j); if (image.getString("assetType").startsWith("station-logo") && image.getInt("width")>maxSize) { icon = image.getString("url"); maxSize = image.getInt("width"); } } String xmltv = name.replaceAll("[^a-zA-Z0-9]", "")+"."+getName(); Channel c = Channel.getChannel(getId(), Long.toString(horizonId), xmltv, name); //Channel c = new HorizonChannel(getId(), horizonId, name); c.addIcon(icon); result.add(c); } return result; } /* * (non-Javadoc) * * @see org.vanbest.xmltv.EPGSource#getProgrammes(java.util.List, int, * boolean) */ @Override public List<Programme> getProgrammes(List<Channel> channels, int day) throws Exception { List<Programme> result = new ArrayList<Programme>(); if (day > MAX_DAYS_AHEAD_SUPPORTED_BY_HORIZON) { return result; // empty list } for (Channel c : channels) { URL url = programmeUrl(c, day); logger.debug("Programme url:" + url); JSONObject jsonObject = fetchJSON(url); logger.debug(jsonObject.toString()); JSONArray listings = jsonObject.getJSONArray("listings"); for (int i = 0; i < listings.size(); i++) { JSONObject listing = listings.getJSONObject(i); Programme p = programmeFromJSON(listing, config.fetchDetails); p.channel = c.getXmltvChannelId(); result.add(p); } } return result; } /* * {"id":"crid:~~2F~~2Feventis.nl~~2F00000000-0000-1000-0004-00000189B7F0-imi:001017B90000FCD2", * "countryCode":"NL", * "languageCode":"nld", * "deviceCode":"web", * "locationId":"15332128", * "startTime":1362399000000, * "endTime":1362399300000, * "stationId":"28070126", * "imi":"imi:001017B90000FCD2", * "program":{"id":"crid:~~2F~~2Feventis.nl~~2F00000000-0000-1000-0004-00000189B7F0", * "mediaGroupId":"crid:~~2F~~2Feventis.nl~~2F00000000-0000-1000-0008-000000007784", * "title":"NOS Sportjournaal (Ned1) - 13:10", * "secondaryTitle":"NOS Sportjournaal", * "description":"Aandacht voor het actuele sportnieuws.", * "shortDescription":"Aandacht voor het actuele sportnieuws.", * "longDescription":"Aandacht voor het actuele sportnieuws.", * "countryCode":"NL", * "languageCode":"nld", * "deviceCode":"web", * "medium":"TV", * "categories":[{"id":"13946291","title":"sports","scheme":"urn:tva:metadata:cs:UPCEventGenreCS:2009"}, * {"id":"13946352","title":"sports/sports","scheme":"urn:tva:metadata:cs:UPCEventGenreCS:2009"}], * "mediaType":"Episode", * "isAdult":false, * "seriesEpisodeNumber":"50108216", * "cast":[], * "directors":[], * "videos":[], * "images":[{"assetType":"tva-boxcover","width":180,"height":260,"url":"https://www.horizon.tv/static-images/926/511/36654624.p.jpg"}, * {"assetType":"boxart-xlarge","width":210,"height":303,"url":"https://www.horizon.tv/static-images/926/511/36654624.p_210x303_34273348255.jpg"}, * {"assetType":"boxart-large","width":180,"height":260,"url":"https://www.horizon.tv/static-images/926/511/36654624.p_180x260_34273348256.jpg"}, * {"assetType":"boxart-medium","width":110,"height":159,"url":"https://www.horizon.tv/static-images/926/511/36654624.p_110x159_34273348257.jpg"}, * {"assetType":"boxart-small","width":75,"height":108,"url":"https://www.horizon.tv/static-images/926/511/36654624.p_75x108_34273348258.jpg"}]}} */ private Programme programmeFromJSON(JSONObject json, boolean fetchDetails) throws Exception { String id = json.getString("id"); Programme result = cache.get(getId(), id); boolean cached = (result != null); boolean doNotCache = false; if (result == null) { stats.cacheMisses++; result = new Programme(); result.startTime = new Date(json.getLong("startTime")); result.endTime = new Date(json.getLong("endTime")); JSONObject prog = json.getJSONObject("program"); + // Sometimes the JSON doesnt contains a prog item + if (prog==null || prog.isNullObject()) return result; String title = null; if (prog.has("title")){ title = prog.getString("title"); } String secondary = null; if (prog.has("secondaryTitle")) { secondary = prog.getString("secondaryTitle"); if (secondary.contains("Zal snel bekend")) secondary = null; } if (title != null && secondary!=null && title.contains(secondary)) { title=secondary; secondary=null; } if (title != null && !title.isEmpty()) { result.addTitle(title); if (secondary!=null && !secondary.isEmpty()) { result.addSecondaryTitle(secondary); } } else { doNotCache = true; if (secondary!=null && !secondary.isEmpty()) { result.addTitle(secondary); } } String description = null; if (prog.has("longDescription")) description = prog.getString("longDescription"); if (description==null || description.isEmpty()) { if (prog.has("description")) description = prog.getString("description"); } if (description==null || description.isEmpty()) { if (prog.has("shortDescription")) description = prog.getString("shortDescription"); } if (description!= null && !description.isEmpty()) { result.addDescription(description); } else { doNotCache = true; } if (prog.has("cast")) { JSONArray cast = prog.getJSONArray("cast"); for( int j=0; j<cast.size(); j++) { result.addActor(cast.getString(j)); } } if (prog.has("directors")) { JSONArray directors = prog.getJSONArray("directors"); for( int j=0; j<directors.size(); j++) { result.addDirector(directors.getString(j)); } } if (prog.has("categories")) { JSONArray categories = prog.getJSONArray("categories"); for( int j=0; j<categories.size(); j++) { String cat = categories.getJSONObject(j).getString("title"); if (!cat.contains("/")) { // Remove things like "drama/drama" and subcategories result.addCategory(config.translateCategory(cat)); } } } if (prog.has("seriesEpisodeNumber")){ String episode = prog.getString("seriesEpisodeNumber"); result.addEpisode(episode,"onscreen"); } /* Disabled, contains disinformation if (prog.has("parentalRating")){ String rating = prog.getString("parentalRating"); result.addRating("kijkwijzer", "Afgeraden voor kinderen jonger dan "+rating+" jaar"); } */ /* // TODO add icon */ } else { // System.out.println("From cache: " + // programme.getString("titel")); stats.cacheHits++; } // TODO other fields if (!cached && !doNotCache) { cache.put(getId(), id, result); } logger.debug(result); return result; } /** * @param args */ public static void main(String[] args) { Config config = Config.getDefaultConfig(); Horizon horizon = new Horizon(3, config); horizon.clearCache(); try { List<Channel> channels = horizon.getChannels(); System.out.println("Channels: " + channels); XMLStreamWriter writer = XMLOutputFactory.newInstance() .createXMLStreamWriter(new FileWriter("horizon.xml")); writer.writeStartDocument(); writer.writeCharacters("\n"); writer.writeDTD("<!DOCTYPE tv SYSTEM \"xmltv.dtd\">"); writer.writeCharacters("\n"); writer.writeStartElement("tv"); // List<Channel> my_channels = channels; List<Channel> my_channels = channels.subList(0, 5); for (Channel c : my_channels) { c.serialize(writer, true); } writer.flush(); for(int day=0; day<5; day++) { List<Programme> programmes = horizon.getProgrammes(my_channels, day); for (Programme p : programmes) { p.serialize(writer); } } writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); if (!config.quiet) { EPGSource.Stats stats = horizon.getStats(); System.out.println("Number of programmes from cache: " + stats.cacheHits); System.out.println("Number of programmes fetched: " + stats.cacheMisses); System.out.println("Number of fetch errors: " + stats.fetchErrors); } horizon.close(); } catch (Exception e) { logger.error("Error in horizon testing", e); } } }
true
true
private Programme programmeFromJSON(JSONObject json, boolean fetchDetails) throws Exception { String id = json.getString("id"); Programme result = cache.get(getId(), id); boolean cached = (result != null); boolean doNotCache = false; if (result == null) { stats.cacheMisses++; result = new Programme(); result.startTime = new Date(json.getLong("startTime")); result.endTime = new Date(json.getLong("endTime")); JSONObject prog = json.getJSONObject("program"); String title = null; if (prog.has("title")){ title = prog.getString("title"); } String secondary = null; if (prog.has("secondaryTitle")) { secondary = prog.getString("secondaryTitle"); if (secondary.contains("Zal snel bekend")) secondary = null; } if (title != null && secondary!=null && title.contains(secondary)) { title=secondary; secondary=null; } if (title != null && !title.isEmpty()) { result.addTitle(title); if (secondary!=null && !secondary.isEmpty()) { result.addSecondaryTitle(secondary); } } else { doNotCache = true; if (secondary!=null && !secondary.isEmpty()) { result.addTitle(secondary); } } String description = null; if (prog.has("longDescription")) description = prog.getString("longDescription"); if (description==null || description.isEmpty()) { if (prog.has("description")) description = prog.getString("description"); } if (description==null || description.isEmpty()) { if (prog.has("shortDescription")) description = prog.getString("shortDescription"); } if (description!= null && !description.isEmpty()) { result.addDescription(description); } else { doNotCache = true; } if (prog.has("cast")) { JSONArray cast = prog.getJSONArray("cast"); for( int j=0; j<cast.size(); j++) { result.addActor(cast.getString(j)); } } if (prog.has("directors")) { JSONArray directors = prog.getJSONArray("directors"); for( int j=0; j<directors.size(); j++) { result.addDirector(directors.getString(j)); } } if (prog.has("categories")) { JSONArray categories = prog.getJSONArray("categories"); for( int j=0; j<categories.size(); j++) { String cat = categories.getJSONObject(j).getString("title"); if (!cat.contains("/")) { // Remove things like "drama/drama" and subcategories result.addCategory(config.translateCategory(cat)); } } } if (prog.has("seriesEpisodeNumber")){ String episode = prog.getString("seriesEpisodeNumber"); result.addEpisode(episode,"onscreen"); } /* Disabled, contains disinformation if (prog.has("parentalRating")){ String rating = prog.getString("parentalRating"); result.addRating("kijkwijzer", "Afgeraden voor kinderen jonger dan "+rating+" jaar"); } */ /* // TODO add icon */ } else { // System.out.println("From cache: " + // programme.getString("titel")); stats.cacheHits++; } // TODO other fields if (!cached && !doNotCache) { cache.put(getId(), id, result); } logger.debug(result); return result; }
private Programme programmeFromJSON(JSONObject json, boolean fetchDetails) throws Exception { String id = json.getString("id"); Programme result = cache.get(getId(), id); boolean cached = (result != null); boolean doNotCache = false; if (result == null) { stats.cacheMisses++; result = new Programme(); result.startTime = new Date(json.getLong("startTime")); result.endTime = new Date(json.getLong("endTime")); JSONObject prog = json.getJSONObject("program"); // Sometimes the JSON doesnt contains a prog item if (prog==null || prog.isNullObject()) return result; String title = null; if (prog.has("title")){ title = prog.getString("title"); } String secondary = null; if (prog.has("secondaryTitle")) { secondary = prog.getString("secondaryTitle"); if (secondary.contains("Zal snel bekend")) secondary = null; } if (title != null && secondary!=null && title.contains(secondary)) { title=secondary; secondary=null; } if (title != null && !title.isEmpty()) { result.addTitle(title); if (secondary!=null && !secondary.isEmpty()) { result.addSecondaryTitle(secondary); } } else { doNotCache = true; if (secondary!=null && !secondary.isEmpty()) { result.addTitle(secondary); } } String description = null; if (prog.has("longDescription")) description = prog.getString("longDescription"); if (description==null || description.isEmpty()) { if (prog.has("description")) description = prog.getString("description"); } if (description==null || description.isEmpty()) { if (prog.has("shortDescription")) description = prog.getString("shortDescription"); } if (description!= null && !description.isEmpty()) { result.addDescription(description); } else { doNotCache = true; } if (prog.has("cast")) { JSONArray cast = prog.getJSONArray("cast"); for( int j=0; j<cast.size(); j++) { result.addActor(cast.getString(j)); } } if (prog.has("directors")) { JSONArray directors = prog.getJSONArray("directors"); for( int j=0; j<directors.size(); j++) { result.addDirector(directors.getString(j)); } } if (prog.has("categories")) { JSONArray categories = prog.getJSONArray("categories"); for( int j=0; j<categories.size(); j++) { String cat = categories.getJSONObject(j).getString("title"); if (!cat.contains("/")) { // Remove things like "drama/drama" and subcategories result.addCategory(config.translateCategory(cat)); } } } if (prog.has("seriesEpisodeNumber")){ String episode = prog.getString("seriesEpisodeNumber"); result.addEpisode(episode,"onscreen"); } /* Disabled, contains disinformation if (prog.has("parentalRating")){ String rating = prog.getString("parentalRating"); result.addRating("kijkwijzer", "Afgeraden voor kinderen jonger dan "+rating+" jaar"); } */ /* // TODO add icon */ } else { // System.out.println("From cache: " + // programme.getString("titel")); stats.cacheHits++; } // TODO other fields if (!cached && !doNotCache) { cache.put(getId(), id, result); } logger.debug(result); return result; }
diff --git a/src/haven/RootWidget.java b/src/haven/RootWidget.java index 058ef5f6..bcacade2 100644 --- a/src/haven/RootWidget.java +++ b/src/haven/RootWidget.java @@ -1,71 +1,71 @@ /* * This file is part of the Haven & Hearth game client. * Copyright (C) 2009 Fredrik Tolf <[email protected]>, and * Björn Johannessen <[email protected]> * * Redistribution and/or modification of this file is subject to the * terms of the GNU Lesser General Public License, version 3, as * published by the Free Software Foundation. * * 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. * * Other parts of this source tree adhere to other copying * rights. Please see the file `COPYING' in the root directory of the * source tree for details. * * A copy the GNU Lesser General Public License is distributed along * with the source tree of which this file is a part in the file * `doc/LPGL-3'. If it is missing for any reason, please see the Free * Software Foundation's website at <http://www.fsf.org/>, or write * to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA */ package haven; import java.awt.event.KeyEvent; public class RootWidget extends ConsoleHost { public static Resource defcurs = Resource.load("gfx/hud/curs/arw"); Logout logout = null; Profile gprof; boolean afk = false; public RootWidget(UI ui, Coord sz) { super(ui, new Coord(0, 0), sz); setfocusctl(true); cursor = defcurs; } public boolean globtype(char key, KeyEvent ev) { if(!super.globtype(key, ev)) { if(Config.profile && (key == '`')) { new Profwnd(findchild(SlenHud.class), gprof, "Glob prof"); - } else if(Config.profile && (key == '!')) { + } else if(key == ':') { entercmd(); } else if(key != 0) { wdgmsg("gk", (int)key); } } return(true); } public void draw(GOut g) { super.draw(g); drawcmd(g, new Coord(20, 580)); if(!afk && (System.currentTimeMillis() - ui.lastevent > 300000)) { afk = true; Widget slen = findchild(SlenHud.class); if(slen != null) slen.wdgmsg("afk"); } else if(afk && (System.currentTimeMillis() - ui.lastevent < 300000)) { afk = false; } } public void error(String msg) { } }
true
true
public boolean globtype(char key, KeyEvent ev) { if(!super.globtype(key, ev)) { if(Config.profile && (key == '`')) { new Profwnd(findchild(SlenHud.class), gprof, "Glob prof"); } else if(Config.profile && (key == '!')) { entercmd(); } else if(key != 0) { wdgmsg("gk", (int)key); } } return(true); }
public boolean globtype(char key, KeyEvent ev) { if(!super.globtype(key, ev)) { if(Config.profile && (key == '`')) { new Profwnd(findchild(SlenHud.class), gprof, "Glob prof"); } else if(key == ':') { entercmd(); } else if(key != 0) { wdgmsg("gk", (int)key); } } return(true); }
diff --git a/plugins/org.eclipse.birt.report.engine.emitter.prototype.excel/src/org/eclipse/birt/report/engine/emitter/excel/layout/LayoutUtil.java b/plugins/org.eclipse.birt.report.engine.emitter.prototype.excel/src/org/eclipse/birt/report/engine/emitter/excel/layout/LayoutUtil.java index 971387eca..5ebc58149 100644 --- a/plugins/org.eclipse.birt.report.engine.emitter.prototype.excel/src/org/eclipse/birt/report/engine/emitter/excel/layout/LayoutUtil.java +++ b/plugins/org.eclipse.birt.report.engine.emitter.prototype.excel/src/org/eclipse/birt/report/engine/emitter/excel/layout/LayoutUtil.java @@ -1,206 +1,218 @@ package org.eclipse.birt.report.engine.emitter.excel.layout; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.birt.report.engine.content.IContent; import org.eclipse.birt.report.engine.content.IForeignContent; import org.eclipse.birt.report.engine.content.IImageContent; import org.eclipse.birt.report.engine.content.IListContent; import org.eclipse.birt.report.engine.content.ITableContent; import org.eclipse.birt.report.engine.emitter.EmitterUtil; import org.eclipse.birt.report.engine.emitter.excel.ExcelUtil; import org.eclipse.birt.report.engine.ir.DimensionType; import org.eclipse.birt.report.engine.ir.ExtendedItemDesign; import org.eclipse.birt.report.engine.layout.emitter.Image; public class LayoutUtil { private static final Logger log = Logger.getLogger( LayoutUtil.class .getName( ) ); public static ColumnsInfo createTable( int col, int width ) { return new ColumnsInfo( col, width ); } public static ColumnsInfo createTable( IListContent list, int width ) { width = getElementWidth(list, width); int[] column = new int[] {width}; return new ColumnsInfo( column ); } public static ColumnsInfo createChart( IForeignContent content, int width ) { ExtendedItemDesign design = (ExtendedItemDesign) content .getGenerateBy( ); DimensionType value = design.getWidth( ); if ( value != null ) { width = getElementWidth( value, width ); } int[] column = new int[]{width}; return new ColumnsInfo( column ); } public static ColumnsInfo createImage( IImageContent image, int width ) { width = getImageWidth( image, width ); int[] column = new int[]{width}; return new ColumnsInfo( column ); } public static int getImageWidth( IImageContent image, int width ) { DimensionType value = image.getWidth( ); if ( value != null ) { width = getElementWidth( value, width ); } else { try { Image imageInfo = EmitterUtil.parseImage( image, image .getImageSource( ), image.getURI( ), image .getMIMEType( ), image.getExtension( ) ); width = (int) ( imageInfo.getWidth( ) * ExcelUtil.PX_PT ); } catch ( IOException e1 ) { log.log( Level.WARNING, e1.getLocalizedMessage( ) ); } } return width; } public static int getElementWidth( IContent content, int width ) { DimensionType value = content.getWidth( ); if ( value != null ) { return getElementWidth( value, width ); } return width; } private static int getElementWidth( DimensionType contentWdith, int width ) { try { width = Math.min( ExcelUtil.covertDimensionType( contentWdith, width ), width ); } catch ( Exception e ) { } return width; } public static int[] createFixedTable( ITableContent table, int tableWidth ) { int columnCount = table.getColumnCount( ); int[] columns = new int[columnCount]; int unassignedCount = 0; int totalAssigned = 0; for(int i = 0; i < columnCount; i++) { DimensionType value = table.getColumn( i ).getWidth( ); if( value == null) { columns[i] = -1; unassignedCount++; } else { columns[i] = ExcelUtil.covertDimensionType( value, tableWidth ); totalAssigned += columns[i]; } } if ( table.getWidth( ) == null && unassignedCount == 0 ) { return columns; } return EmitterUtil.resizeTableColumn( tableWidth, columns, unassignedCount, totalAssigned ); } public static ColumnsInfo createTable( ITableContent table, int width ) { int tableWidth = getElementWidth( table, width ); int columnCount = table.getColumnCount( ); if ( columnCount == 0 ) { return null; } int[] columns = new int[columnCount]; int unassignedCount = 0; int totalAssigned = 0; for ( int i = 0; i < columnCount; i++ ) { DimensionType value = table.getColumn( i ).getWidth( ); if ( value == null ) { columns[i] = -1; unassignedCount++; } else { columns[i] = ExcelUtil.covertDimensionType( value, tableWidth ); totalAssigned += columns[i]; } } int leftWidth = tableWidth - totalAssigned; if ( leftWidth != 0 && unassignedCount == 0 ) { - for ( int i = 0; i < columnCount; i++ ) + int totalResized = 0; + for ( int i = 0; i < columnCount - 1; i++ ) { columns[i] = resize( columns[i], totalAssigned, leftWidth ); + totalResized += columns[i]; } + columns[columnCount - 1] = tableWidth - totalResized; } else if ( leftWidth < 0 && unassignedCount > 0 ) { + int totalResized = 0; + int lastAssignedIndex = 0; for ( int i = 0; i < columnCount; i++ ) { if ( columns[i] == -1 ) + { columns[1] = 0; + } else + { columns[i] = resize( columns[i], totalAssigned, leftWidth ); + lastAssignedIndex = i; + } + totalResized += columns[i]; } + columns[lastAssignedIndex] += tableWidth - totalResized; } else if ( leftWidth >= 0 && unassignedCount > 0 ) { int per = (int) leftWidth / unassignedCount; int index = 0; for ( int i = 0; i < columns.length; i++ ) { if ( columns[i] == -1 ) { columns[i] = per; index = i; } } columns[index] = leftWidth - per * ( unassignedCount - 1 ); } return new ColumnsInfo( columns ); } private static int resize( int width, int total, int left ) { return Math.round( width + (float) width / (float) total * left ); } }
false
true
public static ColumnsInfo createTable( ITableContent table, int width ) { int tableWidth = getElementWidth( table, width ); int columnCount = table.getColumnCount( ); if ( columnCount == 0 ) { return null; } int[] columns = new int[columnCount]; int unassignedCount = 0; int totalAssigned = 0; for ( int i = 0; i < columnCount; i++ ) { DimensionType value = table.getColumn( i ).getWidth( ); if ( value == null ) { columns[i] = -1; unassignedCount++; } else { columns[i] = ExcelUtil.covertDimensionType( value, tableWidth ); totalAssigned += columns[i]; } } int leftWidth = tableWidth - totalAssigned; if ( leftWidth != 0 && unassignedCount == 0 ) { for ( int i = 0; i < columnCount; i++ ) { columns[i] = resize( columns[i], totalAssigned, leftWidth ); } } else if ( leftWidth < 0 && unassignedCount > 0 ) { for ( int i = 0; i < columnCount; i++ ) { if ( columns[i] == -1 ) columns[1] = 0; else columns[i] = resize( columns[i], totalAssigned, leftWidth ); } } else if ( leftWidth >= 0 && unassignedCount > 0 ) { int per = (int) leftWidth / unassignedCount; int index = 0; for ( int i = 0; i < columns.length; i++ ) { if ( columns[i] == -1 ) { columns[i] = per; index = i; } } columns[index] = leftWidth - per * ( unassignedCount - 1 ); } return new ColumnsInfo( columns ); }
public static ColumnsInfo createTable( ITableContent table, int width ) { int tableWidth = getElementWidth( table, width ); int columnCount = table.getColumnCount( ); if ( columnCount == 0 ) { return null; } int[] columns = new int[columnCount]; int unassignedCount = 0; int totalAssigned = 0; for ( int i = 0; i < columnCount; i++ ) { DimensionType value = table.getColumn( i ).getWidth( ); if ( value == null ) { columns[i] = -1; unassignedCount++; } else { columns[i] = ExcelUtil.covertDimensionType( value, tableWidth ); totalAssigned += columns[i]; } } int leftWidth = tableWidth - totalAssigned; if ( leftWidth != 0 && unassignedCount == 0 ) { int totalResized = 0; for ( int i = 0; i < columnCount - 1; i++ ) { columns[i] = resize( columns[i], totalAssigned, leftWidth ); totalResized += columns[i]; } columns[columnCount - 1] = tableWidth - totalResized; } else if ( leftWidth < 0 && unassignedCount > 0 ) { int totalResized = 0; int lastAssignedIndex = 0; for ( int i = 0; i < columnCount; i++ ) { if ( columns[i] == -1 ) { columns[1] = 0; } else { columns[i] = resize( columns[i], totalAssigned, leftWidth ); lastAssignedIndex = i; } totalResized += columns[i]; } columns[lastAssignedIndex] += tableWidth - totalResized; } else if ( leftWidth >= 0 && unassignedCount > 0 ) { int per = (int) leftWidth / unassignedCount; int index = 0; for ( int i = 0; i < columns.length; i++ ) { if ( columns[i] == -1 ) { columns[i] = per; index = i; } } columns[index] = leftWidth - per * ( unassignedCount - 1 ); } return new ColumnsInfo( columns ); }
diff --git a/src/com/android/phone/PhoneApp.java b/src/com/android/phone/PhoneApp.java index 82fda65..ff4b770 100644 --- a/src/com/android/phone/PhoneApp.java +++ b/src/com/android/phone/PhoneApp.java @@ -1,1746 +1,1747 @@ /* * Copyright (C) 2006 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.app.Activity; import android.app.Application; import android.app.KeyguardManager; import android.app.ProgressDialog; import android.app.StatusBarManager; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothHeadset; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Configuration; import android.media.AudioManager; import android.net.Uri; import android.os.AsyncResult; import android.os.Binder; import android.os.Handler; import android.os.IBinder; import android.os.IPowerManager; import android.os.LocalPowerManager; import android.os.Message; import android.os.PowerManager; import android.os.RemoteException; import android.os.ServiceManager; import android.os.SystemClock; import android.os.SystemProperties; import android.preference.PreferenceManager; import android.provider.Settings.System; import android.telephony.ServiceState; import android.util.Config; import android.util.Log; import android.view.KeyEvent; import android.widget.Toast; import com.android.internal.telephony.Call; import com.android.internal.telephony.CallManager; import com.android.internal.telephony.IccCard; import com.android.internal.telephony.MmiCode; import com.android.internal.telephony.Phone; import com.android.internal.telephony.PhoneFactory; import com.android.internal.telephony.TelephonyIntents; import com.android.internal.telephony.cdma.EriInfo; import com.android.internal.telephony.cdma.TtyIntent; import com.android.internal.telephony.sip.SipPhoneFactory; import com.android.phone.OtaUtils.CdmaOtaScreenState; import com.android.server.sip.SipService; import android.os.Vibrator; import android.app.AlarmManager; import android.app.PendingIntent; /** * Top-level Application class for the Phone app. */ public class PhoneApp extends Application implements AccelerometerListener.OrientationListener { /* package */ static final String LOG_TAG = "PhoneApp"; /** * Phone app-wide debug level: * 0 - no debug logging * 1 - normal debug logging if ro.debuggable is set (which is true in * "eng" and "userdebug" builds but not "user" builds) * 2 - ultra-verbose debug logging * * Most individual classes in the phone app have a local DBG constant, * typically set to * (PhoneApp.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1) * or else * (PhoneApp.DBG_LEVEL >= 2) * depending on the desired verbosity. * * ***** DO NOT SUBMIT WITH DBG_LEVEL > 0 ************* */ /* package */ static final int DBG_LEVEL = 0; private static final boolean DBG = (PhoneApp.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1); private static final boolean VDBG = (PhoneApp.DBG_LEVEL >= 2); // Message codes; see mHandler below. private static final int EVENT_SIM_NETWORK_LOCKED = 3; private static final int EVENT_WIRED_HEADSET_PLUG = 7; private static final int EVENT_SIM_STATE_CHANGED = 8; private static final int EVENT_UPDATE_INCALL_NOTIFICATION = 9; private static final int EVENT_DATA_ROAMING_DISCONNECTED = 10; private static final int EVENT_DATA_ROAMING_OK = 11; private static final int EVENT_UNSOL_CDMA_INFO_RECORD = 12; private static final int EVENT_DOCK_STATE_CHANGED = 13; private static final int EVENT_TTY_PREFERRED_MODE_CHANGED = 14; private static final int EVENT_TTY_MODE_GET = 15; private static final int EVENT_TTY_MODE_SET = 16; // The MMI codes are also used by the InCallScreen. public static final int MMI_INITIATE = 51; public static final int MMI_COMPLETE = 52; public static final int MMI_CANCEL = 53; // Don't use message codes larger than 99 here; those are reserved for // the individual Activities of the Phone UI. /** * Allowable values for the poke lock code (timeout between a user activity and the * going to sleep), please refer to {@link com.android.server.PowerManagerService} * for additional reference. * SHORT uses the short delay for the timeout (SHORT_KEYLIGHT_DELAY, 6 sec) * MEDIUM uses the medium delay for the timeout (MEDIUM_KEYLIGHT_DELAY, 15 sec) * DEFAULT is the system-wide default delay for the timeout (1 min) */ public enum ScreenTimeoutDuration { SHORT, MEDIUM, DEFAULT } /** * Allowable values for the wake lock code. * SLEEP means the device can be put to sleep. * PARTIAL means wake the processor, but we display can be kept off. * FULL means wake both the processor and the display. */ public enum WakeState { SLEEP, PARTIAL, FULL } private static PhoneApp sMe; // A few important fields we expose to the rest of the package // directly (rather than thru set/get methods) for efficiency. Phone phone; CallNotifier notifier; Ringer ringer; BluetoothHandsfree mBtHandsfree; PhoneInterfaceManager phoneMgr; CallManager mCM; int mBluetoothHeadsetState = BluetoothHeadset.STATE_ERROR; int mBluetoothHeadsetAudioState = BluetoothHeadset.STATE_ERROR; boolean mShowBluetoothIndication = false; static int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED; // Internal PhoneApp Call state tracker CdmaPhoneCallState cdmaPhoneCallState; // The InCallScreen instance (or null if the InCallScreen hasn't been // created yet.) private InCallScreen mInCallScreen; // The currently-active PUK entry activity and progress dialog. // Normally, these are the Emergency Dialer and the subsequent // progress dialog. null if there is are no such objects in // the foreground. private Activity mPUKEntryActivity; private ProgressDialog mPUKEntryProgressDialog; private boolean mIsSimPinEnabled; private String mCachedSimPin; // True if a wired headset is currently plugged in, based on the state // from the latest Intent.ACTION_HEADSET_PLUG broadcast we received in // mReceiver.onReceive(). private boolean mIsHeadsetPlugged; // True if the keyboard is currently *not* hidden // Gets updated whenever there is a Configuration change private boolean mIsHardKeyboardOpen; // True if we are beginning a call, but the phone state has not changed yet private boolean mBeginningCall; // Last phone state seen by updatePhoneState() Phone.State mLastPhoneState = Phone.State.IDLE; private WakeState mWakeState = WakeState.SLEEP; private ScreenTimeoutDuration mScreenTimeoutDuration = ScreenTimeoutDuration.DEFAULT; private boolean mIgnoreTouchUserActivity = false; private IBinder mPokeLockToken = new Binder(); private IPowerManager mPowerManagerService; private PowerManager.WakeLock mWakeLock; private PowerManager.WakeLock mPartialWakeLock; private PowerManager.WakeLock mProximityWakeLock; private KeyguardManager mKeyguardManager; private StatusBarManager mStatusBarManager; private int mStatusBarDisableCount; private AccelerometerListener mAccelerometerListener; private int mOrientation = AccelerometerListener.ORIENTATION_UNKNOWN; // Broadcast receiver for various intent broadcasts (see onCreate()) private final BroadcastReceiver mReceiver = new PhoneAppBroadcastReceiver(); // Broadcast receiver purely for ACTION_MEDIA_BUTTON broadcasts private final BroadcastReceiver mMediaButtonReceiver = new MediaButtonBroadcastReceiver(); /** boolean indicating restoring mute state on InCallScreen.onResume() */ private boolean mShouldRestoreMuteOnInCallResume; // Following are the CDMA OTA information Objects used during OTA Call. // cdmaOtaProvisionData object store static OTA information that needs // to be maintained even during Slider open/close scenarios. // cdmaOtaConfigData object stores configuration info to control visiblity // of each OTA Screens. // cdmaOtaScreenState object store OTA Screen State information. public OtaUtils.CdmaOtaProvisionData cdmaOtaProvisionData; public OtaUtils.CdmaOtaConfigData cdmaOtaConfigData; public OtaUtils.CdmaOtaScreenState cdmaOtaScreenState; public OtaUtils.CdmaOtaInCallScreenUiState cdmaOtaInCallScreenUiState; // TTY feature enabled on this platform private boolean mTtyEnabled; // Current TTY operating mode selected by user private int mPreferredTtyMode = Phone.TTY_MODE_OFF; // add by cytown private static final String ACTION_VIBRATE_45 = "com.android.phone.PhoneApp.ACTION_VIBRATE_45"; private CallFeaturesSetting mSettings; private static PendingIntent mVibrateIntent; private static Vibrator mVibrator = null; private static AlarmManager mAM; //for adding to Blacklist from call log private static final String INSERT_BLACKLIST = "com.android.phone.INSERT_BLACKLIST"; public void startVib45(long callDurationMsec) { if (VDBG) Log.i(LOG_TAG, "vibrate start @" + callDurationMsec); stopVib45(); long nextalarm = SystemClock.elapsedRealtime() + ((callDurationMsec > 45000) ? 45000 + 60000 - callDurationMsec : 45000 - callDurationMsec); if (VDBG) Log.i(LOG_TAG, "am at: " + nextalarm); mAM.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, nextalarm, mVibrateIntent); } public void stopVib45() { if (VDBG) Log.i(LOG_TAG, "vibrate stop @" + SystemClock.elapsedRealtime()); mAM.cancel(mVibrateIntent); } private final class TriVibRunnable implements Runnable { private int v1, p1, v2; TriVibRunnable(int a, int b, int c) { v1 = a; p1 = b; v2 = c; } public void run() { if (DBG) Log.i(LOG_TAG, "vibrate " + v1 + ":" + p1 + ":" + v2); if (v1 > 0) mVibrator.vibrate(v1); if (p1 > 0) SystemClock.sleep(p1); if (v2 > 0) mVibrator.vibrate(v2); } } public void vibrate(int v1, int p1, int v2) { new Handler().post(new TriVibRunnable(v1, p1, v2)); } /** * Set the restore mute state flag. Used when we are setting the mute state * OUTSIDE of user interaction {@link PhoneUtils#startNewCall(Phone)} */ /*package*/void setRestoreMuteOnInCallResume (boolean mode) { mShouldRestoreMuteOnInCallResume = mode; } /** * Get the restore mute state flag. * This is used by the InCallScreen {@link InCallScreen#onResume()} to figure * out if we need to restore the mute state for the current active call. */ /*package*/boolean getRestoreMuteOnInCallResume () { return mShouldRestoreMuteOnInCallResume; } Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { Phone.State phoneState; switch (msg.what) { // TODO: This event should be handled by the lock screen, just // like the "SIM missing" and "Sim locked" cases (bug 1804111). case EVENT_SIM_NETWORK_LOCKED: if (getResources().getBoolean(R.bool.ignore_sim_network_locked_events)) { // Some products don't have the concept of a "SIM network lock" Log.i(LOG_TAG, "Ignoring EVENT_SIM_NETWORK_LOCKED event; " + "not showing 'SIM network unlock' PIN entry screen"); } else { // Normal case: show the "SIM network unlock" PIN entry screen. // The user won't be able to do anything else until // they enter a valid SIM network PIN. Log.i(LOG_TAG, "show sim depersonal panel"); IccNetworkDepersonalizationPanel ndpPanel = new IccNetworkDepersonalizationPanel(PhoneApp.getInstance()); ndpPanel.show(); } break; case EVENT_UPDATE_INCALL_NOTIFICATION: // Tell the NotificationMgr to update the "ongoing // call" icon in the status bar, if necessary. // Currently, this is triggered by a bluetooth headset // state change (since the status bar icon needs to // turn blue when bluetooth is active.) if (DBG) Log.d (LOG_TAG, "- updating in-call notification from handler..."); NotificationMgr.getDefault().updateInCallNotification(); break; case EVENT_DATA_ROAMING_DISCONNECTED: NotificationMgr.getDefault().showDataDisconnectedRoaming(); break; case EVENT_DATA_ROAMING_OK: NotificationMgr.getDefault().hideDataDisconnectedRoaming(); break; case MMI_COMPLETE: onMMIComplete((AsyncResult) msg.obj); break; case MMI_CANCEL: PhoneUtils.cancelMmiCode(phone); break; case EVENT_WIRED_HEADSET_PLUG: // Since the presence of a wired headset or bluetooth affects the // speakerphone, update the "speaker" state. We ONLY want to do // this on the wired headset connect / disconnect events for now // though, so we're only triggering on EVENT_WIRED_HEADSET_PLUG. phoneState = mCM.getState(); // Do not change speaker state if phone is not off hook if (phoneState == Phone.State.OFFHOOK) { if (mBtHandsfree == null || !mBtHandsfree.isAudioOn()) { if (!isHeadsetPlugged()) { // if the state is "not connected", restore the speaker state. PhoneUtils.restoreSpeakerMode(getApplicationContext()); } else { // if the state is "connected", force the speaker off without // storing the state. PhoneUtils.turnOnSpeaker(getApplicationContext(), false, false); } } } // Update the Proximity sensor based on headset state updateProximitySensorMode(phoneState); // Force TTY state update according to new headset state if (mTtyEnabled) { sendMessage(obtainMessage(EVENT_TTY_PREFERRED_MODE_CHANGED, 0)); } break; case EVENT_SIM_STATE_CHANGED: // Marks the event where the SIM goes into ready state. // Right now, this is only used for the PUK-unlocking // process. if (msg.obj.equals(IccCard.INTENT_VALUE_ICC_READY)) { // when the right event is triggered and there // are UI objects in the foreground, we close // them to display the lock panel. if (mPUKEntryActivity != null) { mPUKEntryActivity.finish(); mPUKEntryActivity = null; } if (mPUKEntryProgressDialog != null) { mPUKEntryProgressDialog.dismiss(); mPUKEntryProgressDialog = null; } } break; case EVENT_UNSOL_CDMA_INFO_RECORD: //TODO: handle message here; break; case EVENT_DOCK_STATE_CHANGED: // If the phone is docked/undocked during a call, and no wired or BT headset // is connected: turn on/off the speaker accordingly. boolean inDockMode = false; if (mDockState == Intent.EXTRA_DOCK_STATE_DESK || mDockState == Intent.EXTRA_DOCK_STATE_CAR) { inDockMode = true; } if (VDBG) Log.d(LOG_TAG, "received EVENT_DOCK_STATE_CHANGED. Phone inDock = " + inDockMode); phoneState = mCM.getState(); if (phoneState == Phone.State.OFFHOOK && !isHeadsetPlugged() && !(mBtHandsfree != null && mBtHandsfree.isAudioOn())) { PhoneUtils.turnOnSpeaker(getApplicationContext(), inDockMode, true); if (mInCallScreen != null) { mInCallScreen.requestUpdateTouchUi(); } } case EVENT_TTY_PREFERRED_MODE_CHANGED: // TTY mode is only applied if a headset is connected int ttyMode; if (isHeadsetPlugged()) { ttyMode = mPreferredTtyMode; } else { ttyMode = Phone.TTY_MODE_OFF; } phone.setTTYMode(ttyMode, mHandler.obtainMessage(EVENT_TTY_MODE_SET)); break; case EVENT_TTY_MODE_GET: handleQueryTTYModeResponse(msg); break; case EVENT_TTY_MODE_SET: handleSetTTYModeResponse(msg); break; } } }; public PhoneApp() { sMe = this; } @Override public void onCreate() { if (VDBG) Log.v(LOG_TAG, "onCreate()..."); ContentResolver resolver = getContentResolver(); if (phone == null) { // Initialize the telephony framework PhoneFactory.makeDefaultPhones(this); // Get the default phone phone = PhoneFactory.getDefaultPhone(); mCM = CallManager.getInstance(); mCM.registerPhone(phone); NotificationMgr.init(this); phoneMgr = new PhoneInterfaceManager(this, phone); // Starts the SIP service. It's a no-op if SIP API is not supported // on the deivce. // TODO: Having the phone process host the SIP service is only // temporary. Will move it to a persistent communication process // later. SipService.start(this); int phoneType = phone.getPhoneType(); if (phoneType == Phone.PHONE_TYPE_CDMA) { // Create an instance of CdmaPhoneCallState and initialize it to IDLE cdmaPhoneCallState = new CdmaPhoneCallState(); cdmaPhoneCallState.CdmaPhoneCallStateInit(); } if (BluetoothAdapter.getDefaultAdapter() != null) { mBtHandsfree = new BluetoothHandsfree(this, mCM); startService(new Intent(this, BluetoothHeadsetService.class)); } else { // Device is not bluetooth capable mBtHandsfree = null; } ringer = new Ringer(this); // before registering for phone state changes PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK - | PowerManager.ACQUIRE_CAUSES_WAKEUP, + | PowerManager.ACQUIRE_CAUSES_WAKEUP + | PowerManager.ON_AFTER_RELEASE, LOG_TAG); // lock used to keep the processor awake, when we don't care for the display. mPartialWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, LOG_TAG); // Wake lock used to control proximity sensor behavior. if ((pm.getSupportedWakeLockFlags() & PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) != 0x0) { mProximityWakeLock = pm.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, LOG_TAG); } if (DBG) Log.d(LOG_TAG, "onCreate: mProximityWakeLock: " + mProximityWakeLock); // create mAccelerometerListener only if we are using the proximity sensor if (proximitySensorModeEnabled()) { mAccelerometerListener = new AccelerometerListener(this, this); } mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); mStatusBarManager = (StatusBarManager) getSystemService(Context.STATUS_BAR_SERVICE); // get a handle to the service so that we can use it later when we // want to set the poke lock. mPowerManagerService = IPowerManager.Stub.asInterface( ServiceManager.getService("power")); notifier = new CallNotifier(this, phone, ringer, mBtHandsfree, new CallLogAsync()); // register for ICC status IccCard sim = phone.getIccCard(); if (sim != null) { if (VDBG) Log.v(LOG_TAG, "register for ICC status"); sim.registerForNetworkLocked(mHandler, EVENT_SIM_NETWORK_LOCKED, null); } // register for MMI/USSD mCM.registerForMmiComplete(mHandler, MMI_COMPLETE, null); // register connection tracking to PhoneUtils PhoneUtils.initializeConnectionHandler(mCM); // Read platform settings for TTY feature mTtyEnabled = getResources().getBoolean(R.bool.tty_enabled); // Register for misc other intent broadcasts. IntentFilter intentFilter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED); intentFilter.addAction(BluetoothHeadset.ACTION_STATE_CHANGED); intentFilter.addAction(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED); intentFilter.addAction(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED); intentFilter.addAction(Intent.ACTION_HEADSET_PLUG); intentFilter.addAction(Intent.ACTION_DOCK_EVENT); intentFilter.addAction(Intent.ACTION_BATTERY_LOW); intentFilter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED); intentFilter.addAction(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED); intentFilter.addAction(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED); intentFilter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED); intentFilter.addAction(ACTION_VIBRATE_45); intentFilter.addAction(INSERT_BLACKLIST); if (mTtyEnabled) { intentFilter.addAction(TtyIntent.TTY_PREFERRED_MODE_CHANGE_ACTION); } intentFilter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION); registerReceiver(mReceiver, intentFilter); // Use a separate receiver for ACTION_MEDIA_BUTTON broadcasts, // since we need to manually adjust its priority (to make sure // we get these intents *before* the media player.) IntentFilter mediaButtonIntentFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON); // // Make sure we're higher priority than the media player's // MediaButtonIntentReceiver (which currently has the default // priority of zero; see apps/Music/AndroidManifest.xml.) mediaButtonIntentFilter.setPriority(1); // registerReceiver(mMediaButtonReceiver, mediaButtonIntentFilter); //set the default values for the preferences in the phone. PreferenceManager.setDefaultValues(this, R.xml.network_setting, false); PreferenceManager.setDefaultValues(this, R.xml.call_feature_setting, false); // Make sure the audio mode (along with some // audio-mode-related state of our own) is initialized // correctly, given the current state of the phone. PhoneUtils.setAudioMode(mCM); } boolean phoneIsCdma = (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA); if (phoneIsCdma) { cdmaOtaProvisionData = new OtaUtils.CdmaOtaProvisionData(); cdmaOtaConfigData = new OtaUtils.CdmaOtaConfigData(); cdmaOtaScreenState = new OtaUtils.CdmaOtaScreenState(); cdmaOtaInCallScreenUiState = new OtaUtils.CdmaOtaInCallScreenUiState(); } // XXX pre-load the SimProvider so that it's ready resolver.getType(Uri.parse("content://icc/adn")); // start with the default value to set the mute state. mShouldRestoreMuteOnInCallResume = false; // add by cytown mSettings = CallFeaturesSetting.getInstance(PreferenceManager.getDefaultSharedPreferences(this)); if (mVibrator == null) { mVibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE); mAM = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); mVibrateIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_VIBRATE_45), 0); } // TODO: Register for Cdma Information Records // phone.registerCdmaInformationRecord(mHandler, EVENT_UNSOL_CDMA_INFO_RECORD, null); // Read TTY settings and store it into BP NV. // AP owns (i.e. stores) the TTY setting in AP settings database and pushes the setting // to BP at power up (BP does not need to make the TTY setting persistent storage). // This way, there is a single owner (i.e AP) for the TTY setting in the phone. if (mTtyEnabled) { mPreferredTtyMode = android.provider.Settings.Secure.getInt( phone.getContext().getContentResolver(), android.provider.Settings.Secure.PREFERRED_TTY_MODE, Phone.TTY_MODE_OFF); mHandler.sendMessage(mHandler.obtainMessage(EVENT_TTY_PREFERRED_MODE_CHANGED, 0)); } // Read HAC settings and configure audio hardware if (getResources().getBoolean(R.bool.hac_enabled)) { int hac = android.provider.Settings.System.getInt(phone.getContext().getContentResolver(), android.provider.Settings.System.HEARING_AID, 0); AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); audioManager.setParameter(CallFeaturesSetting.HAC_KEY, hac != 0 ? CallFeaturesSetting.HAC_VAL_ON : CallFeaturesSetting.HAC_VAL_OFF); } } @Override public void onConfigurationChanged(Configuration newConfig) { if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) { mIsHardKeyboardOpen = true; } else { mIsHardKeyboardOpen = false; } // Update the Proximity sensor based on keyboard state updateProximitySensorMode(mCM.getState()); super.onConfigurationChanged(newConfig); } /** * Returns the singleton instance of the PhoneApp. */ static PhoneApp getInstance() { return sMe; } /** * Returns the Phone associated with this instance */ static Phone getPhone() { return getInstance().phone; } CallFeaturesSetting getSettings() { return mSettings; } Ringer getRinger() { return ringer; } BluetoothHandsfree getBluetoothHandsfree() { return mBtHandsfree; } static Intent createCallLogIntent() { Intent intent = new Intent(Intent.ACTION_VIEW, null); intent.setType("vnd.android.cursor.dir/calls"); return intent; } /** * Return an Intent that can be used to bring up the in-call screen. * * This intent can only be used from within the Phone app, since the * InCallScreen is not exported from our AndroidManifest. */ /* package */ static Intent createInCallIntent() { Intent intent = new Intent(Intent.ACTION_MAIN, null); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_NO_USER_ACTION); intent.setClassName("com.android.phone", getCallScreenClassName()); return intent; } /** * Variation of createInCallIntent() that also specifies whether the * DTMF dialpad should be initially visible when the InCallScreen * comes up. */ /* package */ static Intent createInCallIntent(boolean showDialpad) { Intent intent = createInCallIntent(); intent.putExtra(InCallScreen.SHOW_DIALPAD_EXTRA, showDialpad); return intent; } static String getCallScreenClassName() { return InCallScreen.class.getName(); } /** * Starts the InCallScreen Activity. */ private void displayCallScreen() { if (VDBG) Log.d(LOG_TAG, "displayCallScreen()..."); startActivity(createInCallIntent()); Profiler.callScreenRequested(); } boolean isSimPinEnabled() { return mIsSimPinEnabled; } boolean authenticateAgainstCachedSimPin(String pin) { return (mCachedSimPin != null && mCachedSimPin.equals(pin)); } void setCachedSimPin(String pin) { mCachedSimPin = pin; } void setInCallScreenInstance(InCallScreen inCallScreen) { mInCallScreen = inCallScreen; } /** * @return true if the in-call UI is running as the foreground * activity. (In other words, from the perspective of the * InCallScreen activity, return true between onResume() and * onPause().) * * Note this method will return false if the screen is currently off, * even if the InCallScreen *was* in the foreground just before the * screen turned off. (This is because the foreground activity is * always "paused" while the screen is off.) */ boolean isShowingCallScreen() { if (mInCallScreen == null) return false; return mInCallScreen.isForegroundActivity(); } /** * Dismisses the in-call UI. * * This also ensures that you won't be able to get back to the in-call * UI via the BACK button (since this call removes the InCallScreen * from the activity history.) * For OTA Call, it call InCallScreen api to handle OTA Call End scenario * to display OTA Call End screen. */ void dismissCallScreen() { if (mInCallScreen != null) { if ((phone.getPhoneType() == Phone.PHONE_TYPE_CDMA) && (mInCallScreen.isOtaCallInActiveState() || mInCallScreen.isOtaCallInEndState() || ((cdmaOtaScreenState != null) && (cdmaOtaScreenState.otaScreenState != CdmaOtaScreenState.OtaScreenState.OTA_STATUS_UNDEFINED)))) { // TODO: During OTA Call, display should not become dark to // allow user to see OTA UI update. Phone app needs to hold // a SCREEN_DIM_WAKE_LOCK wake lock during the entire OTA call. wakeUpScreen(); // If InCallScreen is not in foreground we resume it to show the OTA call end screen // Fire off the InCallScreen intent displayCallScreen(); mInCallScreen.handleOtaCallEnd(); return; } else { mInCallScreen.finish(); } } } /** * Handle OTA events * * When OTA call is active and display becomes dark, then CallNotifier will * handle OTA Events by calling this api which then calls OtaUtil function. */ void handleOtaEvents(Message msg) { if (DBG) Log.d(LOG_TAG, "Enter handleOtaEvents"); if ((mInCallScreen != null) && (!isShowingCallScreen())) { if (mInCallScreen.otaUtils != null) { mInCallScreen.otaUtils.onOtaProvisionStatusChanged((AsyncResult) msg.obj); } } } /** * Sets the activity responsible for un-PUK-blocking the device * so that we may close it when we receive a positive result. * mPUKEntryActivity is also used to indicate to the device that * we are trying to un-PUK-lock the phone. In other words, iff * it is NOT null, then we are trying to unlock and waiting for * the SIM to move to READY state. * * @param activity is the activity to close when PUK has * finished unlocking. Can be set to null to indicate the unlock * or SIM READYing process is over. */ void setPukEntryActivity(Activity activity) { mPUKEntryActivity = activity; } Activity getPUKEntryActivity() { return mPUKEntryActivity; } /** * Sets the dialog responsible for notifying the user of un-PUK- * blocking - SIM READYing progress, so that we may dismiss it * when we receive a positive result. * * @param dialog indicates the progress dialog informing the user * of the state of the device. Dismissed upon completion of * READYing process */ void setPukEntryProgressDialog(ProgressDialog dialog) { mPUKEntryProgressDialog = dialog; } ProgressDialog getPUKEntryProgressDialog() { return mPUKEntryProgressDialog; } /** * Disables the status bar. This is used by the phone app when in-call UI is active. * * Any call to this method MUST be followed (eventually) * by a corresponding reenableStatusBar() call. */ /* package */ void disableStatusBar() { if (DBG) Log.d(LOG_TAG, "disable status bar"); synchronized (this) { if (mStatusBarDisableCount++ == 0) { if (DBG) Log.d(LOG_TAG, "StatusBarManager.DISABLE_EXPAND"); mStatusBarManager.disable(StatusBarManager.DISABLE_EXPAND); } } } /** * Re-enables the status bar after a previous disableStatusBar() call. * * Any call to this method MUST correspond to (i.e. be balanced with) * a previous disableStatusBar() call. */ /* package */ void reenableStatusBar() { if (DBG) Log.d(LOG_TAG, "re-enable status bar"); synchronized (this) { if (mStatusBarDisableCount > 0) { if (--mStatusBarDisableCount == 0) { if (DBG) Log.d(LOG_TAG, "StatusBarManager.DISABLE_NONE"); mStatusBarManager.disable(StatusBarManager.DISABLE_NONE); } } else { Log.e(LOG_TAG, "mStatusBarDisableCount is already zero"); } } } /** * Controls how quickly the screen times out. * * The poke lock controls how long it takes before the screen powers * down, and therefore has no immediate effect when the current * WakeState (see {@link PhoneApp#requestWakeState}) is FULL. * If we're in a state where the screen *is* allowed to turn off, * though, the poke lock will determine the timeout interval (long or * short). * * @param shortPokeLock tells the device the timeout duration to use * before going to sleep * {@link com.android.server.PowerManagerService#SHORT_KEYLIGHT_DELAY}. */ /* package */ void setScreenTimeout(ScreenTimeoutDuration duration) { if (VDBG) Log.d(LOG_TAG, "setScreenTimeout(" + duration + ")..."); // make sure we don't set the poke lock repeatedly so that we // avoid triggering the userActivity calls in // PowerManagerService.setPokeLock(). if (duration == mScreenTimeoutDuration) { return; } // stick with default timeout if we are using the proximity sensor if (proximitySensorModeEnabled()) { return; } mScreenTimeoutDuration = duration; updatePokeLock(); } /** * Update the state of the poke lock held by the phone app, * based on the current desired screen timeout and the * current "ignore user activity on touch" flag. */ private void updatePokeLock() { // This is kind of convoluted, but the basic thing to remember is // that the poke lock just sends a message to the screen to tell // it to stay on for a while. // The default is 0, for a long timeout and should be set that way // when we are heading back into a the keyguard / screen off // state, and also when we're trying to keep the screen alive // while ringing. We'll also want to ignore the cheek events // regardless of the timeout duration. // The short timeout is really used whenever we want to give up // the screen lock, such as when we're in call. int pokeLockSetting = LocalPowerManager.POKE_LOCK_IGNORE_CHEEK_EVENTS; switch (mScreenTimeoutDuration) { case SHORT: // Set the poke lock to timeout the display after a short // timeout (5s). This ensures that the screen goes to sleep // as soon as acceptably possible after we the wake lock // has been released. // pokeLockSetting |= LocalPowerManager.POKE_LOCK_SHORT_TIMEOUT; pokeLockSetting |= mSettings.mScreenAwake ? LocalPowerManager.POKE_LOCK_MEDIUM_TIMEOUT : LocalPowerManager.POKE_LOCK_SHORT_TIMEOUT; break; case MEDIUM: // Set the poke lock to timeout the display after a medium // timeout (15s). This ensures that the screen goes to sleep // as soon as acceptably possible after we the wake lock // has been released. pokeLockSetting |= LocalPowerManager.POKE_LOCK_MEDIUM_TIMEOUT; break; case DEFAULT: default: // set the poke lock to timeout the display after a long // delay by default. // TODO: it may be nice to be able to disable cheek presses // for long poke locks (emergency dialer, for instance). break; } if (mIgnoreTouchUserActivity) { pokeLockSetting |= LocalPowerManager.POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS; } // Send the request try { mPowerManagerService.setPokeLock(pokeLockSetting, mPokeLockToken, LOG_TAG); } catch (RemoteException e) { Log.w(LOG_TAG, "mPowerManagerService.setPokeLock() failed: " + e); } } /** * Controls whether or not the screen is allowed to sleep. * * Once sleep is allowed (WakeState is SLEEP), it will rely on the * settings for the poke lock to determine when to timeout and let * the device sleep {@link PhoneApp#setScreenTimeout}. * * @param ws tells the device to how to wake. */ /* package */ void requestWakeState(WakeState ws) { if (VDBG) Log.d(LOG_TAG, "requestWakeState(" + ws + ")..."); synchronized (this) { if (mWakeState != ws) { switch (ws) { case PARTIAL: // acquire the processor wake lock, and release the FULL // lock if it is being held. mPartialWakeLock.acquire(); if (mWakeLock.isHeld()) { mWakeLock.release(); } break; case FULL: // acquire the full wake lock, and release the PARTIAL // lock if it is being held. mWakeLock.acquire(); if (mPartialWakeLock.isHeld()) { mPartialWakeLock.release(); } break; case SLEEP: default: // release both the PARTIAL and FULL locks. if (mWakeLock.isHeld()) { mWakeLock.release(); } if (mPartialWakeLock.isHeld()) { mPartialWakeLock.release(); } break; } mWakeState = ws; } } } /** * If we are not currently keeping the screen on, then poke the power * manager to wake up the screen for the user activity timeout duration. */ /* package */ void wakeUpScreen() { synchronized (this) { if (mWakeState == WakeState.SLEEP) { if (DBG) Log.d(LOG_TAG, "pulse screen lock"); try { mPowerManagerService.userActivityWithForce(SystemClock.uptimeMillis(), false, true); } catch (RemoteException ex) { // Ignore -- the system process is dead. } } } } /** * Sets the wake state and screen timeout based on the current state * of the phone, and the current state of the in-call UI. * * This method is a "UI Policy" wrapper around * {@link PhoneApp#requestWakeState} and {@link PhoneApp#setScreenTimeout}. * * It's safe to call this method regardless of the state of the Phone * (e.g. whether or not it's idle), and regardless of the state of the * Phone UI (e.g. whether or not the InCallScreen is active.) */ /* package */ void updateWakeState() { Phone.State state = mCM.getState(); // True if the in-call UI is the foreground activity. // (Note this will be false if the screen is currently off, // since in that case *no* activity is in the foreground.) boolean isShowingCallScreen = isShowingCallScreen(); // True if the InCallScreen's DTMF dialer is currently opened. // (Note this does NOT imply whether or not the InCallScreen // itself is visible.) boolean isDialerOpened = (mInCallScreen != null) && mInCallScreen.isDialerOpened(); // True if the speakerphone is in use. (If so, we *always* use // the default timeout. Since the user is obviously not holding // the phone up to his/her face, we don't need to worry about // false touches, and thus don't need to turn the screen off so // aggressively.) // Note that we need to make a fresh call to this method any // time the speaker state changes. (That happens in // PhoneUtils.turnOnSpeaker().) boolean isSpeakerInUse = (state == Phone.State.OFFHOOK) && PhoneUtils.isSpeakerOn(this); // TODO (bug 1440854): The screen timeout *might* also need to // depend on the bluetooth state, but this isn't as clear-cut as // the speaker state (since while using BT it's common for the // user to put the phone straight into a pocket, in which case the // timeout should probably still be short.) if (DBG) Log.d(LOG_TAG, "updateWakeState: callscreen " + isShowingCallScreen + ", dialer " + isDialerOpened + ", speaker " + isSpeakerInUse + "..."); // // (1) Set the screen timeout. // // Note that the "screen timeout" value we determine here is // meaningless if the screen is forced on (see (2) below.) // if (!isShowingCallScreen || isSpeakerInUse) { // Use the system-wide default timeout. setScreenTimeout(ScreenTimeoutDuration.DEFAULT); } else { // We're on the in-call screen, and *not* using the speakerphone. if (isDialerOpened) { // The DTMF dialpad is up. This case is special because // the in-call UI has its own "touch lock" mechanism to // disable the dialpad after a very short amount of idle // time (to avoid false touches from the user's face while // in-call.) // // In this case the *physical* screen just uses the // system-wide default timeout. setScreenTimeout(ScreenTimeoutDuration.DEFAULT); } else { // We're on the in-call screen, and not using the DTMF dialpad. // There's actually no touchable UI onscreen at all in // this state. Also, the user is (most likely) not // looking at the screen at all, since they're probably // holding the phone up to their face. Here we use a // special screen timeout value specific to the in-call // screen, purely to save battery life. // setScreenTimeout(ScreenTimeoutDuration.MEDIUM); setScreenTimeout(mSettings.mScreenAwake ? ScreenTimeoutDuration.DEFAULT : ScreenTimeoutDuration.MEDIUM); } } // // (2) Decide whether to force the screen on or not. // // Force the screen to be on if the phone is ringing or dialing, // or if we're displaying the "Call ended" UI for a connection in // the "disconnected" state. // boolean isRinging = (state == Phone.State.RINGING); boolean isDialing = (phone.getForegroundCall().getState() == Call.State.DIALING); boolean showingDisconnectedConnection = PhoneUtils.hasDisconnectedConnections(phone) && isShowingCallScreen; boolean keepScreenOn = isRinging || isDialing || showingDisconnectedConnection; if (DBG) Log.d(LOG_TAG, "updateWakeState: keepScreenOn = " + keepScreenOn + " (isRinging " + isRinging + ", isDialing " + isDialing + ", showingDisc " + showingDisconnectedConnection + ")"); // keepScreenOn == true means we'll hold a full wake lock: requestWakeState(keepScreenOn ? WakeState.FULL : WakeState.SLEEP); } /** * Wrapper around the PowerManagerService.preventScreenOn() API. * This allows the in-call UI to prevent the screen from turning on * even if a subsequent call to updateWakeState() causes us to acquire * a full wake lock. */ /* package */ void preventScreenOn(boolean prevent) { if (VDBG) Log.d(LOG_TAG, "- preventScreenOn(" + prevent + ")..."); try { mPowerManagerService.preventScreenOn(prevent); } catch (RemoteException e) { Log.w(LOG_TAG, "mPowerManagerService.preventScreenOn() failed: " + e); } } /** * Sets or clears the flag that tells the PowerManager that touch * (and cheek) events should NOT be considered "user activity". * * Since the in-call UI is totally insensitive to touch in most * states, we set this flag whenever the InCallScreen is in the * foreground. (Otherwise, repeated unintentional touches could * prevent the device from going to sleep.) * * There *are* some some touch events that really do count as user * activity, though. For those, we need to manually poke the * PowerManager's userActivity method; see pokeUserActivity(). */ /* package */ void setIgnoreTouchUserActivity(boolean ignore) { if (VDBG) Log.d(LOG_TAG, "setIgnoreTouchUserActivity(" + ignore + ")..."); mIgnoreTouchUserActivity = ignore; updatePokeLock(); } /** * Manually pokes the PowerManager's userActivity method. Since we * hold the POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS poke lock while * the InCallScreen is active, we need to do this for touch events * that really do count as user activity (like DTMF key presses, or * unlocking the "touch lock" overlay.) */ /* package */ void pokeUserActivity() { if (VDBG) Log.d(LOG_TAG, "pokeUserActivity()..."); try { mPowerManagerService.userActivity(SystemClock.uptimeMillis(), false); } catch (RemoteException e) { Log.w(LOG_TAG, "mPowerManagerService.userActivity() failed: " + e); } } /** * Set when a new outgoing call is beginning, so we can update * the proximity sensor state. * Cleared when the InCallScreen is no longer in the foreground, * in case the call fails without changing the telephony state. */ /* package */ void setBeginningCall(boolean beginning) { // Note that we are beginning a new call, for proximity sensor support mBeginningCall = beginning; // Update the Proximity sensor based on mBeginningCall state updateProximitySensorMode(mCM.getState()); } /** * Updates the wake lock used to control proximity sensor behavior, * based on the current state of the phone. This method is called * from the CallNotifier on any phone state change. * * On devices that have a proximity sensor, to avoid false touches * during a call, we hold a PROXIMITY_SCREEN_OFF_WAKE_LOCK wake lock * whenever the phone is off hook. (When held, that wake lock causes * the screen to turn off automatically when the sensor detects an * object close to the screen.) * * This method is a no-op for devices that don't have a proximity * sensor. * * Note this method doesn't care if the InCallScreen is the foreground * activity or not. That's because we want the proximity sensor to be * enabled any time the phone is in use, to avoid false cheek events * for whatever app you happen to be running. * * Proximity wake lock will *not* be held if any one of the * conditions is true while on a call: * 1) If the audio is routed via Bluetooth * 2) If a wired headset is connected * 3) if the speaker is ON * 4) If the slider is open(i.e. the hardkeyboard is *not* hidden) * * @param state current state of the phone (see {@link Phone#State}) */ /* package */ void updateProximitySensorMode(Phone.State state) { if (VDBG) Log.d(LOG_TAG, "updateProximitySensorMode: state = " + state); if (proximitySensorModeEnabled()) { synchronized (mProximityWakeLock) { // turn proximity sensor off and turn screen on immediately if // we are using a headset, the keyboard is open, or the device // is being held in a horizontal position. boolean screenOnImmediately = (isHeadsetPlugged() || PhoneUtils.isSpeakerOn(this) || ((mBtHandsfree != null) && mBtHandsfree.isAudioOn()) || mIsHardKeyboardOpen); // We do not keep the screen off when we are horizontal, but we do not force it // on when we become horizontal until the proximity sensor goes negative. boolean horizontal = (mOrientation == AccelerometerListener.ORIENTATION_HORIZONTAL); if (((state == Phone.State.OFFHOOK) || mBeginningCall) && !screenOnImmediately && !horizontal) { // Phone is in use! Arrange for the screen to turn off // automatically when the sensor detects a close object. if (!mProximityWakeLock.isHeld()) { if (DBG) Log.d(LOG_TAG, "updateProximitySensorMode: acquiring..."); mProximityWakeLock.acquire(); } else { if (VDBG) Log.d(LOG_TAG, "updateProximitySensorMode: lock already held."); } } else { // Phone is either idle, or ringing. We don't want any // special proximity sensor behavior in either case. if (mProximityWakeLock.isHeld()) { if (DBG) Log.d(LOG_TAG, "updateProximitySensorMode: releasing..."); // Wait until user has moved the phone away from his head if we are // releasing due to the phone call ending. // Qtherwise, turn screen on immediately int flags = (screenOnImmediately ? 0 : PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE); mProximityWakeLock.release(flags); } else { if (VDBG) { Log.d(LOG_TAG, "updateProximitySensorMode: lock already released."); } } } } } } public void orientationChanged(int orientation) { mOrientation = orientation; updateProximitySensorMode(mCM.getState()); } /** * Notifies the phone app when the phone state changes. * Currently used only for proximity sensor support. */ /* package */ void updatePhoneState(Phone.State state) { if (state != mLastPhoneState) { mLastPhoneState = state; updateProximitySensorMode(state); if (mAccelerometerListener != null) { // use accelerometer to augment proximity sensor when in call mOrientation = AccelerometerListener.ORIENTATION_UNKNOWN; mAccelerometerListener.enable(!mSettings.mAlwaysProximity && state == Phone.State.OFFHOOK); } // clear our beginning call flag mBeginningCall = false; // While we are in call, the in-call screen should dismiss the keyguard. // This allows the user to press Home to go directly home without going through // an insecure lock screen. // But we do not want to do this if there is no active call so we do not // bypass the keyguard if the call is not answered or declined. if (mInCallScreen != null) { mInCallScreen.updateKeyguardPolicy(state == Phone.State.OFFHOOK); } } } /* package */ Phone.State getPhoneState() { return mLastPhoneState; } /** * @return true if this device supports the "proximity sensor * auto-lock" feature while in-call (see updateProximitySensorMode()). */ /* package */ boolean proximitySensorModeEnabled() { return (mProximityWakeLock != null); } KeyguardManager getKeyguardManager() { return mKeyguardManager; } private void onMMIComplete(AsyncResult r) { if (VDBG) Log.d(LOG_TAG, "onMMIComplete()..."); MmiCode mmiCode = (MmiCode) r.result; PhoneUtils.displayMMIComplete(phone, getInstance(), mmiCode, null, null); } private void initForNewRadioTechnology() { if (DBG) Log.d(LOG_TAG, "initForNewRadioTechnology..."); if (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA) { // Create an instance of CdmaPhoneCallState and initialize it to IDLE cdmaPhoneCallState = new CdmaPhoneCallState(); cdmaPhoneCallState.CdmaPhoneCallStateInit(); //create instances of CDMA OTA data classes if (cdmaOtaProvisionData == null) { cdmaOtaProvisionData = new OtaUtils.CdmaOtaProvisionData(); } if (cdmaOtaConfigData == null) { cdmaOtaConfigData = new OtaUtils.CdmaOtaConfigData(); } if (cdmaOtaScreenState == null) { cdmaOtaScreenState = new OtaUtils.CdmaOtaScreenState(); } if (cdmaOtaInCallScreenUiState == null) { cdmaOtaInCallScreenUiState = new OtaUtils.CdmaOtaInCallScreenUiState(); } } else { //Clean up OTA data in GSM/UMTS. It is valid only for CDMA clearOtaState(); } ringer.updateRingerContextAfterRadioTechnologyChange(this.phone); notifier.updateCallNotifierRegistrationsAfterRadioTechnologyChange(); if (mBtHandsfree != null) { mBtHandsfree.updateBtHandsfreeAfterRadioTechnologyChange(); } if (mInCallScreen != null) { mInCallScreen.updateAfterRadioTechnologyChange(); } // Update registration for ICC status after radio technology change IccCard sim = phone.getIccCard(); if (sim != null) { if (DBG) Log.d(LOG_TAG, "Update registration for ICC status..."); //Register all events new to the new active phone sim.registerForNetworkLocked(mHandler, EVENT_SIM_NETWORK_LOCKED, null); } } /** * @return true if a wired headset is currently plugged in. * * @see Intent.ACTION_HEADSET_PLUG (which we listen for in mReceiver.onReceive()) */ boolean isHeadsetPlugged() { return mIsHeadsetPlugged; } /** * @return true if the onscreen UI should currently be showing the * special "bluetooth is active" indication in a couple of places (in * which UI elements turn blue and/or show the bluetooth logo.) * * This depends on the BluetoothHeadset state *and* the current * telephony state; see shouldShowBluetoothIndication(). * * @see CallCard * @see NotificationMgr.updateInCallNotification */ /* package */ boolean showBluetoothIndication() { return mShowBluetoothIndication; } /** * Recomputes the mShowBluetoothIndication flag based on the current * bluetooth state and current telephony state. * * This needs to be called any time the bluetooth headset state or the * telephony state changes. * * @param forceUiUpdate if true, force the UI elements that care * about this flag to update themselves. */ /* package */ void updateBluetoothIndication(boolean forceUiUpdate) { mShowBluetoothIndication = shouldShowBluetoothIndication(mBluetoothHeadsetState, mBluetoothHeadsetAudioState, mCM); if (forceUiUpdate) { // Post Handler messages to the various components that might // need to be refreshed based on the new state. if (isShowingCallScreen()) mInCallScreen.requestUpdateBluetoothIndication(); if (DBG) Log.d (LOG_TAG, "- updating in-call notification for BT state change..."); mHandler.sendEmptyMessage(EVENT_UPDATE_INCALL_NOTIFICATION); } // Update the Proximity sensor based on Bluetooth audio state updateProximitySensorMode(mCM.getState()); } /** * UI policy helper function for the couple of places in the UI that * have some way of indicating that "bluetooth is in use." * * @return true if the onscreen UI should indicate that "bluetooth is in use", * based on the specified bluetooth headset state, and the * current state of the phone. * @see showBluetoothIndication() */ private static boolean shouldShowBluetoothIndication(int bluetoothState, int bluetoothAudioState, CallManager cm) { // We want the UI to indicate that "bluetooth is in use" in two // slightly different cases: // // (a) The obvious case: if a bluetooth headset is currently in // use for an ongoing call. // // (b) The not-so-obvious case: if an incoming call is ringing, // and we expect that audio *will* be routed to a bluetooth // headset once the call is answered. switch (cm.getState()) { case OFFHOOK: // This covers normal active calls, and also the case if // the foreground call is DIALING or ALERTING. In this // case, bluetooth is considered "active" if a headset // is connected *and* audio is being routed to it. return ((bluetoothState == BluetoothHeadset.STATE_CONNECTED) && (bluetoothAudioState == BluetoothHeadset.AUDIO_STATE_CONNECTED)); case RINGING: // If an incoming call is ringing, we're *not* yet routing // audio to the headset (since there's no in-call audio // yet!) In this case, if a bluetooth headset is // connected at all, we assume that it'll become active // once the user answers the phone. return (bluetoothState == BluetoothHeadset.STATE_CONNECTED); default: // Presumably IDLE return false; } } /** * Receiver for misc intent broadcasts the Phone app cares about. */ private class PhoneAppBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) { boolean enabled = System.getInt(getContentResolver(), System.AIRPLANE_MODE_ON, 0) == 0; phone.setRadioPower(enabled); } else if (action.equals(BluetoothHeadset.ACTION_STATE_CHANGED)) { mBluetoothHeadsetState = intent.getIntExtra(BluetoothHeadset.EXTRA_STATE, BluetoothHeadset.STATE_ERROR); if (VDBG) Log.d(LOG_TAG, "mReceiver: HEADSET_STATE_CHANGED_ACTION"); if (VDBG) Log.d(LOG_TAG, "==> new state: " + mBluetoothHeadsetState); updateBluetoothIndication(true); // Also update any visible UI if necessary } else if (action.equals(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED)) { mBluetoothHeadsetAudioState = intent.getIntExtra(BluetoothHeadset.EXTRA_AUDIO_STATE, BluetoothHeadset.STATE_ERROR); if (VDBG) Log.d(LOG_TAG, "mReceiver: HEADSET_AUDIO_STATE_CHANGED_ACTION"); if (VDBG) Log.d(LOG_TAG, "==> new state: " + mBluetoothHeadsetAudioState); updateBluetoothIndication(true); // Also update any visible UI if necessary } else if (action.equals(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED)) { if (VDBG) Log.d(LOG_TAG, "mReceiver: ACTION_ANY_DATA_CONNECTION_STATE_CHANGED"); if (VDBG) Log.d(LOG_TAG, "- state: " + intent.getStringExtra(Phone.STATE_KEY)); if (VDBG) Log.d(LOG_TAG, "- reason: " + intent.getStringExtra(Phone.STATE_CHANGE_REASON_KEY)); // The "data disconnected due to roaming" notification is // visible if you've lost data connectivity because you're // roaming and you have the "data roaming" feature turned off. boolean disconnectedDueToRoaming = false; if ("DISCONNECTED".equals(intent.getStringExtra(Phone.STATE_KEY))) { String reason = intent.getStringExtra(Phone.STATE_CHANGE_REASON_KEY); if (Phone.REASON_ROAMING_ON.equals(reason)) { // We just lost our data connection, and the reason // is that we started roaming. This implies that // the user has data roaming turned off. disconnectedDueToRoaming = true; } } mHandler.sendEmptyMessage(disconnectedDueToRoaming ? EVENT_DATA_ROAMING_DISCONNECTED : EVENT_DATA_ROAMING_OK); } else if (action.equals(Intent.ACTION_HEADSET_PLUG)) { if (VDBG) Log.d(LOG_TAG, "mReceiver: ACTION_HEADSET_PLUG"); if (VDBG) Log.d(LOG_TAG, " state: " + intent.getIntExtra("state", 0)); if (VDBG) Log.d(LOG_TAG, " name: " + intent.getStringExtra("name")); mIsHeadsetPlugged = (intent.getIntExtra("state", 0) == 1); mHandler.sendMessage(mHandler.obtainMessage(EVENT_WIRED_HEADSET_PLUG, 0)); } else if (action.equals(Intent.ACTION_BATTERY_LOW)) { if (VDBG) Log.d(LOG_TAG, "mReceiver: ACTION_BATTERY_LOW"); notifier.sendBatteryLow(); // Play a warning tone if in-call } else if ((action.equals(TelephonyIntents.ACTION_SIM_STATE_CHANGED)) && (mPUKEntryActivity != null)) { // if an attempt to un-PUK-lock the device was made, while we're // receiving this state change notification, notify the handler. // NOTE: This is ONLY triggered if an attempt to un-PUK-lock has // been attempted. mHandler.sendMessage(mHandler.obtainMessage(EVENT_SIM_STATE_CHANGED, intent.getStringExtra(IccCard.INTENT_KEY_ICC_STATE))); } else if (action.equals(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED)) { String newPhone = intent.getStringExtra(Phone.PHONE_NAME_KEY); Log.d(LOG_TAG, "Radio technology switched. Now " + newPhone + " is active."); initForNewRadioTechnology(); } else if (action.equals(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED)) { handleServiceStateChanged(intent); } else if (action.equals(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED)) { if (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA) { Log.d(LOG_TAG, "Emergency Callback Mode arrived in PhoneApp."); // Start Emergency Callback Mode service if (intent.getBooleanExtra("phoneinECMState", false)) { context.startService(new Intent(context, EmergencyCallbackModeService.class)); } } else { Log.e(LOG_TAG, "Error! Emergency Callback Mode not supported for " + phone.getPhoneName() + " phones"); } // Vibrate 45 sec receiver add by cytown } else if (action.equals(ACTION_VIBRATE_45)) { if (VDBG) Log.d(LOG_TAG, "mReceiver: ACTION_VIBRATE_45"); mAM.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 60000, mVibrateIntent); if (DBG) Log.i(LOG_TAG, "vibrate on 45 sec"); mVibrator.vibrate(70); SystemClock.sleep(70); mVibrator.cancel(); if (VDBG) Log.d(LOG_TAG, "mReceiver: force vib cancel"); //vibrate(70, 70, -1); } else if (action.equals(Intent.ACTION_DOCK_EVENT)) { mDockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE, Intent.EXTRA_DOCK_STATE_UNDOCKED); if (VDBG) Log.d(LOG_TAG, "ACTION_DOCK_EVENT -> mDockState = " + mDockState); mHandler.sendMessage(mHandler.obtainMessage(EVENT_DOCK_STATE_CHANGED, 0)); } else if (action.equals(TtyIntent.TTY_PREFERRED_MODE_CHANGE_ACTION)) { mPreferredTtyMode = intent.getIntExtra(TtyIntent.TTY_PREFFERED_MODE, Phone.TTY_MODE_OFF); if (VDBG) Log.d(LOG_TAG, "mReceiver: TTY_PREFERRED_MODE_CHANGE_ACTION"); if (VDBG) Log.d(LOG_TAG, " mode: " + mPreferredTtyMode); mHandler.sendMessage(mHandler.obtainMessage(EVENT_TTY_PREFERRED_MODE_CHANGED, 0)); } else if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) { int ringerMode = intent.getIntExtra(AudioManager.EXTRA_RINGER_MODE, AudioManager.RINGER_MODE_NORMAL); if(ringerMode == AudioManager.RINGER_MODE_SILENT) { notifier.silenceRinger(); } }else if (action.equals(INSERT_BLACKLIST)) { PhoneApp.getInstance().getSettings().addBlackList(intent.getStringExtra("Insert.BLACKLIST")); } } } /** * Broadcast receiver for the ACTION_MEDIA_BUTTON broadcast intent. * * This functionality isn't lumped in with the other intents in * PhoneAppBroadcastReceiver because we instantiate this as a totally * separate BroadcastReceiver instance, since we need to manually * adjust its IntentFilter's priority (to make sure we get these * intents *before* the media player.) */ private class MediaButtonBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT); if (VDBG) Log.d(LOG_TAG, "MediaButtonBroadcastReceiver.onReceive()... event = " + event); if ((event != null) && (event.getKeyCode() == KeyEvent.KEYCODE_HEADSETHOOK)) { if (VDBG) Log.d(LOG_TAG, "MediaButtonBroadcastReceiver: HEADSETHOOK"); boolean consumed = PhoneUtils.handleHeadsetHook(phone, event); if (VDBG) Log.d(LOG_TAG, "==> handleHeadsetHook(): consumed = " + consumed); if (consumed) { // If a headset is attached and the press is consumed, also update // any UI items (such as an InCallScreen mute button) that may need to // be updated if their state changed. if (isShowingCallScreen()) { updateInCallScreenTouchUi(); } abortBroadcast(); } } else if (event.getRepeatCount() == 2) { // Long press to hang up: if (VDBG) Log.d(LOG_TAG, "repeat count = 2 is triggered!"); boolean consumed = PhoneUtils.handleHeadsetHookHangup(phone); if (consumed) { if (VDBG) Log.d(LOG_TAG, "consuming broadcast"); abortBroadcast(); // BUG: Media player on/off is toggled sometimes if used to hang up } } else { if (mCM.getState() != Phone.State.IDLE) { // If the phone is anything other than completely idle, // then we consume and ignore any media key events, // Otherwise it is too easy to accidentally start // playing music while a phone call is in progress. if (VDBG) Log.d(LOG_TAG, "MediaButtonBroadcastReceiver: consumed"); abortBroadcast(); } } } } private void handleServiceStateChanged(Intent intent) { /** * This used to handle updating EriTextWidgetProvider this routine * and and listening for ACTION_SERVICE_STATE_CHANGED intents could * be removed. But leaving just in case it might be needed in the near * future. */ // If service just returned, start sending out the queued messages ServiceState ss = ServiceState.newFromBundle(intent.getExtras()); boolean hasService = true; boolean isCdma = false; String eriText = ""; if (ss != null) { int state = ss.getState(); NotificationMgr.getDefault().updateNetworkSelection(state); switch (state) { case ServiceState.STATE_OUT_OF_SERVICE: case ServiceState.STATE_POWER_OFF: hasService = false; break; } } else { hasService = false; } } public boolean isOtaCallInActiveState() { boolean otaCallActive = false; if (mInCallScreen != null) { otaCallActive = mInCallScreen.isOtaCallInActiveState(); } if (VDBG) Log.d(LOG_TAG, "- isOtaCallInActiveState " + otaCallActive); return otaCallActive; } public boolean isOtaCallInEndState() { boolean otaCallEnded = false; if (mInCallScreen != null) { otaCallEnded = mInCallScreen.isOtaCallInEndState(); } if (VDBG) Log.d(LOG_TAG, "- isOtaCallInEndState " + otaCallEnded); return otaCallEnded; } // it is safe to call clearOtaState() even if the InCallScreen isn't active public void clearOtaState() { if (DBG) Log.d(LOG_TAG, "- clearOtaState ..."); if ((mInCallScreen != null) && (mInCallScreen.otaUtils != null)) { mInCallScreen.otaUtils.cleanOtaScreen(true); if (DBG) Log.d(LOG_TAG, " - clearOtaState clears OTA screen"); } } // it is safe to call dismissOtaDialogs() even if the InCallScreen isn't active public void dismissOtaDialogs() { if (DBG) Log.d(LOG_TAG, "- dismissOtaDialogs ..."); if ((mInCallScreen != null) && (mInCallScreen.otaUtils != null)) { mInCallScreen.otaUtils.dismissAllOtaDialogs(); if (DBG) Log.d(LOG_TAG, " - dismissOtaDialogs clears OTA dialogs"); } } // it is safe to call clearInCallScreenMode() even if the InCallScreen isn't active public void clearInCallScreenMode() { if (DBG) Log.d(LOG_TAG, "- clearInCallScreenMode ..."); if (mInCallScreen != null) { mInCallScreen.resetInCallScreenMode(); } } // Update InCallScreen's touch UI. It is safe to call even if InCallScreen isn't active public void updateInCallScreenTouchUi() { if (DBG) Log.d(LOG_TAG, "- updateInCallScreenTouchUi ..."); if (mInCallScreen != null) { mInCallScreen.requestUpdateTouchUi(); } } private void handleQueryTTYModeResponse(Message msg) { AsyncResult ar = (AsyncResult) msg.obj; if (ar.exception != null) { if (DBG) Log.d(LOG_TAG, "handleQueryTTYModeResponse: Error getting TTY state."); } else { if (DBG) Log.d(LOG_TAG, "handleQueryTTYModeResponse: TTY enable state successfully queried."); int ttymode = ((int[]) ar.result)[0]; if (DBG) Log.d(LOG_TAG, "handleQueryTTYModeResponse:ttymode=" + ttymode); Intent ttyModeChanged = new Intent(TtyIntent.TTY_ENABLED_CHANGE_ACTION); ttyModeChanged.putExtra("ttyEnabled", ttymode != Phone.TTY_MODE_OFF); sendBroadcast(ttyModeChanged); String audioTtyMode; switch (ttymode) { case Phone.TTY_MODE_FULL: audioTtyMode = "tty_full"; break; case Phone.TTY_MODE_VCO: audioTtyMode = "tty_vco"; break; case Phone.TTY_MODE_HCO: audioTtyMode = "tty_hco"; break; case Phone.TTY_MODE_OFF: default: audioTtyMode = "tty_off"; break; } AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); audioManager.setParameters("tty_mode="+audioTtyMode); } } private void handleSetTTYModeResponse(Message msg) { AsyncResult ar = (AsyncResult) msg.obj; if (ar.exception != null) { if (DBG) Log.d (LOG_TAG, "handleSetTTYModeResponse: Error setting TTY mode, ar.exception" + ar.exception); } phone.queryTTYMode(mHandler.obtainMessage(EVENT_TTY_MODE_GET)); } /* package */ void clearUserActivityTimeout() { try { mPowerManagerService.clearUserActivityTimeout(SystemClock.uptimeMillis(), 10*1000 /* 10 sec */); } catch (RemoteException ex) { // System process is dead. } } }
true
true
public void onCreate() { if (VDBG) Log.v(LOG_TAG, "onCreate()..."); ContentResolver resolver = getContentResolver(); if (phone == null) { // Initialize the telephony framework PhoneFactory.makeDefaultPhones(this); // Get the default phone phone = PhoneFactory.getDefaultPhone(); mCM = CallManager.getInstance(); mCM.registerPhone(phone); NotificationMgr.init(this); phoneMgr = new PhoneInterfaceManager(this, phone); // Starts the SIP service. It's a no-op if SIP API is not supported // on the deivce. // TODO: Having the phone process host the SIP service is only // temporary. Will move it to a persistent communication process // later. SipService.start(this); int phoneType = phone.getPhoneType(); if (phoneType == Phone.PHONE_TYPE_CDMA) { // Create an instance of CdmaPhoneCallState and initialize it to IDLE cdmaPhoneCallState = new CdmaPhoneCallState(); cdmaPhoneCallState.CdmaPhoneCallStateInit(); } if (BluetoothAdapter.getDefaultAdapter() != null) { mBtHandsfree = new BluetoothHandsfree(this, mCM); startService(new Intent(this, BluetoothHeadsetService.class)); } else { // Device is not bluetooth capable mBtHandsfree = null; } ringer = new Ringer(this); // before registering for phone state changes PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, LOG_TAG); // lock used to keep the processor awake, when we don't care for the display. mPartialWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, LOG_TAG); // Wake lock used to control proximity sensor behavior. if ((pm.getSupportedWakeLockFlags() & PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) != 0x0) { mProximityWakeLock = pm.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, LOG_TAG); } if (DBG) Log.d(LOG_TAG, "onCreate: mProximityWakeLock: " + mProximityWakeLock); // create mAccelerometerListener only if we are using the proximity sensor if (proximitySensorModeEnabled()) { mAccelerometerListener = new AccelerometerListener(this, this); } mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); mStatusBarManager = (StatusBarManager) getSystemService(Context.STATUS_BAR_SERVICE); // get a handle to the service so that we can use it later when we // want to set the poke lock. mPowerManagerService = IPowerManager.Stub.asInterface( ServiceManager.getService("power")); notifier = new CallNotifier(this, phone, ringer, mBtHandsfree, new CallLogAsync()); // register for ICC status IccCard sim = phone.getIccCard(); if (sim != null) { if (VDBG) Log.v(LOG_TAG, "register for ICC status"); sim.registerForNetworkLocked(mHandler, EVENT_SIM_NETWORK_LOCKED, null); } // register for MMI/USSD mCM.registerForMmiComplete(mHandler, MMI_COMPLETE, null); // register connection tracking to PhoneUtils PhoneUtils.initializeConnectionHandler(mCM); // Read platform settings for TTY feature mTtyEnabled = getResources().getBoolean(R.bool.tty_enabled); // Register for misc other intent broadcasts. IntentFilter intentFilter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED); intentFilter.addAction(BluetoothHeadset.ACTION_STATE_CHANGED); intentFilter.addAction(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED); intentFilter.addAction(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED); intentFilter.addAction(Intent.ACTION_HEADSET_PLUG); intentFilter.addAction(Intent.ACTION_DOCK_EVENT); intentFilter.addAction(Intent.ACTION_BATTERY_LOW); intentFilter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED); intentFilter.addAction(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED); intentFilter.addAction(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED); intentFilter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED); intentFilter.addAction(ACTION_VIBRATE_45); intentFilter.addAction(INSERT_BLACKLIST); if (mTtyEnabled) { intentFilter.addAction(TtyIntent.TTY_PREFERRED_MODE_CHANGE_ACTION); } intentFilter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION); registerReceiver(mReceiver, intentFilter); // Use a separate receiver for ACTION_MEDIA_BUTTON broadcasts, // since we need to manually adjust its priority (to make sure // we get these intents *before* the media player.) IntentFilter mediaButtonIntentFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON); // // Make sure we're higher priority than the media player's // MediaButtonIntentReceiver (which currently has the default // priority of zero; see apps/Music/AndroidManifest.xml.) mediaButtonIntentFilter.setPriority(1); // registerReceiver(mMediaButtonReceiver, mediaButtonIntentFilter); //set the default values for the preferences in the phone. PreferenceManager.setDefaultValues(this, R.xml.network_setting, false); PreferenceManager.setDefaultValues(this, R.xml.call_feature_setting, false); // Make sure the audio mode (along with some // audio-mode-related state of our own) is initialized // correctly, given the current state of the phone. PhoneUtils.setAudioMode(mCM); } boolean phoneIsCdma = (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA); if (phoneIsCdma) { cdmaOtaProvisionData = new OtaUtils.CdmaOtaProvisionData(); cdmaOtaConfigData = new OtaUtils.CdmaOtaConfigData(); cdmaOtaScreenState = new OtaUtils.CdmaOtaScreenState(); cdmaOtaInCallScreenUiState = new OtaUtils.CdmaOtaInCallScreenUiState(); } // XXX pre-load the SimProvider so that it's ready resolver.getType(Uri.parse("content://icc/adn")); // start with the default value to set the mute state. mShouldRestoreMuteOnInCallResume = false; // add by cytown mSettings = CallFeaturesSetting.getInstance(PreferenceManager.getDefaultSharedPreferences(this)); if (mVibrator == null) { mVibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE); mAM = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); mVibrateIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_VIBRATE_45), 0); } // TODO: Register for Cdma Information Records // phone.registerCdmaInformationRecord(mHandler, EVENT_UNSOL_CDMA_INFO_RECORD, null); // Read TTY settings and store it into BP NV. // AP owns (i.e. stores) the TTY setting in AP settings database and pushes the setting // to BP at power up (BP does not need to make the TTY setting persistent storage). // This way, there is a single owner (i.e AP) for the TTY setting in the phone. if (mTtyEnabled) { mPreferredTtyMode = android.provider.Settings.Secure.getInt( phone.getContext().getContentResolver(), android.provider.Settings.Secure.PREFERRED_TTY_MODE, Phone.TTY_MODE_OFF); mHandler.sendMessage(mHandler.obtainMessage(EVENT_TTY_PREFERRED_MODE_CHANGED, 0)); } // Read HAC settings and configure audio hardware if (getResources().getBoolean(R.bool.hac_enabled)) { int hac = android.provider.Settings.System.getInt(phone.getContext().getContentResolver(), android.provider.Settings.System.HEARING_AID, 0); AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); audioManager.setParameter(CallFeaturesSetting.HAC_KEY, hac != 0 ? CallFeaturesSetting.HAC_VAL_ON : CallFeaturesSetting.HAC_VAL_OFF); } }
public void onCreate() { if (VDBG) Log.v(LOG_TAG, "onCreate()..."); ContentResolver resolver = getContentResolver(); if (phone == null) { // Initialize the telephony framework PhoneFactory.makeDefaultPhones(this); // Get the default phone phone = PhoneFactory.getDefaultPhone(); mCM = CallManager.getInstance(); mCM.registerPhone(phone); NotificationMgr.init(this); phoneMgr = new PhoneInterfaceManager(this, phone); // Starts the SIP service. It's a no-op if SIP API is not supported // on the deivce. // TODO: Having the phone process host the SIP service is only // temporary. Will move it to a persistent communication process // later. SipService.start(this); int phoneType = phone.getPhoneType(); if (phoneType == Phone.PHONE_TYPE_CDMA) { // Create an instance of CdmaPhoneCallState and initialize it to IDLE cdmaPhoneCallState = new CdmaPhoneCallState(); cdmaPhoneCallState.CdmaPhoneCallStateInit(); } if (BluetoothAdapter.getDefaultAdapter() != null) { mBtHandsfree = new BluetoothHandsfree(this, mCM); startService(new Intent(this, BluetoothHeadsetService.class)); } else { // Device is not bluetooth capable mBtHandsfree = null; } ringer = new Ringer(this); // before registering for phone state changes PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, LOG_TAG); // lock used to keep the processor awake, when we don't care for the display. mPartialWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, LOG_TAG); // Wake lock used to control proximity sensor behavior. if ((pm.getSupportedWakeLockFlags() & PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) != 0x0) { mProximityWakeLock = pm.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, LOG_TAG); } if (DBG) Log.d(LOG_TAG, "onCreate: mProximityWakeLock: " + mProximityWakeLock); // create mAccelerometerListener only if we are using the proximity sensor if (proximitySensorModeEnabled()) { mAccelerometerListener = new AccelerometerListener(this, this); } mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); mStatusBarManager = (StatusBarManager) getSystemService(Context.STATUS_BAR_SERVICE); // get a handle to the service so that we can use it later when we // want to set the poke lock. mPowerManagerService = IPowerManager.Stub.asInterface( ServiceManager.getService("power")); notifier = new CallNotifier(this, phone, ringer, mBtHandsfree, new CallLogAsync()); // register for ICC status IccCard sim = phone.getIccCard(); if (sim != null) { if (VDBG) Log.v(LOG_TAG, "register for ICC status"); sim.registerForNetworkLocked(mHandler, EVENT_SIM_NETWORK_LOCKED, null); } // register for MMI/USSD mCM.registerForMmiComplete(mHandler, MMI_COMPLETE, null); // register connection tracking to PhoneUtils PhoneUtils.initializeConnectionHandler(mCM); // Read platform settings for TTY feature mTtyEnabled = getResources().getBoolean(R.bool.tty_enabled); // Register for misc other intent broadcasts. IntentFilter intentFilter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED); intentFilter.addAction(BluetoothHeadset.ACTION_STATE_CHANGED); intentFilter.addAction(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED); intentFilter.addAction(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED); intentFilter.addAction(Intent.ACTION_HEADSET_PLUG); intentFilter.addAction(Intent.ACTION_DOCK_EVENT); intentFilter.addAction(Intent.ACTION_BATTERY_LOW); intentFilter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED); intentFilter.addAction(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED); intentFilter.addAction(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED); intentFilter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED); intentFilter.addAction(ACTION_VIBRATE_45); intentFilter.addAction(INSERT_BLACKLIST); if (mTtyEnabled) { intentFilter.addAction(TtyIntent.TTY_PREFERRED_MODE_CHANGE_ACTION); } intentFilter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION); registerReceiver(mReceiver, intentFilter); // Use a separate receiver for ACTION_MEDIA_BUTTON broadcasts, // since we need to manually adjust its priority (to make sure // we get these intents *before* the media player.) IntentFilter mediaButtonIntentFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON); // // Make sure we're higher priority than the media player's // MediaButtonIntentReceiver (which currently has the default // priority of zero; see apps/Music/AndroidManifest.xml.) mediaButtonIntentFilter.setPriority(1); // registerReceiver(mMediaButtonReceiver, mediaButtonIntentFilter); //set the default values for the preferences in the phone. PreferenceManager.setDefaultValues(this, R.xml.network_setting, false); PreferenceManager.setDefaultValues(this, R.xml.call_feature_setting, false); // Make sure the audio mode (along with some // audio-mode-related state of our own) is initialized // correctly, given the current state of the phone. PhoneUtils.setAudioMode(mCM); } boolean phoneIsCdma = (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA); if (phoneIsCdma) { cdmaOtaProvisionData = new OtaUtils.CdmaOtaProvisionData(); cdmaOtaConfigData = new OtaUtils.CdmaOtaConfigData(); cdmaOtaScreenState = new OtaUtils.CdmaOtaScreenState(); cdmaOtaInCallScreenUiState = new OtaUtils.CdmaOtaInCallScreenUiState(); } // XXX pre-load the SimProvider so that it's ready resolver.getType(Uri.parse("content://icc/adn")); // start with the default value to set the mute state. mShouldRestoreMuteOnInCallResume = false; // add by cytown mSettings = CallFeaturesSetting.getInstance(PreferenceManager.getDefaultSharedPreferences(this)); if (mVibrator == null) { mVibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE); mAM = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); mVibrateIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_VIBRATE_45), 0); } // TODO: Register for Cdma Information Records // phone.registerCdmaInformationRecord(mHandler, EVENT_UNSOL_CDMA_INFO_RECORD, null); // Read TTY settings and store it into BP NV. // AP owns (i.e. stores) the TTY setting in AP settings database and pushes the setting // to BP at power up (BP does not need to make the TTY setting persistent storage). // This way, there is a single owner (i.e AP) for the TTY setting in the phone. if (mTtyEnabled) { mPreferredTtyMode = android.provider.Settings.Secure.getInt( phone.getContext().getContentResolver(), android.provider.Settings.Secure.PREFERRED_TTY_MODE, Phone.TTY_MODE_OFF); mHandler.sendMessage(mHandler.obtainMessage(EVENT_TTY_PREFERRED_MODE_CHANGED, 0)); } // Read HAC settings and configure audio hardware if (getResources().getBoolean(R.bool.hac_enabled)) { int hac = android.provider.Settings.System.getInt(phone.getContext().getContentResolver(), android.provider.Settings.System.HEARING_AID, 0); AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); audioManager.setParameter(CallFeaturesSetting.HAC_KEY, hac != 0 ? CallFeaturesSetting.HAC_VAL_ON : CallFeaturesSetting.HAC_VAL_OFF); } }
diff --git a/src/database/Postgres.java b/src/database/Postgres.java index d73f3cd..f12b08a 100644 --- a/src/database/Postgres.java +++ b/src/database/Postgres.java @@ -1,57 +1,57 @@ /** * Postgres.java * * Copyright (C) 2009-2011 Kenneth Prugh * * 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. */ package database; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import config.Config; public class Postgres { private static Postgres _instance; private Connection db; private Postgres() { Config config = Config.getInstance(); try { Class.forName("org.postgresql.Driver"); db = DriverManager.getConnection(config.getDbpath(),config.getDbuser(), config.getDbpass()); - final String DBEncoding = "UNICODE"; + final String DBEncoding = "UTF8"; PreparedStatement statement = db .prepareStatement("SET CLIENT_ENCODING TO '" + DBEncoding + "'"); statement.execute(); statement.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } /** * Return Connection to postgresql */ public static synchronized Postgres getInstance() { if (_instance == null) { _instance = new Postgres(); return _instance; } else { return _instance; } } public Connection getConnection() { return db; } }
true
true
private Postgres() { Config config = Config.getInstance(); try { Class.forName("org.postgresql.Driver"); db = DriverManager.getConnection(config.getDbpath(),config.getDbuser(), config.getDbpass()); final String DBEncoding = "UNICODE"; PreparedStatement statement = db .prepareStatement("SET CLIENT_ENCODING TO '" + DBEncoding + "'"); statement.execute(); statement.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } }
private Postgres() { Config config = Config.getInstance(); try { Class.forName("org.postgresql.Driver"); db = DriverManager.getConnection(config.getDbpath(),config.getDbuser(), config.getDbpass()); final String DBEncoding = "UTF8"; PreparedStatement statement = db .prepareStatement("SET CLIENT_ENCODING TO '" + DBEncoding + "'"); statement.execute(); statement.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } }
diff --git a/src/main/java/org/bukkit/command/defaults/PlaySoundCommand.java b/src/main/java/org/bukkit/command/defaults/PlaySoundCommand.java index 3dfb0483..0cb5ca2d 100644 --- a/src/main/java/org/bukkit/command/defaults/PlaySoundCommand.java +++ b/src/main/java/org/bukkit/command/defaults/PlaySoundCommand.java @@ -1,87 +1,87 @@ package org.bukkit.command.defaults; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class PlaySoundCommand extends VanillaCommand { public PlaySoundCommand() { super("playsound"); this.description = "Plays a sound to a given player"; this.usageMessage = "/playsound <sound> <player> [x] [y] [z] [volume] [pitch] [minimumVolume]"; this.setPermission("bukkit.command.playsound"); } @Override public boolean execute(CommandSender sender, String currentAlias, String[] args) { if (!testPermission(sender)) { return true; } if (args.length < 2) { sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); return false; } final String soundArg = args[0]; final String playerArg = args[1]; final Player player = Bukkit.getPlayerExact(playerArg); if (player == null) { sender.sendMessage(ChatColor.RED + "Can't find player " + playerArg); return false; } final Location location = player.getLocation(); double x = Math.floor(location.getX()); double y = Math.floor(location.getY() + 0.5D); double z = Math.floor(location.getZ()); double volume = 1.0D; double pitch = 1.0D; double minimumVolume = 0.0D; switch (args.length) { default: case 8: minimumVolume = getDouble(sender, args[7], 0.0D, 1.0D); case 7: pitch = getDouble(sender, args[6], 0.0D, 2.0D); case 6: volume = getDouble(sender, args[5], 0.0D, Float.MAX_VALUE); case 5: z = getRelativeDouble(z, sender, args[4]); case 4: y = getRelativeDouble(y, sender, args[3]); case 3: x = getRelativeDouble(x, sender, args[2]); case 2: // Noop } final double fixedVolume = volume > 1.0D ? volume * 16.0D : 16.0D; final Location soundLocation = new Location(player.getWorld(), x, y, z); if (location.distanceSquared(soundLocation) > fixedVolume * fixedVolume) { if (minimumVolume <= 0.0D) { sender.sendMessage(ChatColor.RED + playerArg + " is too far away to hear the sound"); return false; } final double deltaX = x - location.getX(); final double deltaY = y - location.getY(); final double deltaZ = z - location.getZ(); final double delta = Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ) / 2.0D; if (delta > 0.0D) { - soundLocation.add(deltaX / delta, deltaY / delta, deltaZ / delta); + location.add(deltaX / delta, deltaY / delta, deltaZ / delta); } - player.playSound(soundLocation, soundArg, (float) minimumVolume, (float) pitch); + player.playSound(location, soundArg, (float) minimumVolume, (float) pitch); } else { player.playSound(soundLocation, soundArg, (float) volume, (float) pitch); } sender.sendMessage(String.format("Played '%s' to %s", soundArg, playerArg)); return true; } }
false
true
public boolean execute(CommandSender sender, String currentAlias, String[] args) { if (!testPermission(sender)) { return true; } if (args.length < 2) { sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); return false; } final String soundArg = args[0]; final String playerArg = args[1]; final Player player = Bukkit.getPlayerExact(playerArg); if (player == null) { sender.sendMessage(ChatColor.RED + "Can't find player " + playerArg); return false; } final Location location = player.getLocation(); double x = Math.floor(location.getX()); double y = Math.floor(location.getY() + 0.5D); double z = Math.floor(location.getZ()); double volume = 1.0D; double pitch = 1.0D; double minimumVolume = 0.0D; switch (args.length) { default: case 8: minimumVolume = getDouble(sender, args[7], 0.0D, 1.0D); case 7: pitch = getDouble(sender, args[6], 0.0D, 2.0D); case 6: volume = getDouble(sender, args[5], 0.0D, Float.MAX_VALUE); case 5: z = getRelativeDouble(z, sender, args[4]); case 4: y = getRelativeDouble(y, sender, args[3]); case 3: x = getRelativeDouble(x, sender, args[2]); case 2: // Noop } final double fixedVolume = volume > 1.0D ? volume * 16.0D : 16.0D; final Location soundLocation = new Location(player.getWorld(), x, y, z); if (location.distanceSquared(soundLocation) > fixedVolume * fixedVolume) { if (minimumVolume <= 0.0D) { sender.sendMessage(ChatColor.RED + playerArg + " is too far away to hear the sound"); return false; } final double deltaX = x - location.getX(); final double deltaY = y - location.getY(); final double deltaZ = z - location.getZ(); final double delta = Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ) / 2.0D; if (delta > 0.0D) { soundLocation.add(deltaX / delta, deltaY / delta, deltaZ / delta); } player.playSound(soundLocation, soundArg, (float) minimumVolume, (float) pitch); } else { player.playSound(soundLocation, soundArg, (float) volume, (float) pitch); } sender.sendMessage(String.format("Played '%s' to %s", soundArg, playerArg)); return true; }
public boolean execute(CommandSender sender, String currentAlias, String[] args) { if (!testPermission(sender)) { return true; } if (args.length < 2) { sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); return false; } final String soundArg = args[0]; final String playerArg = args[1]; final Player player = Bukkit.getPlayerExact(playerArg); if (player == null) { sender.sendMessage(ChatColor.RED + "Can't find player " + playerArg); return false; } final Location location = player.getLocation(); double x = Math.floor(location.getX()); double y = Math.floor(location.getY() + 0.5D); double z = Math.floor(location.getZ()); double volume = 1.0D; double pitch = 1.0D; double minimumVolume = 0.0D; switch (args.length) { default: case 8: minimumVolume = getDouble(sender, args[7], 0.0D, 1.0D); case 7: pitch = getDouble(sender, args[6], 0.0D, 2.0D); case 6: volume = getDouble(sender, args[5], 0.0D, Float.MAX_VALUE); case 5: z = getRelativeDouble(z, sender, args[4]); case 4: y = getRelativeDouble(y, sender, args[3]); case 3: x = getRelativeDouble(x, sender, args[2]); case 2: // Noop } final double fixedVolume = volume > 1.0D ? volume * 16.0D : 16.0D; final Location soundLocation = new Location(player.getWorld(), x, y, z); if (location.distanceSquared(soundLocation) > fixedVolume * fixedVolume) { if (minimumVolume <= 0.0D) { sender.sendMessage(ChatColor.RED + playerArg + " is too far away to hear the sound"); return false; } final double deltaX = x - location.getX(); final double deltaY = y - location.getY(); final double deltaZ = z - location.getZ(); final double delta = Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ) / 2.0D; if (delta > 0.0D) { location.add(deltaX / delta, deltaY / delta, deltaZ / delta); } player.playSound(location, soundArg, (float) minimumVolume, (float) pitch); } else { player.playSound(soundLocation, soundArg, (float) volume, (float) pitch); } sender.sendMessage(String.format("Played '%s' to %s", soundArg, playerArg)); return true; }
diff --git a/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/presentationTier/renderers/autoCompleteProvider/CPVAutoCompleteProvider.java b/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/presentationTier/renderers/autoCompleteProvider/CPVAutoCompleteProvider.java index ce595105..0aac10ce 100644 --- a/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/presentationTier/renderers/autoCompleteProvider/CPVAutoCompleteProvider.java +++ b/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/presentationTier/renderers/autoCompleteProvider/CPVAutoCompleteProvider.java @@ -1,35 +1,35 @@ package pt.ist.expenditureTrackingSystem.presentationTier.renderers.autoCompleteProvider; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import pt.ist.expenditureTrackingSystem.domain.ExpenditureTrackingSystem; import pt.ist.expenditureTrackingSystem.domain.acquisitions.CPVReference; public class CPVAutoCompleteProvider implements AutoCompleteProvider { public Collection getSearchResults(Map<String, String> argsMap, String value, int maxCount) { List<CPVReference> result = new ArrayList<CPVReference>(); - String[] values = value.split(" "); + String[] values = value.toLowerCase().split(" "); for (final CPVReference cpvCode : ExpenditureTrackingSystem.getInstance().getCPVReferences()) { - if (cpvCode.getCode().startsWith(value) || match(cpvCode.getDescription(), values)) { + if (cpvCode.getCode().startsWith(value) || match(cpvCode.getDescription().toLowerCase(), values)) { result.add(cpvCode); } } return result; } private boolean match(String description, String[] inputParts) { for (final String namePart : inputParts) { if (description.indexOf(namePart) == -1) { return false; } } return true; } }
false
true
public Collection getSearchResults(Map<String, String> argsMap, String value, int maxCount) { List<CPVReference> result = new ArrayList<CPVReference>(); String[] values = value.split(" "); for (final CPVReference cpvCode : ExpenditureTrackingSystem.getInstance().getCPVReferences()) { if (cpvCode.getCode().startsWith(value) || match(cpvCode.getDescription(), values)) { result.add(cpvCode); } } return result; }
public Collection getSearchResults(Map<String, String> argsMap, String value, int maxCount) { List<CPVReference> result = new ArrayList<CPVReference>(); String[] values = value.toLowerCase().split(" "); for (final CPVReference cpvCode : ExpenditureTrackingSystem.getInstance().getCPVReferences()) { if (cpvCode.getCode().startsWith(value) || match(cpvCode.getDescription().toLowerCase(), values)) { result.add(cpvCode); } } return result; }
diff --git a/hyracks-storage-am-lsm-btree/src/main/java/edu/uci/ics/hyracks/storage/am/lsm/btree/impls/LSMBTreeFileManager.java b/hyracks-storage-am-lsm-btree/src/main/java/edu/uci/ics/hyracks/storage/am/lsm/btree/impls/LSMBTreeFileManager.java index 61d956d08..e1dbc9e5a 100644 --- a/hyracks-storage-am-lsm-btree/src/main/java/edu/uci/ics/hyracks/storage/am/lsm/btree/impls/LSMBTreeFileManager.java +++ b/hyracks-storage-am-lsm-btree/src/main/java/edu/uci/ics/hyracks/storage/am/lsm/btree/impls/LSMBTreeFileManager.java @@ -1,202 +1,202 @@ /* * Copyright 2009-2012 by The Regents of the University of California * 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 from * * 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 edu.uci.ics.hyracks.storage.am.lsm.btree.impls; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import edu.uci.ics.hyracks.api.exceptions.HyracksDataException; import edu.uci.ics.hyracks.api.io.FileReference; import edu.uci.ics.hyracks.api.io.IIOManager; import edu.uci.ics.hyracks.api.io.IODeviceHandle; import edu.uci.ics.hyracks.storage.am.common.api.ITreeIndex; import edu.uci.ics.hyracks.storage.am.common.api.IndexException; import edu.uci.ics.hyracks.storage.am.lsm.common.impls.AbstractLSMIndexFileManager; import edu.uci.ics.hyracks.storage.am.lsm.common.impls.LSMComponentFileReferences; import edu.uci.ics.hyracks.storage.am.lsm.common.impls.TreeIndexFactory; import edu.uci.ics.hyracks.storage.common.file.IFileMapProvider; public class LSMBTreeFileManager extends AbstractLSMIndexFileManager { private static final String BTREE_STRING = "b"; private static final String BLOOM_FILTER_STRING = "f"; private final TreeIndexFactory<? extends ITreeIndex> btreeFactory; public LSMBTreeFileManager(IIOManager ioManager, IFileMapProvider fileMapProvider, FileReference file, TreeIndexFactory<? extends ITreeIndex> btreeFactory, int startIODeviceIndex) { super(ioManager, fileMapProvider, file, null, startIODeviceIndex); this.btreeFactory = btreeFactory; } protected void cleanupAndGetValidFilesInternal(IODeviceHandle dev, FilenameFilter filter, TreeIndexFactory<? extends ITreeIndex> treeFactory, ArrayList<ComparableFileName> allFiles) throws HyracksDataException, IndexException { File dir = new File(dev.getPath(), baseDir); String[] files = dir.list(filter); for (String fileName : files) { File file = new File(dir.getPath() + File.separator + fileName); FileReference fileRef = new FileReference(file); if (treeFactory == null || isValidTreeIndex(treeFactory.createIndexInstance(fileRef))) { allFiles.add(new ComparableFileName(fileRef)); } else { file.delete(); } } } @Override public LSMComponentFileReferences getRelFlushFileReference() { Date date = new Date(); String ts = formatter.format(date); String baseName = baseDir + ts + SPLIT_STRING + ts; // Begin timestamp and end timestamp are identical since it is a flush return new LSMComponentFileReferences(createFlushFile(baseName + SPLIT_STRING + BTREE_STRING), null, createFlushFile(baseName + SPLIT_STRING + BLOOM_FILTER_STRING)); } @Override public LSMComponentFileReferences getRelMergeFileReference(String firstFileName, String lastFileName) throws HyracksDataException { String[] firstTimestampRange = firstFileName.split(SPLIT_STRING); String[] lastTimestampRange = lastFileName.split(SPLIT_STRING); String baseName = baseDir + firstTimestampRange[0] + SPLIT_STRING + lastTimestampRange[1]; // Get the range of timestamps by taking the earliest and the latest timestamps return new LSMComponentFileReferences(createMergeFile(baseName + SPLIT_STRING + BTREE_STRING), null, createMergeFile(baseName + SPLIT_STRING + BLOOM_FILTER_STRING)); } private static FilenameFilter btreeFilter = new FilenameFilter() { public boolean accept(File dir, String name) { return !name.startsWith(".") && name.endsWith(BTREE_STRING); } }; private static FilenameFilter bloomFilterFilter = new FilenameFilter() { public boolean accept(File dir, String name) { return !name.startsWith(".") && name.endsWith(BLOOM_FILTER_STRING); } }; @Override public List<LSMComponentFileReferences> cleanupAndGetValidFiles() throws HyracksDataException, IndexException { List<LSMComponentFileReferences> validFiles = new ArrayList<LSMComponentFileReferences>(); ArrayList<ComparableFileName> allBTreeFiles = new ArrayList<ComparableFileName>(); ArrayList<ComparableFileName> allBloomFilterFiles = new ArrayList<ComparableFileName>(); // Gather files from all IODeviceHandles. for (IODeviceHandle dev : ioManager.getIODevices()) { cleanupAndGetValidFilesInternal(dev, bloomFilterFilter, null, allBloomFilterFiles); HashSet<String> bloomFilterFilesSet = new HashSet<String>(); for (ComparableFileName cmpFileName : allBloomFilterFiles) { int index = cmpFileName.fileName.lastIndexOf(SPLIT_STRING); bloomFilterFilesSet.add(cmpFileName.fileName.substring(0, index)); } // List of valid BTree files that may or may not have a bloom filter buddy. Will check for buddies below. ArrayList<ComparableFileName> tmpAllBTreeFiles = new ArrayList<ComparableFileName>(); cleanupAndGetValidFilesInternal(dev, btreeFilter, btreeFactory, tmpAllBTreeFiles); // Look for buddy bloom filters for all valid BTrees. // If no buddy is found, delete the file, otherwise add the BTree to allBTreeFiles. for (ComparableFileName cmpFileName : tmpAllBTreeFiles) { int index = cmpFileName.fileName.lastIndexOf(SPLIT_STRING); String file = cmpFileName.fileName.substring(0, index); if (bloomFilterFilesSet.contains(file)) { allBTreeFiles.add(cmpFileName); } else { // Couldn't find the corresponding bloom filter file; thus, delete // the BTree file. File invalidBTreeFile = new File(cmpFileName.fullPath); invalidBTreeFile.delete(); } } } // Sanity check. if (allBTreeFiles.size() != allBloomFilterFiles.size()) { throw new HyracksDataException( "Unequal number of valid BTree and bloom filter files found. Aborting cleanup."); } // Trivial cases. if (allBTreeFiles.isEmpty() || allBloomFilterFiles.isEmpty()) { return validFiles; } if (allBTreeFiles.size() == 1 && allBloomFilterFiles.size() == 1) { - validFiles.add(new LSMComponentFileReferences(allBTreeFiles.get(0).fileRef, - allBloomFilterFiles.get(0).fileRef, null)); + validFiles.add(new LSMComponentFileReferences(allBTreeFiles.get(0).fileRef, null, allBloomFilterFiles + .get(0).fileRef)); return validFiles; } // Sorts files names from earliest to latest timestamp. Collections.sort(allBTreeFiles); Collections.sort(allBloomFilterFiles); List<ComparableFileName> validComparableBTreeFiles = new ArrayList<ComparableFileName>(); ComparableFileName lastBTree = allBTreeFiles.get(0); validComparableBTreeFiles.add(lastBTree); List<ComparableFileName> validComparableBloomFilterFiles = new ArrayList<ComparableFileName>(); ComparableFileName lastBloomFilter = allBloomFilterFiles.get(0); validComparableBloomFilterFiles.add(lastBloomFilter); for (int i = 1; i < allBTreeFiles.size(); i++) { ComparableFileName currentBTree = allBTreeFiles.get(i); ComparableFileName currentBloomFilter = allBloomFilterFiles.get(i); // Current start timestamp is greater than last stop timestamp. if (currentBTree.interval[0].compareTo(lastBTree.interval[1]) > 0 && currentBloomFilter.interval[0].compareTo(lastBloomFilter.interval[1]) > 0) { validComparableBTreeFiles.add(currentBTree); validComparableBloomFilterFiles.add(currentBloomFilter); lastBTree = currentBTree; lastBloomFilter = currentBloomFilter; } else if (currentBTree.interval[0].compareTo(lastBTree.interval[0]) >= 0 && currentBTree.interval[1].compareTo(lastBTree.interval[1]) <= 0 && currentBloomFilter.interval[0].compareTo(lastBloomFilter.interval[0]) >= 0 && currentBloomFilter.interval[1].compareTo(lastBloomFilter.interval[1]) <= 0) { // Invalid files are completely contained in last interval. File invalidBTreeFile = new File(currentBTree.fullPath); invalidBTreeFile.delete(); File invalidBloomFilterFile = new File(currentBloomFilter.fullPath); invalidBloomFilterFile.delete(); } else { // This scenario should not be possible. throw new HyracksDataException("Found LSM files with overlapping but not contained timetamp intervals."); } } // Sort valid files in reverse lexicographical order, such that newer // files come first. Collections.sort(validComparableBTreeFiles, recencyCmp); Collections.sort(validComparableBloomFilterFiles, recencyCmp); Iterator<ComparableFileName> btreeFileIter = validComparableBTreeFiles.iterator(); Iterator<ComparableFileName> bloomFilterFileIter = validComparableBloomFilterFiles.iterator(); while (btreeFileIter.hasNext() && bloomFilterFileIter.hasNext()) { ComparableFileName cmpBTreeFileName = btreeFileIter.next(); ComparableFileName cmpBloomFilterFileName = bloomFilterFileIter.next(); validFiles.add(new LSMComponentFileReferences(cmpBTreeFileName.fileRef, null, cmpBloomFilterFileName.fileRef)); } return validFiles; } }
true
true
public List<LSMComponentFileReferences> cleanupAndGetValidFiles() throws HyracksDataException, IndexException { List<LSMComponentFileReferences> validFiles = new ArrayList<LSMComponentFileReferences>(); ArrayList<ComparableFileName> allBTreeFiles = new ArrayList<ComparableFileName>(); ArrayList<ComparableFileName> allBloomFilterFiles = new ArrayList<ComparableFileName>(); // Gather files from all IODeviceHandles. for (IODeviceHandle dev : ioManager.getIODevices()) { cleanupAndGetValidFilesInternal(dev, bloomFilterFilter, null, allBloomFilterFiles); HashSet<String> bloomFilterFilesSet = new HashSet<String>(); for (ComparableFileName cmpFileName : allBloomFilterFiles) { int index = cmpFileName.fileName.lastIndexOf(SPLIT_STRING); bloomFilterFilesSet.add(cmpFileName.fileName.substring(0, index)); } // List of valid BTree files that may or may not have a bloom filter buddy. Will check for buddies below. ArrayList<ComparableFileName> tmpAllBTreeFiles = new ArrayList<ComparableFileName>(); cleanupAndGetValidFilesInternal(dev, btreeFilter, btreeFactory, tmpAllBTreeFiles); // Look for buddy bloom filters for all valid BTrees. // If no buddy is found, delete the file, otherwise add the BTree to allBTreeFiles. for (ComparableFileName cmpFileName : tmpAllBTreeFiles) { int index = cmpFileName.fileName.lastIndexOf(SPLIT_STRING); String file = cmpFileName.fileName.substring(0, index); if (bloomFilterFilesSet.contains(file)) { allBTreeFiles.add(cmpFileName); } else { // Couldn't find the corresponding bloom filter file; thus, delete // the BTree file. File invalidBTreeFile = new File(cmpFileName.fullPath); invalidBTreeFile.delete(); } } } // Sanity check. if (allBTreeFiles.size() != allBloomFilterFiles.size()) { throw new HyracksDataException( "Unequal number of valid BTree and bloom filter files found. Aborting cleanup."); } // Trivial cases. if (allBTreeFiles.isEmpty() || allBloomFilterFiles.isEmpty()) { return validFiles; } if (allBTreeFiles.size() == 1 && allBloomFilterFiles.size() == 1) { validFiles.add(new LSMComponentFileReferences(allBTreeFiles.get(0).fileRef, allBloomFilterFiles.get(0).fileRef, null)); return validFiles; } // Sorts files names from earliest to latest timestamp. Collections.sort(allBTreeFiles); Collections.sort(allBloomFilterFiles); List<ComparableFileName> validComparableBTreeFiles = new ArrayList<ComparableFileName>(); ComparableFileName lastBTree = allBTreeFiles.get(0); validComparableBTreeFiles.add(lastBTree); List<ComparableFileName> validComparableBloomFilterFiles = new ArrayList<ComparableFileName>(); ComparableFileName lastBloomFilter = allBloomFilterFiles.get(0); validComparableBloomFilterFiles.add(lastBloomFilter); for (int i = 1; i < allBTreeFiles.size(); i++) { ComparableFileName currentBTree = allBTreeFiles.get(i); ComparableFileName currentBloomFilter = allBloomFilterFiles.get(i); // Current start timestamp is greater than last stop timestamp. if (currentBTree.interval[0].compareTo(lastBTree.interval[1]) > 0 && currentBloomFilter.interval[0].compareTo(lastBloomFilter.interval[1]) > 0) { validComparableBTreeFiles.add(currentBTree); validComparableBloomFilterFiles.add(currentBloomFilter); lastBTree = currentBTree; lastBloomFilter = currentBloomFilter; } else if (currentBTree.interval[0].compareTo(lastBTree.interval[0]) >= 0 && currentBTree.interval[1].compareTo(lastBTree.interval[1]) <= 0 && currentBloomFilter.interval[0].compareTo(lastBloomFilter.interval[0]) >= 0 && currentBloomFilter.interval[1].compareTo(lastBloomFilter.interval[1]) <= 0) { // Invalid files are completely contained in last interval. File invalidBTreeFile = new File(currentBTree.fullPath); invalidBTreeFile.delete(); File invalidBloomFilterFile = new File(currentBloomFilter.fullPath); invalidBloomFilterFile.delete(); } else { // This scenario should not be possible. throw new HyracksDataException("Found LSM files with overlapping but not contained timetamp intervals."); } } // Sort valid files in reverse lexicographical order, such that newer // files come first. Collections.sort(validComparableBTreeFiles, recencyCmp); Collections.sort(validComparableBloomFilterFiles, recencyCmp); Iterator<ComparableFileName> btreeFileIter = validComparableBTreeFiles.iterator(); Iterator<ComparableFileName> bloomFilterFileIter = validComparableBloomFilterFiles.iterator(); while (btreeFileIter.hasNext() && bloomFilterFileIter.hasNext()) { ComparableFileName cmpBTreeFileName = btreeFileIter.next(); ComparableFileName cmpBloomFilterFileName = bloomFilterFileIter.next(); validFiles.add(new LSMComponentFileReferences(cmpBTreeFileName.fileRef, null, cmpBloomFilterFileName.fileRef)); } return validFiles; }
public List<LSMComponentFileReferences> cleanupAndGetValidFiles() throws HyracksDataException, IndexException { List<LSMComponentFileReferences> validFiles = new ArrayList<LSMComponentFileReferences>(); ArrayList<ComparableFileName> allBTreeFiles = new ArrayList<ComparableFileName>(); ArrayList<ComparableFileName> allBloomFilterFiles = new ArrayList<ComparableFileName>(); // Gather files from all IODeviceHandles. for (IODeviceHandle dev : ioManager.getIODevices()) { cleanupAndGetValidFilesInternal(dev, bloomFilterFilter, null, allBloomFilterFiles); HashSet<String> bloomFilterFilesSet = new HashSet<String>(); for (ComparableFileName cmpFileName : allBloomFilterFiles) { int index = cmpFileName.fileName.lastIndexOf(SPLIT_STRING); bloomFilterFilesSet.add(cmpFileName.fileName.substring(0, index)); } // List of valid BTree files that may or may not have a bloom filter buddy. Will check for buddies below. ArrayList<ComparableFileName> tmpAllBTreeFiles = new ArrayList<ComparableFileName>(); cleanupAndGetValidFilesInternal(dev, btreeFilter, btreeFactory, tmpAllBTreeFiles); // Look for buddy bloom filters for all valid BTrees. // If no buddy is found, delete the file, otherwise add the BTree to allBTreeFiles. for (ComparableFileName cmpFileName : tmpAllBTreeFiles) { int index = cmpFileName.fileName.lastIndexOf(SPLIT_STRING); String file = cmpFileName.fileName.substring(0, index); if (bloomFilterFilesSet.contains(file)) { allBTreeFiles.add(cmpFileName); } else { // Couldn't find the corresponding bloom filter file; thus, delete // the BTree file. File invalidBTreeFile = new File(cmpFileName.fullPath); invalidBTreeFile.delete(); } } } // Sanity check. if (allBTreeFiles.size() != allBloomFilterFiles.size()) { throw new HyracksDataException( "Unequal number of valid BTree and bloom filter files found. Aborting cleanup."); } // Trivial cases. if (allBTreeFiles.isEmpty() || allBloomFilterFiles.isEmpty()) { return validFiles; } if (allBTreeFiles.size() == 1 && allBloomFilterFiles.size() == 1) { validFiles.add(new LSMComponentFileReferences(allBTreeFiles.get(0).fileRef, null, allBloomFilterFiles .get(0).fileRef)); return validFiles; } // Sorts files names from earliest to latest timestamp. Collections.sort(allBTreeFiles); Collections.sort(allBloomFilterFiles); List<ComparableFileName> validComparableBTreeFiles = new ArrayList<ComparableFileName>(); ComparableFileName lastBTree = allBTreeFiles.get(0); validComparableBTreeFiles.add(lastBTree); List<ComparableFileName> validComparableBloomFilterFiles = new ArrayList<ComparableFileName>(); ComparableFileName lastBloomFilter = allBloomFilterFiles.get(0); validComparableBloomFilterFiles.add(lastBloomFilter); for (int i = 1; i < allBTreeFiles.size(); i++) { ComparableFileName currentBTree = allBTreeFiles.get(i); ComparableFileName currentBloomFilter = allBloomFilterFiles.get(i); // Current start timestamp is greater than last stop timestamp. if (currentBTree.interval[0].compareTo(lastBTree.interval[1]) > 0 && currentBloomFilter.interval[0].compareTo(lastBloomFilter.interval[1]) > 0) { validComparableBTreeFiles.add(currentBTree); validComparableBloomFilterFiles.add(currentBloomFilter); lastBTree = currentBTree; lastBloomFilter = currentBloomFilter; } else if (currentBTree.interval[0].compareTo(lastBTree.interval[0]) >= 0 && currentBTree.interval[1].compareTo(lastBTree.interval[1]) <= 0 && currentBloomFilter.interval[0].compareTo(lastBloomFilter.interval[0]) >= 0 && currentBloomFilter.interval[1].compareTo(lastBloomFilter.interval[1]) <= 0) { // Invalid files are completely contained in last interval. File invalidBTreeFile = new File(currentBTree.fullPath); invalidBTreeFile.delete(); File invalidBloomFilterFile = new File(currentBloomFilter.fullPath); invalidBloomFilterFile.delete(); } else { // This scenario should not be possible. throw new HyracksDataException("Found LSM files with overlapping but not contained timetamp intervals."); } } // Sort valid files in reverse lexicographical order, such that newer // files come first. Collections.sort(validComparableBTreeFiles, recencyCmp); Collections.sort(validComparableBloomFilterFiles, recencyCmp); Iterator<ComparableFileName> btreeFileIter = validComparableBTreeFiles.iterator(); Iterator<ComparableFileName> bloomFilterFileIter = validComparableBloomFilterFiles.iterator(); while (btreeFileIter.hasNext() && bloomFilterFileIter.hasNext()) { ComparableFileName cmpBTreeFileName = btreeFileIter.next(); ComparableFileName cmpBloomFilterFileName = bloomFilterFileIter.next(); validFiles.add(new LSMComponentFileReferences(cmpBTreeFileName.fileRef, null, cmpBloomFilterFileName.fileRef)); } return validFiles; }
diff --git a/src/com/yahoo/platform/yui/compressor/JavaScriptCompressor.java b/src/com/yahoo/platform/yui/compressor/JavaScriptCompressor.java index f398898..5906cd2 100644 --- a/src/com/yahoo/platform/yui/compressor/JavaScriptCompressor.java +++ b/src/com/yahoo/platform/yui/compressor/JavaScriptCompressor.java @@ -1,1297 +1,1297 @@ /* * YUI Compressor * Author: Julien Lecomte <[email protected]> * Copyright (c) 2007, Yahoo! Inc. All rights reserved. * Code licensed under the BSD License: * http://developer.yahoo.net/yui/license.txt */ package com.yahoo.platform.yui.compressor; import org.mozilla.javascript.*; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.*; import java.util.regex.Pattern; import java.util.regex.Matcher; public class JavaScriptCompressor { static final ArrayList ones; static final ArrayList twos; static final ArrayList threes; static final Set builtin = new HashSet(); static final Map literals = new Hashtable(); static final Set reserved = new HashSet(); static { // This list contains all the 3 characters or less built-in global // symbols available in a browser. Please add to this list if you // see anything missing. builtin.add("NaN"); builtin.add("top"); ones = new ArrayList(); for (char c = 'A'; c <= 'Z'; c++) ones.add(Character.toString(c)); for (char c = 'a'; c <= 'z'; c++) ones.add(Character.toString(c)); twos = new ArrayList(); for (int i = 0; i < ones.size(); i++) { String one = (String) ones.get(i); for (char c = 'A'; c <= 'Z'; c++) twos.add(one + Character.toString(c)); for (char c = 'a'; c <= 'z'; c++) twos.add(one + Character.toString(c)); for (char c = '0'; c <= '9'; c++) twos.add(one + Character.toString(c)); } // Remove two-letter JavaScript reserved words and built-in globals... twos.remove("as"); twos.remove("is"); twos.remove("do"); twos.remove("if"); twos.remove("in"); twos.removeAll(builtin); threes = new ArrayList(); for (int i = 0; i < twos.size(); i++) { String two = (String) twos.get(i); for (char c = 'A'; c <= 'Z'; c++) threes.add(two + Character.toString(c)); for (char c = 'a'; c <= 'z'; c++) threes.add(two + Character.toString(c)); for (char c = '0'; c <= '9'; c++) threes.add(two + Character.toString(c)); } // Remove three-letter JavaScript reserved words and built-in globals... threes.remove("for"); threes.remove("int"); threes.remove("new"); threes.remove("try"); threes.remove("use"); threes.remove("var"); threes.removeAll(builtin); // That's up to ((26+26)*(1+(26+26+10)))*(1+(26+26+10))-8 // (206,380 symbols per scope) // The following list comes from org/mozilla/javascript/Decompiler.java... literals.put(new Integer(Token.GET), "get "); literals.put(new Integer(Token.SET), "set "); literals.put(new Integer(Token.TRUE), "true"); literals.put(new Integer(Token.FALSE), "false"); literals.put(new Integer(Token.NULL), "null"); literals.put(new Integer(Token.THIS), "this"); literals.put(new Integer(Token.FUNCTION), "function "); literals.put(new Integer(Token.COMMA), ","); literals.put(new Integer(Token.LC), "{"); literals.put(new Integer(Token.RC), "}"); literals.put(new Integer(Token.LP), "("); literals.put(new Integer(Token.RP), ")"); literals.put(new Integer(Token.LB), "["); literals.put(new Integer(Token.RB), "]"); literals.put(new Integer(Token.DOT), "."); literals.put(new Integer(Token.NEW), "new "); literals.put(new Integer(Token.DELPROP), "delete "); literals.put(new Integer(Token.IF), "if"); literals.put(new Integer(Token.ELSE), "else"); literals.put(new Integer(Token.FOR), "for"); literals.put(new Integer(Token.IN), " in "); literals.put(new Integer(Token.WITH), "with"); literals.put(new Integer(Token.WHILE), "while"); literals.put(new Integer(Token.DO), "do"); literals.put(new Integer(Token.TRY), "try"); literals.put(new Integer(Token.CATCH), "catch"); literals.put(new Integer(Token.FINALLY), "finally"); literals.put(new Integer(Token.THROW), "throw "); literals.put(new Integer(Token.SWITCH), "switch"); literals.put(new Integer(Token.BREAK), "break "); literals.put(new Integer(Token.CONTINUE), "continue "); literals.put(new Integer(Token.CASE), "case "); literals.put(new Integer(Token.DEFAULT), "default"); literals.put(new Integer(Token.RETURN), "return "); literals.put(new Integer(Token.VAR), "var "); literals.put(new Integer(Token.SEMI), ";"); literals.put(new Integer(Token.ASSIGN), "="); literals.put(new Integer(Token.ASSIGN_ADD), "+="); literals.put(new Integer(Token.ASSIGN_SUB), "-="); literals.put(new Integer(Token.ASSIGN_MUL), "*="); literals.put(new Integer(Token.ASSIGN_DIV), "/="); literals.put(new Integer(Token.ASSIGN_MOD), "%="); literals.put(new Integer(Token.ASSIGN_BITOR), "|="); literals.put(new Integer(Token.ASSIGN_BITXOR), "^="); literals.put(new Integer(Token.ASSIGN_BITAND), "&="); literals.put(new Integer(Token.ASSIGN_LSH), "<<="); literals.put(new Integer(Token.ASSIGN_RSH), ">>="); literals.put(new Integer(Token.ASSIGN_URSH), ">>>="); literals.put(new Integer(Token.HOOK), "?"); literals.put(new Integer(Token.OBJECTLIT), ":"); literals.put(new Integer(Token.COLON), ":"); literals.put(new Integer(Token.OR), "||"); literals.put(new Integer(Token.AND), "&&"); literals.put(new Integer(Token.BITOR), "|"); literals.put(new Integer(Token.BITXOR), "^"); literals.put(new Integer(Token.BITAND), "&"); literals.put(new Integer(Token.SHEQ), "==="); literals.put(new Integer(Token.SHNE), "!=="); literals.put(new Integer(Token.EQ), "=="); literals.put(new Integer(Token.NE), "!="); literals.put(new Integer(Token.LE), "<="); literals.put(new Integer(Token.LT), "<"); literals.put(new Integer(Token.GE), ">="); literals.put(new Integer(Token.GT), ">"); literals.put(new Integer(Token.INSTANCEOF), " instanceof "); literals.put(new Integer(Token.LSH), "<<"); literals.put(new Integer(Token.RSH), ">>"); literals.put(new Integer(Token.URSH), ">>>"); literals.put(new Integer(Token.TYPEOF), "typeof "); literals.put(new Integer(Token.VOID), "void "); literals.put(new Integer(Token.CONST), "const "); literals.put(new Integer(Token.NOT), "!"); literals.put(new Integer(Token.BITNOT), "~"); literals.put(new Integer(Token.POS), "+"); literals.put(new Integer(Token.NEG), "-"); literals.put(new Integer(Token.INC), "++"); literals.put(new Integer(Token.DEC), "--"); literals.put(new Integer(Token.ADD), "+"); literals.put(new Integer(Token.SUB), "-"); literals.put(new Integer(Token.MUL), "*"); literals.put(new Integer(Token.DIV), "/"); literals.put(new Integer(Token.MOD), "%"); literals.put(new Integer(Token.COLONCOLON), "::"); literals.put(new Integer(Token.DOTDOT), ".."); literals.put(new Integer(Token.DOTQUERY), ".("); literals.put(new Integer(Token.XMLATTR), "@"); // See http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Reserved_Words // JavaScript 1.5 reserved words reserved.add("break"); reserved.add("case"); reserved.add("catch"); reserved.add("continue"); reserved.add("default"); reserved.add("delete"); reserved.add("do"); reserved.add("else"); reserved.add("finally"); reserved.add("for"); reserved.add("function"); reserved.add("if"); reserved.add("in"); reserved.add("instanceof"); reserved.add("new"); reserved.add("return"); reserved.add("switch"); reserved.add("this"); reserved.add("throw"); reserved.add("try"); reserved.add("typeof"); reserved.add("var"); reserved.add("void"); reserved.add("while"); reserved.add("with"); // Words reserved for future use reserved.add("abstract"); reserved.add("boolean"); reserved.add("byte"); reserved.add("char"); reserved.add("class"); reserved.add("const"); reserved.add("debugger"); reserved.add("double"); reserved.add("enum"); reserved.add("export"); reserved.add("extends"); reserved.add("final"); reserved.add("float"); reserved.add("goto"); reserved.add("implements"); reserved.add("import"); reserved.add("int"); reserved.add("interface"); reserved.add("long"); reserved.add("native"); reserved.add("package"); reserved.add("private"); reserved.add("protected"); reserved.add("public"); reserved.add("short"); reserved.add("static"); reserved.add("super"); reserved.add("synchronized"); reserved.add("throws"); reserved.add("transient"); reserved.add("volatile"); } private static int countChar(String haystack, char needle) { int idx = 0; int count = 0; int length = haystack.length(); while (idx < length) { char c = haystack.charAt(idx++); if (c == needle) { count++; } } return count; } private static int printSourceString(String source, int offset, StringBuffer sb) { int length = source.charAt(offset); ++offset; if ((0x8000 & length) != 0) { length = ((0x7FFF & length) << 16) | source.charAt(offset); ++offset; } if (sb != null) { String str = source.substring(offset, offset + length); sb.append(str); } return offset + length; } private static int printSourceNumber(String source, int offset, StringBuffer sb) { double number = 0.0; char type = source.charAt(offset); ++offset; if (type == 'S') { if (sb != null) { number = source.charAt(offset); } ++offset; } else if (type == 'J' || type == 'D') { if (sb != null) { long lbits; lbits = (long) source.charAt(offset) << 48; lbits |= (long) source.charAt(offset + 1) << 32; lbits |= (long) source.charAt(offset + 2) << 16; lbits |= (long) source.charAt(offset + 3); if (type == 'J') { number = lbits; } else { number = Double.longBitsToDouble(lbits); } } offset += 4; } else { // Bad source throw new RuntimeException(); } if (sb != null) { sb.append(ScriptRuntime.numberToString(number, 10)); } return offset; } private static ArrayList parse(Reader in, ErrorReporter reporter) throws IOException, EvaluatorException { CompilerEnvirons env = new CompilerEnvirons(); Parser parser = new Parser(env, reporter); parser.parse(in, null, 1); String source = parser.getEncodedSource(); int offset = 0; int length = source.length(); ArrayList tokens = new ArrayList(); StringBuffer sb = new StringBuffer(); while (offset < length) { int tt = source.charAt(offset++); switch (tt) { case Token.IECC: case Token.NAME: case Token.REGEXP: case Token.STRING: sb.setLength(0); offset = printSourceString(source, offset, sb); tokens.add(new JavaScriptToken(tt, sb.toString())); break; case Token.NUMBER: sb.setLength(0); offset = printSourceNumber(source, offset, sb); tokens.add(new JavaScriptToken(tt, sb.toString())); break; default: String literal = (String) literals.get(new Integer(tt)); if (literal != null) { tokens.add(new JavaScriptToken(tt, literal)); } break; } } return tokens; } private static void processStringLiterals(ArrayList tokens, boolean merge) { String tv; int i, length = tokens.size(); JavaScriptToken token, prevToken, nextToken; if (merge) { // Concatenate string literals that are being appended wherever // it is safe to do so. Note that we take care of the case: // "a" + "b".toUpperCase() for (i = 0; i < length; i++) { token = (JavaScriptToken) tokens.get(i); switch (token.getType()) { case Token.ADD: if (i > 0 && i < length) { prevToken = (JavaScriptToken) tokens.get(i - 1); nextToken = (JavaScriptToken) tokens.get(i + 1); if (prevToken.getType() == Token.STRING && nextToken.getType() == Token.STRING && (i == length - 1 || ((JavaScriptToken) tokens.get(i + 2)).getType() != Token.DOT)) { tokens.set(i - 1, new JavaScriptToken(Token.STRING, prevToken.getValue() + nextToken.getValue())); tokens.remove(i + 1); tokens.remove(i); i = i - 1; length = length - 2; break; } } } } } // Second pass... for (i = 0; i < length; i++) { token = (JavaScriptToken) tokens.get(i); if (token.getType() == Token.STRING) { tv = token.getValue(); // Finally, add the quoting characters and escape the string. We use // the quoting character that minimizes the amount of escaping to save // a few additional bytes. char quotechar; int singleQuoteCount = countChar(tv, '\''); int doubleQuoteCount = countChar(tv, '"'); if (doubleQuoteCount <= singleQuoteCount) { quotechar = '"'; } else { quotechar = '\''; } tv = quotechar + escapeString(tv, quotechar) + quotechar; // String concatenation transforms the old script scheme: // '<scr'+'ipt ...><'+'/script>' // into the following: // '<script ...></script>' // which breaks if this code is embedded inside an HTML document. // Since this is not the right way to do this, let's fix the code by // transforming all "</script" into "<\/script" if (tv.indexOf("</script") >= 0) { tv = tv.replaceAll("<\\/script", "<\\\\/script"); } tokens.set(i, new JavaScriptToken(Token.STRING, tv)); } } } // Add necessary escaping that was removed in Rhino's tokenizer. private static String escapeString(String s, char quotechar) { assert quotechar == '"' || quotechar == '\''; if (s == null) { return null; } StringBuffer sb = new StringBuffer(); for (int i = 0, L = s.length(); i < L; i++) { int c = s.charAt(i); if (c == quotechar) { sb.append("\\"); } sb.append((char) c); } return sb.toString(); } /* * Simple check to see whether a string is a valid identifier name. * If a string matches this pattern, it means it IS a valid * identifier name. If a string doesn't match it, it does not * necessarily mean it is not a valid identifier name. */ private static final Pattern SIMPLE_IDENTIFIER_NAME_PATTERN = Pattern.compile("^[a-zA-Z_][a-zA-Z0-9_]*$"); private static boolean isValidIdentifier(String s) { Matcher m = SIMPLE_IDENTIFIER_NAME_PATTERN.matcher(s); return (m.matches() && !reserved.contains(s)); } /* * Transforms obj["foo"] into obj.foo whenever possible, saving 3 bytes. */ private static void optimizeObjectMemberAccess(ArrayList tokens) { String tv; int i, length; JavaScriptToken token; for (i = 0, length = tokens.size(); i < length; i++) { if (((JavaScriptToken) tokens.get(i)).getType() == Token.LB && i > 0 && i < length - 2 && ((JavaScriptToken) tokens.get(i - 1)).getType() == Token.NAME && ((JavaScriptToken) tokens.get(i + 1)).getType() == Token.STRING && ((JavaScriptToken) tokens.get(i + 2)).getType() == Token.RB) { token = (JavaScriptToken) tokens.get(i + 1); tv = token.getValue(); tv = tv.substring(1, tv.length() - 1); if (isValidIdentifier(tv)) { tokens.set(i, new JavaScriptToken(Token.DOT, ".")); tokens.set(i + 1, new JavaScriptToken(Token.NAME, tv)); tokens.remove(i + 2); i = i + 2; length = length - 1; } } } } /* * Transforms 'foo': ... into foo: ... whenever possible, saving 2 bytes. */ private static void optimizeObjLitMemberDecl(ArrayList tokens) { String tv; int i, length; JavaScriptToken token; for (i = 0, length = tokens.size(); i < length; i++) { if (((JavaScriptToken) tokens.get(i)).getType() == Token.OBJECTLIT && i > 0 && ((JavaScriptToken) tokens.get(i - 1)).getType() == Token.STRING) { token = (JavaScriptToken) tokens.get(i - 1); tv = token.getValue(); tv = tv.substring(1, tv.length() - 1); if (isValidIdentifier(tv)) { tokens.set(i - 1, new JavaScriptToken(Token.NAME, tv)); } } } } private ErrorReporter logger; private boolean munge; private boolean verbose; private static final int BUILDING_SYMBOL_TREE = 1; private static final int CHECKING_SYMBOL_TREE = 2; private int mode; private int offset; private int braceNesting; private ArrayList tokens; private Stack scopes = new Stack(); private ScriptOrFnScope globalScope = new ScriptOrFnScope(-1, null); private Hashtable indexedScopes = new Hashtable(); public JavaScriptCompressor(Reader in, ErrorReporter reporter) throws IOException, EvaluatorException { this.logger = reporter; this.tokens = parse(in, reporter); } public void compress(Writer out, int linebreak, boolean munge, boolean verbose, boolean preserveAllSemiColons, boolean disableOptimizations) throws IOException { this.munge = munge; this.verbose = verbose; processStringLiterals(this.tokens, !disableOptimizations); if (!disableOptimizations) { optimizeObjectMemberAccess(this.tokens); optimizeObjLitMemberDecl(this.tokens); } buildSymbolTree(); mungeSymboltree(); StringBuffer sb = printSymbolTree(linebreak, preserveAllSemiColons); out.write(sb.toString()); } private ScriptOrFnScope getCurrentScope() { return (ScriptOrFnScope) scopes.peek(); } private void enterScope(ScriptOrFnScope scope) { scopes.push(scope); } private void leaveCurrentScope() { scopes.pop(); } private JavaScriptToken consumeToken() { return (JavaScriptToken) tokens.get(offset++); } private JavaScriptToken getToken(int delta) { return (JavaScriptToken) tokens.get(offset + delta); } /* * Returns the identifier for the specified symbol defined in * the specified scope or in any scope above it. Returns null * if this symbol does not have a corresponding identifier. */ private JavaScriptIdentifier getIdentifier(String symbol, ScriptOrFnScope scope) { JavaScriptIdentifier identifier; while (scope != null) { identifier = scope.getIdentifier(symbol); if (identifier != null) { return identifier; } scope = scope.getParentScope(); } return null; } /* * If either 'eval' or 'with' is used in a local scope, we must make * sure that all containing local scopes don't get munged. Otherwise, * the obfuscation would potentially introduce bugs. */ private void protectScopeFromObfuscation(ScriptOrFnScope scope) { assert scope != null; if (scope == globalScope) { // The global scope does not get obfuscated, // so we don't need to worry about it... return; } // Find the highest local scope containing the specified scope. while (scope.getParentScope() != globalScope) { scope = scope.getParentScope(); } assert scope.getParentScope() == globalScope; scope.preventMunging(); } private String getDebugString(int max) { assert max > 0; StringBuffer result = new StringBuffer(); int start = Math.max(offset - max, 0); int end = Math.min(offset + max, tokens.size()); for (int i = start; i < end; i++) { JavaScriptToken token = (JavaScriptToken) tokens.get(i); if (i == offset - 1) { result.append(" ---> "); } result.append(token.getValue()); if (i == offset - 1) { result.append(" <--- "); } } return result.toString(); } private void warn(String message, boolean showDebugString) { if (verbose) { if (showDebugString) { message = message + "\n" + getDebugString(10); } logger.warning(message, null, -1, null, -1); } } private void parseFunctionDeclaration() { String symbol; JavaScriptToken token; ScriptOrFnScope currentScope, fnScope; JavaScriptIdentifier identifier; currentScope = getCurrentScope(); token = consumeToken(); if (token.getType() == Token.NAME) { if (mode == BUILDING_SYMBOL_TREE) { // Get the name of the function and declare it in the current scope. symbol = token.getValue(); if (currentScope.getIdentifier(symbol) != null) { warn("The function " + symbol + " has already been declared in the same scope...", true); } currentScope.declareIdentifier(symbol); } token = consumeToken(); } assert token.getType() == Token.LP; if (mode == BUILDING_SYMBOL_TREE) { fnScope = new ScriptOrFnScope(braceNesting, currentScope); indexedScopes.put(new Integer(offset), fnScope); } else { fnScope = (ScriptOrFnScope) indexedScopes.get(new Integer(offset)); } // Parse function arguments. int argpos = 0; while ((token = consumeToken()).getType() != Token.RP) { assert token.getType() == Token.NAME || token.getType() == Token.COMMA; if (token.getType() == Token.NAME && mode == BUILDING_SYMBOL_TREE) { symbol = token.getValue(); identifier = fnScope.declareIdentifier(symbol); if (symbol.equals("$super") && argpos == 0) { // Exception for Prototype 1.6... identifier.preventMunging(); } argpos++; } } token = consumeToken(); assert token.getType() == Token.LC; braceNesting++; token = getToken(0); if (token.getType() == Token.STRING && getToken(1).getType() == Token.SEMI) { // This is a hint. Hints are empty statements that look like // "localvar1:nomunge, localvar2:nomunge"; They allow developers // to prevent specific symbols from getting obfuscated (some heretic // implementations, such as Prototype 1.6, require specific variable // names, such as $super for example, in order to work appropriately. // Note: right now, only "nomunge" is supported in the right hand side // of a hint. However, in the future, the right hand side may contain // other values. consumeToken(); String hints = token.getValue(); // Remove the leading and trailing quotes... hints = hints.substring(1, hints.length() - 1).trim(); StringTokenizer st1 = new StringTokenizer(hints, ","); while (st1.hasMoreTokens()) { String hint = st1.nextToken(); int idx = hint.indexOf(':'); if (idx <= 0 || idx >= hint.length() - 1) { if (mode == BUILDING_SYMBOL_TREE) { // No need to report the error twice, hence the test... warn("Invalid hint syntax: " + hint, true); } break; } String variableName = hint.substring(0, idx).trim(); String variableType = hint.substring(idx + 1).trim(); if (mode == BUILDING_SYMBOL_TREE) { fnScope.addHint(variableName, variableType); } else if (mode == CHECKING_SYMBOL_TREE) { identifier = fnScope.getIdentifier(variableName); if (identifier != null) { if (variableType.equals("nomunge")) { identifier.preventMunging(); } else { warn("Unsupported hint value: " + hint, true); } } else { warn("Hint refers to an unknown identifier: " + hint, true); } } } } parseScope(fnScope); } private void parseCatch() { String symbol; JavaScriptToken token; ScriptOrFnScope currentScope; JavaScriptIdentifier identifier; token = getToken(-1); assert token.getType() == Token.CATCH; token = consumeToken(); assert token.getType() == Token.LP; token = consumeToken(); assert token.getType() == Token.NAME; symbol = token.getValue(); currentScope = getCurrentScope(); if (mode == BUILDING_SYMBOL_TREE) { // We must declare the exception identifier in the containing function // scope to avoid errors related to the obfuscation process. No need to // display a warning if the symbol was already declared here... currentScope.declareIdentifier(symbol); } else { identifier = getIdentifier(symbol, currentScope); identifier.incrementRefcount(); } token = consumeToken(); assert token.getType() == Token.RP; } private void parseExpression() { // Parse the expression until we encounter a comma or a semi-colon // in the same brace nesting, bracket nesting and paren nesting. // Parse functions if any... String symbol; JavaScriptToken token; ScriptOrFnScope currentScope; JavaScriptIdentifier identifier; int expressionBraceNesting = braceNesting; int bracketNesting = 0; int parensNesting = 0; int length = tokens.size(); while (offset < length) { token = consumeToken(); currentScope = getCurrentScope(); switch (token.getType()) { case Token.SEMI: case Token.COMMA: if (braceNesting == expressionBraceNesting && bracketNesting == 0 && parensNesting == 0) { return; } break; case Token.FUNCTION: parseFunctionDeclaration(); break; case Token.LC: braceNesting++; break; case Token.RC: braceNesting--; assert braceNesting >= expressionBraceNesting; break; case Token.LB: bracketNesting++; break; case Token.RB: bracketNesting--; break; case Token.LP: parensNesting++; break; case Token.RP: parensNesting--; break; case Token.IECC: if (mode == BUILDING_SYMBOL_TREE) { protectScopeFromObfuscation(currentScope); warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression!" : ""), true); } break; case Token.NAME: symbol = token.getValue(); if (mode == BUILDING_SYMBOL_TREE) { if (symbol.equals("eval")) { protectScopeFromObfuscation(currentScope); warn("Using 'eval' is not recommended." + (munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true); } } else if (mode == CHECKING_SYMBOL_TREE) { if ((offset < 2 || (getToken(-2).getType() != Token.DOT && getToken(-2).getType() != Token.GET && getToken(-2).getType() != Token.SET)) && getToken(0).getType() != Token.OBJECTLIT) { identifier = getIdentifier(symbol, currentScope); if (identifier == null) { if (symbol.length() <= 3 && !builtin.contains(symbol)) { // Here, we found an undeclared and un-namespaced symbol that is // 3 characters or less in length. Declare it in the global scope. // We don't need to declare longer symbols since they won't cause // any conflict with other munged symbols. globalScope.declareIdentifier(symbol); warn("Found an undeclared symbol: " + symbol, true); } } else { identifier.incrementRefcount(); } } } break; } } } private void parseScope(ScriptOrFnScope scope) { String symbol; JavaScriptToken token; JavaScriptIdentifier identifier; int length = tokens.size(); enterScope(scope); while (offset < length) { token = consumeToken(); switch (token.getType()) { case Token.VAR: case Token.CONST: // The var keyword is followed by at least one symbol name. // If several symbols follow, they are comma separated. for (; ;) { token = consumeToken(); assert token.getType() == Token.NAME; if (mode == BUILDING_SYMBOL_TREE) { symbol = token.getValue(); if (scope.getIdentifier(symbol) == null) { scope.declareIdentifier(symbol); } else { warn("The variable " + symbol + " has already been declared in the same scope...", true); } } token = getToken(0); assert token.getType() == Token.SEMI || token.getType() == Token.ASSIGN || token.getType() == Token.COMMA || token.getType() == Token.IN; if (token.getType() == Token.IN) { break; } else { parseExpression(); token = getToken(-1); if (token.getType() == Token.SEMI) { break; } } } break; case Token.FUNCTION: parseFunctionDeclaration(); break; case Token.LC: braceNesting++; break; case Token.RC: braceNesting--; assert braceNesting >= scope.getBraceNesting(); if (braceNesting == scope.getBraceNesting()) { leaveCurrentScope(); return; } break; case Token.WITH: if (mode == BUILDING_SYMBOL_TREE) { // Inside a 'with' block, it is impossible to figure out // statically whether a symbol is a local variable or an // object member. As a consequence, the only thing we can // do is turn the obfuscation off for the highest scope // containing the 'with' block. protectScopeFromObfuscation(scope); warn("Using 'with' is not recommended." + (munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true); } break; case Token.CATCH: parseCatch(); break; case Token.IECC: if (mode == BUILDING_SYMBOL_TREE) { protectScopeFromObfuscation(scope); warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true); } break; case Token.NAME: symbol = token.getValue(); if (mode == BUILDING_SYMBOL_TREE) { if (symbol.equals("eval")) { protectScopeFromObfuscation(scope); warn("Using 'eval' is not recommended." + (munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true); } } else if (mode == CHECKING_SYMBOL_TREE) { if ((offset < 2 || getToken(-2).getType() != Token.DOT) && getToken(0).getType() != Token.OBJECTLIT) { identifier = getIdentifier(symbol, scope); if (identifier == null) { if (symbol.length() <= 3 && !builtin.contains(symbol)) { // Here, we found an undeclared and un-namespaced symbol that is // 3 characters or less in length. Declare it in the global scope. // We don't need to declare longer symbols since they won't cause // any conflict with other munged symbols. globalScope.declareIdentifier(symbol); warn("Found an undeclared symbol: " + symbol, true); } } else { identifier.incrementRefcount(); } } } break; } } } private void buildSymbolTree() { offset = 0; braceNesting = 0; scopes.clear(); indexedScopes.clear(); indexedScopes.put(new Integer(0), globalScope); mode = BUILDING_SYMBOL_TREE; parseScope(globalScope); } private void mungeSymboltree() { if (!munge) { return; } // One problem with obfuscation resides in the use of undeclared // and un-namespaced global symbols that are 3 characters or less // in length. Here is an example: // // var declaredGlobalVar; // // function declaredGlobalFn() { // var localvar; // localvar = abc; // abc is an undeclared global symbol // } // // In the example above, there is a slim chance that localvar may be // munged to 'abc', conflicting with the undeclared global symbol // abc, creating a potential bug. The following code detects such // global symbols. This must be done AFTER the entire file has been // parsed, and BEFORE munging the symbol tree. Note that declaring // extra symbols in the global scope won't hurt. // // Note: Since we go through all the tokens to do this, we also use // the opportunity to count how many times each identifier is used. offset = 0; braceNesting = 0; scopes.clear(); mode = CHECKING_SYMBOL_TREE; parseScope(globalScope); globalScope.munge(); } private StringBuffer printSymbolTree(int linebreakpos, boolean preserveAllSemiColons) throws IOException { offset = 0; braceNesting = 0; scopes.clear(); String symbol; JavaScriptToken token; ScriptOrFnScope currentScope; JavaScriptIdentifier identifier; int length = tokens.size(); StringBuffer result = new StringBuffer(); int linestartpos = 0; enterScope(globalScope); while (offset < length) { token = consumeToken(); symbol = token.getValue(); currentScope = getCurrentScope(); switch (token.getType()) { case Token.NAME: if (offset >= 2 && getToken(-2).getType() == Token.DOT || getToken(0).getType() == Token.OBJECTLIT) { result.append(symbol); } else { identifier = getIdentifier(symbol, currentScope); if (identifier != null) { if (identifier.getMungedValue() != null) { result.append(identifier.getMungedValue()); } else { result.append(symbol); } if (currentScope != globalScope && identifier.getRefcount() == 0) { warn("The symbol " + symbol + " is declared but is apparently never used.\nThis code can probably be written in a more efficient way.", true); } } else { result.append(symbol); } } break; case Token.REGEXP: case Token.NUMBER: case Token.STRING: result.append(symbol); break; case Token.ADD: case Token.SUB: result.append((String) literals.get(new Integer(token.getType()))); if (offset < length) { token = getToken(0); if (token.getType() == Token.INC || token.getType() == Token.DEC || token.getType() == Token.ADD || token.getType() == Token.DEC) { // Handle the case x +/- ++/-- y // We must keep a white space here. Otherwise, x +++ y would be // interpreted as x ++ + y by the compiler, which is a bug (due // to the implicit assignment being done on the wrong variable) result.append(' '); } else if (token.getType() == Token.POS && getToken(-1).getType() == Token.ADD || token.getType() == Token.NEG && getToken(-1).getType() == Token.SUB) { // Handle the case x + + y and x - - y result.append(' '); } } break; case Token.FUNCTION: result.append("function"); token = consumeToken(); if (token.getType() == Token.NAME) { result.append(' '); symbol = token.getValue(); identifier = getIdentifier(symbol, currentScope); assert identifier != null; if (identifier.getMungedValue() != null) { result.append(identifier.getMungedValue()); } else { result.append(symbol); } if (currentScope != globalScope && identifier.getRefcount() == 0) { warn("The symbol " + symbol + " is declared but is apparently never used.\nThis code can probably be written in a more efficient way.", true); } token = consumeToken(); } assert token.getType() == Token.LP; result.append('('); currentScope = (ScriptOrFnScope) indexedScopes.get(new Integer(offset)); enterScope(currentScope); while ((token = consumeToken()).getType() != Token.RP) { assert token.getType() == Token.NAME || token.getType() == Token.COMMA; if (token.getType() == Token.NAME) { symbol = token.getValue(); identifier = getIdentifier(symbol, currentScope); assert identifier != null; if (identifier.getMungedValue() != null) { result.append(identifier.getMungedValue()); } else { result.append(symbol); } } else if (token.getType() == Token.COMMA) { result.append(','); } } result.append(')'); token = consumeToken(); assert token.getType() == Token.LC; result.append('{'); braceNesting++; token = getToken(0); if (token.getType() == Token.STRING) { // This is a hint. Skip it! consumeToken(); token = getToken(0); assert token.getType() == Token.SEMI; consumeToken(); } break; case Token.RETURN: result.append("return"); // No space needed after 'return' when followed // by '(', '[', '{', a string or a regexp. if (offset < length) { token = getToken(0); if (token.getType() != Token.LP && token.getType() != Token.LB && token.getType() != Token.LC && token.getType() != Token.STRING && token.getType() != Token.REGEXP) { result.append(' '); } } break; case Token.CASE: result.append("case"); // White-space needed after 'case' when not followed by a string. if (offset < length && getToken(0).getType() != Token.STRING) { result.append(' '); } break; case Token.THROW: // White-space needed after 'throw' when not followed by a string. result.append("throw"); if (offset < length && getToken(0).getType() != Token.STRING) { result.append(' '); } break; case Token.BREAK: result.append("break"); if (offset < length && getToken(0).getType() != Token.SEMI) { // If 'break' is not followed by a semi-colon, it must be // followed by a label, hence the need for a white space. result.append(' '); } break; case Token.CONTINUE: result.append("continue"); if (offset < length && getToken(0).getType() != Token.SEMI) { // If 'continue' is not followed by a semi-colon, it must be // followed by a label, hence the need for a white space. result.append(' '); } break; case Token.LC: result.append('{'); braceNesting++; break; case Token.RC: result.append('}'); braceNesting--; assert braceNesting >= currentScope.getBraceNesting(); if (braceNesting == currentScope.getBraceNesting()) { leaveCurrentScope(); } break; case Token.SEMI: // No need to output a semi-colon if the next character is a right-curly... if (preserveAllSemiColons || offset < length && getToken(0).getType() != Token.RC) { result.append(';'); } if (linebreakpos >= 0 && result.length() - linestartpos > linebreakpos) { // Some source control tools don't like it when files containing lines longer // than, say 8000 characters, are checked in. The linebreak option is used in // that case to split long lines after a specific column. result.append('\n'); linestartpos = result.length(); } break; case Token.IECC: result.append("/*"); result.append(symbol); result.append("*/"); break; default: String literal = (String) literals.get(new Integer(token.getType())); if (literal != null) { result.append(literal); } else { warn("This symbol cannot be printed: " + symbol, true); } break; } } // Append a semi-colon at the end, even if unnecessary semi-colons are // supposed to be removed. This is especially useful when concatenating // several minified files (the absence of an ending semi-colon at the // end of one file may very likely cause a syntax error) - if (!preserveAllSemiColons) { + if (!preserveAllSemiColons && result.length() > 0) { if (result.charAt(result.length() - 1) == '\n') { result.setCharAt(result.length() - 1, ';'); } else { result.append(';'); } } return result; } }
true
true
private StringBuffer printSymbolTree(int linebreakpos, boolean preserveAllSemiColons) throws IOException { offset = 0; braceNesting = 0; scopes.clear(); String symbol; JavaScriptToken token; ScriptOrFnScope currentScope; JavaScriptIdentifier identifier; int length = tokens.size(); StringBuffer result = new StringBuffer(); int linestartpos = 0; enterScope(globalScope); while (offset < length) { token = consumeToken(); symbol = token.getValue(); currentScope = getCurrentScope(); switch (token.getType()) { case Token.NAME: if (offset >= 2 && getToken(-2).getType() == Token.DOT || getToken(0).getType() == Token.OBJECTLIT) { result.append(symbol); } else { identifier = getIdentifier(symbol, currentScope); if (identifier != null) { if (identifier.getMungedValue() != null) { result.append(identifier.getMungedValue()); } else { result.append(symbol); } if (currentScope != globalScope && identifier.getRefcount() == 0) { warn("The symbol " + symbol + " is declared but is apparently never used.\nThis code can probably be written in a more efficient way.", true); } } else { result.append(symbol); } } break; case Token.REGEXP: case Token.NUMBER: case Token.STRING: result.append(symbol); break; case Token.ADD: case Token.SUB: result.append((String) literals.get(new Integer(token.getType()))); if (offset < length) { token = getToken(0); if (token.getType() == Token.INC || token.getType() == Token.DEC || token.getType() == Token.ADD || token.getType() == Token.DEC) { // Handle the case x +/- ++/-- y // We must keep a white space here. Otherwise, x +++ y would be // interpreted as x ++ + y by the compiler, which is a bug (due // to the implicit assignment being done on the wrong variable) result.append(' '); } else if (token.getType() == Token.POS && getToken(-1).getType() == Token.ADD || token.getType() == Token.NEG && getToken(-1).getType() == Token.SUB) { // Handle the case x + + y and x - - y result.append(' '); } } break; case Token.FUNCTION: result.append("function"); token = consumeToken(); if (token.getType() == Token.NAME) { result.append(' '); symbol = token.getValue(); identifier = getIdentifier(symbol, currentScope); assert identifier != null; if (identifier.getMungedValue() != null) { result.append(identifier.getMungedValue()); } else { result.append(symbol); } if (currentScope != globalScope && identifier.getRefcount() == 0) { warn("The symbol " + symbol + " is declared but is apparently never used.\nThis code can probably be written in a more efficient way.", true); } token = consumeToken(); } assert token.getType() == Token.LP; result.append('('); currentScope = (ScriptOrFnScope) indexedScopes.get(new Integer(offset)); enterScope(currentScope); while ((token = consumeToken()).getType() != Token.RP) { assert token.getType() == Token.NAME || token.getType() == Token.COMMA; if (token.getType() == Token.NAME) { symbol = token.getValue(); identifier = getIdentifier(symbol, currentScope); assert identifier != null; if (identifier.getMungedValue() != null) { result.append(identifier.getMungedValue()); } else { result.append(symbol); } } else if (token.getType() == Token.COMMA) { result.append(','); } } result.append(')'); token = consumeToken(); assert token.getType() == Token.LC; result.append('{'); braceNesting++; token = getToken(0); if (token.getType() == Token.STRING) { // This is a hint. Skip it! consumeToken(); token = getToken(0); assert token.getType() == Token.SEMI; consumeToken(); } break; case Token.RETURN: result.append("return"); // No space needed after 'return' when followed // by '(', '[', '{', a string or a regexp. if (offset < length) { token = getToken(0); if (token.getType() != Token.LP && token.getType() != Token.LB && token.getType() != Token.LC && token.getType() != Token.STRING && token.getType() != Token.REGEXP) { result.append(' '); } } break; case Token.CASE: result.append("case"); // White-space needed after 'case' when not followed by a string. if (offset < length && getToken(0).getType() != Token.STRING) { result.append(' '); } break; case Token.THROW: // White-space needed after 'throw' when not followed by a string. result.append("throw"); if (offset < length && getToken(0).getType() != Token.STRING) { result.append(' '); } break; case Token.BREAK: result.append("break"); if (offset < length && getToken(0).getType() != Token.SEMI) { // If 'break' is not followed by a semi-colon, it must be // followed by a label, hence the need for a white space. result.append(' '); } break; case Token.CONTINUE: result.append("continue"); if (offset < length && getToken(0).getType() != Token.SEMI) { // If 'continue' is not followed by a semi-colon, it must be // followed by a label, hence the need for a white space. result.append(' '); } break; case Token.LC: result.append('{'); braceNesting++; break; case Token.RC: result.append('}'); braceNesting--; assert braceNesting >= currentScope.getBraceNesting(); if (braceNesting == currentScope.getBraceNesting()) { leaveCurrentScope(); } break; case Token.SEMI: // No need to output a semi-colon if the next character is a right-curly... if (preserveAllSemiColons || offset < length && getToken(0).getType() != Token.RC) { result.append(';'); } if (linebreakpos >= 0 && result.length() - linestartpos > linebreakpos) { // Some source control tools don't like it when files containing lines longer // than, say 8000 characters, are checked in. The linebreak option is used in // that case to split long lines after a specific column. result.append('\n'); linestartpos = result.length(); } break; case Token.IECC: result.append("/*"); result.append(symbol); result.append("*/"); break; default: String literal = (String) literals.get(new Integer(token.getType())); if (literal != null) { result.append(literal); } else { warn("This symbol cannot be printed: " + symbol, true); } break; } } // Append a semi-colon at the end, even if unnecessary semi-colons are // supposed to be removed. This is especially useful when concatenating // several minified files (the absence of an ending semi-colon at the // end of one file may very likely cause a syntax error) if (!preserveAllSemiColons) { if (result.charAt(result.length() - 1) == '\n') { result.setCharAt(result.length() - 1, ';'); } else { result.append(';'); } } return result; }
private StringBuffer printSymbolTree(int linebreakpos, boolean preserveAllSemiColons) throws IOException { offset = 0; braceNesting = 0; scopes.clear(); String symbol; JavaScriptToken token; ScriptOrFnScope currentScope; JavaScriptIdentifier identifier; int length = tokens.size(); StringBuffer result = new StringBuffer(); int linestartpos = 0; enterScope(globalScope); while (offset < length) { token = consumeToken(); symbol = token.getValue(); currentScope = getCurrentScope(); switch (token.getType()) { case Token.NAME: if (offset >= 2 && getToken(-2).getType() == Token.DOT || getToken(0).getType() == Token.OBJECTLIT) { result.append(symbol); } else { identifier = getIdentifier(symbol, currentScope); if (identifier != null) { if (identifier.getMungedValue() != null) { result.append(identifier.getMungedValue()); } else { result.append(symbol); } if (currentScope != globalScope && identifier.getRefcount() == 0) { warn("The symbol " + symbol + " is declared but is apparently never used.\nThis code can probably be written in a more efficient way.", true); } } else { result.append(symbol); } } break; case Token.REGEXP: case Token.NUMBER: case Token.STRING: result.append(symbol); break; case Token.ADD: case Token.SUB: result.append((String) literals.get(new Integer(token.getType()))); if (offset < length) { token = getToken(0); if (token.getType() == Token.INC || token.getType() == Token.DEC || token.getType() == Token.ADD || token.getType() == Token.DEC) { // Handle the case x +/- ++/-- y // We must keep a white space here. Otherwise, x +++ y would be // interpreted as x ++ + y by the compiler, which is a bug (due // to the implicit assignment being done on the wrong variable) result.append(' '); } else if (token.getType() == Token.POS && getToken(-1).getType() == Token.ADD || token.getType() == Token.NEG && getToken(-1).getType() == Token.SUB) { // Handle the case x + + y and x - - y result.append(' '); } } break; case Token.FUNCTION: result.append("function"); token = consumeToken(); if (token.getType() == Token.NAME) { result.append(' '); symbol = token.getValue(); identifier = getIdentifier(symbol, currentScope); assert identifier != null; if (identifier.getMungedValue() != null) { result.append(identifier.getMungedValue()); } else { result.append(symbol); } if (currentScope != globalScope && identifier.getRefcount() == 0) { warn("The symbol " + symbol + " is declared but is apparently never used.\nThis code can probably be written in a more efficient way.", true); } token = consumeToken(); } assert token.getType() == Token.LP; result.append('('); currentScope = (ScriptOrFnScope) indexedScopes.get(new Integer(offset)); enterScope(currentScope); while ((token = consumeToken()).getType() != Token.RP) { assert token.getType() == Token.NAME || token.getType() == Token.COMMA; if (token.getType() == Token.NAME) { symbol = token.getValue(); identifier = getIdentifier(symbol, currentScope); assert identifier != null; if (identifier.getMungedValue() != null) { result.append(identifier.getMungedValue()); } else { result.append(symbol); } } else if (token.getType() == Token.COMMA) { result.append(','); } } result.append(')'); token = consumeToken(); assert token.getType() == Token.LC; result.append('{'); braceNesting++; token = getToken(0); if (token.getType() == Token.STRING) { // This is a hint. Skip it! consumeToken(); token = getToken(0); assert token.getType() == Token.SEMI; consumeToken(); } break; case Token.RETURN: result.append("return"); // No space needed after 'return' when followed // by '(', '[', '{', a string or a regexp. if (offset < length) { token = getToken(0); if (token.getType() != Token.LP && token.getType() != Token.LB && token.getType() != Token.LC && token.getType() != Token.STRING && token.getType() != Token.REGEXP) { result.append(' '); } } break; case Token.CASE: result.append("case"); // White-space needed after 'case' when not followed by a string. if (offset < length && getToken(0).getType() != Token.STRING) { result.append(' '); } break; case Token.THROW: // White-space needed after 'throw' when not followed by a string. result.append("throw"); if (offset < length && getToken(0).getType() != Token.STRING) { result.append(' '); } break; case Token.BREAK: result.append("break"); if (offset < length && getToken(0).getType() != Token.SEMI) { // If 'break' is not followed by a semi-colon, it must be // followed by a label, hence the need for a white space. result.append(' '); } break; case Token.CONTINUE: result.append("continue"); if (offset < length && getToken(0).getType() != Token.SEMI) { // If 'continue' is not followed by a semi-colon, it must be // followed by a label, hence the need for a white space. result.append(' '); } break; case Token.LC: result.append('{'); braceNesting++; break; case Token.RC: result.append('}'); braceNesting--; assert braceNesting >= currentScope.getBraceNesting(); if (braceNesting == currentScope.getBraceNesting()) { leaveCurrentScope(); } break; case Token.SEMI: // No need to output a semi-colon if the next character is a right-curly... if (preserveAllSemiColons || offset < length && getToken(0).getType() != Token.RC) { result.append(';'); } if (linebreakpos >= 0 && result.length() - linestartpos > linebreakpos) { // Some source control tools don't like it when files containing lines longer // than, say 8000 characters, are checked in. The linebreak option is used in // that case to split long lines after a specific column. result.append('\n'); linestartpos = result.length(); } break; case Token.IECC: result.append("/*"); result.append(symbol); result.append("*/"); break; default: String literal = (String) literals.get(new Integer(token.getType())); if (literal != null) { result.append(literal); } else { warn("This symbol cannot be printed: " + symbol, true); } break; } } // Append a semi-colon at the end, even if unnecessary semi-colons are // supposed to be removed. This is especially useful when concatenating // several minified files (the absence of an ending semi-colon at the // end of one file may very likely cause a syntax error) if (!preserveAllSemiColons && result.length() > 0) { if (result.charAt(result.length() - 1) == '\n') { result.setCharAt(result.length() - 1, ';'); } else { result.append(';'); } } return result; }
diff --git a/src/checkstyle/com/puppycrawl/tools/checkstyle/Checker.java b/src/checkstyle/com/puppycrawl/tools/checkstyle/Checker.java index 0cf386ae3..79ccf235f 100644 --- a/src/checkstyle/com/puppycrawl/tools/checkstyle/Checker.java +++ b/src/checkstyle/com/puppycrawl/tools/checkstyle/Checker.java @@ -1,341 +1,342 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2002 Oliver Burn // // This library 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 library 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 library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.Locale; import com.puppycrawl.tools.checkstyle.api.AutomaticBean; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.Configuration; import com.puppycrawl.tools.checkstyle.api.Context; import com.puppycrawl.tools.checkstyle.api.FileSetCheck; import com.puppycrawl.tools.checkstyle.api.LocalizedMessage; import com.puppycrawl.tools.checkstyle.api.MessageDispatcher; /** * This class provides the functionality to check a set of files. * @author <a href="mailto:[email protected]">Oliver Burn</a> * @author <a href="mailto:[email protected]">Stephane Bailliez</a> * @author lkuehne */ public class Checker extends AutomaticBean implements MessageDispatcher { /** * An AuditListener that maintains the number of errors. */ private class ErrorCounter implements AuditListener { /** keeps track of the number of errors */ private int mCount = 0; /** @see AuditListener */ public void addError(AuditEvent aEvt) { mCount++; } /** @see AuditListener */ public void addException(AuditEvent aEvt, Throwable aThrowable) { mCount++; } /** @see AuditListener */ public void auditStarted(AuditEvent aEvt) { mCount = 0; } /** @see AuditListener */ public void fileStarted(AuditEvent aEvt) { } /** @see AuditListener */ public void auditFinished(AuditEvent aEvt) { } /** @see AuditListener */ public void fileFinished(AuditEvent aEvt) { } /** * @return the number of errors since audit started. */ private int getCount() { return mCount; } } /** maintains error count */ private final ErrorCounter mCounter = new ErrorCounter(); /** vector of listeners */ private final ArrayList mListeners = new ArrayList(); /** vector of fileset checks */ private final ArrayList mFileSetChecks = new ArrayList(); /** class loader to resolve classes with. **/ private ClassLoader mLoader = Thread.currentThread().getContextClassLoader(); /** the basedir to strip off in filenames */ private String mBasedir; /** locale country to report messages **/ private String mLocaleCountry = Locale.getDefault().getCountry(); /** locale language to report messages **/ private String mLocaleLanguage = Locale.getDefault().getLanguage(); /** The factory for instantiating submodules */ private ModuleFactory mModuleFactory; /** the context of all child components */ private Context mChildContext; /** * Creates a new <code>Checker</code> instance. * The instance needs to be contextualized and configured. * * @throws CheckstyleException if an error occurs */ public Checker() throws CheckstyleException { addListener(mCounter); } /** @see AutomaticBean */ public void finishLocalSetup() throws CheckstyleException { final Locale locale = new Locale(mLocaleLanguage, mLocaleCountry); LocalizedMessage.setLocale(locale); if (mModuleFactory == null) { mModuleFactory = PackageNamesLoader.loadModuleFactory( this.getClass().getClassLoader()); } final DefaultContext context = new DefaultContext(); context.add("classLoader", mLoader); context.add("moduleFactory", mModuleFactory); mChildContext = context; } /** * Instantiates, configures and registers a FileSetCheck * that is specified in the provided configuration. * @see com.puppycrawl.tools.checkstyle.api.AutomaticBean */ protected void setupChild(Configuration aChildConf) throws CheckstyleException { final String name = aChildConf.getName(); try { final Object module = mModuleFactory.createModule(name); if (!(module instanceof FileSetCheck)) { - throw new CheckstyleException(name + " is not a FileSetCheck"); + throw new CheckstyleException(name + + " is not allowed as a module in Checker"); } final FileSetCheck fsc = (FileSetCheck) module; fsc.contextualize(mChildContext); fsc.configure(aChildConf); addFileSetCheck(fsc); } catch (Exception ex) { // TODO i18n throw new CheckstyleException( - "cannot initialize filesetcheck with name " + "cannot initialize module " + name + " - " + ex.getMessage()); } } /** * Adds a FileSetCheck to the list of FileSetChecks * that is executed in process(). * @param aFileSetCheck the additional FileSetCheck */ public void addFileSetCheck(FileSetCheck aFileSetCheck) { aFileSetCheck.setMessageDispatcher(this); mFileSetChecks.add(aFileSetCheck); } /** Cleans up the object **/ public void destroy() { mListeners.clear(); } /** * Add the listener that will be used to receive events from the audit * @param aListener the nosy thing */ public void addListener(AuditListener aListener) { mListeners.add(aListener); } /** * Processes a set of files with all FileSetChecks. * Once this is done, it is highly recommended to call for * the destroy method to close and remove the listeners. * @param aFiles the list of files to be audited. * @return the total number of errors found * @see #destroy() */ public int process(File[] aFiles) { fireAuditStarted(); for (int i = 0; i < mFileSetChecks.size(); i++) { FileSetCheck fileSetCheck = (FileSetCheck) mFileSetChecks.get(i); fileSetCheck.process(aFiles); fileSetCheck.destroy(); } int errorCount = mCounter.getCount(); fireAuditFinished(); return errorCount; } /** * Create a stripped down version of a filename. * @param aFileName the original filename * @return the filename where an initial prefix of basedir is stripped */ private String getStrippedFileName(final String aFileName) { final String stripped; if ((mBasedir == null) || !aFileName.startsWith(mBasedir)) { stripped = aFileName; } else { // making the assumption that there is text after basedir final int skipSep = mBasedir.endsWith(File.separator) ? 0 : 1; stripped = aFileName.substring(mBasedir.length() + skipSep); } return stripped; } /** @param aBasedir the base directory to strip off in filenames */ public void setBasedir(String aBasedir) { mBasedir = aBasedir; } /** notify all listeners about the audit start */ protected void fireAuditStarted() { final AuditEvent evt = new AuditEvent(this); final Iterator it = mListeners.iterator(); while (it.hasNext()) { final AuditListener listener = (AuditListener) it.next(); listener.auditStarted(evt); } } /** notify all listeners about the audit end */ protected void fireAuditFinished() { final AuditEvent evt = new AuditEvent(this); final Iterator it = mListeners.iterator(); while (it.hasNext()) { final AuditListener listener = (AuditListener) it.next(); listener.auditFinished(evt); } } /** * notify all listeners about the beginning of a file audit * @param aFileName the file to be audited */ public void fireFileStarted(String aFileName) { final String stripped = getStrippedFileName(aFileName); final AuditEvent evt = new AuditEvent(this, stripped); final Iterator it = mListeners.iterator(); while (it.hasNext()) { final AuditListener listener = (AuditListener) it.next(); listener.fileStarted(evt); } } /** * notify all listeners about the end of a file audit * @param aFileName the audited file */ public void fireFileFinished(String aFileName) { final String stripped = getStrippedFileName(aFileName); final AuditEvent evt = new AuditEvent(this, stripped); final Iterator it = mListeners.iterator(); while (it.hasNext()) { final AuditListener listener = (AuditListener) it.next(); listener.fileFinished(evt); } } /** * notify all listeners about the errors in a file. * @param aFileName the audited file * @param aErrors the audit errors from the file */ public void fireErrors(String aFileName, LocalizedMessage[] aErrors) { final String stripped = getStrippedFileName(aFileName); for (int i = 0; i < aErrors.length; i++) { final AuditEvent evt = new AuditEvent(this, stripped, aErrors[i]); final Iterator it = mListeners.iterator(); while (it.hasNext()) { final AuditListener listener = (AuditListener) it.next(); listener.addError(evt); } } } /** * Sets the factory for creating submodules. * * @param aModuleFactory the factory for creating FileSetChecks */ public void setModuleFactory(ModuleFactory aModuleFactory) { mModuleFactory = aModuleFactory; } /** @param aLocaleCountry the country to report messages **/ public void setLocaleCountry(String aLocaleCountry) { mLocaleCountry = aLocaleCountry; } /** @param aLocaleLanguage the language to report messages **/ public void setLocaleLanguage(String aLocaleLanguage) { mLocaleLanguage = aLocaleLanguage; } }
false
true
protected void setupChild(Configuration aChildConf) throws CheckstyleException { final String name = aChildConf.getName(); try { final Object module = mModuleFactory.createModule(name); if (!(module instanceof FileSetCheck)) { throw new CheckstyleException(name + " is not a FileSetCheck"); } final FileSetCheck fsc = (FileSetCheck) module; fsc.contextualize(mChildContext); fsc.configure(aChildConf); addFileSetCheck(fsc); } catch (Exception ex) { // TODO i18n throw new CheckstyleException( "cannot initialize filesetcheck with name " + name + " - " + ex.getMessage()); } }
protected void setupChild(Configuration aChildConf) throws CheckstyleException { final String name = aChildConf.getName(); try { final Object module = mModuleFactory.createModule(name); if (!(module instanceof FileSetCheck)) { throw new CheckstyleException(name + " is not allowed as a module in Checker"); } final FileSetCheck fsc = (FileSetCheck) module; fsc.contextualize(mChildContext); fsc.configure(aChildConf); addFileSetCheck(fsc); } catch (Exception ex) { // TODO i18n throw new CheckstyleException( "cannot initialize module " + name + " - " + ex.getMessage()); } }
diff --git a/src/main/java/net/sf/jooreports/templates/xmlfilters/DynamicImageFilter.java b/src/main/java/net/sf/jooreports/templates/xmlfilters/DynamicImageFilter.java index 1ef07a0..1f41fbc 100644 --- a/src/main/java/net/sf/jooreports/templates/xmlfilters/DynamicImageFilter.java +++ b/src/main/java/net/sf/jooreports/templates/xmlfilters/DynamicImageFilter.java @@ -1,70 +1,68 @@ package net.sf.jooreports.templates.xmlfilters; import net.sf.jooreports.opendocument.OpenDocumentNamespaces; import net.sf.jooreports.templates.TemplateFreemarkerNamespace; import nu.xom.Attribute; import nu.xom.Document; import nu.xom.Element; import nu.xom.Nodes; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Processes content.xml for dynamic images<p> * Only images enclosed in a draw:frame with a name starting with {@link #IMAGE_NAME_PREFIX} and ending with {@link #IMAGE_NAME_SUFFIX} will be processed */ public class DynamicImageFilter extends XmlEntryFilter { /** * Only images enclosed in a draw:frame with a name starting with * this prefix will be processed */ public static final String IMAGE_NAME_PREFIX = TemplateFreemarkerNamespace.NAME + ".image("; /** * Only images enclosed in a draw:frame with a name ending with * this suffix will be processed */ public static final String IMAGE_NAME_SUFFIX = ")"; private static final String IMAGE_WIDTH_PREFIX = TemplateFreemarkerNamespace.NAME + ".imageWidth("; private static final String IMAGE_HEIGHT_PREFIX = TemplateFreemarkerNamespace.NAME + ".imageHeight("; private static final Log log = LogFactory.getLog(DynamicImageFilter.class); public void doFilter(Document document) { Nodes nodes = document.query("//draw:image", OpenDocumentNamespaces.XPATH_CONTEXT); for (int nodeIndex = 0; nodeIndex < nodes.size(); nodeIndex++) { Element imageElement = (Element) nodes.get(nodeIndex); Element frameElement = (Element) imageElement.getParent(); if (!"draw:frame".equals(frameElement.getQualifiedName())) { log.warn("draw:image not inside a draw:frame? skipping"); continue; } String frameName = frameElement.getAttributeValue("name", OpenDocumentNamespaces.URI_DRAW); if (frameName != null && frameName.toLowerCase().startsWith(IMAGE_NAME_PREFIX) && frameName.endsWith(IMAGE_NAME_SUFFIX)) { Attribute hrefAttribute = imageElement.getAttribute("href", OpenDocumentNamespaces.URI_XLINK); String defaultImageName = hrefAttribute.getValue(); if (frameName.contains(",")) { Attribute widthAttribute = frameElement.getAttribute("width", OpenDocumentNamespaces.URI_SVG); Attribute heightAttribute = frameElement.getAttribute("height", OpenDocumentNamespaces.URI_SVG); String maxSize = ",'" + widthAttribute.getValue().trim() + "','" + heightAttribute.getValue().trim() + "',"; String sizeParameters = frameName.replaceFirst(",", maxSize); widthAttribute.setValue("${" + sizeParameters.replace(IMAGE_NAME_PREFIX, IMAGE_WIDTH_PREFIX+"'"+defaultImageName+"',") + "}"); heightAttribute.setValue("${" + sizeParameters.replace(IMAGE_NAME_PREFIX, IMAGE_HEIGHT_PREFIX+"'"+defaultImageName+"',") + "}"); - System.out.println("widthAttribute:"+widthAttribute.getValue()); - System.out.println("heightAttribute:"+heightAttribute.getValue()); frameName = frameName.split(",")[0] + IMAGE_NAME_SUFFIX; } hrefAttribute.setValue("${" + frameName.replace(IMAGE_NAME_PREFIX, IMAGE_NAME_PREFIX+"'"+defaultImageName+"',") + "}"); } } } }
true
true
public void doFilter(Document document) { Nodes nodes = document.query("//draw:image", OpenDocumentNamespaces.XPATH_CONTEXT); for (int nodeIndex = 0; nodeIndex < nodes.size(); nodeIndex++) { Element imageElement = (Element) nodes.get(nodeIndex); Element frameElement = (Element) imageElement.getParent(); if (!"draw:frame".equals(frameElement.getQualifiedName())) { log.warn("draw:image not inside a draw:frame? skipping"); continue; } String frameName = frameElement.getAttributeValue("name", OpenDocumentNamespaces.URI_DRAW); if (frameName != null && frameName.toLowerCase().startsWith(IMAGE_NAME_PREFIX) && frameName.endsWith(IMAGE_NAME_SUFFIX)) { Attribute hrefAttribute = imageElement.getAttribute("href", OpenDocumentNamespaces.URI_XLINK); String defaultImageName = hrefAttribute.getValue(); if (frameName.contains(",")) { Attribute widthAttribute = frameElement.getAttribute("width", OpenDocumentNamespaces.URI_SVG); Attribute heightAttribute = frameElement.getAttribute("height", OpenDocumentNamespaces.URI_SVG); String maxSize = ",'" + widthAttribute.getValue().trim() + "','" + heightAttribute.getValue().trim() + "',"; String sizeParameters = frameName.replaceFirst(",", maxSize); widthAttribute.setValue("${" + sizeParameters.replace(IMAGE_NAME_PREFIX, IMAGE_WIDTH_PREFIX+"'"+defaultImageName+"',") + "}"); heightAttribute.setValue("${" + sizeParameters.replace(IMAGE_NAME_PREFIX, IMAGE_HEIGHT_PREFIX+"'"+defaultImageName+"',") + "}"); System.out.println("widthAttribute:"+widthAttribute.getValue()); System.out.println("heightAttribute:"+heightAttribute.getValue()); frameName = frameName.split(",")[0] + IMAGE_NAME_SUFFIX; } hrefAttribute.setValue("${" + frameName.replace(IMAGE_NAME_PREFIX, IMAGE_NAME_PREFIX+"'"+defaultImageName+"',") + "}"); } } }
public void doFilter(Document document) { Nodes nodes = document.query("//draw:image", OpenDocumentNamespaces.XPATH_CONTEXT); for (int nodeIndex = 0; nodeIndex < nodes.size(); nodeIndex++) { Element imageElement = (Element) nodes.get(nodeIndex); Element frameElement = (Element) imageElement.getParent(); if (!"draw:frame".equals(frameElement.getQualifiedName())) { log.warn("draw:image not inside a draw:frame? skipping"); continue; } String frameName = frameElement.getAttributeValue("name", OpenDocumentNamespaces.URI_DRAW); if (frameName != null && frameName.toLowerCase().startsWith(IMAGE_NAME_PREFIX) && frameName.endsWith(IMAGE_NAME_SUFFIX)) { Attribute hrefAttribute = imageElement.getAttribute("href", OpenDocumentNamespaces.URI_XLINK); String defaultImageName = hrefAttribute.getValue(); if (frameName.contains(",")) { Attribute widthAttribute = frameElement.getAttribute("width", OpenDocumentNamespaces.URI_SVG); Attribute heightAttribute = frameElement.getAttribute("height", OpenDocumentNamespaces.URI_SVG); String maxSize = ",'" + widthAttribute.getValue().trim() + "','" + heightAttribute.getValue().trim() + "',"; String sizeParameters = frameName.replaceFirst(",", maxSize); widthAttribute.setValue("${" + sizeParameters.replace(IMAGE_NAME_PREFIX, IMAGE_WIDTH_PREFIX+"'"+defaultImageName+"',") + "}"); heightAttribute.setValue("${" + sizeParameters.replace(IMAGE_NAME_PREFIX, IMAGE_HEIGHT_PREFIX+"'"+defaultImageName+"',") + "}"); frameName = frameName.split(",")[0] + IMAGE_NAME_SUFFIX; } hrefAttribute.setValue("${" + frameName.replace(IMAGE_NAME_PREFIX, IMAGE_NAME_PREFIX+"'"+defaultImageName+"',") + "}"); } } }
diff --git a/tests/plugins/org.jboss.tools.tests.installation/src/org/jboss/tools/tests/installation/CheckForUpdatesTest.java b/tests/plugins/org.jboss.tools.tests.installation/src/org/jboss/tools/tests/installation/CheckForUpdatesTest.java index e462d7537..d9697f030 100644 --- a/tests/plugins/org.jboss.tools.tests.installation/src/org/jboss/tools/tests/installation/CheckForUpdatesTest.java +++ b/tests/plugins/org.jboss.tools.tests.installation/src/org/jboss/tools/tests/installation/CheckForUpdatesTest.java @@ -1,43 +1,44 @@ /******************************************************************************* * Copyright (c) 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.tests.installation; import org.eclipse.swtbot.eclipse.finder.SWTBotEclipseTestCase; import org.eclipse.swtbot.swt.finder.SWTBot; import org.eclipse.swtbot.swt.finder.waits.ICondition; import org.junit.Test; /** * @author mistria */ public class CheckForUpdatesTest extends SWTBotEclipseTestCase { @Test public void testCheckForUpdates() throws Exception { - bot.menu("Help").menu("Check for Updates"); + bot.menu("Help").menu("Check for Updates").click(); + bot.shell("Contacting Software Sites"); this.bot.waitWhile(new ICondition() { @Override public boolean test() throws Exception { return bot.activeShell().getText().equals("Contacting Software Sites"); } @Override public void init(SWTBot bot) { } @Override public String getFailureMessage() { return "Blocking while calculating deps"; } }, 10 * 60000); // 5 minutes timeout InstallTest.continueInstall(bot); } }
true
true
public void testCheckForUpdates() throws Exception { bot.menu("Help").menu("Check for Updates"); this.bot.waitWhile(new ICondition() { @Override public boolean test() throws Exception { return bot.activeShell().getText().equals("Contacting Software Sites"); } @Override public void init(SWTBot bot) { } @Override public String getFailureMessage() { return "Blocking while calculating deps"; } }, 10 * 60000); // 5 minutes timeout InstallTest.continueInstall(bot); }
public void testCheckForUpdates() throws Exception { bot.menu("Help").menu("Check for Updates").click(); bot.shell("Contacting Software Sites"); this.bot.waitWhile(new ICondition() { @Override public boolean test() throws Exception { return bot.activeShell().getText().equals("Contacting Software Sites"); } @Override public void init(SWTBot bot) { } @Override public String getFailureMessage() { return "Blocking while calculating deps"; } }, 10 * 60000); // 5 minutes timeout InstallTest.continueInstall(bot); }
diff --git a/drools-compiler/src/test/java/org/drools/integrationtests/CepEspTest.java b/drools-compiler/src/test/java/org/drools/integrationtests/CepEspTest.java index 140381da14..7fcc3e361e 100644 --- a/drools-compiler/src/test/java/org/drools/integrationtests/CepEspTest.java +++ b/drools-compiler/src/test/java/org/drools/integrationtests/CepEspTest.java @@ -1,722 +1,722 @@ package org.drools.integrationtests; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import junit.framework.Assert; import junit.framework.TestCase; import org.drools.ClockType; import org.drools.OrderEvent; import org.drools.RuleBase; import org.drools.RuleBaseConfiguration; import org.drools.RuleBaseFactory; import org.drools.SessionConfiguration; import org.drools.StatefulSession; import org.drools.StockTick; import org.drools.RuleBaseConfiguration.EventProcessingMode; import org.drools.common.EventFactHandle; import org.drools.common.InternalFactHandle; import org.drools.compiler.DrlParser; import org.drools.compiler.DroolsParserException; import org.drools.compiler.PackageBuilder; import org.drools.lang.descr.PackageDescr; import org.drools.rule.Package; import org.drools.time.SessionPseudoClock; import org.drools.time.impl.PseudoClockScheduler; public class CepEspTest extends TestCase { protected RuleBase getRuleBase() throws Exception { return RuleBaseFactory.newRuleBase( RuleBase.RETEOO, null ); } protected RuleBase getRuleBase(final RuleBaseConfiguration config) throws Exception { return RuleBaseFactory.newRuleBase( RuleBase.RETEOO, config ); } private RuleBase loadRuleBase(final Reader reader) throws IOException, DroolsParserException, Exception { return loadRuleBase( reader, null ); } private RuleBase loadRuleBase(final Reader reader, final RuleBaseConfiguration conf) throws IOException, DroolsParserException, Exception { final DrlParser parser = new DrlParser(); final PackageDescr packageDescr = parser.parse( reader ); if ( parser.hasErrors() ) { System.out.println( parser.getErrors() ); Assert.fail( "Error messages in parser, need to sort this our (or else collect error messages)" ); } // pre build the package final PackageBuilder builder = new PackageBuilder(); builder.addPackage( packageDescr ); final Package pkg = builder.getPackage(); // add the package to a rulebase RuleBase ruleBase = getRuleBase( conf ); ruleBase.addPackage( pkg ); // load up the rulebase ruleBase = SerializationHelper.serializeObject( ruleBase ); return ruleBase; } public void testEventAssertion() throws Exception { // read in the source final Reader reader = new InputStreamReader( getClass().getResourceAsStream( "test_CEP_SimpleEventAssertion.drl" ) ); RuleBase ruleBase = loadRuleBase( reader ); SessionConfiguration conf = new SessionConfiguration(); conf.setClockType( ClockType.PSEUDO_CLOCK ); StatefulSession session = ruleBase.newStatefulSession( conf ); final List results = new ArrayList(); session.setGlobal( "results", results ); StockTick tick1 = new StockTick( 1, "DROO", 50, 10000 ); StockTick tick2 = new StockTick( 2, "ACME", 10, 10010 ); StockTick tick3 = new StockTick( 3, "ACME", 10, 10100 ); StockTick tick4 = new StockTick( 4, "DROO", 50, 11000 ); InternalFactHandle handle1 = (InternalFactHandle) session.insert( tick1 ); InternalFactHandle handle2 = (InternalFactHandle) session.insert( tick2 ); InternalFactHandle handle3 = (InternalFactHandle) session.insert( tick3 ); InternalFactHandle handle4 = (InternalFactHandle) session.insert( tick4 ); assertNotNull( handle1 ); assertNotNull( handle2 ); assertNotNull( handle3 ); assertNotNull( handle4 ); assertTrue( handle1.isEvent() ); assertTrue( handle2.isEvent() ); assertTrue( handle3.isEvent() ); assertTrue( handle4.isEvent() ); session = SerializationHelper.getSerialisedStatefulSession( session, ruleBase ); session.fireAllRules(); assertEquals( 2, ((List) session.getGlobal( "results" )).size() ); } public void testEventAssertionWithDuration() throws Exception { // read in the source final Reader reader = new InputStreamReader( getClass().getResourceAsStream( "test_CEP_SimpleEventAssertionWithDuration.drl" ) ); final RuleBase ruleBase = loadRuleBase( reader ); SessionConfiguration conf = new SessionConfiguration(); conf.setClockType( ClockType.PSEUDO_CLOCK ); StatefulSession wm = ruleBase.newStatefulSession( conf ); final List results = new ArrayList(); wm.setGlobal( "results", results ); StockTick tick1 = new StockTick( 1, "DROO", 50, 10000, 5 ); StockTick tick2 = new StockTick( 2, "ACME", 10, 11000, 10 ); StockTick tick3 = new StockTick( 3, "ACME", 10, 12000, 8 ); StockTick tick4 = new StockTick( 4, "DROO", 50, 13000, 7 ); InternalFactHandle handle1 = (InternalFactHandle) wm.insert( tick1 ); InternalFactHandle handle2 = (InternalFactHandle) wm.insert( tick2 ); InternalFactHandle handle3 = (InternalFactHandle) wm.insert( tick3 ); InternalFactHandle handle4 = (InternalFactHandle) wm.insert( tick4 ); assertNotNull( handle1 ); assertNotNull( handle2 ); assertNotNull( handle3 ); assertNotNull( handle4 ); assertTrue( handle1.isEvent() ); assertTrue( handle2.isEvent() ); assertTrue( handle3.isEvent() ); assertTrue( handle4.isEvent() ); EventFactHandle eh1 = (EventFactHandle) handle1; EventFactHandle eh2 = (EventFactHandle) handle2; EventFactHandle eh3 = (EventFactHandle) handle3; EventFactHandle eh4 = (EventFactHandle) handle4; assertEquals( tick1.getTime(), eh1.getStartTimestamp() ); assertEquals( tick2.getTime(), eh2.getStartTimestamp() ); assertEquals( tick3.getTime(), eh3.getStartTimestamp() ); assertEquals( tick4.getTime(), eh4.getStartTimestamp() ); assertEquals( tick1.getDuration(), eh1.getDuration() ); assertEquals( tick2.getDuration(), eh2.getDuration() ); assertEquals( tick3.getDuration(), eh3.getDuration() ); assertEquals( tick4.getDuration(), eh4.getDuration() ); wm.fireAllRules(); assertEquals( 2, results.size() ); } public void testEventAssertionWithDateTimestamp() throws Exception { // read in the source final Reader reader = new InputStreamReader( getClass().getResourceAsStream( "test_CEP_SimpleEventAssertionWithDateTimestamp.drl" ) ); final RuleBase ruleBase = loadRuleBase( reader ); SessionConfiguration conf = new SessionConfiguration(); conf.setClockType( ClockType.PSEUDO_CLOCK ); StatefulSession wm = ruleBase.newStatefulSession( conf ); final List results = new ArrayList(); wm.setGlobal( "results", results ); StockTick tick1 = new StockTick( 1, "DROO", 50, 10000, 5 ); StockTick tick2 = new StockTick( 2, "ACME", 10, 11000, 10 ); StockTick tick3 = new StockTick( 3, "ACME", 10, 12000, 8 ); StockTick tick4 = new StockTick( 4, "DROO", 50, 13000, 7 ); InternalFactHandle handle1 = (InternalFactHandle) wm.insert( tick1 ); InternalFactHandle handle2 = (InternalFactHandle) wm.insert( tick2 ); InternalFactHandle handle3 = (InternalFactHandle) wm.insert( tick3 ); InternalFactHandle handle4 = (InternalFactHandle) wm.insert( tick4 ); assertNotNull( handle1 ); assertNotNull( handle2 ); assertNotNull( handle3 ); assertNotNull( handle4 ); assertTrue( handle1.isEvent() ); assertTrue( handle2.isEvent() ); assertTrue( handle3.isEvent() ); assertTrue( handle4.isEvent() ); EventFactHandle eh1 = (EventFactHandle) handle1; EventFactHandle eh2 = (EventFactHandle) handle2; EventFactHandle eh3 = (EventFactHandle) handle3; EventFactHandle eh4 = (EventFactHandle) handle4; assertEquals( tick1.getTime(), eh1.getStartTimestamp() ); assertEquals( tick2.getTime(), eh2.getStartTimestamp() ); assertEquals( tick3.getTime(), eh3.getStartTimestamp() ); assertEquals( tick4.getTime(), eh4.getStartTimestamp() ); wm.fireAllRules(); assertEquals( 2, results.size() ); } public void testTimeRelationalOperators() throws Exception { // read in the source final Reader reader = new InputStreamReader( getClass().getResourceAsStream( "test_CEP_TimeRelationalOperators.drl" ) ); final RuleBaseConfiguration rbconf = new RuleBaseConfiguration(); rbconf.setEventProcessingMode( EventProcessingMode.STREAM ); final RuleBase ruleBase = loadRuleBase( reader, rbconf ); SessionConfiguration conf = new SessionConfiguration(); conf.setClockType( ClockType.PSEUDO_CLOCK ); StatefulSession wm = ruleBase.newStatefulSession( conf ); final PseudoClockScheduler clock = (PseudoClockScheduler) wm.getSessionClock(); clock.setStartupTime( 1000 ); final List results_coincides = new ArrayList(); final List results_before = new ArrayList(); final List results_after = new ArrayList(); final List results_meets = new ArrayList(); final List results_met_by = new ArrayList(); final List results_overlaps = new ArrayList(); final List results_overlapped_by = new ArrayList(); final List results_during = new ArrayList(); final List results_includes = new ArrayList(); final List results_starts = new ArrayList(); final List results_started_by = new ArrayList(); final List results_finishes = new ArrayList(); final List results_finished_by = new ArrayList(); wm.setGlobal( "results_coincides", results_coincides ); wm.setGlobal( "results_before", results_before ); wm.setGlobal( "results_after", results_after ); wm.setGlobal( "results_meets", results_meets ); wm.setGlobal( "results_met_by", results_met_by ); wm.setGlobal( "results_overlaps", results_overlaps ); wm.setGlobal( "results_overlapped_by", results_overlapped_by ); wm.setGlobal( "results_during", results_during ); wm.setGlobal( "results_includes", results_includes ); wm.setGlobal( "results_starts", results_starts ); wm.setGlobal( "results_started_by", results_started_by ); wm.setGlobal( "results_finishes", results_finishes ); wm.setGlobal( "results_finished_by", results_finished_by ); StockTick tick1 = new StockTick( 1, "DROO", 50, System.currentTimeMillis(), 3 ); StockTick tick2 = new StockTick( 2, "ACME", 10, System.currentTimeMillis(), 3 ); StockTick tick3 = new StockTick( 3, "ACME", 10, System.currentTimeMillis(), 3 ); StockTick tick4 = new StockTick( 4, "DROO", 50, System.currentTimeMillis(), 5 ); StockTick tick5 = new StockTick( 5, "ACME", 10, System.currentTimeMillis(), 5 ); StockTick tick6 = new StockTick( 6, "ACME", 10, System.currentTimeMillis(), 3 ); StockTick tick7 = new StockTick( 7, "ACME", 10, System.currentTimeMillis(), 5 ); StockTick tick8 = new StockTick( 8, "ACME", 10, System.currentTimeMillis(), 3 ); InternalFactHandle handle1 = (InternalFactHandle) wm.insert( tick1 ); clock.advanceTime( 4, TimeUnit.MILLISECONDS ); InternalFactHandle handle2 = (InternalFactHandle) wm.insert( tick2 ); clock.advanceTime( 4, TimeUnit.MILLISECONDS ); InternalFactHandle handle3 = (InternalFactHandle) wm.insert( tick3 ); clock.advanceTime( 4, TimeUnit.MILLISECONDS ); InternalFactHandle handle4 = (InternalFactHandle) wm.insert( tick4 ); InternalFactHandle handle5 = (InternalFactHandle) wm.insert( tick5 ); clock.advanceTime( 1, TimeUnit.MILLISECONDS ); InternalFactHandle handle6 = (InternalFactHandle) wm.insert( tick6 ); InternalFactHandle handle7 = (InternalFactHandle) wm.insert( tick7 ); clock.advanceTime( 2, TimeUnit.MILLISECONDS ); InternalFactHandle handle8 = (InternalFactHandle) wm.insert( tick8 ); assertNotNull( handle1 ); assertNotNull( handle2 ); assertNotNull( handle3 ); assertNotNull( handle4 ); assertNotNull( handle5 ); assertNotNull( handle6 ); assertNotNull( handle7 ); assertNotNull( handle8 ); assertTrue( handle1.isEvent() ); assertTrue( handle2.isEvent() ); assertTrue( handle3.isEvent() ); assertTrue( handle4.isEvent() ); assertTrue( handle6.isEvent() ); assertTrue( handle7.isEvent() ); assertTrue( handle8.isEvent() ); // wm = SerializationHelper.serializeObject(wm); wm.fireAllRules(); assertEquals( 1, results_coincides.size() ); assertEquals( tick5, results_coincides.get( 0 ) ); assertEquals( 1, results_before.size() ); assertEquals( tick2, results_before.get( 0 ) ); assertEquals( 1, results_after.size() ); assertEquals( tick3, results_after.get( 0 ) ); assertEquals( 1, results_meets.size() ); assertEquals( tick3, results_meets.get( 0 ) ); assertEquals( 1, results_met_by.size() ); assertEquals( tick2, results_met_by.get( 0 ) ); assertEquals( 1, results_met_by.size() ); assertEquals( tick2, results_met_by.get( 0 ) ); assertEquals( 1, results_overlaps.size() ); assertEquals( tick4, results_overlaps.get( 0 ) ); assertEquals( 1, results_overlapped_by.size() ); - assertEquals( tick7, + assertEquals( tick8, results_overlapped_by.get( 0 ) ); assertEquals( 1, results_during.size() ); assertEquals( tick6, results_during.get( 0 ) ); assertEquals( 1, results_includes.size() ); assertEquals( tick4, results_includes.get( 0 ) ); assertEquals( 1, results_starts.size() ); assertEquals( tick6, results_starts.get( 0 ) ); assertEquals( 1, results_started_by.size() ); assertEquals( tick7, results_started_by.get( 0 ) ); assertEquals( 1, results_finishes.size() ); assertEquals( tick8, results_finishes.get( 0 ) ); assertEquals( 1, results_finished_by.size() ); assertEquals( tick7, results_finished_by.get( 0 ) ); } // @FIXME: we need to decide on the semantics of expiration public void FIXME_testSimpleTimeWindow() throws Exception { // read in the source final Reader reader = new InputStreamReader( getClass().getResourceAsStream( "test_CEP_SimpleTimeWindow.drl" ) ); final RuleBaseConfiguration rbconf = new RuleBaseConfiguration(); rbconf.setEventProcessingMode( EventProcessingMode.STREAM ); final RuleBase ruleBase = loadRuleBase( reader, rbconf ); SessionConfiguration conf = new SessionConfiguration(); conf.setClockType( ClockType.PSEUDO_CLOCK ); StatefulSession wm = ruleBase.newStatefulSession( conf ); List results = new ArrayList(); wm.setGlobal( "results", results ); // how to initialize the clock? // how to configure the clock? SessionPseudoClock clock = (SessionPseudoClock) wm.getSessionClock(); clock.advanceTime( 5, TimeUnit.SECONDS ); // 5 seconds EventFactHandle handle1 = (EventFactHandle) wm.insert( new OrderEvent( "1", "customer A", 70 ) ); assertEquals( 5000, handle1.getStartTimestamp() ); assertEquals( 0, handle1.getDuration() ); // wm = SerializationHelper.getSerialisedStatefulSession( wm ); // results = (List) wm.getGlobal( "results" ); // clock = (SessionPseudoClock) wm.getSessionClock(); wm.fireAllRules(); assertEquals( 1, results.size() ); assertEquals( 70, ((Number) results.get( 0 )).intValue() ); // advance clock and assert new data clock.advanceTime( 10, TimeUnit.SECONDS ); // 10 seconds EventFactHandle handle2 = (EventFactHandle) wm.insert( new OrderEvent( "2", "customer A", 60 ) ); assertEquals( 15000, handle2.getStartTimestamp() ); assertEquals( 0, handle2.getDuration() ); wm.fireAllRules(); assertEquals( 2, results.size() ); assertEquals( 65, ((Number) results.get( 1 )).intValue() ); // advance clock and assert new data clock.advanceTime( 10, TimeUnit.SECONDS ); // 10 seconds EventFactHandle handle3 = (EventFactHandle) wm.insert( new OrderEvent( "3", "customer A", 50 ) ); assertEquals( 25000, handle3.getStartTimestamp() ); assertEquals( 0, handle3.getDuration() ); wm.fireAllRules(); assertEquals( 3, results.size() ); assertEquals( 60, ((Number) results.get( 2 )).intValue() ); // advance clock and assert new data clock.advanceTime( 10, TimeUnit.SECONDS ); // 10 seconds EventFactHandle handle4 = (EventFactHandle) wm.insert( new OrderEvent( "4", "customer A", 25 ) ); assertEquals( 35000, handle4.getStartTimestamp() ); assertEquals( 0, handle4.getDuration() ); wm.fireAllRules(); // first event should have expired, making average under the rule threshold, so no additional rule fire assertEquals( 3, results.size() ); // advance clock and assert new data clock.advanceTime( 10, TimeUnit.SECONDS ); // 10 seconds EventFactHandle handle5 = (EventFactHandle) wm.insert( new OrderEvent( "5", "customer A", 70 ) ); assertEquals( 45000, handle5.getStartTimestamp() ); assertEquals( 0, handle5.getDuration() ); // wm = SerializationHelper.serializeObject(wm); wm.fireAllRules(); // still under the threshold, so no fire assertEquals( 3, results.size() ); // advance clock and assert new data clock.advanceTime( 10, TimeUnit.SECONDS ); // 10 seconds EventFactHandle handle6 = (EventFactHandle) wm.insert( new OrderEvent( "6", "customer A", 115 ) ); assertEquals( 55000, handle6.getStartTimestamp() ); assertEquals( 0, handle6.getDuration() ); wm.fireAllRules(); assertEquals( 4, results.size() ); assertEquals( 70, ((Number) results.get( 3 )).intValue() ); } public void testSimpleLengthWindow() throws Exception { // read in the source final Reader reader = new InputStreamReader( getClass().getResourceAsStream( "test_CEP_SimpleLengthWindow.drl" ) ); final RuleBaseConfiguration rbconf = new RuleBaseConfiguration(); rbconf.setEventProcessingMode( EventProcessingMode.STREAM ); final RuleBase ruleBase = loadRuleBase( reader, rbconf ); SessionConfiguration conf = new SessionConfiguration(); conf.setClockType( ClockType.REALTIME_CLOCK ); StatefulSession wm = ruleBase.newStatefulSession( conf ); final List results = new ArrayList(); wm.setGlobal( "results", results ); EventFactHandle handle1 = (EventFactHandle) wm.insert( new OrderEvent( "1", "customer A", 70 ) ); // wm = SerializationHelper.serializeObject(wm); wm.fireAllRules(); assertEquals( 1, results.size() ); assertEquals( 70, ((Number) results.get( 0 )).intValue() ); // assert new data EventFactHandle handle2 = (EventFactHandle) wm.insert( new OrderEvent( "2", "customer A", 60 ) ); wm.fireAllRules(); assertEquals( 2, results.size() ); assertEquals( 65, ((Number) results.get( 1 )).intValue() ); // assert new data EventFactHandle handle3 = (EventFactHandle) wm.insert( new OrderEvent( "3", "customer A", 50 ) ); wm.fireAllRules(); assertEquals( 3, results.size() ); assertEquals( 60, ((Number) results.get( 2 )).intValue() ); // assert new data EventFactHandle handle4 = (EventFactHandle) wm.insert( new OrderEvent( "4", "customer A", 25 ) ); wm.fireAllRules(); // first event should have expired, making average under the rule threshold, so no additional rule fire assertEquals( 3, results.size() ); // assert new data EventFactHandle handle5 = (EventFactHandle) wm.insert( new OrderEvent( "5", "customer A", 70 ) ); // wm = SerializationHelper.serializeObject(wm); wm.fireAllRules(); // still under the threshold, so no fire assertEquals( 3, results.size() ); // assert new data EventFactHandle handle6 = (EventFactHandle) wm.insert( new OrderEvent( "6", "customer A", 115 ) ); wm.fireAllRules(); assertEquals( 4, results.size() ); assertEquals( 70, ((Number) results.get( 3 )).intValue() ); } // public void FIXME_testTransactionCorrelation() throws Exception { // // read in the source // final Reader reader = new InputStreamReader( getClass().getResourceAsStream( "test_TransactionCorrelation.drl" ) ); // final RuleBase ruleBase = loadRuleBase( reader ); // // final WorkingMemory wm = ruleBase.newStatefulSession(); // final List results = new ArrayList(); // // wm.setGlobal( "results", // results ); // // // } }
true
true
public void testTimeRelationalOperators() throws Exception { // read in the source final Reader reader = new InputStreamReader( getClass().getResourceAsStream( "test_CEP_TimeRelationalOperators.drl" ) ); final RuleBaseConfiguration rbconf = new RuleBaseConfiguration(); rbconf.setEventProcessingMode( EventProcessingMode.STREAM ); final RuleBase ruleBase = loadRuleBase( reader, rbconf ); SessionConfiguration conf = new SessionConfiguration(); conf.setClockType( ClockType.PSEUDO_CLOCK ); StatefulSession wm = ruleBase.newStatefulSession( conf ); final PseudoClockScheduler clock = (PseudoClockScheduler) wm.getSessionClock(); clock.setStartupTime( 1000 ); final List results_coincides = new ArrayList(); final List results_before = new ArrayList(); final List results_after = new ArrayList(); final List results_meets = new ArrayList(); final List results_met_by = new ArrayList(); final List results_overlaps = new ArrayList(); final List results_overlapped_by = new ArrayList(); final List results_during = new ArrayList(); final List results_includes = new ArrayList(); final List results_starts = new ArrayList(); final List results_started_by = new ArrayList(); final List results_finishes = new ArrayList(); final List results_finished_by = new ArrayList(); wm.setGlobal( "results_coincides", results_coincides ); wm.setGlobal( "results_before", results_before ); wm.setGlobal( "results_after", results_after ); wm.setGlobal( "results_meets", results_meets ); wm.setGlobal( "results_met_by", results_met_by ); wm.setGlobal( "results_overlaps", results_overlaps ); wm.setGlobal( "results_overlapped_by", results_overlapped_by ); wm.setGlobal( "results_during", results_during ); wm.setGlobal( "results_includes", results_includes ); wm.setGlobal( "results_starts", results_starts ); wm.setGlobal( "results_started_by", results_started_by ); wm.setGlobal( "results_finishes", results_finishes ); wm.setGlobal( "results_finished_by", results_finished_by ); StockTick tick1 = new StockTick( 1, "DROO", 50, System.currentTimeMillis(), 3 ); StockTick tick2 = new StockTick( 2, "ACME", 10, System.currentTimeMillis(), 3 ); StockTick tick3 = new StockTick( 3, "ACME", 10, System.currentTimeMillis(), 3 ); StockTick tick4 = new StockTick( 4, "DROO", 50, System.currentTimeMillis(), 5 ); StockTick tick5 = new StockTick( 5, "ACME", 10, System.currentTimeMillis(), 5 ); StockTick tick6 = new StockTick( 6, "ACME", 10, System.currentTimeMillis(), 3 ); StockTick tick7 = new StockTick( 7, "ACME", 10, System.currentTimeMillis(), 5 ); StockTick tick8 = new StockTick( 8, "ACME", 10, System.currentTimeMillis(), 3 ); InternalFactHandle handle1 = (InternalFactHandle) wm.insert( tick1 ); clock.advanceTime( 4, TimeUnit.MILLISECONDS ); InternalFactHandle handle2 = (InternalFactHandle) wm.insert( tick2 ); clock.advanceTime( 4, TimeUnit.MILLISECONDS ); InternalFactHandle handle3 = (InternalFactHandle) wm.insert( tick3 ); clock.advanceTime( 4, TimeUnit.MILLISECONDS ); InternalFactHandle handle4 = (InternalFactHandle) wm.insert( tick4 ); InternalFactHandle handle5 = (InternalFactHandle) wm.insert( tick5 ); clock.advanceTime( 1, TimeUnit.MILLISECONDS ); InternalFactHandle handle6 = (InternalFactHandle) wm.insert( tick6 ); InternalFactHandle handle7 = (InternalFactHandle) wm.insert( tick7 ); clock.advanceTime( 2, TimeUnit.MILLISECONDS ); InternalFactHandle handle8 = (InternalFactHandle) wm.insert( tick8 ); assertNotNull( handle1 ); assertNotNull( handle2 ); assertNotNull( handle3 ); assertNotNull( handle4 ); assertNotNull( handle5 ); assertNotNull( handle6 ); assertNotNull( handle7 ); assertNotNull( handle8 ); assertTrue( handle1.isEvent() ); assertTrue( handle2.isEvent() ); assertTrue( handle3.isEvent() ); assertTrue( handle4.isEvent() ); assertTrue( handle6.isEvent() ); assertTrue( handle7.isEvent() ); assertTrue( handle8.isEvent() ); // wm = SerializationHelper.serializeObject(wm); wm.fireAllRules(); assertEquals( 1, results_coincides.size() ); assertEquals( tick5, results_coincides.get( 0 ) ); assertEquals( 1, results_before.size() ); assertEquals( tick2, results_before.get( 0 ) ); assertEquals( 1, results_after.size() ); assertEquals( tick3, results_after.get( 0 ) ); assertEquals( 1, results_meets.size() ); assertEquals( tick3, results_meets.get( 0 ) ); assertEquals( 1, results_met_by.size() ); assertEquals( tick2, results_met_by.get( 0 ) ); assertEquals( 1, results_met_by.size() ); assertEquals( tick2, results_met_by.get( 0 ) ); assertEquals( 1, results_overlaps.size() ); assertEquals( tick4, results_overlaps.get( 0 ) ); assertEquals( 1, results_overlapped_by.size() ); assertEquals( tick7, results_overlapped_by.get( 0 ) ); assertEquals( 1, results_during.size() ); assertEquals( tick6, results_during.get( 0 ) ); assertEquals( 1, results_includes.size() ); assertEquals( tick4, results_includes.get( 0 ) ); assertEquals( 1, results_starts.size() ); assertEquals( tick6, results_starts.get( 0 ) ); assertEquals( 1, results_started_by.size() ); assertEquals( tick7, results_started_by.get( 0 ) ); assertEquals( 1, results_finishes.size() ); assertEquals( tick8, results_finishes.get( 0 ) ); assertEquals( 1, results_finished_by.size() ); assertEquals( tick7, results_finished_by.get( 0 ) ); }
public void testTimeRelationalOperators() throws Exception { // read in the source final Reader reader = new InputStreamReader( getClass().getResourceAsStream( "test_CEP_TimeRelationalOperators.drl" ) ); final RuleBaseConfiguration rbconf = new RuleBaseConfiguration(); rbconf.setEventProcessingMode( EventProcessingMode.STREAM ); final RuleBase ruleBase = loadRuleBase( reader, rbconf ); SessionConfiguration conf = new SessionConfiguration(); conf.setClockType( ClockType.PSEUDO_CLOCK ); StatefulSession wm = ruleBase.newStatefulSession( conf ); final PseudoClockScheduler clock = (PseudoClockScheduler) wm.getSessionClock(); clock.setStartupTime( 1000 ); final List results_coincides = new ArrayList(); final List results_before = new ArrayList(); final List results_after = new ArrayList(); final List results_meets = new ArrayList(); final List results_met_by = new ArrayList(); final List results_overlaps = new ArrayList(); final List results_overlapped_by = new ArrayList(); final List results_during = new ArrayList(); final List results_includes = new ArrayList(); final List results_starts = new ArrayList(); final List results_started_by = new ArrayList(); final List results_finishes = new ArrayList(); final List results_finished_by = new ArrayList(); wm.setGlobal( "results_coincides", results_coincides ); wm.setGlobal( "results_before", results_before ); wm.setGlobal( "results_after", results_after ); wm.setGlobal( "results_meets", results_meets ); wm.setGlobal( "results_met_by", results_met_by ); wm.setGlobal( "results_overlaps", results_overlaps ); wm.setGlobal( "results_overlapped_by", results_overlapped_by ); wm.setGlobal( "results_during", results_during ); wm.setGlobal( "results_includes", results_includes ); wm.setGlobal( "results_starts", results_starts ); wm.setGlobal( "results_started_by", results_started_by ); wm.setGlobal( "results_finishes", results_finishes ); wm.setGlobal( "results_finished_by", results_finished_by ); StockTick tick1 = new StockTick( 1, "DROO", 50, System.currentTimeMillis(), 3 ); StockTick tick2 = new StockTick( 2, "ACME", 10, System.currentTimeMillis(), 3 ); StockTick tick3 = new StockTick( 3, "ACME", 10, System.currentTimeMillis(), 3 ); StockTick tick4 = new StockTick( 4, "DROO", 50, System.currentTimeMillis(), 5 ); StockTick tick5 = new StockTick( 5, "ACME", 10, System.currentTimeMillis(), 5 ); StockTick tick6 = new StockTick( 6, "ACME", 10, System.currentTimeMillis(), 3 ); StockTick tick7 = new StockTick( 7, "ACME", 10, System.currentTimeMillis(), 5 ); StockTick tick8 = new StockTick( 8, "ACME", 10, System.currentTimeMillis(), 3 ); InternalFactHandle handle1 = (InternalFactHandle) wm.insert( tick1 ); clock.advanceTime( 4, TimeUnit.MILLISECONDS ); InternalFactHandle handle2 = (InternalFactHandle) wm.insert( tick2 ); clock.advanceTime( 4, TimeUnit.MILLISECONDS ); InternalFactHandle handle3 = (InternalFactHandle) wm.insert( tick3 ); clock.advanceTime( 4, TimeUnit.MILLISECONDS ); InternalFactHandle handle4 = (InternalFactHandle) wm.insert( tick4 ); InternalFactHandle handle5 = (InternalFactHandle) wm.insert( tick5 ); clock.advanceTime( 1, TimeUnit.MILLISECONDS ); InternalFactHandle handle6 = (InternalFactHandle) wm.insert( tick6 ); InternalFactHandle handle7 = (InternalFactHandle) wm.insert( tick7 ); clock.advanceTime( 2, TimeUnit.MILLISECONDS ); InternalFactHandle handle8 = (InternalFactHandle) wm.insert( tick8 ); assertNotNull( handle1 ); assertNotNull( handle2 ); assertNotNull( handle3 ); assertNotNull( handle4 ); assertNotNull( handle5 ); assertNotNull( handle6 ); assertNotNull( handle7 ); assertNotNull( handle8 ); assertTrue( handle1.isEvent() ); assertTrue( handle2.isEvent() ); assertTrue( handle3.isEvent() ); assertTrue( handle4.isEvent() ); assertTrue( handle6.isEvent() ); assertTrue( handle7.isEvent() ); assertTrue( handle8.isEvent() ); // wm = SerializationHelper.serializeObject(wm); wm.fireAllRules(); assertEquals( 1, results_coincides.size() ); assertEquals( tick5, results_coincides.get( 0 ) ); assertEquals( 1, results_before.size() ); assertEquals( tick2, results_before.get( 0 ) ); assertEquals( 1, results_after.size() ); assertEquals( tick3, results_after.get( 0 ) ); assertEquals( 1, results_meets.size() ); assertEquals( tick3, results_meets.get( 0 ) ); assertEquals( 1, results_met_by.size() ); assertEquals( tick2, results_met_by.get( 0 ) ); assertEquals( 1, results_met_by.size() ); assertEquals( tick2, results_met_by.get( 0 ) ); assertEquals( 1, results_overlaps.size() ); assertEquals( tick4, results_overlaps.get( 0 ) ); assertEquals( 1, results_overlapped_by.size() ); assertEquals( tick8, results_overlapped_by.get( 0 ) ); assertEquals( 1, results_during.size() ); assertEquals( tick6, results_during.get( 0 ) ); assertEquals( 1, results_includes.size() ); assertEquals( tick4, results_includes.get( 0 ) ); assertEquals( 1, results_starts.size() ); assertEquals( tick6, results_starts.get( 0 ) ); assertEquals( 1, results_started_by.size() ); assertEquals( tick7, results_started_by.get( 0 ) ); assertEquals( 1, results_finishes.size() ); assertEquals( tick8, results_finishes.get( 0 ) ); assertEquals( 1, results_finished_by.size() ); assertEquals( tick7, results_finished_by.get( 0 ) ); }
diff --git a/src/main/java/PermissionsExListener.java b/src/main/java/PermissionsExListener.java index 995a5ca..5db4ae1 100644 --- a/src/main/java/PermissionsExListener.java +++ b/src/main/java/PermissionsExListener.java @@ -1,59 +1,59 @@ import com.daemitus.deadbolt.listener.DeadboltListener; import com.daemitus.deadbolt.Deadbolt; import com.daemitus.deadbolt.Deadbolted; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerInteractEvent; import ru.tehkode.permissions.PermissionGroup; import ru.tehkode.permissions.PermissionManager; import ru.tehkode.permissions.bukkit.PermissionsEx; public final class PermissionsExListener extends DeadboltListener { private PermissionManager permissions; private static final String patternBracketTooLong = "\\[.{14,}\\]"; @Override public List<String> getDependencies() { return Arrays.asList("PermissionsEx"); } @Override public void load(final Deadbolt plugin) { permissions = PermissionsEx.getPermissionManager(); } @Override public boolean canPlayerInteract(Deadbolted db, PlayerInteractEvent event) { Player player = event.getPlayer(); Set<String> allGroupNames = new HashSet<String>(); - for (PermissionGroup g : permissions.getUser(player).getGroups()) { + for (PermissionGroup g : permissions.getUser(player.getName()).getGroups()) { allGroupNames.add(g.getName()); getInherited(g, allGroupNames); } for (String group : allGroupNames) { if (db.getUsers().contains(truncate("[" + group + "]").toLowerCase())) return true; } return false; } private void getInherited(PermissionGroup group, Set<String> groupNames) { for (PermissionGroup g : group.getParentGroups()) { if (groupNames.add(g.getName())) { getInherited(g, groupNames); } } } private String truncate(String text) { if (text.matches(patternBracketTooLong)) return "[" + text.substring(1, 14) + "]"; return text; } }
true
true
public boolean canPlayerInteract(Deadbolted db, PlayerInteractEvent event) { Player player = event.getPlayer(); Set<String> allGroupNames = new HashSet<String>(); for (PermissionGroup g : permissions.getUser(player).getGroups()) { allGroupNames.add(g.getName()); getInherited(g, allGroupNames); } for (String group : allGroupNames) { if (db.getUsers().contains(truncate("[" + group + "]").toLowerCase())) return true; } return false; }
public boolean canPlayerInteract(Deadbolted db, PlayerInteractEvent event) { Player player = event.getPlayer(); Set<String> allGroupNames = new HashSet<String>(); for (PermissionGroup g : permissions.getUser(player.getName()).getGroups()) { allGroupNames.add(g.getName()); getInherited(g, allGroupNames); } for (String group : allGroupNames) { if (db.getUsers().contains(truncate("[" + group + "]").toLowerCase())) return true; } return false; }
diff --git a/src/edu/brown/cs/systems/modes/lib/Manager.java b/src/edu/brown/cs/systems/modes/lib/Manager.java index 22e3a51..b09f988 100644 --- a/src/edu/brown/cs/systems/modes/lib/Manager.java +++ b/src/edu/brown/cs/systems/modes/lib/Manager.java @@ -1,206 +1,206 @@ package edu.brown.cs.systems.modes.lib; import java.util.ArrayList; import java.util.List; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import edu.brown.cs.systems.modes.lib.data.ModeData; /** * @author Marcelo Martins <[email protected]> * */ public class Manager { private static final String PREFERENCES_FILE = "AppModePreferences"; private static final String TAG = "ModeManager"; private IModeService modeService; private ModeServiceConnection modeConnection; private Context context; private int uid; private String appName; private String packageName; public Manager(Context context) { assert context != null; this.context = context; ApplicationInfo ai = context.getApplicationInfo(); PackageManager pm = context.getPackageManager(); uid = ai.uid; appName = (String) pm.getApplicationLabel(ai); packageName = context.getApplicationInfo().packageName; } /** * Connects a mode-supporting app to the middleware. Should be called by * apps on its main activity onCreate() * * @return whether connection succeded or not */ public boolean connectApplication() { // If app is running for the first time, register its info and modes // to middleware if (isFirstTimeRun()) { return bindModeService(); } return true; } /** * Disconnects a mode-supporting app from middleware * * @return whether disconnection was okay */ public boolean disconnectApplication() { releaseModeService(); return true; } /** * Binding occurs asynchronously and bound-service methods cannot be called * immediately. We can only use bound service after receiving a callback * telling the connection has been established (onServiceConnected). */ private void connectionCallback() { // Get supported modes from application ArrayList<ModeData> modes = null; try { modes = (ArrayList<ModeData>) modeService.getModes(); } catch (RemoteException e) { Log.e(TAG, "Couldn't get mones from application"); e.printStackTrace(); } // Send to middleware basic info on app. Also, send its modes as // intent's extra data. Intent intent = new Intent(); intent.setComponent(new ComponentName( Constants.REGISTRY_PACKAGENAME, Constants.REGISTRY_CLASSNAME)); intent.setAction(Constants.ACTION_REGISTER_APP); intent.putExtra("uid", uid); intent.putExtra("name", appName); // Here's the deal: in order to request info from an app, the // middleware must send an intent. Implicit intents won't work, // since all apps supporting the intent will respond and we want to // communicate to a specific one. Explicit intents will work, but // need to be told its package and class destination. We register // them here so that the middleware can use them later. intent.putExtra("packageName", packageName); - intent.putExtra("className", packageName + "." + intent.putExtra("modeProxyClassName", packageName + "." + Constants.MODE_PROXY_CLASS); Bundle bundle = new Bundle(); bundle.putParcelableArrayList("modes", modes); intent.putExtras(bundle); context.sendBroadcast(intent); setFirstTimeRun(false); } /** * * @return whether mode-supporting app is being run for the first time */ private boolean isFirstTimeRun() { SharedPreferences prefs = context.getSharedPreferences( PREFERENCES_FILE, Context.MODE_PRIVATE); return !prefs.getBoolean("RegisteredModes", false); } /** * Saves whether app has been run before to storage for later reference * * @param value */ private void setFirstTimeRun(boolean value) { SharedPreferences prefs = context.getSharedPreferences( PREFERENCES_FILE, Context.MODE_PRIVATE); SharedPreferences.Editor ed = prefs.edit(); ed.putBoolean("RegisteredModes", !value); ed.commit(); } /** * Binds to application implementing mode service. Used by middleware. * * @return whether binding worked or not **/ private boolean bindModeService() { boolean ret = true; if (modeService == null) { modeConnection = new ModeServiceConnection(); Intent intent = new Intent(); intent.setComponent(new ComponentName(packageName, packageName + "." + Constants.MODE_PROXY_CLASS)); ret = context.bindService(intent, modeConnection, Context.BIND_AUTO_CREATE); Log.d(TAG, "bindModeService() bound with " + ret); } else { Log.w(TAG, "Cannot bind to mode service - Service already bound"); } return ret; } /** * Unbinds from app implementing mode service. Used by middleware. * **/ private void releaseModeService() { if (modeService != null) { modeService = null; context.unbindService(modeConnection); modeConnection = null; Log.d(TAG, "releaseModeService()"); } else { Log.w(TAG, "Cannot unbind mode service - Service not bound"); } } /** * Connection to application mode service * * @author Marcelo Martins <[email protected]> * */ class ModeServiceConnection implements ServiceConnection { public void onServiceConnected(ComponentName name, IBinder boundService) { modeService = IModeService.Stub.asInterface((IBinder) boundService); Log.d(TAG, "onServiceConnected() connected"); connectionCallback(); } public void onServiceDisconnected(ComponentName name) { modeService = null; Log.d(TAG, "onServiceDisconnected() disconnected"); } } }
true
true
private void connectionCallback() { // Get supported modes from application ArrayList<ModeData> modes = null; try { modes = (ArrayList<ModeData>) modeService.getModes(); } catch (RemoteException e) { Log.e(TAG, "Couldn't get mones from application"); e.printStackTrace(); } // Send to middleware basic info on app. Also, send its modes as // intent's extra data. Intent intent = new Intent(); intent.setComponent(new ComponentName( Constants.REGISTRY_PACKAGENAME, Constants.REGISTRY_CLASSNAME)); intent.setAction(Constants.ACTION_REGISTER_APP); intent.putExtra("uid", uid); intent.putExtra("name", appName); // Here's the deal: in order to request info from an app, the // middleware must send an intent. Implicit intents won't work, // since all apps supporting the intent will respond and we want to // communicate to a specific one. Explicit intents will work, but // need to be told its package and class destination. We register // them here so that the middleware can use them later. intent.putExtra("packageName", packageName); intent.putExtra("className", packageName + "." + Constants.MODE_PROXY_CLASS); Bundle bundle = new Bundle(); bundle.putParcelableArrayList("modes", modes); intent.putExtras(bundle); context.sendBroadcast(intent); setFirstTimeRun(false); }
private void connectionCallback() { // Get supported modes from application ArrayList<ModeData> modes = null; try { modes = (ArrayList<ModeData>) modeService.getModes(); } catch (RemoteException e) { Log.e(TAG, "Couldn't get mones from application"); e.printStackTrace(); } // Send to middleware basic info on app. Also, send its modes as // intent's extra data. Intent intent = new Intent(); intent.setComponent(new ComponentName( Constants.REGISTRY_PACKAGENAME, Constants.REGISTRY_CLASSNAME)); intent.setAction(Constants.ACTION_REGISTER_APP); intent.putExtra("uid", uid); intent.putExtra("name", appName); // Here's the deal: in order to request info from an app, the // middleware must send an intent. Implicit intents won't work, // since all apps supporting the intent will respond and we want to // communicate to a specific one. Explicit intents will work, but // need to be told its package and class destination. We register // them here so that the middleware can use them later. intent.putExtra("packageName", packageName); intent.putExtra("modeProxyClassName", packageName + "." + Constants.MODE_PROXY_CLASS); Bundle bundle = new Bundle(); bundle.putParcelableArrayList("modes", modes); intent.putExtras(bundle); context.sendBroadcast(intent); setFirstTimeRun(false); }
diff --git a/LoECraftPack.java b/LoECraftPack.java index cfaf8e0..885a121 100644 --- a/LoECraftPack.java +++ b/LoECraftPack.java @@ -1,303 +1,303 @@ package loecraftpack; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import loecraftpack.blocks.BlockBedColor; import loecraftpack.blocks.ProtectionMonolithBlock; import loecraftpack.blocks.te.ProtectionMonolithTileEntity; import loecraftpack.items.Bits; import loecraftpack.items.ItemBedColor; import loecraftpack.logic.handlers.EventHandler; import loecraftpack.logic.handlers.GuiHandler; import loecraftpack.packethandling.ClientPacketHandler; import loecraftpack.packethandling.ServerPacketHandler; import loecraftpack.proxies.CommonProxy; import net.minecraft.block.Block; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.item.crafting.IRecipe; import net.minecraftforge.common.MinecraftForge; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.Init; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.Mod.PostInit; import cpw.mods.fml.common.Mod.PreInit; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.network.NetworkMod; import cpw.mods.fml.common.network.NetworkMod.SidedPacketHandler; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.LanguageRegistry; @Mod(modid = "loecraftpack", name = "LoECraft Pack", version = "1.0") @NetworkMod(clientSideRequired=true, serverSideRequired=false, clientPacketHandlerSpec = @SidedPacketHandler(channels = {"loecraftpack" }, packetHandler = ClientPacketHandler.class), serverPacketHandlerSpec = @SidedPacketHandler(channels = {"loecraftpack" }, packetHandler = ServerPacketHandler.class)) public class LoECraftPack { @Instance public static LoECraftPack instance = new LoECraftPack(); ///Colored Beds/// private static ItemBedColor iBedWhite; private static ItemBedColor iBedOrange; private static ItemBedColor iBedMagenta; private static ItemBedColor iBedLightBlue; private static ItemBedColor iBedYellow; private static ItemBedColor iBedLime; private static ItemBedColor iBedPink; private static ItemBedColor iBedGray; private static ItemBedColor iBedLightGray; private static ItemBedColor iBedCyan; private static ItemBedColor iBedPurple; private static ItemBedColor iBedBlue; private static ItemBedColor iBedBrown; private static ItemBedColor iBedGreen; private static ItemBedColor iBedRed; private static ItemBedColor iBedBlack; private static BlockBedColor bBedWhite; private static BlockBedColor bBedOrange; private static BlockBedColor bBedMagenta; private static BlockBedColor bBedLightBlue; private static BlockBedColor bBedYellow; private static BlockBedColor bBedLime; private static BlockBedColor bBedPink; private static BlockBedColor bBedGray; private static BlockBedColor bBedLightGray; private static BlockBedColor bBedCyan; private static BlockBedColor bBedPurple; private static BlockBedColor bBedBlue; private static BlockBedColor bBedBrown; private static BlockBedColor bBedGreen; private static BlockBedColor bBedRed; private static BlockBedColor bBedBlack; ///Colored-Beds END/// @SidedProxy(clientSide = "loecraftpack.proxies.ClientProxy", serverSide = "loecraftpack.proxies.CommonProxy") public static CommonProxy proxy; public static CreativeTabs LoECraftTab = new CreativeTabs("LoECraftTab") { public ItemStack getIconItemStack() { return new ItemStack(Item.writableBook, 1, 0); } }; public static final Bits bits = new Bits(667); public static final ProtectionMonolithBlock monolith = new ProtectionMonolithBlock(666); @PreInit public void preInit(FMLPreInitializationEvent event) { ///Colored Beds/// iBedWhite = new ItemBedColor(670); iBedOrange = new ItemBedColor(671); iBedMagenta = new ItemBedColor(672); iBedLightBlue = new ItemBedColor(673); iBedYellow = new ItemBedColor(674); iBedLime = new ItemBedColor(675); iBedPink = new ItemBedColor(676); iBedGray = new ItemBedColor(677); iBedLightGray = new ItemBedColor(678); iBedCyan = new ItemBedColor(679); iBedPurple = new ItemBedColor(680); iBedBlue = new ItemBedColor(681); iBedBrown = new ItemBedColor(682); iBedGreen = new ItemBedColor(683); iBedRed = new ItemBedColor(684); iBedBlack = new ItemBedColor(685); bBedWhite = new BlockBedColor(670); bBedOrange = new BlockBedColor(671); bBedMagenta = new BlockBedColor(672); bBedLightBlue = new BlockBedColor(673); bBedYellow = new BlockBedColor(674); bBedLime = new BlockBedColor(675); bBedPink = new BlockBedColor(676); bBedGray = new BlockBedColor(677); bBedLightGray = new BlockBedColor(678); bBedCyan = new BlockBedColor(679); bBedPurple = new BlockBedColor(680); bBedBlue = new BlockBedColor(681); bBedBrown = new BlockBedColor(682); bBedGreen = new BlockBedColor(683); bBedRed = new BlockBedColor(684); bBedBlack = new BlockBedColor(685); //Link relation information directly iBedWhite.block = bBedWhite; bBedWhite.item = iBedWhite; iBedOrange.block = bBedOrange; bBedOrange.item = iBedOrange; iBedMagenta.block = bBedMagenta; bBedMagenta.item = iBedMagenta; iBedLightBlue.block = bBedLightBlue; bBedLightBlue.item = iBedLightBlue; iBedYellow.block = bBedYellow; bBedYellow.item = iBedYellow; iBedLime.block = bBedLime; bBedLime.item = iBedLime; iBedPink.block = bBedPink; bBedPink.item = iBedPink; iBedGray.block = bBedGray; bBedGray.item = iBedGray; iBedLightGray.block = bBedLightGray; bBedLightGray.item = iBedLightGray; iBedCyan.block = bBedCyan; bBedCyan.item = iBedCyan; iBedPurple.block = bBedPurple; bBedPurple.item = iBedPurple; iBedBlue.block = bBedBlue; bBedBlue.item = iBedBlue; iBedBrown.block = bBedBrown; bBedBrown.item = iBedBrown; iBedGreen.block = bBedGreen; bBedGreen.item = iBedGreen; iBedRed.block = bBedRed; bBedRed.item = iBedRed; iBedBlack.block = bBedBlack; bBedBlack.item = iBedBlack; ///Colored-Beds END/// } @Init public void load(FMLInitializationEvent e) { LanguageRegistry.instance().addStringLocalization("itemGroup.LoECraftTab", "en_US", "LoECraft"); for(int i = 0; i < Bits.names.length; i++ ) LanguageRegistry.instance().addStringLocalization("item.itemBits." + Bits.iconNames[i] + ".name", "en_US", Bits.names[i]); GameRegistry.registerBlock(monolith, "ProtectionMonolithBlock"); LanguageRegistry.addName(monolith, "Protection Monolith"); GameRegistry.registerTileEntity(ProtectionMonolithTileEntity.class, "ProtectionMonolithTileEntity"); NetworkRegistry.instance().registerGuiHandler(this, new GuiHandler()); MinecraftForge.EVENT_BUS.register(new EventHandler()); proxy.doProxyStuff(); ///Colored Beds/// //Bed Items LanguageRegistry.addName(iBedWhite, "Bed : White"); LanguageRegistry.addName(iBedOrange, "Bed : Orange"); LanguageRegistry.addName(iBedMagenta, "Bed : Magenta"); LanguageRegistry.addName(iBedLightBlue, "Bed : Light Blue"); LanguageRegistry.addName(iBedYellow, "Bed : Yellow"); LanguageRegistry.addName(iBedLime, "Bed : Lime"); LanguageRegistry.addName(iBedPink, "Bed : Pink"); LanguageRegistry.addName(iBedGray, "Bed : Gray"); LanguageRegistry.addName(iBedLightGray, "Bed : Light Gray"); LanguageRegistry.addName(iBedCyan, "Bed : Cyan"); LanguageRegistry.addName(iBedPurple, "Bed : Purple"); LanguageRegistry.addName(iBedBlue, "Bed : Blue"); LanguageRegistry.addName(iBedBrown, "Bed : Brown"); LanguageRegistry.addName(iBedGreen, "Bed : Green"); LanguageRegistry.addName(iBedRed, "Bed : Red"); LanguageRegistry.addName(iBedBlack, "Bed : Black"); //Bed Blocks LanguageRegistry.addName( bBedWhite, "Bed : White"); GameRegistry.registerBlock(bBedWhite, "bedWhite"); LanguageRegistry.addName( bBedOrange, "Bed : Orange"); GameRegistry.registerBlock(bBedOrange, "bedOrange"); LanguageRegistry.addName( bBedMagenta, "Bed : Magenta"); GameRegistry.registerBlock(bBedMagenta, "bedMagenta"); LanguageRegistry.addName( bBedLightBlue, "Bed : Light Blue"); GameRegistry.registerBlock(bBedLightBlue, "bedLightBlue"); LanguageRegistry.addName( bBedYellow, "Bed : Yellow"); GameRegistry.registerBlock(bBedYellow, "bedYellow"); LanguageRegistry.addName( bBedLime, "Bed : Lime"); GameRegistry.registerBlock(bBedLime, "bedLime"); LanguageRegistry.addName( bBedPink, "Bed : Pink"); GameRegistry.registerBlock(bBedPink, "bedPink"); LanguageRegistry.addName( bBedGray, "Bed : Gray"); GameRegistry.registerBlock(bBedGray, "bedGray"); LanguageRegistry.addName( bBedLightGray, "Bed : Light Gray"); GameRegistry.registerBlock(bBedLightGray, "bedLightGray"); LanguageRegistry.addName( bBedCyan, "Bed : Cyan"); GameRegistry.registerBlock(bBedCyan, "bedCyan"); LanguageRegistry.addName( bBedPurple, "Bed : Purple"); GameRegistry.registerBlock(bBedPurple, "bedPurple"); LanguageRegistry.addName( bBedBlue, "Bed : Blue"); GameRegistry.registerBlock(bBedBlue, "bedBlue"); LanguageRegistry.addName( bBedBrown, "Bed : Brown"); GameRegistry.registerBlock(bBedBrown, "bedBrown"); LanguageRegistry.addName( bBedGreen, "Bed : Green"); GameRegistry.registerBlock(bBedGreen, "bedGreen"); LanguageRegistry.addName( bBedRed, "Bed : Red"); GameRegistry.registerBlock(bBedRed, "bedRed"); LanguageRegistry.addName( bBedBlack, "Bed : Black"); GameRegistry.registerBlock(bBedBlack, "bedBlack"); ///Colored-Beds END/// ///Colored Beds/// ///Update Recipes //bed list by wool color Item[] bedItems = new Item[16]; bedItems [0] = iBedWhite; bedItems [1] = iBedOrange; bedItems [2] = iBedMagenta; bedItems [3] = iBedLightBlue; bedItems [4] = iBedYellow; bedItems [5] = iBedLime; bedItems [6] = iBedPink; bedItems [7] = iBedGray; bedItems [8] = iBedLightGray; bedItems [9] = iBedCyan; bedItems [10] = iBedPurple; bedItems [11] = iBedBlue; bedItems [12] = iBedBrown; - bedItems [13] = iBedGreen; + bedItems [15] = iBedGreen; bedItems [14] = iBedRed; - bedItems [15] = iBedBlack; + bedItems [13] = iBedBlack; //get CraftingManager CraftingManager cmi = CraftingManager.getInstance(); //locate and remove old bed recipe List recipes = cmi.getRecipeList(); Iterator r = recipes.iterator(); while (r.hasNext()) { //test if recipe creates a bed IRecipe ir = (IRecipe)r.next(); if( ir != null && ir.getRecipeOutput() != null && ir.getRecipeOutput().itemID == Item.bed.itemID ) { //clear old recipe and move on r.remove(); break;//there really should only be one vanilla bed to remove } } //add new recipes to replace the old one for (int i = 0; i < 16; i++) - cmi.addRecipe(new ItemStack(bedItems[i], 1), "###", "XXX", '#', new ItemStack(Block.cloth, 1, i), 'X', Block.planks); + cmi.addRecipe(new ItemStack(bedItems[i]), "###", "XXX", '#', new ItemStack(Block.cloth, 1, i), 'X', Block.planks); ///Colored-Beds END/// } @PostInit public void postLoad(FMLPostInitializationEvent e) { List recipeList = new ArrayList(); recipeList.addAll(CraftingManager.getInstance().getRecipeList()); for(int i = 0; i < recipeList.size(); i++) { IRecipe recipe = (IRecipe)recipeList.get(i); ItemStack output = recipe.getRecipeOutput(); if (output != null && output.itemID == 130) CraftingManager.getInstance().getRecipeList().remove(recipe); } } }
false
true
public void load(FMLInitializationEvent e) { LanguageRegistry.instance().addStringLocalization("itemGroup.LoECraftTab", "en_US", "LoECraft"); for(int i = 0; i < Bits.names.length; i++ ) LanguageRegistry.instance().addStringLocalization("item.itemBits." + Bits.iconNames[i] + ".name", "en_US", Bits.names[i]); GameRegistry.registerBlock(monolith, "ProtectionMonolithBlock"); LanguageRegistry.addName(monolith, "Protection Monolith"); GameRegistry.registerTileEntity(ProtectionMonolithTileEntity.class, "ProtectionMonolithTileEntity"); NetworkRegistry.instance().registerGuiHandler(this, new GuiHandler()); MinecraftForge.EVENT_BUS.register(new EventHandler()); proxy.doProxyStuff(); ///Colored Beds/// //Bed Items LanguageRegistry.addName(iBedWhite, "Bed : White"); LanguageRegistry.addName(iBedOrange, "Bed : Orange"); LanguageRegistry.addName(iBedMagenta, "Bed : Magenta"); LanguageRegistry.addName(iBedLightBlue, "Bed : Light Blue"); LanguageRegistry.addName(iBedYellow, "Bed : Yellow"); LanguageRegistry.addName(iBedLime, "Bed : Lime"); LanguageRegistry.addName(iBedPink, "Bed : Pink"); LanguageRegistry.addName(iBedGray, "Bed : Gray"); LanguageRegistry.addName(iBedLightGray, "Bed : Light Gray"); LanguageRegistry.addName(iBedCyan, "Bed : Cyan"); LanguageRegistry.addName(iBedPurple, "Bed : Purple"); LanguageRegistry.addName(iBedBlue, "Bed : Blue"); LanguageRegistry.addName(iBedBrown, "Bed : Brown"); LanguageRegistry.addName(iBedGreen, "Bed : Green"); LanguageRegistry.addName(iBedRed, "Bed : Red"); LanguageRegistry.addName(iBedBlack, "Bed : Black"); //Bed Blocks LanguageRegistry.addName( bBedWhite, "Bed : White"); GameRegistry.registerBlock(bBedWhite, "bedWhite"); LanguageRegistry.addName( bBedOrange, "Bed : Orange"); GameRegistry.registerBlock(bBedOrange, "bedOrange"); LanguageRegistry.addName( bBedMagenta, "Bed : Magenta"); GameRegistry.registerBlock(bBedMagenta, "bedMagenta"); LanguageRegistry.addName( bBedLightBlue, "Bed : Light Blue"); GameRegistry.registerBlock(bBedLightBlue, "bedLightBlue"); LanguageRegistry.addName( bBedYellow, "Bed : Yellow"); GameRegistry.registerBlock(bBedYellow, "bedYellow"); LanguageRegistry.addName( bBedLime, "Bed : Lime"); GameRegistry.registerBlock(bBedLime, "bedLime"); LanguageRegistry.addName( bBedPink, "Bed : Pink"); GameRegistry.registerBlock(bBedPink, "bedPink"); LanguageRegistry.addName( bBedGray, "Bed : Gray"); GameRegistry.registerBlock(bBedGray, "bedGray"); LanguageRegistry.addName( bBedLightGray, "Bed : Light Gray"); GameRegistry.registerBlock(bBedLightGray, "bedLightGray"); LanguageRegistry.addName( bBedCyan, "Bed : Cyan"); GameRegistry.registerBlock(bBedCyan, "bedCyan"); LanguageRegistry.addName( bBedPurple, "Bed : Purple"); GameRegistry.registerBlock(bBedPurple, "bedPurple"); LanguageRegistry.addName( bBedBlue, "Bed : Blue"); GameRegistry.registerBlock(bBedBlue, "bedBlue"); LanguageRegistry.addName( bBedBrown, "Bed : Brown"); GameRegistry.registerBlock(bBedBrown, "bedBrown"); LanguageRegistry.addName( bBedGreen, "Bed : Green"); GameRegistry.registerBlock(bBedGreen, "bedGreen"); LanguageRegistry.addName( bBedRed, "Bed : Red"); GameRegistry.registerBlock(bBedRed, "bedRed"); LanguageRegistry.addName( bBedBlack, "Bed : Black"); GameRegistry.registerBlock(bBedBlack, "bedBlack"); ///Colored-Beds END/// ///Colored Beds/// ///Update Recipes //bed list by wool color Item[] bedItems = new Item[16]; bedItems [0] = iBedWhite; bedItems [1] = iBedOrange; bedItems [2] = iBedMagenta; bedItems [3] = iBedLightBlue; bedItems [4] = iBedYellow; bedItems [5] = iBedLime; bedItems [6] = iBedPink; bedItems [7] = iBedGray; bedItems [8] = iBedLightGray; bedItems [9] = iBedCyan; bedItems [10] = iBedPurple; bedItems [11] = iBedBlue; bedItems [12] = iBedBrown; bedItems [13] = iBedGreen; bedItems [14] = iBedRed; bedItems [15] = iBedBlack; //get CraftingManager CraftingManager cmi = CraftingManager.getInstance(); //locate and remove old bed recipe List recipes = cmi.getRecipeList(); Iterator r = recipes.iterator(); while (r.hasNext()) { //test if recipe creates a bed IRecipe ir = (IRecipe)r.next(); if( ir != null && ir.getRecipeOutput() != null && ir.getRecipeOutput().itemID == Item.bed.itemID ) { //clear old recipe and move on r.remove(); break;//there really should only be one vanilla bed to remove } } //add new recipes to replace the old one for (int i = 0; i < 16; i++) cmi.addRecipe(new ItemStack(bedItems[i], 1), "###", "XXX", '#', new ItemStack(Block.cloth, 1, i), 'X', Block.planks); ///Colored-Beds END/// }
public void load(FMLInitializationEvent e) { LanguageRegistry.instance().addStringLocalization("itemGroup.LoECraftTab", "en_US", "LoECraft"); for(int i = 0; i < Bits.names.length; i++ ) LanguageRegistry.instance().addStringLocalization("item.itemBits." + Bits.iconNames[i] + ".name", "en_US", Bits.names[i]); GameRegistry.registerBlock(monolith, "ProtectionMonolithBlock"); LanguageRegistry.addName(monolith, "Protection Monolith"); GameRegistry.registerTileEntity(ProtectionMonolithTileEntity.class, "ProtectionMonolithTileEntity"); NetworkRegistry.instance().registerGuiHandler(this, new GuiHandler()); MinecraftForge.EVENT_BUS.register(new EventHandler()); proxy.doProxyStuff(); ///Colored Beds/// //Bed Items LanguageRegistry.addName(iBedWhite, "Bed : White"); LanguageRegistry.addName(iBedOrange, "Bed : Orange"); LanguageRegistry.addName(iBedMagenta, "Bed : Magenta"); LanguageRegistry.addName(iBedLightBlue, "Bed : Light Blue"); LanguageRegistry.addName(iBedYellow, "Bed : Yellow"); LanguageRegistry.addName(iBedLime, "Bed : Lime"); LanguageRegistry.addName(iBedPink, "Bed : Pink"); LanguageRegistry.addName(iBedGray, "Bed : Gray"); LanguageRegistry.addName(iBedLightGray, "Bed : Light Gray"); LanguageRegistry.addName(iBedCyan, "Bed : Cyan"); LanguageRegistry.addName(iBedPurple, "Bed : Purple"); LanguageRegistry.addName(iBedBlue, "Bed : Blue"); LanguageRegistry.addName(iBedBrown, "Bed : Brown"); LanguageRegistry.addName(iBedGreen, "Bed : Green"); LanguageRegistry.addName(iBedRed, "Bed : Red"); LanguageRegistry.addName(iBedBlack, "Bed : Black"); //Bed Blocks LanguageRegistry.addName( bBedWhite, "Bed : White"); GameRegistry.registerBlock(bBedWhite, "bedWhite"); LanguageRegistry.addName( bBedOrange, "Bed : Orange"); GameRegistry.registerBlock(bBedOrange, "bedOrange"); LanguageRegistry.addName( bBedMagenta, "Bed : Magenta"); GameRegistry.registerBlock(bBedMagenta, "bedMagenta"); LanguageRegistry.addName( bBedLightBlue, "Bed : Light Blue"); GameRegistry.registerBlock(bBedLightBlue, "bedLightBlue"); LanguageRegistry.addName( bBedYellow, "Bed : Yellow"); GameRegistry.registerBlock(bBedYellow, "bedYellow"); LanguageRegistry.addName( bBedLime, "Bed : Lime"); GameRegistry.registerBlock(bBedLime, "bedLime"); LanguageRegistry.addName( bBedPink, "Bed : Pink"); GameRegistry.registerBlock(bBedPink, "bedPink"); LanguageRegistry.addName( bBedGray, "Bed : Gray"); GameRegistry.registerBlock(bBedGray, "bedGray"); LanguageRegistry.addName( bBedLightGray, "Bed : Light Gray"); GameRegistry.registerBlock(bBedLightGray, "bedLightGray"); LanguageRegistry.addName( bBedCyan, "Bed : Cyan"); GameRegistry.registerBlock(bBedCyan, "bedCyan"); LanguageRegistry.addName( bBedPurple, "Bed : Purple"); GameRegistry.registerBlock(bBedPurple, "bedPurple"); LanguageRegistry.addName( bBedBlue, "Bed : Blue"); GameRegistry.registerBlock(bBedBlue, "bedBlue"); LanguageRegistry.addName( bBedBrown, "Bed : Brown"); GameRegistry.registerBlock(bBedBrown, "bedBrown"); LanguageRegistry.addName( bBedGreen, "Bed : Green"); GameRegistry.registerBlock(bBedGreen, "bedGreen"); LanguageRegistry.addName( bBedRed, "Bed : Red"); GameRegistry.registerBlock(bBedRed, "bedRed"); LanguageRegistry.addName( bBedBlack, "Bed : Black"); GameRegistry.registerBlock(bBedBlack, "bedBlack"); ///Colored-Beds END/// ///Colored Beds/// ///Update Recipes //bed list by wool color Item[] bedItems = new Item[16]; bedItems [0] = iBedWhite; bedItems [1] = iBedOrange; bedItems [2] = iBedMagenta; bedItems [3] = iBedLightBlue; bedItems [4] = iBedYellow; bedItems [5] = iBedLime; bedItems [6] = iBedPink; bedItems [7] = iBedGray; bedItems [8] = iBedLightGray; bedItems [9] = iBedCyan; bedItems [10] = iBedPurple; bedItems [11] = iBedBlue; bedItems [12] = iBedBrown; bedItems [15] = iBedGreen; bedItems [14] = iBedRed; bedItems [13] = iBedBlack; //get CraftingManager CraftingManager cmi = CraftingManager.getInstance(); //locate and remove old bed recipe List recipes = cmi.getRecipeList(); Iterator r = recipes.iterator(); while (r.hasNext()) { //test if recipe creates a bed IRecipe ir = (IRecipe)r.next(); if( ir != null && ir.getRecipeOutput() != null && ir.getRecipeOutput().itemID == Item.bed.itemID ) { //clear old recipe and move on r.remove(); break;//there really should only be one vanilla bed to remove } } //add new recipes to replace the old one for (int i = 0; i < 16; i++) cmi.addRecipe(new ItemStack(bedItems[i]), "###", "XXX", '#', new ItemStack(Block.cloth, 1, i), 'X', Block.planks); ///Colored-Beds END/// }
diff --git a/src/hoten/serving/ServingSocket.java b/src/hoten/serving/ServingSocket.java index efc3d66..0791575 100644 --- a/src/hoten/serving/ServingSocket.java +++ b/src/hoten/serving/ServingSocket.java @@ -1,222 +1,221 @@ package hoten.serving; import java.io.File; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.Arrays; import java.util.Stack; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * ServingSocket.java * * Extend this class to act as a server. See the chat example. * * @author Hoten */ public abstract class ServingSocket extends Thread { final private ServerSocket socket; final private ScheduledExecutorService heartbeatScheduler; final protected CopyOnWriteArrayList<SocketHandler> clients = new CopyOnWriteArrayList(); private File clientDataFolder; private ByteArray clientDataHashes; private boolean open; public ServingSocket(int port) throws IOException { super("Serving Socket " + port); socket = new ServerSocket(port); clientDataHashes = null; //start heartbeat final int ms = 250; heartbeatScheduler = Executors.newScheduledThreadPool(1); final ByteArray msg = new ByteArray(); final Runnable heartbeat = new Runnable() { @Override public void run() { sendToAll(msg); } }; heartbeatScheduler.scheduleAtFixedRate(heartbeat, ms, ms, TimeUnit.MILLISECONDS); } //use this constructor if you want to transfer data files to clients public ServingSocket(int port, File clientDataFolder) throws IOException { this(port); this.clientDataFolder = clientDataFolder; if (!clientDataFolder.exists()) { clientDataFolder.mkdirs(); } //build the hashes clientDataHashes = new ByteArray(); Stack<File> a = new Stack(); a.addAll(Arrays.asList(clientDataFolder.listFiles())); while (!a.isEmpty()) { File cur = a.pop(); if (cur.isDirectory()) { a.addAll(Arrays.asList(cur.listFiles())); } else { String path = cur.getName(); File f = cur; ByteArray ba = ByteArray.readFromFile(f); //build the relative path to the clientDataFolder //TODO use stringbuilder. find a way to do it when adding to begining while ((f = f.getParentFile()) != null && !f.equals(clientDataFolder)) { path = f.getName() + File.separator + path; } clientDataHashes.writeUTF(path); clientDataHashes.writeUTF(ba.getMD5Hash()); } } clientDataHashes.trim(); } public ByteArray getFilesForClient(ByteArray requests) { ByteArray ba = new ByteArray(); while (requests.getBytesAvailable() > 0) { String fileName = requests.readUTF(); ByteArray fileBytes = ByteArray.readFromFile(new File(clientDataFolder, fileName)); ba.writeUTF(fileName); ba.writeInt(fileBytes.getSize()); ba.writeBytes(fileBytes); } ba.trim(); //ba.compress(); return ba; } public ByteArray getClientDataHashes() { return clientDataHashes; } public void sendToAll(ByteArray msg) { for (SocketHandler c : clients) { c.send(msg); } } public void sendToAllBut(ByteArray msg, SocketHandler client) { for (SocketHandler c : clients) { if (c != client) { c.send(msg); } } } @Override public void run() { open = true; while (open) { try { SocketHandler newClient = makeNewConnection(socket.accept()); clients.add(newClient); } catch (IOException ex) { System.out.println("error making new connection: " + ex); } } try { socket.close(); } catch (IOException ex) { System.out.println("error closing server: " + ex); } } public void close() { for (SocketHandler c : clients) { c.close(); } open = false; } public void removeClient(SocketHandler client) { clients.remove(client); } protected abstract SocketHandler makeNewConnection(Socket newConnection) throws IOException; /** * * CLIENT SIDE - for use on java clients * * reader = message from server contains MD5 hashes of all the necessary * client data files...music, graphics, etc. see how clientDataHashes is * built for reference * * if the server hash != the client's local hash, the file does not exist, * or if there exists files/folders in the localdata folder that the server * does not explicitly list, then delete the excess files/folders * * returns a byte array of file names that the client needs to request * * also prunes the client's localdata of files that are not in the server's * clientdata folder * */ public static ByteArray clientRespondToHashes(ByteArray reader) { ByteArray msg = new ByteArray(); File local = new File("localdata"); //ensure it exists if (!local.exists()) { local.mkdirs(); } //create an arraylist of all the files in the localdata folder ArrayList<File> currentf = new ArrayList(); Stack<File> all = new Stack(); all.addAll(Arrays.asList(local.listFiles())); while (!all.isEmpty()) { File cur = all.pop(); if (cur.isDirectory()) { all.addAll(Arrays.asList(cur.listFiles())); currentf.add(cur); } else { currentf.add(cur); } } //now lets go through the hashes and compare with the local files while (reader.getBytesAvailable() > 0) { String fileName = reader.readUTF(); String fileHash = reader.readUTF(); File f = new File("localdata" + File.separator + fileName); //remove this file as a candidate for pruning for (File cf : currentf) { if (cf.equals(f)) { currentf.remove(cf); break; } } //if locally the file doesn't exist or the hash is wrong, request update if (!f.exists() || !ByteArray.readFromFile(f).getMD5Hash().equals(fileHash)) { msg.writeUTF(fileName); } } /** * currentf should now only contains files that were not listed by the * server,but are still in the localdata folder. we do not want to keep * these files,so let's delete them. also should have all the * directories, but that is okay because they can't be deleted if they * contain files. */ for (File f : currentf) { f.delete(); } - msg.rewind(); return msg; } }
true
true
public static ByteArray clientRespondToHashes(ByteArray reader) { ByteArray msg = new ByteArray(); File local = new File("localdata"); //ensure it exists if (!local.exists()) { local.mkdirs(); } //create an arraylist of all the files in the localdata folder ArrayList<File> currentf = new ArrayList(); Stack<File> all = new Stack(); all.addAll(Arrays.asList(local.listFiles())); while (!all.isEmpty()) { File cur = all.pop(); if (cur.isDirectory()) { all.addAll(Arrays.asList(cur.listFiles())); currentf.add(cur); } else { currentf.add(cur); } } //now lets go through the hashes and compare with the local files while (reader.getBytesAvailable() > 0) { String fileName = reader.readUTF(); String fileHash = reader.readUTF(); File f = new File("localdata" + File.separator + fileName); //remove this file as a candidate for pruning for (File cf : currentf) { if (cf.equals(f)) { currentf.remove(cf); break; } } //if locally the file doesn't exist or the hash is wrong, request update if (!f.exists() || !ByteArray.readFromFile(f).getMD5Hash().equals(fileHash)) { msg.writeUTF(fileName); } } /** * currentf should now only contains files that were not listed by the * server,but are still in the localdata folder. we do not want to keep * these files,so let's delete them. also should have all the * directories, but that is okay because they can't be deleted if they * contain files. */ for (File f : currentf) { f.delete(); } msg.rewind(); return msg; }
public static ByteArray clientRespondToHashes(ByteArray reader) { ByteArray msg = new ByteArray(); File local = new File("localdata"); //ensure it exists if (!local.exists()) { local.mkdirs(); } //create an arraylist of all the files in the localdata folder ArrayList<File> currentf = new ArrayList(); Stack<File> all = new Stack(); all.addAll(Arrays.asList(local.listFiles())); while (!all.isEmpty()) { File cur = all.pop(); if (cur.isDirectory()) { all.addAll(Arrays.asList(cur.listFiles())); currentf.add(cur); } else { currentf.add(cur); } } //now lets go through the hashes and compare with the local files while (reader.getBytesAvailable() > 0) { String fileName = reader.readUTF(); String fileHash = reader.readUTF(); File f = new File("localdata" + File.separator + fileName); //remove this file as a candidate for pruning for (File cf : currentf) { if (cf.equals(f)) { currentf.remove(cf); break; } } //if locally the file doesn't exist or the hash is wrong, request update if (!f.exists() || !ByteArray.readFromFile(f).getMD5Hash().equals(fileHash)) { msg.writeUTF(fileName); } } /** * currentf should now only contains files that were not listed by the * server,but are still in the localdata folder. we do not want to keep * these files,so let's delete them. also should have all the * directories, but that is okay because they can't be deleted if they * contain files. */ for (File f : currentf) { f.delete(); } return msg; }
diff --git a/src/org/biojava/bio/seq/impl/AssembledSymbolList.java b/src/org/biojava/bio/seq/impl/AssembledSymbolList.java index 1f3624096..6f07c2642 100644 --- a/src/org/biojava/bio/seq/impl/AssembledSymbolList.java +++ b/src/org/biojava/bio/seq/impl/AssembledSymbolList.java @@ -1,197 +1,197 @@ /* * 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.seq.impl; import java.util.*; import org.biojava.bio.*; import org.biojava.bio.seq.*; import org.biojava.utils.*; import org.biojava.bio.symbol.*; /** * Support class for applications which need to patch together sections * of sequence into a single SymbolList. This class isn't intended * for direct use in user code -- instead, it is a helper for people * implementing the full BioJava assembly model. See SimpleAssembly * for an example. * * @author Thomas Down * @since 1.1 */ public class AssembledSymbolList extends AbstractSymbolList { private int length = 0; private SortedMap components; private List componentList; private final static Symbol N; static { try { N = DNATools.getDNA().getParser("token").parseToken("n"); } catch (BioException ex) { throw new BioError(ex); } } { components = new TreeMap(Location.naturalOrder); componentList = new ArrayList(); } public void setLength(int len) { length = len; } public void putComponent(Location loc, ComponentFeature f) { components.put(loc, f); componentList.clear(); componentList.addAll(components.keySet()); } public void removeComponent(Location loc) { components.remove(loc); componentList.clear(); componentList.addAll(components.keySet()); } public SymbolList getComponentSymbols(Location loc) { ComponentFeature cf = (ComponentFeature) components.get(loc); return cf.getSymbols(); } /** * Find the location containing p in a sorted list of non-overlapping contiguous * locations. */ public Location locationOfPoint(int p) { int first = 0; int last = componentList.size() - 1; while (first <= last) { int check = (first + last) / 2; Location checkL = (Location) componentList.get(check); if (checkL.contains(p)) return checkL; if (p < checkL.getMin()) last = check - 1; else first = check + 1; } return null; } public Location locationUpstreamOfPoint(int p) { int first = 0; int last = componentList.size() - 1; while (first <= last) { int check = (first + last) / 2; Location checkL = (Location) componentList.get(check); if (checkL.contains(p)) return checkL; if (p < checkL.getMin()) last = check - 1; else first = check + 1; } try { return (Location) componentList.get(Math.max(last, first) + 1); } catch (IndexOutOfBoundsException ex) { return null; } } public Alphabet getAlphabet() { return DNATools.getDNA(); } public int length() { return length; } public Symbol symbolAt(int pos) { Location l = locationOfPoint(pos); if (l != null) { SymbolList syms = getComponentSymbols(l); return syms.symbolAt(pos - l.getMin() + 1); } return N; } public SymbolList subList(int start, int end) { Location l = locationOfPoint(start); if (l != null && l.contains(end)) { SymbolList symbols = getComponentSymbols(l); int tstart = start - l.getMin() + 1; int tend = end - l.getMin() + 1; return symbols.subList(tstart, tend); } // All is lost. Fall back onto `view' subList from AbstractSymbolList return super.subList(start, end); } public String subStr(int start, int end) { if (start < 1 || end > length) { throw new IndexOutOfBoundsException("Range out of bounds: " + start + " - " + end); } StringBuffer sb = new StringBuffer(); int pos = start; while (pos <= end) { Location loc = locationOfPoint(pos); if (loc != null) { SymbolList sl = getComponentSymbols(loc); int slStart = Math.max(1, pos - loc.getMin() + 1); int slEnd = Math.min(loc.getMax() - loc.getMin() + 1, end - loc.getMin() + 1); sb.append(sl.subStr(slStart, slEnd)); pos += (slEnd - slStart + 1); } else { loc = locationUpstreamOfPoint(pos); int numNs; if (loc != null) { - numNs = Math.min(loc.getMin(), end) - pos; + numNs = Math.min(loc.getMin(), end + 1) - pos; pos = loc.getMin(); } else { numNs = end - pos + 1; pos = end + 1; } for (int i = 0; i < numNs; ++i) { sb.append(N.getToken()); } } } return sb.toString(); } }
true
true
public String subStr(int start, int end) { if (start < 1 || end > length) { throw new IndexOutOfBoundsException("Range out of bounds: " + start + " - " + end); } StringBuffer sb = new StringBuffer(); int pos = start; while (pos <= end) { Location loc = locationOfPoint(pos); if (loc != null) { SymbolList sl = getComponentSymbols(loc); int slStart = Math.max(1, pos - loc.getMin() + 1); int slEnd = Math.min(loc.getMax() - loc.getMin() + 1, end - loc.getMin() + 1); sb.append(sl.subStr(slStart, slEnd)); pos += (slEnd - slStart + 1); } else { loc = locationUpstreamOfPoint(pos); int numNs; if (loc != null) { numNs = Math.min(loc.getMin(), end) - pos; pos = loc.getMin(); } else { numNs = end - pos + 1; pos = end + 1; } for (int i = 0; i < numNs; ++i) { sb.append(N.getToken()); } } } return sb.toString(); }
public String subStr(int start, int end) { if (start < 1 || end > length) { throw new IndexOutOfBoundsException("Range out of bounds: " + start + " - " + end); } StringBuffer sb = new StringBuffer(); int pos = start; while (pos <= end) { Location loc = locationOfPoint(pos); if (loc != null) { SymbolList sl = getComponentSymbols(loc); int slStart = Math.max(1, pos - loc.getMin() + 1); int slEnd = Math.min(loc.getMax() - loc.getMin() + 1, end - loc.getMin() + 1); sb.append(sl.subStr(slStart, slEnd)); pos += (slEnd - slStart + 1); } else { loc = locationUpstreamOfPoint(pos); int numNs; if (loc != null) { numNs = Math.min(loc.getMin(), end + 1) - pos; pos = loc.getMin(); } else { numNs = end - pos + 1; pos = end + 1; } for (int i = 0; i < numNs; ++i) { sb.append(N.getToken()); } } } return sb.toString(); }
diff --git a/src/main/java/com/github/ucchyocean/ct/command/CTPCommand.java b/src/main/java/com/github/ucchyocean/ct/command/CTPCommand.java index f8cbf6d..a16e9f6 100644 --- a/src/main/java/com/github/ucchyocean/ct/command/CTPCommand.java +++ b/src/main/java/com/github/ucchyocean/ct/command/CTPCommand.java @@ -1,360 +1,364 @@ /* * @author ucchy * @license LGPLv3 * @copyright Copyright ucchy 2013 */ package com.github.ucchyocean.ct.command; import java.util.ArrayList; import java.util.HashMap; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.command.BlockCommandSender; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.github.ucchyocean.ct.ColorTeaming; import com.github.ucchyocean.ct.DelayedTeleportTask; import com.github.ucchyocean.ct.config.RespawnConfiguration; import com.github.ucchyocean.ct.config.TeamNameSetting; /** * colortp(ctp)コマンドの実行クラス * @author ucchy */ public class CTPCommand implements CommandExecutor { private static final String PREERR = ChatColor.RED.toString(); private static final String PREINFO = ChatColor.GRAY.toString(); private static final String PRE_LIST_MESSAGE = PREINFO + "=== TP Points Information ==="; private ColorTeaming plugin; public CTPCommand(ColorTeaming plugin) { this.plugin = plugin; } /** * @see org.bukkit.plugin.java.JavaPlugin#onCommand(org.bukkit.command.CommandSender, org.bukkit.command.Command, java.lang.String, java.lang.String[]) */ public boolean onCommand( CommandSender sender, Command command, String label, String[] args) { // 引数が一つもない場合は、ここで終了 if ( args.length == 0 ) { return false; } if ( args[0].equalsIgnoreCase("list") ) { // ctp list の実行 sender.sendMessage(PRE_LIST_MESSAGE); ArrayList<String> list = plugin.getAPI().getTppointConfig().list(); for ( String l : list ) { sender.sendMessage(PREINFO + l); } return true; } // ここ以降は引数が最低2つ必要なので、1つしかない場合はここで終了させておく if ( args.length == 1 ) { return false; } if ( args[0].equalsIgnoreCase("all") ) { HashMap<String, ArrayList<Player>> members = plugin.getAPI().getAllTeamMembers(); if ( args[1].equalsIgnoreCase("spawn") ) { // ctp all spawn の実行 // テレポート実行 String respawnMapName = plugin.getAPI().getRespawnMapName(); RespawnConfiguration respawnConfig = plugin.getAPI().getRespawnConfig(); HashMap<Player, Location> map = new HashMap<Player, Location>(); for ( String team : members.keySet() ) { TeamNameSetting tns = plugin.getAPI().getTeamNameFromID(team); Location location = respawnConfig.get(team, respawnMapName); if ( location == null ) { sender.sendMessage(PREERR + "チーム " + tns.getName() + " にリスポーンポイントが指定されていません。"); } else { location = location.add(0.5, 0, 0.5); for ( Player p : members.get(team) ) { map.put(p, location); } sender.sendMessage(PREINFO + "チーム " + tns.getName() + " のプレイヤーを全員テレポートします。"); } } if ( map.size() > 0 ) { DelayedTeleportTask task = new DelayedTeleportTask(map, plugin.getCTConfig().getTeleportDelay()); task.startTask(); } } else { // ctp all (point) の実行 String point = args[1]; Location location = plugin.getAPI().getTppointConfig().get(point); // point が登録済みのポイントかどうかを確認する if ( location == null ) { sender.sendMessage(PREERR + "ポイント " + point + " は登録されていません。"); return true; } // テレポート実行 HashMap<Player, Location> map = new HashMap<Player, Location>(); for ( String team : members.keySet() ) { for ( Player p : members.get(team) ) { map.put(p, location); } TeamNameSetting tns = plugin.getAPI().getTeamNameFromID(team); sender.sendMessage(PREINFO + "チーム " + tns.getName() + " のプレイヤーを全員テレポートします。"); } - DelayedTeleportTask task = new DelayedTeleportTask(map, - plugin.getCTConfig().getTeleportDelay()); - task.startTask(); + if ( map.size() > 0 ) { + DelayedTeleportTask task = new DelayedTeleportTask(map, + plugin.getCTConfig().getTeleportDelay()); + task.startTask(); + } } return true; } else if ( args[0].equalsIgnoreCase("set") ) { String point = args[1]; // 引数が3個以下なら、ここで終了 if ( args.length < 3 ) { return false; } Location location; if ( args.length == 2 || args[2].equalsIgnoreCase("here") ) { // ctp set (point) [here] if ( sender instanceof Player ) { location = ((Player)sender).getLocation(); } else { sender.sendMessage(PREERR + "ctp set point [here] 指定は、" + "コンソールやコマンドブロックからは実行できません。"); return true; } } else { // ctp set (point) [world] (x) (y) (z) location = checkAndGetLocation(sender, args, 2); if ( location == null ) { return true; } } // ポイント登録の実行 plugin.getAPI().getTppointConfig().set(point, location); String message = String.format( PREINFO + "ポイント %s を (%d, %d, %d) に設定しました。", point, location.getBlockX(), location.getBlockY(), location.getBlockZ()); sender.sendMessage(message); return true; } else if ( args[0].equalsIgnoreCase("remove") ) { String point = args[1]; // point が登録済みのポイントかどうかを確認する、未登録なら終了 if ( plugin.getAPI().getTppointConfig().get(point) == null ) { sender.sendMessage(PREERR + "ポイント " + point + " は登録されていません。"); return true; } // ポイント削除の実行 plugin.getAPI().getTppointConfig().set(point, null); String message = String.format( PREINFO + "ポイント %s を削除しました。", point); sender.sendMessage(message); return true; } else { // ctp (group) ほにゃらら の実行 String group = args[0]; HashMap<String, ArrayList<Player>> members = plugin.getAPI().getAllTeamMembers(); // 有効なチーム名が指定されたか確認する if ( !members.containsKey(group) ) { sender.sendMessage(PREERR + "チーム " + group + " が存在しません。"); return true; } Location location; if ( args[1].equalsIgnoreCase("here") ) { // ctp (group) here // コマンド実行者の場所を取得、コンソールなら終了 if ( sender instanceof Player ) { location = ((Player)sender).getLocation(); } else if ( sender instanceof BlockCommandSender ) { location = ((BlockCommandSender)sender).getBlock().getLocation().add(0.5, 1, 0.5); } else { sender.sendMessage(PREERR + "ctp の here 指定は、コンソールからは実行できません。"); return true; } } else if ( args[1].equalsIgnoreCase("spawn") ) { // ctp (group) spawn // チームのリスポーンポイントを取得、登録されていなければ終了 String respawnMapName = plugin.getAPI().getRespawnMapName(); RespawnConfiguration respawnConfig = plugin.getAPI().getRespawnConfig(); location = respawnConfig.get(group, respawnMapName); if ( location == null ) { sender.sendMessage(PREERR + "チーム " + group + " にリスポーンポイントが指定されていません。"); return true; } location = location.add(0.5, 0, 0.5); } else if ( args.length <= 3 ) { // ctp (group) (point) // 登録ポイントの取得、ポイントがなければ終了 String point = args[1]; location = plugin.getAPI().getTppointConfig().get(point); if ( location == null ) { sender.sendMessage(PREERR + "ポイント " + point + " は登録されていません。"); return true; } location = location.add(0.5, 0, 0.5); } else { // ctp (group) [world] (x) (y) (z) // 指定された座標からlocationを取得、取得できなければ終了 location = checkAndGetLocation(sender, args, 1); if ( location == null ) { return true; } location = location.add(0.5, 0, 0.5); } // テレポートの実行 HashMap<Player, Location> map = new HashMap<Player, Location>(); for ( Player p : members.get(group) ) { map.put(p, location); } - DelayedTeleportTask task = new DelayedTeleportTask(map, - plugin.getCTConfig().getTeleportDelay()); - task.startTask(); + if ( map.size() > 0 ) { + DelayedTeleportTask task = new DelayedTeleportTask(map, + plugin.getCTConfig().getTeleportDelay()); + task.startTask(); + } sender.sendMessage(PREINFO + "チーム " + group + " のプレイヤーを全員テレポートします。"); return true; } } /** * Locationを作成できるかどうかチェックして、Locationを作成し、返すメソッド。 * @param sender コマンド実行者 * @param args コマンドの引数 * @param fromIndex コマンドの引数の、どのインデクスからチェックを開始するか * @return 作成したLocation。ただし、作成に失敗した場合はnullになる。 */ private Location checkAndGetLocation(CommandSender sender, String[] args, int fromIndex) { String world = "world"; String x_str, y_str, z_str; if ( args.length >= fromIndex + 4 ) { world = args[fromIndex]; x_str = args[fromIndex + 1]; y_str = args[fromIndex + 2]; z_str = args[fromIndex + 3]; } else if ( args.length >= fromIndex + 3 ) { x_str = args[fromIndex]; y_str = args[fromIndex + 1]; z_str = args[fromIndex + 2]; if ( sender instanceof BlockCommandSender ) { BlockCommandSender block = (BlockCommandSender)sender; world = block.getBlock().getWorld().getName(); } else if ( sender instanceof Player ) { Player player = (Player)sender; world = player.getWorld().getName(); } } else { sender.sendMessage(PREERR + "引数の指定が足りません。"); return null; } // 有効な座標が指定されたか確認する if ( !checkXYZ(sender, x_str) || !checkXYZ(sender, y_str) || !checkXYZ(sender, z_str) ) { return null; } // 有効なワールド名が指定されたか確認する if ( Bukkit.getWorld(world) == null ) { sender.sendMessage(PREERR + "ワールド " + world + " が存在しません。"); return null; } // Locationを作成して返す。 double x = Integer.parseInt(x_str) + 0.5; double y = Integer.parseInt(y_str); double z = Integer.parseInt(z_str) + 0.5; return new Location(Bukkit.getWorld(world), x, y, z); } /** * value が、座標の数値として適切な内容かどうかを確認する。 * @param sender エラー時のメッセージ送り先 * @param value 検査対象の文字列 * @return 座標の数値として適切かどうか */ private boolean checkXYZ (CommandSender sender, String value) { // 数値かどうかをチェックする if ( !value.matches("-?[0-9]+") ) { sender.sendMessage(PREERR + value + " は数値ではありません。"); return false; } int v = Integer.parseInt(value); // 大きすぎる値でないかどうかチェックする if ( v < -30000000 || 30000000 < v ) { sender.sendMessage(PREERR + value + " は遠すぎて指定できません。"); return false; } return true; } }
false
true
public boolean onCommand( CommandSender sender, Command command, String label, String[] args) { // 引数が一つもない場合は、ここで終了 if ( args.length == 0 ) { return false; } if ( args[0].equalsIgnoreCase("list") ) { // ctp list の実行 sender.sendMessage(PRE_LIST_MESSAGE); ArrayList<String> list = plugin.getAPI().getTppointConfig().list(); for ( String l : list ) { sender.sendMessage(PREINFO + l); } return true; } // ここ以降は引数が最低2つ必要なので、1つしかない場合はここで終了させておく if ( args.length == 1 ) { return false; } if ( args[0].equalsIgnoreCase("all") ) { HashMap<String, ArrayList<Player>> members = plugin.getAPI().getAllTeamMembers(); if ( args[1].equalsIgnoreCase("spawn") ) { // ctp all spawn の実行 // テレポート実行 String respawnMapName = plugin.getAPI().getRespawnMapName(); RespawnConfiguration respawnConfig = plugin.getAPI().getRespawnConfig(); HashMap<Player, Location> map = new HashMap<Player, Location>(); for ( String team : members.keySet() ) { TeamNameSetting tns = plugin.getAPI().getTeamNameFromID(team); Location location = respawnConfig.get(team, respawnMapName); if ( location == null ) { sender.sendMessage(PREERR + "チーム " + tns.getName() + " にリスポーンポイントが指定されていません。"); } else { location = location.add(0.5, 0, 0.5); for ( Player p : members.get(team) ) { map.put(p, location); } sender.sendMessage(PREINFO + "チーム " + tns.getName() + " のプレイヤーを全員テレポートします。"); } } if ( map.size() > 0 ) { DelayedTeleportTask task = new DelayedTeleportTask(map, plugin.getCTConfig().getTeleportDelay()); task.startTask(); } } else { // ctp all (point) の実行 String point = args[1]; Location location = plugin.getAPI().getTppointConfig().get(point); // point が登録済みのポイントかどうかを確認する if ( location == null ) { sender.sendMessage(PREERR + "ポイント " + point + " は登録されていません。"); return true; } // テレポート実行 HashMap<Player, Location> map = new HashMap<Player, Location>(); for ( String team : members.keySet() ) { for ( Player p : members.get(team) ) { map.put(p, location); } TeamNameSetting tns = plugin.getAPI().getTeamNameFromID(team); sender.sendMessage(PREINFO + "チーム " + tns.getName() + " のプレイヤーを全員テレポートします。"); } DelayedTeleportTask task = new DelayedTeleportTask(map, plugin.getCTConfig().getTeleportDelay()); task.startTask(); } return true; } else if ( args[0].equalsIgnoreCase("set") ) { String point = args[1]; // 引数が3個以下なら、ここで終了 if ( args.length < 3 ) { return false; } Location location; if ( args.length == 2 || args[2].equalsIgnoreCase("here") ) { // ctp set (point) [here] if ( sender instanceof Player ) { location = ((Player)sender).getLocation(); } else { sender.sendMessage(PREERR + "ctp set point [here] 指定は、" + "コンソールやコマンドブロックからは実行できません。"); return true; } } else { // ctp set (point) [world] (x) (y) (z) location = checkAndGetLocation(sender, args, 2); if ( location == null ) { return true; } } // ポイント登録の実行 plugin.getAPI().getTppointConfig().set(point, location); String message = String.format( PREINFO + "ポイント %s を (%d, %d, %d) に設定しました。", point, location.getBlockX(), location.getBlockY(), location.getBlockZ()); sender.sendMessage(message); return true; } else if ( args[0].equalsIgnoreCase("remove") ) { String point = args[1]; // point が登録済みのポイントかどうかを確認する、未登録なら終了 if ( plugin.getAPI().getTppointConfig().get(point) == null ) { sender.sendMessage(PREERR + "ポイント " + point + " は登録されていません。"); return true; } // ポイント削除の実行 plugin.getAPI().getTppointConfig().set(point, null); String message = String.format( PREINFO + "ポイント %s を削除しました。", point); sender.sendMessage(message); return true; } else { // ctp (group) ほにゃらら の実行 String group = args[0]; HashMap<String, ArrayList<Player>> members = plugin.getAPI().getAllTeamMembers(); // 有効なチーム名が指定されたか確認する if ( !members.containsKey(group) ) { sender.sendMessage(PREERR + "チーム " + group + " が存在しません。"); return true; } Location location; if ( args[1].equalsIgnoreCase("here") ) { // ctp (group) here // コマンド実行者の場所を取得、コンソールなら終了 if ( sender instanceof Player ) { location = ((Player)sender).getLocation(); } else if ( sender instanceof BlockCommandSender ) { location = ((BlockCommandSender)sender).getBlock().getLocation().add(0.5, 1, 0.5); } else { sender.sendMessage(PREERR + "ctp の here 指定は、コンソールからは実行できません。"); return true; } } else if ( args[1].equalsIgnoreCase("spawn") ) { // ctp (group) spawn // チームのリスポーンポイントを取得、登録されていなければ終了 String respawnMapName = plugin.getAPI().getRespawnMapName(); RespawnConfiguration respawnConfig = plugin.getAPI().getRespawnConfig(); location = respawnConfig.get(group, respawnMapName); if ( location == null ) { sender.sendMessage(PREERR + "チーム " + group + " にリスポーンポイントが指定されていません。"); return true; } location = location.add(0.5, 0, 0.5); } else if ( args.length <= 3 ) { // ctp (group) (point) // 登録ポイントの取得、ポイントがなければ終了 String point = args[1]; location = plugin.getAPI().getTppointConfig().get(point); if ( location == null ) { sender.sendMessage(PREERR + "ポイント " + point + " は登録されていません。"); return true; } location = location.add(0.5, 0, 0.5); } else { // ctp (group) [world] (x) (y) (z) // 指定された座標からlocationを取得、取得できなければ終了 location = checkAndGetLocation(sender, args, 1); if ( location == null ) { return true; } location = location.add(0.5, 0, 0.5); } // テレポートの実行 HashMap<Player, Location> map = new HashMap<Player, Location>(); for ( Player p : members.get(group) ) { map.put(p, location); } DelayedTeleportTask task = new DelayedTeleportTask(map, plugin.getCTConfig().getTeleportDelay()); task.startTask(); sender.sendMessage(PREINFO + "チーム " + group + " のプレイヤーを全員テレポートします。"); return true; } }
public boolean onCommand( CommandSender sender, Command command, String label, String[] args) { // 引数が一つもない場合は、ここで終了 if ( args.length == 0 ) { return false; } if ( args[0].equalsIgnoreCase("list") ) { // ctp list の実行 sender.sendMessage(PRE_LIST_MESSAGE); ArrayList<String> list = plugin.getAPI().getTppointConfig().list(); for ( String l : list ) { sender.sendMessage(PREINFO + l); } return true; } // ここ以降は引数が最低2つ必要なので、1つしかない場合はここで終了させておく if ( args.length == 1 ) { return false; } if ( args[0].equalsIgnoreCase("all") ) { HashMap<String, ArrayList<Player>> members = plugin.getAPI().getAllTeamMembers(); if ( args[1].equalsIgnoreCase("spawn") ) { // ctp all spawn の実行 // テレポート実行 String respawnMapName = plugin.getAPI().getRespawnMapName(); RespawnConfiguration respawnConfig = plugin.getAPI().getRespawnConfig(); HashMap<Player, Location> map = new HashMap<Player, Location>(); for ( String team : members.keySet() ) { TeamNameSetting tns = plugin.getAPI().getTeamNameFromID(team); Location location = respawnConfig.get(team, respawnMapName); if ( location == null ) { sender.sendMessage(PREERR + "チーム " + tns.getName() + " にリスポーンポイントが指定されていません。"); } else { location = location.add(0.5, 0, 0.5); for ( Player p : members.get(team) ) { map.put(p, location); } sender.sendMessage(PREINFO + "チーム " + tns.getName() + " のプレイヤーを全員テレポートします。"); } } if ( map.size() > 0 ) { DelayedTeleportTask task = new DelayedTeleportTask(map, plugin.getCTConfig().getTeleportDelay()); task.startTask(); } } else { // ctp all (point) の実行 String point = args[1]; Location location = plugin.getAPI().getTppointConfig().get(point); // point が登録済みのポイントかどうかを確認する if ( location == null ) { sender.sendMessage(PREERR + "ポイント " + point + " は登録されていません。"); return true; } // テレポート実行 HashMap<Player, Location> map = new HashMap<Player, Location>(); for ( String team : members.keySet() ) { for ( Player p : members.get(team) ) { map.put(p, location); } TeamNameSetting tns = plugin.getAPI().getTeamNameFromID(team); sender.sendMessage(PREINFO + "チーム " + tns.getName() + " のプレイヤーを全員テレポートします。"); } if ( map.size() > 0 ) { DelayedTeleportTask task = new DelayedTeleportTask(map, plugin.getCTConfig().getTeleportDelay()); task.startTask(); } } return true; } else if ( args[0].equalsIgnoreCase("set") ) { String point = args[1]; // 引数が3個以下なら、ここで終了 if ( args.length < 3 ) { return false; } Location location; if ( args.length == 2 || args[2].equalsIgnoreCase("here") ) { // ctp set (point) [here] if ( sender instanceof Player ) { location = ((Player)sender).getLocation(); } else { sender.sendMessage(PREERR + "ctp set point [here] 指定は、" + "コンソールやコマンドブロックからは実行できません。"); return true; } } else { // ctp set (point) [world] (x) (y) (z) location = checkAndGetLocation(sender, args, 2); if ( location == null ) { return true; } } // ポイント登録の実行 plugin.getAPI().getTppointConfig().set(point, location); String message = String.format( PREINFO + "ポイント %s を (%d, %d, %d) に設定しました。", point, location.getBlockX(), location.getBlockY(), location.getBlockZ()); sender.sendMessage(message); return true; } else if ( args[0].equalsIgnoreCase("remove") ) { String point = args[1]; // point が登録済みのポイントかどうかを確認する、未登録なら終了 if ( plugin.getAPI().getTppointConfig().get(point) == null ) { sender.sendMessage(PREERR + "ポイント " + point + " は登録されていません。"); return true; } // ポイント削除の実行 plugin.getAPI().getTppointConfig().set(point, null); String message = String.format( PREINFO + "ポイント %s を削除しました。", point); sender.sendMessage(message); return true; } else { // ctp (group) ほにゃらら の実行 String group = args[0]; HashMap<String, ArrayList<Player>> members = plugin.getAPI().getAllTeamMembers(); // 有効なチーム名が指定されたか確認する if ( !members.containsKey(group) ) { sender.sendMessage(PREERR + "チーム " + group + " が存在しません。"); return true; } Location location; if ( args[1].equalsIgnoreCase("here") ) { // ctp (group) here // コマンド実行者の場所を取得、コンソールなら終了 if ( sender instanceof Player ) { location = ((Player)sender).getLocation(); } else if ( sender instanceof BlockCommandSender ) { location = ((BlockCommandSender)sender).getBlock().getLocation().add(0.5, 1, 0.5); } else { sender.sendMessage(PREERR + "ctp の here 指定は、コンソールからは実行できません。"); return true; } } else if ( args[1].equalsIgnoreCase("spawn") ) { // ctp (group) spawn // チームのリスポーンポイントを取得、登録されていなければ終了 String respawnMapName = plugin.getAPI().getRespawnMapName(); RespawnConfiguration respawnConfig = plugin.getAPI().getRespawnConfig(); location = respawnConfig.get(group, respawnMapName); if ( location == null ) { sender.sendMessage(PREERR + "チーム " + group + " にリスポーンポイントが指定されていません。"); return true; } location = location.add(0.5, 0, 0.5); } else if ( args.length <= 3 ) { // ctp (group) (point) // 登録ポイントの取得、ポイントがなければ終了 String point = args[1]; location = plugin.getAPI().getTppointConfig().get(point); if ( location == null ) { sender.sendMessage(PREERR + "ポイント " + point + " は登録されていません。"); return true; } location = location.add(0.5, 0, 0.5); } else { // ctp (group) [world] (x) (y) (z) // 指定された座標からlocationを取得、取得できなければ終了 location = checkAndGetLocation(sender, args, 1); if ( location == null ) { return true; } location = location.add(0.5, 0, 0.5); } // テレポートの実行 HashMap<Player, Location> map = new HashMap<Player, Location>(); for ( Player p : members.get(group) ) { map.put(p, location); } if ( map.size() > 0 ) { DelayedTeleportTask task = new DelayedTeleportTask(map, plugin.getCTConfig().getTeleportDelay()); task.startTask(); } sender.sendMessage(PREINFO + "チーム " + group + " のプレイヤーを全員テレポートします。"); return true; } }
diff --git a/src/main/java/de/hliebau/tracktivity/presentation/UserController.java b/src/main/java/de/hliebau/tracktivity/presentation/UserController.java index 3470f7f..9b5c9dc 100644 --- a/src/main/java/de/hliebau/tracktivity/presentation/UserController.java +++ b/src/main/java/de/hliebau/tracktivity/presentation/UserController.java @@ -1,67 +1,67 @@ package de.hliebau.tracktivity.presentation; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.security.authentication.encoding.PasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import de.hliebau.tracktivity.domain.User; import de.hliebau.tracktivity.service.UserService; @Controller public class UserController { @Autowired private PasswordEncoder passwordEncoder; @Autowired private UserService userService; @RequestMapping(value = "/user/{username}", method = RequestMethod.GET) public String displayUserProfile(@PathVariable String username, Model model) { User user = userService.retrieveUser(username); if (user != null) { model.addAttribute(user); } return "user"; } @RequestMapping(value = "/users") public String listUsers(Model model) { model.addAttribute(userService.getAllUsers()); return "users"; } @RequestMapping(value = "/register", method = RequestMethod.GET) public String registerUser(Model model) { model.addAttribute(new User()); return "register"; } @RequestMapping(value = "/register", method = RequestMethod.POST) public String registerUser(@Valid User user, BindingResult bindingResult) { if (!bindingResult.hasErrors()) { try { String plainPassword = user.getPassword(); - user.setPassword(passwordEncoder.encodePassword(plainPassword, user)); + user.setPassword(passwordEncoder.encodePassword(plainPassword, user.getUsername())); userService.createUser(user); } catch (DataIntegrityViolationException e) { bindingResult.addError(new FieldError("user", "username", "Please choose another username, <em>" + user.getUsername() + "</em> is already taken.")); } } if (bindingResult.hasErrors()) { return "register"; } return "redirect:user/" + user.getUsername(); } }
true
true
public String registerUser(@Valid User user, BindingResult bindingResult) { if (!bindingResult.hasErrors()) { try { String plainPassword = user.getPassword(); user.setPassword(passwordEncoder.encodePassword(plainPassword, user)); userService.createUser(user); } catch (DataIntegrityViolationException e) { bindingResult.addError(new FieldError("user", "username", "Please choose another username, <em>" + user.getUsername() + "</em> is already taken.")); } } if (bindingResult.hasErrors()) { return "register"; } return "redirect:user/" + user.getUsername(); }
public String registerUser(@Valid User user, BindingResult bindingResult) { if (!bindingResult.hasErrors()) { try { String plainPassword = user.getPassword(); user.setPassword(passwordEncoder.encodePassword(plainPassword, user.getUsername())); userService.createUser(user); } catch (DataIntegrityViolationException e) { bindingResult.addError(new FieldError("user", "username", "Please choose another username, <em>" + user.getUsername() + "</em> is already taken.")); } } if (bindingResult.hasErrors()) { return "register"; } return "redirect:user/" + user.getUsername(); }
diff --git a/core/src/test/java/org/apache/accumulo/core/cli/TestClientOpts.java b/core/src/test/java/org/apache/accumulo/core/cli/TestClientOpts.java index e3e7a67eb..8ddf490fc 100644 --- a/core/src/test/java/org/apache/accumulo/core/cli/TestClientOpts.java +++ b/core/src/test/java/org/apache/accumulo/core/cli/TestClientOpts.java @@ -1,90 +1,91 @@ /* * 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.accumulo.core.cli; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.concurrent.TimeUnit; import org.apache.accumulo.core.Constants; import org.apache.accumulo.core.client.BatchWriterConfig; import org.apache.accumulo.core.security.Authorizations; import org.junit.Test; import com.beust.jcommander.JCommander; public class TestClientOpts { @Test public void test() { BatchWriterConfig cfg = new BatchWriterConfig(); // document the defaults ClientOpts args = new ClientOpts(); BatchWriterOpts bwOpts = new BatchWriterOpts(); BatchScannerOpts bsOpts = new BatchScannerOpts(); assertEquals(System.getProperty("user.name"), args.user); assertNull(args.securePassword); assertArrayEquals("secret".getBytes(), args.getPassword()); assertEquals(new Long(cfg.getMaxLatency(TimeUnit.MILLISECONDS)), bwOpts.batchLatency); assertEquals(new Long(cfg.getTimeout(TimeUnit.MILLISECONDS)), bwOpts.batchTimeout); assertEquals(new Long(cfg.getMaxMemory()), bwOpts.batchMemory); assertFalse(args.debug); assertFalse(args.trace); assertEquals(10, bsOpts.scanThreads.intValue()); assertEquals(null, args.instance); assertEquals(Constants.NO_AUTHS, args.auths); assertEquals("localhost:2181", args.zookeepers); assertFalse(args.help); JCommander jc = new JCommander(); jc.addObject(args); jc.addObject(bwOpts); + jc.addObject(bsOpts); jc.parse( "-u", "bar", "-p", "foo", "--batchLatency", "3s", "--batchTimeout", "2s", "--batchMemory", "1M", "--debug", "--trace", "--scanThreads", "7", "-i", "instance", "--auths", "G1,G2,G3", "-z", "zoohost1,zoohost2", "--help"); assertEquals("bar", args.user); assertNull(args.securePassword); assertArrayEquals("foo".getBytes(), args.getPassword()); assertEquals(new Long(3000), bwOpts.batchLatency); assertEquals(new Long(2000), bwOpts.batchTimeout); assertEquals(new Long(1024*1024), bwOpts.batchMemory); assertTrue(args.debug); assertTrue(args.trace); assertEquals(7, bsOpts.scanThreads.intValue()); assertEquals("instance", args.instance); assertEquals(new Authorizations("G1", "G2", "G3"), args.auths); assertEquals("zoohost1,zoohost2", args.zookeepers); assertTrue(args.help); } }
true
true
public void test() { BatchWriterConfig cfg = new BatchWriterConfig(); // document the defaults ClientOpts args = new ClientOpts(); BatchWriterOpts bwOpts = new BatchWriterOpts(); BatchScannerOpts bsOpts = new BatchScannerOpts(); assertEquals(System.getProperty("user.name"), args.user); assertNull(args.securePassword); assertArrayEquals("secret".getBytes(), args.getPassword()); assertEquals(new Long(cfg.getMaxLatency(TimeUnit.MILLISECONDS)), bwOpts.batchLatency); assertEquals(new Long(cfg.getTimeout(TimeUnit.MILLISECONDS)), bwOpts.batchTimeout); assertEquals(new Long(cfg.getMaxMemory()), bwOpts.batchMemory); assertFalse(args.debug); assertFalse(args.trace); assertEquals(10, bsOpts.scanThreads.intValue()); assertEquals(null, args.instance); assertEquals(Constants.NO_AUTHS, args.auths); assertEquals("localhost:2181", args.zookeepers); assertFalse(args.help); JCommander jc = new JCommander(); jc.addObject(args); jc.addObject(bwOpts); jc.parse( "-u", "bar", "-p", "foo", "--batchLatency", "3s", "--batchTimeout", "2s", "--batchMemory", "1M", "--debug", "--trace", "--scanThreads", "7", "-i", "instance", "--auths", "G1,G2,G3", "-z", "zoohost1,zoohost2", "--help"); assertEquals("bar", args.user); assertNull(args.securePassword); assertArrayEquals("foo".getBytes(), args.getPassword()); assertEquals(new Long(3000), bwOpts.batchLatency); assertEquals(new Long(2000), bwOpts.batchTimeout); assertEquals(new Long(1024*1024), bwOpts.batchMemory); assertTrue(args.debug); assertTrue(args.trace); assertEquals(7, bsOpts.scanThreads.intValue()); assertEquals("instance", args.instance); assertEquals(new Authorizations("G1", "G2", "G3"), args.auths); assertEquals("zoohost1,zoohost2", args.zookeepers); assertTrue(args.help); }
public void test() { BatchWriterConfig cfg = new BatchWriterConfig(); // document the defaults ClientOpts args = new ClientOpts(); BatchWriterOpts bwOpts = new BatchWriterOpts(); BatchScannerOpts bsOpts = new BatchScannerOpts(); assertEquals(System.getProperty("user.name"), args.user); assertNull(args.securePassword); assertArrayEquals("secret".getBytes(), args.getPassword()); assertEquals(new Long(cfg.getMaxLatency(TimeUnit.MILLISECONDS)), bwOpts.batchLatency); assertEquals(new Long(cfg.getTimeout(TimeUnit.MILLISECONDS)), bwOpts.batchTimeout); assertEquals(new Long(cfg.getMaxMemory()), bwOpts.batchMemory); assertFalse(args.debug); assertFalse(args.trace); assertEquals(10, bsOpts.scanThreads.intValue()); assertEquals(null, args.instance); assertEquals(Constants.NO_AUTHS, args.auths); assertEquals("localhost:2181", args.zookeepers); assertFalse(args.help); JCommander jc = new JCommander(); jc.addObject(args); jc.addObject(bwOpts); jc.addObject(bsOpts); jc.parse( "-u", "bar", "-p", "foo", "--batchLatency", "3s", "--batchTimeout", "2s", "--batchMemory", "1M", "--debug", "--trace", "--scanThreads", "7", "-i", "instance", "--auths", "G1,G2,G3", "-z", "zoohost1,zoohost2", "--help"); assertEquals("bar", args.user); assertNull(args.securePassword); assertArrayEquals("foo".getBytes(), args.getPassword()); assertEquals(new Long(3000), bwOpts.batchLatency); assertEquals(new Long(2000), bwOpts.batchTimeout); assertEquals(new Long(1024*1024), bwOpts.batchMemory); assertTrue(args.debug); assertTrue(args.trace); assertEquals(7, bsOpts.scanThreads.intValue()); assertEquals("instance", args.instance); assertEquals(new Authorizations("G1", "G2", "G3"), args.auths); assertEquals("zoohost1,zoohost2", args.zookeepers); assertTrue(args.help); }
diff --git a/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/bliki/WikiServletScalaris.java b/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/bliki/WikiServletScalaris.java index 9c8aa603..7cf33698 100644 --- a/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/bliki/WikiServletScalaris.java +++ b/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/bliki/WikiServletScalaris.java @@ -1,536 +1,536 @@ /** * Copyright 2011 Zuse Institute Berlin * * 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 de.zib.scalaris.examples.wikipedia.bliki; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.math.BigInteger; import java.util.Arrays; import java.util.Calendar; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Random; import java.util.TreeSet; import javax.servlet.RequestDispatcher; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import de.zib.scalaris.Connection; import de.zib.scalaris.ConnectionFactory; import de.zib.scalaris.ConnectionPool; import de.zib.scalaris.TransactionSingleOp; import de.zib.scalaris.examples.wikipedia.CircularByteArrayOutputStream; import de.zib.scalaris.examples.wikipedia.PageHistoryResult; import de.zib.scalaris.examples.wikipedia.RevisionResult; import de.zib.scalaris.examples.wikipedia.SavePageResult; import de.zib.scalaris.examples.wikipedia.ScalarisDataHandler; import de.zib.scalaris.examples.wikipedia.ValueResult; import de.zib.scalaris.examples.wikipedia.data.Contribution; import de.zib.scalaris.examples.wikipedia.data.Revision; import de.zib.scalaris.examples.wikipedia.data.SiteInfo; import de.zib.scalaris.examples.wikipedia.data.xml.SAXParsingInterruptedException; import de.zib.scalaris.examples.wikipedia.data.xml.WikiDump; import de.zib.scalaris.examples.wikipedia.data.xml.WikiDumpHandler; import de.zib.scalaris.examples.wikipedia.data.xml.WikiDumpPreparedSQLiteToScalaris; import de.zib.scalaris.examples.wikipedia.data.xml.WikiDumpToScalarisHandler; /** * Wiki servlet connecting to Scalaris. * * @author Nico Kruber, [email protected] */ public class WikiServletScalaris extends WikiServlet<Connection> { private static final long serialVersionUID = 1L; private static final int CONNECTION_POOL_SIZE = 100; private static final int MAX_WAIT_FOR_CONNECTION = 10000; // 10s private ConnectionPool cPool; /** * Default constructor creating the servlet. */ public WikiServletScalaris() { super(); } /** * Servlet initialisation: creates the connection to the erlang node and * imports site information. */ @Override public void init2(ServletConfig config) throws ServletException { super.init2(config); Properties properties = new Properties(); try { InputStream fis = config.getServletContext().getResourceAsStream("/WEB-INF/scalaris.properties"); if (fis != null) { properties.load(fis); properties.setProperty("PropertyLoader.loadedfile", "/WEB-INF/scalaris.properties"); fis.close(); } else { properties = null; } } catch (IOException e) { // e.printStackTrace(); properties = null; } ConnectionFactory cFactory; if (properties != null) { cFactory = new ConnectionFactory(properties); } else { cFactory = new ConnectionFactory(); cFactory.setClientName("wiki"); } Random random = new Random(); String clientName = new BigInteger(128, random).toString(16); cFactory.setClientName(cFactory.getClientName() + '_' + clientName); cFactory.setClientNameAppendUUID(true); // cFactory.setConnectionPolicy(new RoundRobinConnectionPolicy(cFactory.getNodes())); cPool = new ConnectionPool(cFactory, CONNECTION_POOL_SIZE); } /** * Loads the siteinfo object from Scalaris. * * @return <tt>true</tt> on success, * <tt>false</tt> if not found or no connection available */ @Override protected synchronized boolean loadSiteInfo() { TransactionSingleOp scalaris_single; try { Connection conn = cPool.getConnection(MAX_WAIT_FOR_CONNECTION); if (conn == null) { System.err.println("Could not get a connection to Scalaris for siteinfo, waited " + MAX_WAIT_FOR_CONNECTION + "ms"); return false; } scalaris_single = new TransactionSingleOp(conn); try { siteinfo = scalaris_single.read("siteinfo").jsonValue(SiteInfo.class); // TODO: fix siteinfo's base url namespace = new MyNamespace(siteinfo); initialized = true; setLocalisedSpecialPageNames(); } catch (Exception e) { // no warning here - this probably is an empty wiki return false; } } catch (Exception e) { System.out.println(e); e.printStackTrace(); return false; } return true; } /** * Sets up the connection to the Scalaris erlang node once on the server. * * @param request * request to the servlet or <tt>null</tt> if there is none */ @Override protected Connection getConnection(HttpServletRequest request) { try { Connection conn = cPool.getConnection(MAX_WAIT_FOR_CONNECTION); if (conn == null) { System.err.println("Could not get a connection to Scalaris, waited " + MAX_WAIT_FOR_CONNECTION + "ms"); if (request != null) { setParam_error(request, "ERROR: DB unavailable"); addToParam_notice(request, "error: <pre>Could not get a connection to Scalaris, waited " + MAX_WAIT_FOR_CONNECTION + "ms</pre>"); } return null; } return conn; } catch (Exception e) { if (request != null) { setParam_error(request, "ERROR: DB unavailable"); addToParam_notice(request, "error: <pre>" + e.getMessage() + "</pre>"); } else { System.out.println(e); e.printStackTrace(); } return null; } } /** * Releases the connection back into the Scalaris connection pool. * * @param request * the request to the servlet or <tt>null</tt> if there is none * @param conn * the connection to release */ @Override protected void releaseConnection(HttpServletRequest request, Connection conn) { cPool.releaseConnection(conn); } /** * Shows a page for importing a DB dump. * * @param request * the request of the current operation * @param response * the response of the current operation * * @throws IOException * @throws ServletException */ @Override protected synchronized void showImportPage(HttpServletRequest request, HttpServletResponse response, Connection connection) throws ServletException, IOException { WikiPageBean page = new WikiPageBean(); page.setNotAvailable(true); request.setAttribute("pageBean", page); StringBuilder content = new StringBuilder(); String dumpsPath = getServletContext().getRealPath("/WEB-INF/dumps"); if (currentImport.isEmpty() && importHandler == null) { TreeSet<String> availableDumps = new TreeSet<String>(); File dumpsDir = new File(dumpsPath); if (dumpsDir.isDirectory()) { availableDumps.addAll(Arrays.asList(dumpsDir.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return MATCH_WIKI_IMPORT_FILE.matcher(name).matches(); } }))); } // get parameters: String req_import = request.getParameter("import"); if (req_import == null || !availableDumps.contains(req_import)) { content.append("<h2>Please select a wiki dump to import</h2>\n"); content.append("<form method=\"get\" action=\"wiki\">\n"); content.append("<p>\n"); content.append(" <select name=\"import\" size=\"10\" style=\"width:500px;\">\n"); for (String dump: availableDumps) { content.append(" <option>" + dump + "</option>\n"); } content.append(" </select>\n"); content.append(" </p>\n"); content.append(" <p>Maximum number of revisions per page: <input name=\"max_revisions\" size=\"2\" value=\"2\" /></br><span style=\"font-size:80%\">(<tt>-1</tt> to import everything)</span></p>\n"); content.append(" <p>No entry newer than: <input name=\"max_time\" size=\"20\" value=\"\" /></br><span style=\"font-size:80%\">(ISO8601 format, e.g. <tt>2004-01-07T08:09:29Z</tt> - leave empty to import everything)</span></p>\n"); content.append(" <input type=\"submit\" value=\"Import\" />\n"); content.append("</form>\n"); content.append("<p>Note: You will be re-directed to the main page when the import finishes.</p>"); } else { content.append("<h2>Importing \"" + req_import + "\"...</h2>\n"); try { currentImport = req_import; int maxRevisions = parseInt(request.getParameter("max_revisions"), 2); Calendar maxTime = parseDate(request.getParameter("max_time"), null); importLog = new CircularByteArrayOutputStream(1024 * 1024); PrintStream ps = new PrintStream(importLog); ps.println("starting import..."); String fileName = dumpsPath + File.separator + req_import; if (fileName.endsWith(".db")) { importHandler = new WikiDumpPreparedSQLiteToScalaris(fileName, cPool.getConnectionFactory()); } else { importHandler = new WikiDumpToScalarisHandler( de.zib.scalaris.examples.wikipedia.data.xml.Main.blacklist, null, maxRevisions, null, maxTime, cPool.getConnectionFactory()); } importHandler.setMsgOut(ps); this.new ImportThread(importHandler, fileName, ps).start(); response.setHeader("Refresh", "2; url = wiki?import=" + currentImport + "#refresh"); content.append("<p>Current log file (refreshed automatically every " + IMPORT_REDIRECT_EVERY + " seconds):</p>\n"); content.append("<pre>"); content.append("starting import...\n"); content.append("</pre>"); content.append("<p><a name=\"refresh\" href=\"wiki?import=" + currentImport + "#refresh\">refresh</a></p>"); content.append("<p><a href=\"wiki?stop_import=" + currentImport + "\">stop</a> (WARNING: pages may be incomplete due to missing templates)</p>"); } catch (Exception e) { setParam_error(request, "ERROR: import failed"); addToParam_notice(request, "error: <pre>" + e.getMessage() + "</pre>"); currentImport = ""; } } } else { content.append("<h2>Importing \"" + currentImport + "\"...</h2>\n"); String req_stop_import = request.getParameter("stop_import"); boolean stopImport; if (req_stop_import == null || req_stop_import.isEmpty()) { stopImport = false; - response.setHeader("Refresh", IMPORT_REDIRECT_EVERY + "; url = wiki?import=" + currentImport); + response.setHeader("Refresh", IMPORT_REDIRECT_EVERY + "; url = wiki?import=" + currentImport + "#refresh"); content.append("<p>Current log file (refreshed automatically every " + IMPORT_REDIRECT_EVERY + " seconds):</p>\n"); } else { stopImport = true; importHandler.stopParsing(); content.append("<p>Current log file:</p>\n"); } content.append("<pre>"); String log = importLog.toString(); int start = log.indexOf("\n"); if (start != -1) { content.append(log.substring(start)); } content.append("</pre>"); if (!stopImport) { - content.append("<p><a href=\"wiki?import=" + currentImport + "\">refresh</a></p>"); + content.append("<p><a name=\"refresh\" href=\"wiki?import=" + currentImport + "#refresh\">refresh</a></p>"); content.append("<p><a href=\"wiki?stop_import=" + currentImport + "\">stop</a> (WARNING: pages may be incomplete due to missing templates)</p>"); } else { content.append("<p>Import has been stopped by the user. Return to <a href=\"wiki?title=" + MAIN_PAGE + "\">" + MAIN_PAGE + "</a>.</p>"); } } page.setNotice(WikiServlet.getParam_notice(request)); page.setError(getParam_error(request)); page.setTitle("Import Wiki dump"); page.setPage(content.toString()); RequestDispatcher dispatcher = request.getRequestDispatcher("page.jsp"); dispatcher.forward(request, response); } private class ImportThread extends Thread { private WikiDump handler; private String fileName; private PrintStream ps; public ImportThread(WikiDump handler, String fileName, PrintStream ps) { this.handler = handler; this.fileName = fileName; this.ps = ps; } /* (non-Javadoc) * @see java.lang.Thread#run() */ @Override public void run() { InputSource is = null; try { handler.setUp(); if (handler instanceof WikiDumpHandler) { WikiDumpHandler xmlHandler = (WikiDumpHandler) handler; XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(xmlHandler); is = de.zib.scalaris.examples.wikipedia.data.xml.Main.getFileReader(fileName); reader.parse(is); xmlHandler.new ReportAtShutDown().run(); ps.println("import finished"); } else if (handler instanceof WikiDumpPreparedSQLiteToScalaris) { WikiDumpPreparedSQLiteToScalaris sqlHandler = (WikiDumpPreparedSQLiteToScalaris) handler; sqlHandler.writeToScalaris(); sqlHandler.new ReportAtShutDown().run(); } } catch (Exception e) { if (e instanceof SAXParsingInterruptedException) { // this is ok - we told the parser to stop } else { e.printStackTrace(ps); } } finally { handler.tearDown(); if (is != null) { try { is.getCharacterStream().close(); } catch (IOException e) { // don't care } } } synchronized (WikiServletScalaris.this) { WikiServletScalaris.this.currentImport = ""; WikiServletScalaris.this.importHandler = null; WikiServletScalaris.this.updateExistingPages(); } } } @Override protected MyScalarisWikiModel getWikiModel(Connection connection) { final MyScalarisWikiModel model = new MyScalarisWikiModel(WikiServlet.imageBaseURL, WikiServlet.linkBaseURL, connection, namespace); model.setExistingPages(existingPages); return model; } @Override public String getSiteInfoKey() { return ScalarisDataHandler.getSiteInfoKey(); } @Override public String getPageListKey(int namespace) { return ScalarisDataHandler.getPageListKey(namespace); } @Override public String getPageCountKey(int namespace) { return ScalarisDataHandler.getPageCountKey(namespace); } @Override public String getArticleCountKey() { return ScalarisDataHandler.getArticleCountKey(); } @Override public String getRevKey(String title, int id, final MyNamespace nsObject) { return ScalarisDataHandler.getRevKey(title, id, nsObject); } @Override public String getPageKey(String title, final MyNamespace nsObject) { return ScalarisDataHandler.getPageKey(title, nsObject); } @Override public String getRevListKey(String title, final MyNamespace nsObject) { return ScalarisDataHandler.getRevListKey(title, nsObject); } @Override public String getCatPageListKey(String title, final MyNamespace nsObject) { return ScalarisDataHandler.getCatPageListKey(title, nsObject); } @Override public String getCatPageCountKey(String title, final MyNamespace nsObject) { return ScalarisDataHandler.getCatPageCountKey(title, nsObject); } @Override public String getTplPageListKey(String title, final MyNamespace nsObject) { return ScalarisDataHandler.getTplPageListKey(title, nsObject); } @Override public String getBackLinksPageListKey(String title, final MyNamespace nsObject) { return ScalarisDataHandler.getBackLinksPageListKey(title, nsObject); } @Override public String getStatsPageEditsKey() { return ScalarisDataHandler.getStatsPageEditsKey(); } @Override public String getContributionListKey(String contributor) { return ScalarisDataHandler.getContributionListKey(contributor); } @Override public ValueResult<String> getDbVersion(Connection connection) { return ScalarisDataHandler.getDbVersion(connection); } @Override public PageHistoryResult getPageHistory(Connection connection, String title, final MyNamespace nsObject) { return ScalarisDataHandler.getPageHistory(connection, title, nsObject); } @Override public RevisionResult getRevision(Connection connection, String title, final MyNamespace nsObject) { return ScalarisDataHandler.getRevision(connection, title, nsObject); } @Override public RevisionResult getRevision(Connection connection, String title, int id, final MyNamespace nsObject) { return ScalarisDataHandler.getRevision(connection, title, id, nsObject); } @Override public ValueResult<List<String>> getPageList(Connection connection) { return ScalarisDataHandler.getPageList(connection); } @Override public ValueResult<List<String>> getPageList(int namespace, Connection connection) { return ScalarisDataHandler.getPageList(namespace, connection); } @Override public ValueResult<List<String>> getPagesInCategory(Connection connection, String title, final MyNamespace nsObject) { return ScalarisDataHandler.getPagesInCategory(connection, title, nsObject); } @Override public ValueResult<List<String>> getPagesInTemplate(Connection connection, String title, final MyNamespace nsObject) { return ScalarisDataHandler.getPagesInTemplate(connection, title, nsObject); } @Override public ValueResult<List<String>> getPagesLinkingTo(Connection connection, String title, final MyNamespace nsObject) { return ScalarisDataHandler.getPagesLinkingTo(connection, title, nsObject); } @Override public ValueResult<List<Contribution>> getContributions( Connection connection, String contributor) { return ScalarisDataHandler.getContributions(connection, contributor); } @Override public ValueResult<BigInteger> getPageCount(Connection connection) { return ScalarisDataHandler.getPageCount(connection); } @Override public ValueResult<BigInteger> getPageCount(int namespace, Connection connection) { return ScalarisDataHandler.getPageCount(namespace, connection); } @Override public ValueResult<BigInteger> getArticleCount(Connection connection) { return ScalarisDataHandler.getArticleCount(connection); } @Override public ValueResult<BigInteger> getPagesInCategoryCount(Connection connection, String title, final MyNamespace nsObject) { return ScalarisDataHandler.getPagesInCategoryCount(connection, title, nsObject); } @Override public ValueResult<BigInteger> getStatsPageEdits(Connection connection) { return ScalarisDataHandler.getStatsPageEdits(connection); } @Override public ValueResult<String> getRandomArticle(Connection connection, Random random) { return ScalarisDataHandler.getRandomArticle(connection, random); } @Override public SavePageResult savePage(Connection connection, String title, Revision newRev, int prevRevId, Map<String, String> restrictions, SiteInfo siteinfo, String username, final MyNamespace nsObject) { return ScalarisDataHandler.savePage(connection, title, newRev, prevRevId, restrictions, siteinfo, username, nsObject); } }
false
true
protected synchronized void showImportPage(HttpServletRequest request, HttpServletResponse response, Connection connection) throws ServletException, IOException { WikiPageBean page = new WikiPageBean(); page.setNotAvailable(true); request.setAttribute("pageBean", page); StringBuilder content = new StringBuilder(); String dumpsPath = getServletContext().getRealPath("/WEB-INF/dumps"); if (currentImport.isEmpty() && importHandler == null) { TreeSet<String> availableDumps = new TreeSet<String>(); File dumpsDir = new File(dumpsPath); if (dumpsDir.isDirectory()) { availableDumps.addAll(Arrays.asList(dumpsDir.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return MATCH_WIKI_IMPORT_FILE.matcher(name).matches(); } }))); } // get parameters: String req_import = request.getParameter("import"); if (req_import == null || !availableDumps.contains(req_import)) { content.append("<h2>Please select a wiki dump to import</h2>\n"); content.append("<form method=\"get\" action=\"wiki\">\n"); content.append("<p>\n"); content.append(" <select name=\"import\" size=\"10\" style=\"width:500px;\">\n"); for (String dump: availableDumps) { content.append(" <option>" + dump + "</option>\n"); } content.append(" </select>\n"); content.append(" </p>\n"); content.append(" <p>Maximum number of revisions per page: <input name=\"max_revisions\" size=\"2\" value=\"2\" /></br><span style=\"font-size:80%\">(<tt>-1</tt> to import everything)</span></p>\n"); content.append(" <p>No entry newer than: <input name=\"max_time\" size=\"20\" value=\"\" /></br><span style=\"font-size:80%\">(ISO8601 format, e.g. <tt>2004-01-07T08:09:29Z</tt> - leave empty to import everything)</span></p>\n"); content.append(" <input type=\"submit\" value=\"Import\" />\n"); content.append("</form>\n"); content.append("<p>Note: You will be re-directed to the main page when the import finishes.</p>"); } else { content.append("<h2>Importing \"" + req_import + "\"...</h2>\n"); try { currentImport = req_import; int maxRevisions = parseInt(request.getParameter("max_revisions"), 2); Calendar maxTime = parseDate(request.getParameter("max_time"), null); importLog = new CircularByteArrayOutputStream(1024 * 1024); PrintStream ps = new PrintStream(importLog); ps.println("starting import..."); String fileName = dumpsPath + File.separator + req_import; if (fileName.endsWith(".db")) { importHandler = new WikiDumpPreparedSQLiteToScalaris(fileName, cPool.getConnectionFactory()); } else { importHandler = new WikiDumpToScalarisHandler( de.zib.scalaris.examples.wikipedia.data.xml.Main.blacklist, null, maxRevisions, null, maxTime, cPool.getConnectionFactory()); } importHandler.setMsgOut(ps); this.new ImportThread(importHandler, fileName, ps).start(); response.setHeader("Refresh", "2; url = wiki?import=" + currentImport + "#refresh"); content.append("<p>Current log file (refreshed automatically every " + IMPORT_REDIRECT_EVERY + " seconds):</p>\n"); content.append("<pre>"); content.append("starting import...\n"); content.append("</pre>"); content.append("<p><a name=\"refresh\" href=\"wiki?import=" + currentImport + "#refresh\">refresh</a></p>"); content.append("<p><a href=\"wiki?stop_import=" + currentImport + "\">stop</a> (WARNING: pages may be incomplete due to missing templates)</p>"); } catch (Exception e) { setParam_error(request, "ERROR: import failed"); addToParam_notice(request, "error: <pre>" + e.getMessage() + "</pre>"); currentImport = ""; } } } else { content.append("<h2>Importing \"" + currentImport + "\"...</h2>\n"); String req_stop_import = request.getParameter("stop_import"); boolean stopImport; if (req_stop_import == null || req_stop_import.isEmpty()) { stopImport = false; response.setHeader("Refresh", IMPORT_REDIRECT_EVERY + "; url = wiki?import=" + currentImport); content.append("<p>Current log file (refreshed automatically every " + IMPORT_REDIRECT_EVERY + " seconds):</p>\n"); } else { stopImport = true; importHandler.stopParsing(); content.append("<p>Current log file:</p>\n"); } content.append("<pre>"); String log = importLog.toString(); int start = log.indexOf("\n"); if (start != -1) { content.append(log.substring(start)); } content.append("</pre>"); if (!stopImport) { content.append("<p><a href=\"wiki?import=" + currentImport + "\">refresh</a></p>"); content.append("<p><a href=\"wiki?stop_import=" + currentImport + "\">stop</a> (WARNING: pages may be incomplete due to missing templates)</p>"); } else { content.append("<p>Import has been stopped by the user. Return to <a href=\"wiki?title=" + MAIN_PAGE + "\">" + MAIN_PAGE + "</a>.</p>"); } } page.setNotice(WikiServlet.getParam_notice(request)); page.setError(getParam_error(request)); page.setTitle("Import Wiki dump"); page.setPage(content.toString()); RequestDispatcher dispatcher = request.getRequestDispatcher("page.jsp"); dispatcher.forward(request, response); }
protected synchronized void showImportPage(HttpServletRequest request, HttpServletResponse response, Connection connection) throws ServletException, IOException { WikiPageBean page = new WikiPageBean(); page.setNotAvailable(true); request.setAttribute("pageBean", page); StringBuilder content = new StringBuilder(); String dumpsPath = getServletContext().getRealPath("/WEB-INF/dumps"); if (currentImport.isEmpty() && importHandler == null) { TreeSet<String> availableDumps = new TreeSet<String>(); File dumpsDir = new File(dumpsPath); if (dumpsDir.isDirectory()) { availableDumps.addAll(Arrays.asList(dumpsDir.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return MATCH_WIKI_IMPORT_FILE.matcher(name).matches(); } }))); } // get parameters: String req_import = request.getParameter("import"); if (req_import == null || !availableDumps.contains(req_import)) { content.append("<h2>Please select a wiki dump to import</h2>\n"); content.append("<form method=\"get\" action=\"wiki\">\n"); content.append("<p>\n"); content.append(" <select name=\"import\" size=\"10\" style=\"width:500px;\">\n"); for (String dump: availableDumps) { content.append(" <option>" + dump + "</option>\n"); } content.append(" </select>\n"); content.append(" </p>\n"); content.append(" <p>Maximum number of revisions per page: <input name=\"max_revisions\" size=\"2\" value=\"2\" /></br><span style=\"font-size:80%\">(<tt>-1</tt> to import everything)</span></p>\n"); content.append(" <p>No entry newer than: <input name=\"max_time\" size=\"20\" value=\"\" /></br><span style=\"font-size:80%\">(ISO8601 format, e.g. <tt>2004-01-07T08:09:29Z</tt> - leave empty to import everything)</span></p>\n"); content.append(" <input type=\"submit\" value=\"Import\" />\n"); content.append("</form>\n"); content.append("<p>Note: You will be re-directed to the main page when the import finishes.</p>"); } else { content.append("<h2>Importing \"" + req_import + "\"...</h2>\n"); try { currentImport = req_import; int maxRevisions = parseInt(request.getParameter("max_revisions"), 2); Calendar maxTime = parseDate(request.getParameter("max_time"), null); importLog = new CircularByteArrayOutputStream(1024 * 1024); PrintStream ps = new PrintStream(importLog); ps.println("starting import..."); String fileName = dumpsPath + File.separator + req_import; if (fileName.endsWith(".db")) { importHandler = new WikiDumpPreparedSQLiteToScalaris(fileName, cPool.getConnectionFactory()); } else { importHandler = new WikiDumpToScalarisHandler( de.zib.scalaris.examples.wikipedia.data.xml.Main.blacklist, null, maxRevisions, null, maxTime, cPool.getConnectionFactory()); } importHandler.setMsgOut(ps); this.new ImportThread(importHandler, fileName, ps).start(); response.setHeader("Refresh", "2; url = wiki?import=" + currentImport + "#refresh"); content.append("<p>Current log file (refreshed automatically every " + IMPORT_REDIRECT_EVERY + " seconds):</p>\n"); content.append("<pre>"); content.append("starting import...\n"); content.append("</pre>"); content.append("<p><a name=\"refresh\" href=\"wiki?import=" + currentImport + "#refresh\">refresh</a></p>"); content.append("<p><a href=\"wiki?stop_import=" + currentImport + "\">stop</a> (WARNING: pages may be incomplete due to missing templates)</p>"); } catch (Exception e) { setParam_error(request, "ERROR: import failed"); addToParam_notice(request, "error: <pre>" + e.getMessage() + "</pre>"); currentImport = ""; } } } else { content.append("<h2>Importing \"" + currentImport + "\"...</h2>\n"); String req_stop_import = request.getParameter("stop_import"); boolean stopImport; if (req_stop_import == null || req_stop_import.isEmpty()) { stopImport = false; response.setHeader("Refresh", IMPORT_REDIRECT_EVERY + "; url = wiki?import=" + currentImport + "#refresh"); content.append("<p>Current log file (refreshed automatically every " + IMPORT_REDIRECT_EVERY + " seconds):</p>\n"); } else { stopImport = true; importHandler.stopParsing(); content.append("<p>Current log file:</p>\n"); } content.append("<pre>"); String log = importLog.toString(); int start = log.indexOf("\n"); if (start != -1) { content.append(log.substring(start)); } content.append("</pre>"); if (!stopImport) { content.append("<p><a name=\"refresh\" href=\"wiki?import=" + currentImport + "#refresh\">refresh</a></p>"); content.append("<p><a href=\"wiki?stop_import=" + currentImport + "\">stop</a> (WARNING: pages may be incomplete due to missing templates)</p>"); } else { content.append("<p>Import has been stopped by the user. Return to <a href=\"wiki?title=" + MAIN_PAGE + "\">" + MAIN_PAGE + "</a>.</p>"); } } page.setNotice(WikiServlet.getParam_notice(request)); page.setError(getParam_error(request)); page.setTitle("Import Wiki dump"); page.setPage(content.toString()); RequestDispatcher dispatcher = request.getRequestDispatcher("page.jsp"); dispatcher.forward(request, response); }
diff --git a/components/bio-formats/src/loci/formats/in/ZeissLSMReader.java b/components/bio-formats/src/loci/formats/in/ZeissLSMReader.java index 099d794ac..f7bfc8611 100644 --- a/components/bio-formats/src/loci/formats/in/ZeissLSMReader.java +++ b/components/bio-formats/src/loci/formats/in/ZeissLSMReader.java @@ -1,2157 +1,2156 @@ // // ZeissLSMReader.java // /* OME Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc. 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats.in; import java.io.File; import java.io.IOException; import java.util.Hashtable; import java.util.Vector; import ome.xml.model.primitives.NonNegativeInteger; import ome.xml.model.primitives.PositiveInteger; import loci.common.DataTools; import loci.common.DateTools; import loci.common.Location; import loci.common.RandomAccessInputStream; import loci.common.Region; import loci.common.services.DependencyException; import loci.common.services.ServiceFactory; import loci.formats.CoreMetadata; import loci.formats.FormatException; import loci.formats.FormatReader; import loci.formats.FormatTools; import loci.formats.ImageTools; import loci.formats.MetadataTools; import loci.formats.meta.MetadataStore; import loci.formats.services.MDBService; import loci.formats.tiff.IFD; import loci.formats.tiff.IFDList; import loci.formats.tiff.PhotoInterp; import loci.formats.tiff.TiffCompression; import loci.formats.tiff.TiffConstants; import loci.formats.tiff.TiffParser; /** * ZeissLSMReader is the file format reader for Zeiss LSM files. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="http://dev.loci.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/in/ZeissLSMReader.java">Trac</a>, * <a href="http://dev.loci.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/in/ZeissLSMReader.java">SVN</a></dd></dl> * * @author Eric Kjellman egkjellman at wisc.edu * @author Melissa Linkert melissa at glencoesoftware.com * @author Curtis Rueden ctrueden at wisc.edu */ public class ZeissLSMReader extends FormatReader { // -- Constants -- public static final String[] MDB_SUFFIX = {"mdb"}; /** Tag identifying a Zeiss LSM file. */ private static final int ZEISS_ID = 34412; /** Data types. */ private static final int TYPE_SUBBLOCK = 0; private static final int TYPE_ASCII = 2; private static final int TYPE_LONG = 4; private static final int TYPE_RATIONAL = 5; /** Subblock types. */ private static final int SUBBLOCK_RECORDING = 0x10000000; private static final int SUBBLOCK_LASER = 0x50000000; private static final int SUBBLOCK_TRACK = 0x40000000; private static final int SUBBLOCK_DETECTION_CHANNEL = 0x70000000; private static final int SUBBLOCK_ILLUMINATION_CHANNEL = 0x90000000; private static final int SUBBLOCK_BEAM_SPLITTER = 0xb0000000; private static final int SUBBLOCK_DATA_CHANNEL = 0xd0000000; private static final int SUBBLOCK_TIMER = 0x12000000; private static final int SUBBLOCK_MARKER = 0x14000000; private static final int SUBBLOCK_END = (int) 0xffffffff; /** Data types. */ private static final int RECORDING_NAME = 0x10000001; private static final int RECORDING_DESCRIPTION = 0x10000002; private static final int RECORDING_OBJECTIVE = 0x10000004; private static final int RECORDING_ZOOM = 0x10000016; private static final int RECORDING_SAMPLE_0TIME = 0x10000036; private static final int RECORDING_CAMERA_BINNING = 0x10000052; private static final int TRACK_ACQUIRE = 0x40000006; private static final int TRACK_TIME_BETWEEN_STACKS = 0x4000000b; private static final int LASER_NAME = 0x50000001; private static final int LASER_ACQUIRE = 0x50000002; private static final int LASER_POWER = 0x50000003; private static final int CHANNEL_DETECTOR_GAIN = 0x70000003; private static final int CHANNEL_PINHOLE_DIAMETER = 0x70000009; private static final int CHANNEL_AMPLIFIER_GAIN = 0x70000005; private static final int CHANNEL_FILTER_SET = 0x7000000f; private static final int CHANNEL_FILTER = 0x70000010; private static final int CHANNEL_ACQUIRE = 0x7000000b; private static final int CHANNEL_NAME = 0x70000014; private static final int ILLUM_CHANNEL_NAME = 0x90000001; private static final int ILLUM_CHANNEL_ATTENUATION = 0x90000002; private static final int ILLUM_CHANNEL_WAVELENGTH = 0x90000003; private static final int ILLUM_CHANNEL_ACQUIRE = 0x90000004; private static final int START_TIME = 0x10000036; private static final int DATA_CHANNEL_NAME = 0xd0000001; private static final int DATA_CHANNEL_ACQUIRE = 0xd0000017; private static final int BEAM_SPLITTER_FILTER = 0xb0000002; private static final int BEAM_SPLITTER_FILTER_SET = 0xb0000003; /** Drawing element types. */ private static final int TEXT = 13; private static final int LINE = 14; private static final int SCALE_BAR = 15; private static final int OPEN_ARROW = 16; private static final int CLOSED_ARROW = 17; private static final int RECTANGLE = 18; private static final int ELLIPSE = 19; private static final int CLOSED_POLYLINE = 20; private static final int OPEN_POLYLINE = 21; private static final int CLOSED_BEZIER = 22; private static final int OPEN_BEZIER = 23; private static final int CIRCLE = 24; private static final int PALETTE = 25; private static final int POLYLINE_ARROW = 26; private static final int BEZIER_WITH_ARROW = 27; private static final int ANGLE = 28; private static final int CIRCLE_3POINT = 29; // -- Static fields -- private static final Hashtable<Integer, String> METADATA_KEYS = createKeys(); // -- Fields -- private double pixelSizeX, pixelSizeY, pixelSizeZ; private byte[][][] lut = null; private Vector<Double> timestamps; private int validChannels; private String[] lsmFilenames; private Vector<IFDList> ifdsList; private TiffParser tiffParser; private int nextLaser = 0, nextDetector = 0; private int nextFilter = 0, nextDichroicChannel = 0, nextDichroic = 0; private int nextDataChannel = 0, nextIllumChannel = 0, nextDetectChannel = 0; private boolean splitPlanes = false; private double zoom; private Vector<String> imageNames; private String binning; private Vector<Double> xCoordinates, yCoordinates, zCoordinates; private int dimensionM, dimensionP; private Hashtable<String, Integer> seriesCounts; private String userName; private double originX, originY, originZ; private int totalROIs = 0; private int prevPlane = -1; private int prevChannel = 0; private byte[] prevBuf = null; private Region prevRegion = null; // -- Constructor -- /** Constructs a new Zeiss LSM reader. */ public ZeissLSMReader() { super("Zeiss Laser-Scanning Microscopy", new String[] {"lsm", "mdb"}); domains = new String[] {FormatTools.LM_DOMAIN}; hasCompanionFiles = true; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isSingleFile(String) */ public boolean isSingleFile(String id) throws FormatException, IOException { if (checkSuffix(id, MDB_SUFFIX)) return false; return isGroupFiles() ? getMDBFile(id) != null : true; } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly) { pixelSizeX = pixelSizeY = pixelSizeZ = 0; lut = null; timestamps = null; validChannels = 0; lsmFilenames = null; ifdsList = null; tiffParser = null; nextLaser = nextDetector = 0; nextFilter = nextDichroicChannel = nextDichroic = 0; nextDataChannel = nextIllumChannel = nextDetectChannel = 0; splitPlanes = false; zoom = 0; imageNames = null; binning = null; totalROIs = 0; prevPlane = -1; prevChannel = 0; prevBuf = null; prevRegion = null; xCoordinates = null; yCoordinates = null; zCoordinates = null; dimensionM = 0; dimensionP = 0; seriesCounts = null; originX = originY = originZ = 0d; userName = null; } } /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { final int blockLen = 4; if (!FormatTools.validStream(stream, blockLen, false)) return false; TiffParser parser = new TiffParser(stream); return parser.isValidHeader() || stream.readShort() == 0x5374; } /* @see loci.formats.IFormatReader#fileGroupOption(String) */ public int fileGroupOption(String id) throws FormatException, IOException { return FormatTools.MUST_GROUP; } /* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */ public String[] getSeriesUsedFiles(boolean noPixels) { FormatTools.assertId(currentId, true, 1); if (noPixels) { if (checkSuffix(currentId, MDB_SUFFIX)) return new String[] {currentId}; return null; } if (lsmFilenames == null) return new String[] {currentId}; if (lsmFilenames.length == 1 && currentId.equals(lsmFilenames[0])) { return lsmFilenames; } return new String[] {currentId, getLSMFileFromSeries(getSeries())}; } /* @see loci.formats.IFormatReader#get8BitLookupTable() */ public byte[][] get8BitLookupTable() throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); if (lut == null || lut[getSeries()] == null || getPixelType() != FormatTools.UINT8) { return null; } byte[][] b = new byte[3][]; b[0] = lut[getSeries()][prevChannel * 3]; b[1] = lut[getSeries()][prevChannel * 3 + 1]; b[2] = lut[getSeries()][prevChannel * 3 + 2]; return b; } /* @see loci.formats.IFormatReader#get16BitLookupTable() */ public short[][] get16BitLookupTable() throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); if (lut == null || lut[getSeries()] == null || getPixelType() != FormatTools.UINT16) { return null; } short[][] s = new short[3][65536]; for (int i=2; i>=3-validChannels; i--) { for (int j=0; j<s[i].length; j++) { s[i][j] = (short) j; } } return s; } /* @see loci.formats.IFormatReader#setSeries(int) */ public void setSeries(int series) { if (series != getSeries()) { prevBuf = null; } super.setSeries(series); } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h); if (getSeriesCount() > 1) { in.close(); in = new RandomAccessInputStream(getLSMFileFromSeries(getSeries())); in.order(!isLittleEndian()); tiffParser = new TiffParser(in); } IFDList ifds = ifdsList.get(getSeries()); if (splitPlanes && getSizeC() > 1 && ifds.size() == getSizeZ() * getSizeT()) { int bpp = FormatTools.getBytesPerPixel(getPixelType()); int plane = no / getSizeC(); int c = no % getSizeC(); Region region = new Region(x, y, w, h); if (prevPlane != plane || prevBuf == null || prevBuf.length < w * h * bpp * getSizeC() || !region.equals(prevRegion)) { prevBuf = new byte[w * h * bpp * getSizeC()]; tiffParser.getSamples(ifds.get(plane), prevBuf, x, y, w, h); prevPlane = plane; prevRegion = region; } ImageTools.splitChannels( prevBuf, buf, c, getSizeC(), bpp, false, false, w * h * bpp); prevChannel = c; } else { tiffParser.getSamples(ifds.get(no), buf, x, y, w, h); prevChannel = getZCTCoords(no)[1]; } if (getSeriesCount() > 1) in.close(); return buf; } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); if (!checkSuffix(id, MDB_SUFFIX) && isGroupFiles()) { String mdb = getMDBFile(id); if (mdb != null) { setId(mdb); return; } lsmFilenames = new String[] {id}; } else if (checkSuffix(id, MDB_SUFFIX)) { lsmFilenames = parseMDB(id); } else lsmFilenames = new String[] {id}; if (lsmFilenames == null || lsmFilenames.length == 0) { throw new FormatException("LSM files were not found."); } timestamps = new Vector<Double>(); imageNames = new Vector<String>(); xCoordinates = new Vector<Double>(); yCoordinates = new Vector<Double>(); zCoordinates = new Vector<Double>(); seriesCounts = new Hashtable<String, Integer>(); int seriesCount = 0; Vector<String> validFiles = new Vector<String>(); for (String filename : lsmFilenames) { try { int extraSeries = getExtraSeries(filename); seriesCounts.put(filename, extraSeries); seriesCount += extraSeries; validFiles.add(filename); } catch (IOException e) { LOGGER.debug("Failed to parse " + filename, e); } } lsmFilenames = validFiles.toArray(new String[validFiles.size()]); core = new CoreMetadata[seriesCount]; ifdsList = new Vector<IFDList>(); ifdsList.setSize(core.length); int realSeries = 0; for (int i=0; i<lsmFilenames.length; i++) { RandomAccessInputStream stream = new RandomAccessInputStream(lsmFilenames[i]); int count = seriesCounts.get(lsmFilenames[i]); TiffParser tp = new TiffParser(stream); Boolean littleEndian = tp.checkHeader(); long[] ifdOffsets = tp.getIFDOffsets(); int ifdsPerSeries = (ifdOffsets.length / 2) / count; int offset = 0; Object zeissTag = null; for (int s=0; s<count; s++, realSeries++) { core[realSeries] = new CoreMetadata(); core[realSeries].littleEndian = littleEndian; IFDList ifds = new IFDList(); while (ifds.size() < ifdsPerSeries) { tp.setDoCaching(offset == 0); IFD ifd = tp.getIFD(ifdOffsets[offset]); if (offset == 0) zeissTag = ifd.get(ZEISS_ID); if (offset > 0 && ifds.size() == 0) { ifd.putIFDValue(ZEISS_ID, zeissTag); } ifds.add(ifd); if (zeissTag != null) offset += 2; else offset++; } for (IFD ifd : ifds) { tp.fillInIFD(ifd); } ifdsList.set(realSeries, ifds); } stream.close(); } MetadataStore store = makeFilterMetadata(); lut = new byte[ifdsList.size()][][]; for (int series=0; series<ifdsList.size(); series++) { IFDList ifds = ifdsList.get(series); for (IFD ifd : ifds) { // check that predictor is set to 1 if anything other // than LZW compression is used if (ifd.getCompression() != TiffCompression.LZW) { ifd.putIFDValue(IFD.PREDICTOR, 1); } } // fix the offsets for > 4 GB files RandomAccessInputStream s = new RandomAccessInputStream(getLSMFileFromSeries(series)); for (int i=1; i<ifds.size(); i++) { long[] stripOffsets = ifds.get(i).getStripOffsets(); long[] previousStripOffsets = ifds.get(i - 1).getStripOffsets(); if (stripOffsets == null || previousStripOffsets == null) { throw new FormatException( "Strip offsets are missing; this is an invalid file."); } boolean neededAdjustment = false; for (int j=0; j<stripOffsets.length; j++) { if (j >= previousStripOffsets.length) break; if (stripOffsets[j] < previousStripOffsets[j]) { stripOffsets[j] = (previousStripOffsets[j] & ~0xffffffffL) | (stripOffsets[j] & 0xffffffffL); if (stripOffsets[j] < previousStripOffsets[j]) { stripOffsets[j] += 0x100000000L; } neededAdjustment = true; } if (neededAdjustment) { ifds.get(i).putIFDValue(IFD.STRIP_OFFSETS, stripOffsets); } } } s.close(); initMetadata(series); } for (int i=0; i<getSeriesCount(); i++) { core[i].imageCount = core[i].sizeZ * core[i].sizeC * core[i].sizeT; } MetadataTools.populatePixels(store, this, true); for (int series=0; series<ifdsList.size(); series++) { setSeries(series); if (series < imageNames.size()) { store.setImageName(imageNames.get(series), series); } store.setPixelsBinDataBigEndian(!isLittleEndian(), series, 0); } setSeries(0); } // -- Helper methods -- private String getMDBFile(String id) throws FormatException, IOException { Location parentFile = new Location(id).getAbsoluteFile().getParentFile(); String[] fileList = parentFile.list(); for (int i=0; i<fileList.length; i++) { if (fileList[i].startsWith(".")) continue; if (checkSuffix(fileList[i], MDB_SUFFIX)) { Location file = new Location(parentFile, fileList[i]).getAbsoluteFile(); if (file.isDirectory()) continue; // make sure that the .mdb references this .lsm String[] lsms = parseMDB(file.getAbsolutePath()); if (lsms == null) return null; for (String lsm : lsms) { if (id.endsWith(lsm) || lsm.endsWith(id)) { return file.getAbsolutePath(); } } } } return null; } private int getEffectiveSeries(int currentSeries) { int seriesCount = 0; for (int i=0; i<lsmFilenames.length; i++) { Integer count = seriesCounts.get(lsmFilenames[i]); if (count == null) count = 1; seriesCount += count; if (seriesCount > currentSeries) return i; } return -1; } private String getLSMFileFromSeries(int currentSeries) { int effectiveSeries = getEffectiveSeries(currentSeries); return effectiveSeries < 0 ? null : lsmFilenames[effectiveSeries]; } private int getExtraSeries(String file) throws FormatException, IOException { if (in != null) in.close(); in = new RandomAccessInputStream(file); boolean littleEndian = in.read() == TiffConstants.LITTLE; in.order(littleEndian); tiffParser = new TiffParser(in); IFD ifd = tiffParser.getFirstIFD(); RandomAccessInputStream ras = getCZTag(ifd); if (ras == null) return 1; ras.order(littleEndian); ras.seek(264); dimensionP = ras.readInt(); dimensionM = ras.readInt(); ras.close(); int nSeries = dimensionM * dimensionP; return nSeries <= 0 ? 1 : nSeries; } private int getPosition(int currentSeries) { int effectiveSeries = getEffectiveSeries(currentSeries); int firstPosition = 0; for (int i=0; i<effectiveSeries; i++) { firstPosition += seriesCounts.get(lsmFilenames[i]); } return currentSeries - firstPosition; } private RandomAccessInputStream getCZTag(IFD ifd) throws FormatException, IOException { // get TIF_CZ_LSMINFO structure short[] s = ifd.getIFDShortArray(ZEISS_ID); if (s == null) { LOGGER.warn("Invalid Zeiss LSM file. Tag {} not found.", ZEISS_ID); TiffReader reader = new TiffReader(); reader.setId(getLSMFileFromSeries(series)); core[getSeries()] = reader.getCoreMetadata()[0]; reader.close(); return null; } byte[] cz = new byte[s.length]; for (int i=0; i<s.length; i++) { cz[i] = (byte) s[i]; } RandomAccessInputStream ras = new RandomAccessInputStream(cz); ras.order(isLittleEndian()); return ras; } protected void initMetadata(int series) throws FormatException, IOException { setSeries(series); IFDList ifds = ifdsList.get(series); IFD ifd = ifds.get(0); in.close(); in = new RandomAccessInputStream(getLSMFileFromSeries(series)); in.order(isLittleEndian()); tiffParser = new TiffParser(in); PhotoInterp photo = ifd.getPhotometricInterpretation(); int samples = ifd.getSamplesPerPixel(); core[series].sizeX = (int) ifd.getImageWidth(); core[series].sizeY = (int) ifd.getImageLength(); core[series].rgb = samples > 1 || photo == PhotoInterp.RGB; core[series].interleaved = false; core[series].sizeC = isRGB() ? samples : 1; core[series].pixelType = ifd.getPixelType(); core[series].imageCount = ifds.size(); core[series].sizeZ = getImageCount(); core[series].sizeT = 1; LOGGER.info("Reading LSM metadata for series #{}", series); MetadataStore store = makeFilterMetadata(); int instrument = getEffectiveSeries(series); String imageName = getLSMFileFromSeries(series); if (imageName.indexOf(".") != -1) { imageName = imageName.substring(0, imageName.lastIndexOf(".")); } if (imageName.indexOf(File.separator) != -1) { imageName = imageName.substring(imageName.lastIndexOf(File.separator) + 1); } if (lsmFilenames.length != getSeriesCount()) { imageName += " #" + (getPosition(series) + 1); } // link Instrument and Image store.setImageID(MetadataTools.createLSID("Image", series), series); String instrumentID = MetadataTools.createLSID("Instrument", instrument); store.setInstrumentID(instrumentID, instrument); store.setImageInstrumentRef(instrumentID, series); RandomAccessInputStream ras = getCZTag(ifd); if (ras == null) { imageNames.add(imageName); return; } ras.seek(16); core[series].sizeZ = ras.readInt(); ras.skipBytes(4); core[series].sizeT = ras.readInt(); int dataType = ras.readInt(); switch (dataType) { case 2: addSeriesMeta("DataType", "12 bit unsigned integer"); break; case 5: addSeriesMeta("DataType", "32 bit float"); break; case 0: addSeriesMeta("DataType", "varying data types"); break; default: addSeriesMeta("DataType", "8 bit unsigned integer"); } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { ras.seek(0); addSeriesMeta("MagicNumber ", ras.readInt()); addSeriesMeta("StructureSize", ras.readInt()); addSeriesMeta("DimensionX", ras.readInt()); addSeriesMeta("DimensionY", ras.readInt()); ras.seek(32); addSeriesMeta("ThumbnailX", ras.readInt()); addSeriesMeta("ThumbnailY", ras.readInt()); // pixel sizes are stored in meters, we need them in microns pixelSizeX = ras.readDouble() * 1000000; pixelSizeY = ras.readDouble() * 1000000; pixelSizeZ = ras.readDouble() * 1000000; addSeriesMeta("VoxelSizeX", new Double(pixelSizeX)); addSeriesMeta("VoxelSizeY", new Double(pixelSizeY)); addSeriesMeta("VoxelSizeZ", new Double(pixelSizeZ)); originX = ras.readDouble() * 1000000; originY = ras.readDouble() * 1000000; originZ = ras.readDouble() * 1000000; addSeriesMeta("OriginX", originX); addSeriesMeta("OriginY", originY); addSeriesMeta("OriginZ", originZ); } else ras.seek(88); int scanType = ras.readShort(); switch (scanType) { case 0: addSeriesMeta("ScanType", "x-y-z scan"); core[series].dimensionOrder = "XYZCT"; break; case 1: addSeriesMeta("ScanType", "z scan (x-z plane)"); core[series].dimensionOrder = "XYZCT"; break; case 2: addSeriesMeta("ScanType", "line scan"); core[series].dimensionOrder = "XYZCT"; break; case 3: addSeriesMeta("ScanType", "time series x-y"); core[series].dimensionOrder = "XYTCZ"; break; case 4: addSeriesMeta("ScanType", "time series x-z"); core[series].dimensionOrder = "XYZTC"; break; case 5: addSeriesMeta("ScanType", "time series 'Mean of ROIs'"); core[series].dimensionOrder = "XYTCZ"; break; case 6: addSeriesMeta("ScanType", "time series x-y-z"); core[series].dimensionOrder = "XYZTC"; break; case 7: addSeriesMeta("ScanType", "spline scan"); core[series].dimensionOrder = "XYCTZ"; break; case 8: addSeriesMeta("ScanType", "spline scan x-z"); core[series].dimensionOrder = "XYCZT"; break; case 9: addSeriesMeta("ScanType", "time series spline plane x-z"); core[series].dimensionOrder = "XYTCZ"; break; case 10: addSeriesMeta("ScanType", "point mode"); core[series].dimensionOrder = "XYZCT"; break; default: addSeriesMeta("ScanType", "x-y-z scan"); core[series].dimensionOrder = "XYZCT"; } core[series].indexed = lut != null && lut[series] != null; if (isIndexed()) { core[series].rgb = false; } if (getSizeC() == 0) core[series].sizeC = 1; if (isRGB()) { // shuffle C to front of order string core[series].dimensionOrder = getDimensionOrder().replaceAll("C", ""); core[series].dimensionOrder = getDimensionOrder().replaceAll("XY", "XYC"); } if (getEffectiveSizeC() == 0) { core[series].imageCount = getSizeZ() * getSizeT(); } else { core[series].imageCount = getSizeZ() * getSizeT() * getEffectiveSizeC(); } if (getImageCount() != ifds.size()) { int diff = getImageCount() - ifds.size(); core[series].imageCount = ifds.size(); if (diff % getSizeZ() == 0) { core[series].sizeT -= (diff / getSizeZ()); } else if (diff % getSizeT() == 0) { core[series].sizeZ -= (diff / getSizeT()); } else if (getSizeZ() > 1) { core[series].sizeZ = ifds.size(); core[series].sizeT = 1; } else if (getSizeT() > 1) { core[series].sizeT = ifds.size(); core[series].sizeZ = 1; } } if (getSizeZ() == 0) core[series].sizeZ = getImageCount(); if (getSizeT() == 0) core[series].sizeT = getImageCount() / getSizeZ(); long channelColorsOffset = 0; long timeStampOffset = 0; long eventListOffset = 0; long scanInformationOffset = 0; long channelWavelengthOffset = 0; if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { int spectralScan = ras.readShort(); if (spectralScan != 1) { addSeriesMeta("SpectralScan", "no spectral scan"); } else addSeriesMeta("SpectralScan", "acquired with spectral scan"); int type = ras.readInt(); switch (type) { case 1: addSeriesMeta("DataType2", "calculated data"); break; case 2: addSeriesMeta("DataType2", "animation"); break; default: addSeriesMeta("DataType2", "original scan data"); } long[] overlayOffsets = new long[9]; String[] overlayKeys = new String[] {"VectorOverlay", "InputLut", "OutputLut", "ROI", "BleachROI", "MeanOfRoisOverlay", "TopoIsolineOverlay", "TopoProfileOverlay", "LinescanOverlay"}; overlayOffsets[0] = ras.readInt(); overlayOffsets[1] = ras.readInt(); overlayOffsets[2] = ras.readInt(); channelColorsOffset = ras.readInt(); addSeriesMeta("TimeInterval", ras.readDouble()); ras.skipBytes(4); scanInformationOffset = ras.readInt(); ras.skipBytes(4); timeStampOffset = ras.readInt(); eventListOffset = ras.readInt(); overlayOffsets[3] = ras.readInt(); overlayOffsets[4] = ras.readInt(); ras.skipBytes(4); addSeriesMeta("DisplayAspectX", ras.readDouble()); addSeriesMeta("DisplayAspectY", ras.readDouble()); addSeriesMeta("DisplayAspectZ", ras.readDouble()); addSeriesMeta("DisplayAspectTime", ras.readDouble()); overlayOffsets[5] = ras.readInt(); overlayOffsets[6] = ras.readInt(); overlayOffsets[7] = ras.readInt(); overlayOffsets[8] = ras.readInt(); if (getMetadataOptions().getMetadataLevel() != MetadataLevel.NO_OVERLAYS) { for (int i=0; i<overlayOffsets.length; i++) { parseOverlays(series, overlayOffsets[i], overlayKeys[i], store); } } totalROIs = 0; addSeriesMeta("ToolbarFlags", ras.readInt()); channelWavelengthOffset = ras.readInt(); ras.skipBytes(64); } else ras.skipBytes(182); MetadataTools.setDefaultCreationDate(store, getCurrentFile(), series); if (getSizeC() > 1) { if (!splitPlanes) splitPlanes = isRGB(); core[series].rgb = false; if (splitPlanes) core[series].imageCount *= getSizeC(); } for (int c=0; c<getEffectiveSizeC(); c++) { String lsid = MetadataTools.createLSID("Channel", series, c); store.setChannelID(lsid, series, c); } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { // NB: the Zeiss LSM 5.5 specification indicates that there should be // 15 32-bit integers here; however, there are actually 16 32-bit // integers before the tile position offset. // We have confirmed with Zeiss that this is correct, and the 6.0 // specification was updated to contain the correct information. ras.skipBytes(64); int tilePositionOffset = ras.readInt(); ras.skipBytes(36); int positionOffset = ras.readInt(); // read referenced structures addSeriesMeta("DimensionZ", getSizeZ()); addSeriesMeta("DimensionChannels", getSizeC()); addSeriesMeta("DimensionM", dimensionM); addSeriesMeta("DimensionP", dimensionP); if (positionOffset != 0) { in.seek(positionOffset); int nPositions = in.readInt(); for (int i=0; i<nPositions; i++) { double xPos = originX + in.readDouble() * 1000000; double yPos = originY + in.readDouble() * 1000000; double zPos = originZ + in.readDouble() * 1000000; xCoordinates.add(xPos); yCoordinates.add(yPos); zCoordinates.add(zPos); addGlobalMeta("X position for position #" + (i + 1), xPos); addGlobalMeta("Y position for position #" + (i + 1), yPos); addGlobalMeta("Z position for position #" + (i + 1), zPos); } } if (tilePositionOffset != 0) { in.seek(tilePositionOffset); int nTiles = in.readInt(); for (int i=0; i<nTiles; i++) { double xPos = originX + in.readDouble() * 1000000; double yPos = originY + in.readDouble() * 1000000; double zPos = originZ + in.readDouble() * 1000000; if (xCoordinates.size() > i) { xPos += xCoordinates.get(i); xCoordinates.setElementAt(xPos, i); } if (yCoordinates.size() > i) { yPos += yCoordinates.get(i); yCoordinates.setElementAt(yPos, i); } if (zCoordinates.size() > i) { zPos += zCoordinates.get(i); zCoordinates.setElementAt(zPos, i); } addGlobalMeta("X position for position #" + (i + 1), xPos); addGlobalMeta("Y position for position #" + (i + 1), yPos); addGlobalMeta("Z position for position #" + (i + 1), zPos); } } if (channelColorsOffset != 0) { in.seek(channelColorsOffset + 12); int colorsOffset = in.readInt(); int namesOffset = in.readInt(); // read the color of each channel if (colorsOffset > 0) { in.seek(channelColorsOffset + colorsOffset); lut[getSeries()] = new byte[getSizeC() * 3][256]; core[getSeries()].indexed = true; for (int i=0; i<getSizeC(); i++) { int color = in.readInt(); int red = color & 0xff; int green = (color & 0xff00) >> 8; int blue = (color & 0xff0000) >> 16; for (int j=0; j<256; j++) { lut[getSeries()][i * 3][j] = (byte) ((red / 255.0) * j); lut[getSeries()][i * 3 + 1][j] = (byte) ((green / 255.0) * j); lut[getSeries()][i * 3 + 2][j] = (byte) ((blue / 255.0) * j); } } } // read the name of each channel if (namesOffset > 0) { in.seek(channelColorsOffset + namesOffset + 4); for (int i=0; i<getSizeC(); i++) { if (in.getFilePointer() >= in.length() - 1) break; // we want to read until we find a null char String name = in.readCString(); if (name.length() <= 128) { addSeriesMeta("ChannelName" + i, name); } } } } if (timeStampOffset != 0) { in.seek(timeStampOffset + 8); for (int i=0; i<getSizeT(); i++) { double stamp = in.readDouble(); addSeriesMeta("TimeStamp" + i, stamp); timestamps.add(new Double(stamp)); } } if (eventListOffset != 0) { in.seek(eventListOffset + 4); int numEvents = in.readInt(); in.seek(in.getFilePointer() - 4); in.order(!in.isLittleEndian()); int tmpEvents = in.readInt(); if (numEvents < 0) numEvents = tmpEvents; else numEvents = (int) Math.min(numEvents, tmpEvents); in.order(!in.isLittleEndian()); if (numEvents > 65535) numEvents = 0; for (int i=0; i<numEvents; i++) { if (in.getFilePointer() + 16 <= in.length()) { int size = in.readInt(); double eventTime = in.readDouble(); int eventType = in.readInt(); addSeriesMeta("Event" + i + " Time", eventTime); addSeriesMeta("Event" + i + " Type", eventType); long fp = in.getFilePointer(); int len = size - 16; if (len > 65536) len = 65536; if (len < 0) len = 0; addSeriesMeta("Event" + i + " Description", in.readString(len)); in.seek(fp + size - 16); if (in.getFilePointer() < 0) break; } } } if (scanInformationOffset != 0) { in.seek(scanInformationOffset); nextLaser = nextDetector = 0; nextFilter = nextDichroicChannel = nextDichroic = 0; nextDataChannel = nextDetectChannel = nextIllumChannel = 0; Vector<SubBlock> blocks = new Vector<SubBlock>(); while (in.getFilePointer() < in.length() - 12) { if (in.getFilePointer() < 0) break; int entry = in.readInt(); int blockType = in.readInt(); int dataSize = in.readInt(); if (blockType == TYPE_SUBBLOCK) { SubBlock block = null; switch (entry) { case SUBBLOCK_RECORDING: block = new Recording(); break; case SUBBLOCK_LASER: block = new Laser(); break; case SUBBLOCK_TRACK: block = new Track(); break; case SUBBLOCK_DETECTION_CHANNEL: block = new DetectionChannel(); break; case SUBBLOCK_ILLUMINATION_CHANNEL: block = new IlluminationChannel(); break; case SUBBLOCK_BEAM_SPLITTER: block = new BeamSplitter(); break; case SUBBLOCK_DATA_CHANNEL: block = new DataChannel(); break; case SUBBLOCK_TIMER: block = new Timer(); break; case SUBBLOCK_MARKER: block = new Marker(); break; } if (block != null) { blocks.add(block); } } else if (dataSize + in.getFilePointer() <= in.length() && dataSize > 0) { in.skipBytes(dataSize); } else break; } Vector<SubBlock> nonAcquiredBlocks = new Vector<SubBlock>(); SubBlock[] metadataBlocks = blocks.toArray(new SubBlock[0]); for (SubBlock block : metadataBlocks) { block.addToHashtable(); if (!block.acquire) { nonAcquiredBlocks.add(block); blocks.remove(block); } } for (int i=0; i<blocks.size(); i++) { SubBlock block = blocks.get(i); // every valid IlluminationChannel must be immediately followed by // a valid DataChannel or IlluminationChannel if ((block instanceof IlluminationChannel) && i < blocks.size() - 1) { SubBlock nextBlock = blocks.get(i + 1); if (!(nextBlock instanceof DataChannel) && !(nextBlock instanceof IlluminationChannel)) { ((IlluminationChannel) block).wavelength = null; } } // every valid DetectionChannel must be immediately preceded by // a valid Track or DetectionChannel else if ((block instanceof DetectionChannel) && i > 0) { SubBlock prevBlock = blocks.get(i - 1); if (!(prevBlock instanceof Track) && !(prevBlock instanceof DetectionChannel)) { block.acquire = false; nonAcquiredBlocks.add(block); } } if (block.acquire) populateMetadataStore(block, store, series); } for (SubBlock block : nonAcquiredBlocks) { populateMetadataStore(block, store, series); } } } imageNames.add(imageName); if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { if (userName != null) { String experimenterID = MetadataTools.createLSID("Experimenter", 0); store.setExperimenterID(experimenterID, 0); store.setExperimenterUserName(userName, 0); store.setExperimenterDisplayName(userName, 0); } Double pixX = new Double(pixelSizeX); Double pixY = new Double(pixelSizeY); Double pixZ = new Double(pixelSizeZ); store.setPixelsPhysicalSizeX(pixX, series); store.setPixelsPhysicalSizeY(pixY, series); store.setPixelsPhysicalSizeZ(pixZ, series); double firstStamp = 0; if (timestamps.size() > 0) { firstStamp = timestamps.get(0).doubleValue(); } for (int i=0; i<getImageCount(); i++) { int[] zct = FormatTools.getZCTCoords(this, i); if (zct[2] < timestamps.size()) { double thisStamp = timestamps.get(zct[2]).doubleValue(); store.setPlaneDeltaT(thisStamp - firstStamp, series, i); int index = zct[2] + 1; double nextStamp = index < timestamps.size() ? timestamps.get(index).doubleValue() : thisStamp; if (i == getSizeT() - 1 && zct[2] > 0) { thisStamp = timestamps.get(zct[2] - 1).doubleValue(); } store.setPlaneExposureTime(nextStamp - thisStamp, series, i); } if (xCoordinates.size() > series) { store.setPlanePositionX(xCoordinates.get(series), series, i); store.setPlanePositionY(yCoordinates.get(series), series, i); store.setPlanePositionZ(zCoordinates.get(series), series, i); } } } ras.close(); - in.close(); } protected void populateMetadataStore(SubBlock block, MetadataStore store, int series) throws FormatException { if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM) { return; } int instrument = getEffectiveSeries(series); // NB: block.acquire can be false. If that is the case, Instrument data // is the only thing that should be populated. if (block instanceof Recording) { Recording recording = (Recording) block; String objectiveID = MetadataTools.createLSID("Objective", instrument, 0); if (recording.acquire) { store.setImageDescription(recording.description, series); store.setImageAcquiredDate(recording.startTime, series); store.setImageObjectiveSettingsID(objectiveID, series); binning = recording.binning; } store.setObjectiveCorrection( getCorrection(recording.correction), instrument, 0); store.setObjectiveImmersion( getImmersion(recording.immersion), instrument, 0); if (recording.magnification != null && recording.magnification > 0) { store.setObjectiveNominalMagnification( new PositiveInteger(recording.magnification), instrument, 0); } store.setObjectiveLensNA(recording.lensNA, instrument, 0); store.setObjectiveIris(recording.iris, instrument, 0); store.setObjectiveID(objectiveID, instrument, 0); } else if (block instanceof Laser) { Laser laser = (Laser) block; if (laser.medium != null) { store.setLaserLaserMedium(getLaserMedium(laser.medium), instrument, nextLaser); } if (laser.type != null) { store.setLaserType(getLaserType(laser.type), instrument, nextLaser); } if (laser.model != null) { store.setLaserModel(laser.model, instrument, nextLaser); } String lightSourceID = MetadataTools.createLSID("LightSource", instrument, nextLaser); store.setLaserID(lightSourceID, instrument, nextLaser); nextLaser++; } else if (block instanceof Track) { Track track = (Track) block; if (track.acquire) { store.setPixelsTimeIncrement(track.timeIncrement, series); } } else if (block instanceof DataChannel) { DataChannel channel = (DataChannel) block; if (channel.name != null && nextDataChannel < getSizeC() && channel.acquire) { store.setChannelName(channel.name, series, nextDataChannel++); } } else if (block instanceof DetectionChannel) { DetectionChannel channel = (DetectionChannel) block; if (channel.pinhole != null && channel.pinhole.doubleValue() != 0f && nextDetectChannel < getSizeC() && channel.acquire) { store.setChannelPinholeSize(channel.pinhole, series, nextDetectChannel); } if (channel.filter != null) { String id = MetadataTools.createLSID("Filter", instrument, nextFilter); if (channel.acquire && nextDetectChannel < getSizeC()) { store.setLightPathEmissionFilterRef( id, instrument, nextDetectChannel, 0); } store.setFilterID(id, instrument, nextFilter); store.setFilterModel(channel.filter, instrument, nextFilter); int space = channel.filter.indexOf(" "); if (space != -1) { String type = channel.filter.substring(0, space).trim(); if (type.equals("BP")) type = "BandPass"; else if (type.equals("LP")) type = "LongPass"; store.setFilterType(getFilterType(type), instrument, nextFilter); String transmittance = channel.filter.substring(space + 1).trim(); String[] v = transmittance.split("-"); try { store.setTransmittanceRangeCutIn( PositiveInteger.valueOf(v[0].trim()), instrument, nextFilter); } catch (NumberFormatException e) { } if (v.length > 1) { try { store.setTransmittanceRangeCutOut( PositiveInteger.valueOf(v[1].trim()), instrument, nextFilter); } catch (NumberFormatException e) { } } } nextFilter++; } if (channel.channelName != null) { String detectorID = MetadataTools.createLSID("Detector", instrument, nextDetector); store.setDetectorID(detectorID, instrument, nextDetector); if (channel.acquire && nextDetector < getSizeC()) { store.setDetectorSettingsID(detectorID, series, nextDetector); store.setDetectorSettingsBinning( getBinning(binning), series, nextDetector); } } if (channel.amplificationGain != null) { store.setDetectorAmplificationGain( channel.amplificationGain, instrument, nextDetector); } if (channel.gain != null) { store.setDetectorGain(channel.gain, instrument, nextDetector); } store.setDetectorType(getDetectorType("PMT"), instrument, nextDetector); store.setDetectorZoom(zoom, instrument, nextDetector); nextDetectChannel++; nextDetector++; } else if (block instanceof BeamSplitter) { BeamSplitter beamSplitter = (BeamSplitter) block; if (beamSplitter.filterSet != null) { if (beamSplitter.filter != null) { String id = MetadataTools.createLSID( "Dichroic", instrument, nextDichroic); store.setDichroicID(id, instrument, nextDichroic); store.setDichroicModel(beamSplitter.filter, instrument, nextDichroic); if (nextDichroicChannel < getEffectiveSizeC()) { store.setLightPathDichroicRef(id, series, nextDichroicChannel); } nextDichroic++; } nextDichroicChannel++; } } else if (block instanceof IlluminationChannel) { IlluminationChannel channel = (IlluminationChannel) block; if (channel.acquire && channel.wavelength != null) { store.setChannelEmissionWavelength( new PositiveInteger(channel.wavelength), series, nextIllumChannel++); } } } /** Parses overlay-related fields. */ protected void parseOverlays(int series, long data, String suffix, MetadataStore store) throws IOException { if (data == 0) return; String prefix = "Series " + series + " "; in.seek(data); int numberOfShapes = in.readInt(); int size = in.readInt(); if (size <= 194) return; in.skipBytes(20); boolean valid = in.readInt() == 1; in.skipBytes(164); for (int i=totalROIs; i<totalROIs+numberOfShapes; i++) { long offset = in.getFilePointer(); int type = in.readInt(); int blockLength = in.readInt(); double lineWidth = in.readInt(); int measurements = in.readInt(); double textOffsetX = in.readDouble(); double textOffsetY = in.readDouble(); int color = in.readInt(); boolean validShape = in.readInt() != 0; int knotWidth = in.readInt(); int catchArea = in.readInt(); int fontHeight = in.readInt(); int fontWidth = in.readInt(); int fontEscapement = in.readInt(); int fontOrientation = in.readInt(); int fontWeight = in.readInt(); boolean fontItalic = in.readInt() != 0; boolean fontUnderlined = in.readInt() != 0; boolean fontStrikeout = in.readInt() != 0; int fontCharSet = in.readInt(); int fontOutputPrecision = in.readInt(); int fontClipPrecision = in.readInt(); int fontQuality = in.readInt(); int fontPitchAndFamily = in.readInt(); String fontName = DataTools.stripString(in.readString(64)); boolean enabled = in.readShort() == 0; boolean moveable = in.readInt() == 0; in.skipBytes(34); String roiID = MetadataTools.createLSID("ROI", i); String shapeID = MetadataTools.createLSID("Shape", i, 0); switch (type) { case TEXT: double x = in.readDouble(); double y = in.readDouble(); String text = DataTools.stripString(in.readCString()); store.setTextValue(text, i, 0); store.setTextFontSize(new NonNegativeInteger(fontHeight), i, 0); store.setTextStrokeWidth(lineWidth, i, 0); store.setROIID(roiID, i); store.setTextID(shapeID, i, 0); break; case LINE: in.skipBytes(4); double startX = in.readDouble(); double startY = in.readDouble(); double endX = in.readDouble(); double endY = in.readDouble(); store.setLineX1(startX, i, 0); store.setLineY1(startY, i, 0); store.setLineX2(endX, i, 0); store.setLineY2(endY, i, 0); store.setLineFontSize(new NonNegativeInteger(fontHeight), i, 0); store.setLineStrokeWidth(lineWidth, i, 0); store.setROIID(roiID, i); store.setLineID(shapeID, i, 0); break; case SCALE_BAR: case OPEN_ARROW: case CLOSED_ARROW: case PALETTE: in.skipBytes(36); break; case RECTANGLE: in.skipBytes(4); double topX = in.readDouble(); double topY = in.readDouble(); double bottomX = in.readDouble(); double bottomY = in.readDouble(); double width = Math.abs(bottomX - topX); double height = Math.abs(bottomY - topY); topX = Math.min(topX, bottomX); topY = Math.min(topY, bottomY); store.setRectangleX(topX, i, 0); store.setRectangleY(topY, i, 0); store.setRectangleWidth(width, i, 0); store.setRectangleHeight(height, i, 0); store.setRectangleFontSize(new NonNegativeInteger(fontHeight), i, 0); store.setRectangleStrokeWidth(lineWidth, i, 0); store.setROIID(roiID, i); store.setRectangleID(shapeID, i, 0); break; case ELLIPSE: int knots = in.readInt(); double[] xs = new double[knots]; double[] ys = new double[knots]; for (int j=0; j<xs.length; j++) { xs[j] = in.readDouble(); ys[j] = in.readDouble(); } double rx = 0, ry = 0, centerX = 0, centerY = 0; if (knots == 4) { double r1x = Math.abs(xs[2] - xs[0]) / 2; double r1y = Math.abs(ys[2] - ys[0]) / 2; double r2x = Math.abs(xs[3] - xs[1]) / 2; double r2y = Math.abs(ys[3] - ys[1]) / 2; if (r1x > r2x) { ry = r1y; rx = r2x; centerX = Math.min(xs[3], xs[1]) + rx; centerY = Math.min(ys[2], ys[0]) + ry; } else { ry = r2y; rx = r1x; centerX = Math.min(xs[2], xs[0]) + rx; centerY = Math.min(ys[3], ys[1]) + ry; } } else if (knots == 3) { // we are given the center point and one cut point for each axis centerX = xs[0]; centerY = ys[0]; rx = Math.sqrt(Math.pow(xs[1] - xs[0], 2) + Math.pow(ys[1] - ys[0], 2)); ry = Math.sqrt(Math.pow(xs[2] - xs[0], 2) + Math.pow(ys[2] - ys[0], 2)); // calculate rotation angle double slope = (ys[2] - centerY) / (xs[2] - centerX); double theta = Math.toDegrees(Math.atan(slope)); store.setEllipseTransform("rotate(" + theta + " " + centerX + " " + centerY + ")", i, 0); } store.setEllipseX(centerX, i, 0); store.setEllipseY(centerY, i, 0); store.setEllipseRadiusX(rx, i, 0); store.setEllipseRadiusY(ry, i, 0); store.setEllipseFontSize(new NonNegativeInteger(fontHeight), i, 0); store.setEllipseStrokeWidth(lineWidth, i, 0); store.setROIID(roiID, i); store.setEllipseID(shapeID, i, 0); break; case CIRCLE: in.skipBytes(4); centerX = in.readDouble(); centerY = in.readDouble(); double curveX = in.readDouble(); double curveY = in.readDouble(); double radius = Math.sqrt(Math.pow(curveX - centerX, 2) + Math.pow(curveY - centerY, 2)); store.setEllipseX(centerX, i, 0); store.setEllipseY(centerY, i, 0); store.setEllipseRadiusX(radius, i, 0); store.setEllipseRadiusY(radius, i, 0); store.setEllipseFontSize(new NonNegativeInteger(fontHeight), i, 0); store.setEllipseStrokeWidth(lineWidth, i, 0); store.setROIID(roiID, i); store.setEllipseID(shapeID, i, 0); break; case CIRCLE_3POINT: in.skipBytes(4); // given 3 points on the perimeter of the circle, we need to // calculate the center and radius double[][] points = new double[3][2]; for (int j=0; j<points.length; j++) { for (int k=0; k<points[j].length; k++) { points[j][k] = in.readDouble(); } } double s = 0.5 * ((points[1][0] - points[2][0]) * (points[0][0] - points[2][0]) - (points[1][1] - points[2][1]) * (points[2][1] - points[0][1])); double div = (points[0][0] - points[1][0]) * (points[2][1] - points[0][1]) - (points[1][1] - points[0][1]) * (points[0][0] - points[2][0]); s /= div; double cx = 0.5 * (points[0][0] + points[1][0]) + s * (points[1][1] - points[0][1]); double cy = 0.5 * (points[0][1] + points[1][1]) + s * (points[0][0] - points[1][0]); double r = Math.sqrt(Math.pow(points[0][0] - cx, 2) + Math.pow(points[0][1] - cy, 2)); store.setEllipseX(cx, i, 0); store.setEllipseY(cy, i, 0); store.setEllipseRadiusX(r, i, 0); store.setEllipseRadiusY(r, i, 0); store.setEllipseFontSize(new NonNegativeInteger(fontHeight), i, 0); store.setEllipseStrokeWidth(lineWidth, i, 0); store.setROIID(roiID, i); store.setEllipseID(shapeID, i, 0); break; case ANGLE: in.skipBytes(4); points = new double[3][2]; for (int j=0; j<points.length; j++) { for (int k=0; k<points[j].length; k++) { points[j][k] = in.readDouble(); } } StringBuffer p = new StringBuffer(); for (int j=0; j<points.length; j++) { p.append(points[j][0]); p.append(","); p.append(points[j][1]); if (j < points.length - 1) p.append(" "); } store.setPolylinePoints(p.toString(), i, 0); store.setPolylineFontSize(new NonNegativeInteger(fontHeight), i, 0); store.setPolylineStrokeWidth(lineWidth, i, 0); store.setROIID(roiID, i); store.setPolylineID(shapeID, i, 0); break; case CLOSED_POLYLINE: case OPEN_POLYLINE: case POLYLINE_ARROW: int nKnots = in.readInt(); points = new double[nKnots][2]; for (int j=0; j<points.length; j++) { for (int k=0; k<points[j].length; k++) { points[j][k] = in.readDouble(); } } p = new StringBuffer(); for (int j=0; j<points.length; j++) { p.append(points[j][0]); p.append(","); p.append(points[j][1]); if (j < points.length - 1) p.append(" "); } store.setPolylinePoints(p.toString(), i, 0); store.setPolylineClosed(type == CLOSED_POLYLINE, i, 0); store.setPolylineFontSize(new NonNegativeInteger(fontHeight), i, 0); store.setPolylineStrokeWidth(lineWidth, i, 0); store.setROIID(roiID, i); store.setPolylineID(shapeID, i, 0); break; case CLOSED_BEZIER: case OPEN_BEZIER: case BEZIER_WITH_ARROW: nKnots = in.readInt(); points = new double[nKnots][2]; for (int j=0; j<points.length; j++) { for (int k=0; k<points[j].length; k++) { points[j][k] = in.readDouble(); } } p = new StringBuffer(); for (int j=0; j<points.length; j++) { p.append(points[j][0]); p.append(","); p.append(points[j][1]); if (j < points.length - 1) p.append(" "); } store.setPolylinePoints(p.toString(), i, 0); store.setPolylineClosed(type != OPEN_BEZIER, i, 0); store.setPolylineFontSize(new NonNegativeInteger(fontHeight), i, 0); store.setPolylineStrokeWidth(lineWidth, i, 0); store.setROIID(roiID, i); store.setPolylineID(shapeID, i, 0); break; default: i--; numberOfShapes--; continue; } // populate shape attributes in.seek(offset + blockLength); } totalROIs += numberOfShapes; } /** Parse a .mdb file and return a list of referenced .lsm files. */ private String[] parseMDB(String mdbFile) throws FormatException, IOException { Location mdb = new Location(mdbFile).getAbsoluteFile(); Location parent = mdb.getParentFile(); MDBService mdbService = null; try { ServiceFactory factory = new ServiceFactory(); mdbService = factory.getInstance(MDBService.class); } catch (DependencyException de) { throw new FormatException("MDB Tools Java library not found", de); } try { mdbService.initialize(mdbFile); } catch (Exception e) { return null; } Vector<Vector<String[]>> tables = mdbService.parseDatabase(); Vector<String> referencedLSMs = new Vector<String>(); for (Vector<String[]> table : tables) { String[] columnNames = table.get(0); String tableName = columnNames[0]; for (int row=1; row<table.size(); row++) { String[] tableRow = table.get(row); for (int col=0; col<tableRow.length; col++) { String key = tableName + " " + columnNames[col + 1] + " " + row; if (currentId != null) { addGlobalMeta(key, tableRow[col]); } if (tableName.equals("Recordings") && columnNames[col + 1] != null && columnNames[col + 1].equals("SampleData")) { String filename = tableRow[col].trim(); filename = filename.replace('\\', File.separatorChar); filename = filename.replace('/', File.separatorChar); filename = filename.substring(filename.lastIndexOf(File.separator) + 1); if (filename.length() > 0) { Location file = new Location(parent, filename); if (file.exists()) { referencedLSMs.add(file.getAbsolutePath()); } } } } } } if (referencedLSMs.size() > 0) { return referencedLSMs.toArray(new String[0]); } String[] fileList = parent.list(true); for (int i=0; i<fileList.length; i++) { if (checkSuffix(fileList[i], new String[] {"lsm"}) && !fileList[i].startsWith(".")) { referencedLSMs.add(new Location(parent, fileList[i]).getAbsolutePath()); } } return referencedLSMs.toArray(new String[0]); } private static Hashtable<Integer, String> createKeys() { Hashtable<Integer, String> h = new Hashtable<Integer, String>(); h.put(new Integer(0x10000001), "Name"); h.put(new Integer(0x4000000c), "Name"); h.put(new Integer(0x50000001), "Name"); h.put(new Integer(0x90000001), "Name"); h.put(new Integer(0x90000005), "Detection Channel Name"); h.put(new Integer(0xb0000003), "Name"); h.put(new Integer(0xd0000001), "Name"); h.put(new Integer(0x12000001), "Name"); h.put(new Integer(0x14000001), "Name"); h.put(new Integer(0x10000002), "Description"); h.put(new Integer(0x14000002), "Description"); h.put(new Integer(0x10000003), "Notes"); h.put(new Integer(0x10000004), "Objective"); h.put(new Integer(0x10000005), "Processing Summary"); h.put(new Integer(0x10000006), "Special Scan Mode"); h.put(new Integer(0x10000007), "Scan Type"); h.put(new Integer(0x10000008), "Scan Mode"); h.put(new Integer(0x10000009), "Number of Stacks"); h.put(new Integer(0x1000000a), "Lines Per Plane"); h.put(new Integer(0x1000000b), "Samples Per Line"); h.put(new Integer(0x1000000c), "Planes Per Volume"); h.put(new Integer(0x1000000d), "Images Width"); h.put(new Integer(0x1000000e), "Images Height"); h.put(new Integer(0x1000000f), "Number of Planes"); h.put(new Integer(0x10000010), "Number of Stacks"); h.put(new Integer(0x10000011), "Number of Channels"); h.put(new Integer(0x10000012), "Linescan XY Size"); h.put(new Integer(0x10000013), "Scan Direction"); h.put(new Integer(0x10000014), "Time Series"); h.put(new Integer(0x10000015), "Original Scan Data"); h.put(new Integer(0x10000016), "Zoom X"); h.put(new Integer(0x10000017), "Zoom Y"); h.put(new Integer(0x10000018), "Zoom Z"); h.put(new Integer(0x10000019), "Sample 0X"); h.put(new Integer(0x1000001a), "Sample 0Y"); h.put(new Integer(0x1000001b), "Sample 0Z"); h.put(new Integer(0x1000001c), "Sample Spacing"); h.put(new Integer(0x1000001d), "Line Spacing"); h.put(new Integer(0x1000001e), "Plane Spacing"); h.put(new Integer(0x1000001f), "Plane Width"); h.put(new Integer(0x10000020), "Plane Height"); h.put(new Integer(0x10000021), "Volume Depth"); h.put(new Integer(0x10000034), "Rotation"); h.put(new Integer(0x10000035), "Precession"); h.put(new Integer(0x10000036), "Sample 0Time"); h.put(new Integer(0x10000037), "Start Scan Trigger In"); h.put(new Integer(0x10000038), "Start Scan Trigger Out"); h.put(new Integer(0x10000039), "Start Scan Event"); h.put(new Integer(0x10000040), "Start Scan Time"); h.put(new Integer(0x10000041), "Stop Scan Trigger In"); h.put(new Integer(0x10000042), "Stop Scan Trigger Out"); h.put(new Integer(0x10000043), "Stop Scan Event"); h.put(new Integer(0x10000044), "Stop Scan Time"); h.put(new Integer(0x10000045), "Use ROIs"); h.put(new Integer(0x10000046), "Use Reduced Memory ROIs"); h.put(new Integer(0x10000047), "User"); h.put(new Integer(0x10000048), "Use B/C Correction"); h.put(new Integer(0x10000049), "Position B/C Contrast 1"); h.put(new Integer(0x10000050), "Position B/C Contrast 2"); h.put(new Integer(0x10000051), "Interpolation Y"); h.put(new Integer(0x10000052), "Camera Binning"); h.put(new Integer(0x10000053), "Camera Supersampling"); h.put(new Integer(0x10000054), "Camera Frame Width"); h.put(new Integer(0x10000055), "Camera Frame Height"); h.put(new Integer(0x10000056), "Camera Offset X"); h.put(new Integer(0x10000057), "Camera Offset Y"); h.put(new Integer(0x40000001), "Multiplex Type"); h.put(new Integer(0x40000002), "Multiplex Order"); h.put(new Integer(0x40000003), "Sampling Mode"); h.put(new Integer(0x40000004), "Sampling Method"); h.put(new Integer(0x40000005), "Sampling Number"); h.put(new Integer(0x40000006), "Acquire"); h.put(new Integer(0x50000002), "Acquire"); h.put(new Integer(0x7000000b), "Acquire"); h.put(new Integer(0x90000004), "Acquire"); h.put(new Integer(0xd0000017), "Acquire"); h.put(new Integer(0x40000007), "Sample Observation Time"); h.put(new Integer(0x40000008), "Time Between Stacks"); h.put(new Integer(0x4000000d), "Collimator 1 Name"); h.put(new Integer(0x4000000e), "Collimator 1 Position"); h.put(new Integer(0x4000000f), "Collimator 2 Name"); h.put(new Integer(0x40000010), "Collimator 2 Position"); h.put(new Integer(0x40000011), "Is Bleach Track"); h.put(new Integer(0x40000012), "Bleach After Scan Number"); h.put(new Integer(0x40000013), "Bleach Scan Number"); h.put(new Integer(0x40000014), "Trigger In"); h.put(new Integer(0x12000004), "Trigger In"); h.put(new Integer(0x14000003), "Trigger In"); h.put(new Integer(0x40000015), "Trigger Out"); h.put(new Integer(0x12000005), "Trigger Out"); h.put(new Integer(0x14000004), "Trigger Out"); h.put(new Integer(0x40000016), "Is Ratio Track"); h.put(new Integer(0x40000017), "Bleach Count"); h.put(new Integer(0x40000018), "SPI Center Wavelength"); h.put(new Integer(0x40000019), "Pixel Time"); h.put(new Integer(0x40000020), "ID Condensor Frontlens"); h.put(new Integer(0x40000021), "Condensor Frontlens"); h.put(new Integer(0x40000022), "ID Field Stop"); h.put(new Integer(0x40000023), "Field Stop Value"); h.put(new Integer(0x40000024), "ID Condensor Aperture"); h.put(new Integer(0x40000025), "Condensor Aperture"); h.put(new Integer(0x40000026), "ID Condensor Revolver"); h.put(new Integer(0x40000027), "Condensor Revolver"); h.put(new Integer(0x40000028), "ID Transmission Filter 1"); h.put(new Integer(0x40000029), "ID Transmission 1"); h.put(new Integer(0x40000030), "ID Transmission Filter 2"); h.put(new Integer(0x40000031), "ID Transmission 2"); h.put(new Integer(0x40000032), "Repeat Bleach"); h.put(new Integer(0x40000033), "Enable Spot Bleach Pos"); h.put(new Integer(0x40000034), "Spot Bleach Position X"); h.put(new Integer(0x40000035), "Spot Bleach Position Y"); h.put(new Integer(0x40000036), "Bleach Position Z"); h.put(new Integer(0x50000003), "Power"); h.put(new Integer(0x90000002), "Power"); h.put(new Integer(0x70000003), "Detector Gain"); h.put(new Integer(0x70000005), "Amplifier Gain"); h.put(new Integer(0x70000007), "Amplifier Offset"); h.put(new Integer(0x70000009), "Pinhole Diameter"); h.put(new Integer(0x7000000c), "Detector Name"); h.put(new Integer(0x7000000d), "Amplifier Name"); h.put(new Integer(0x7000000e), "Pinhole Name"); h.put(new Integer(0x7000000f), "Filter Set Name"); h.put(new Integer(0x70000010), "Filter Name"); h.put(new Integer(0x70000013), "Integrator Name"); h.put(new Integer(0x70000014), "Detection Channel Name"); h.put(new Integer(0x70000015), "Detector Gain B/C 1"); h.put(new Integer(0x70000016), "Detector Gain B/C 2"); h.put(new Integer(0x70000017), "Amplifier Gain B/C 1"); h.put(new Integer(0x70000018), "Amplifier Gain B/C 2"); h.put(new Integer(0x70000019), "Amplifier Offset B/C 1"); h.put(new Integer(0x70000020), "Amplifier Offset B/C 2"); h.put(new Integer(0x70000021), "Spectral Scan Channels"); h.put(new Integer(0x70000022), "SPI Wavelength Start"); h.put(new Integer(0x70000023), "SPI Wavelength End"); h.put(new Integer(0x70000026), "Dye Name"); h.put(new Integer(0xd0000014), "Dye Name"); h.put(new Integer(0x70000027), "Dye Folder"); h.put(new Integer(0xd0000015), "Dye Folder"); h.put(new Integer(0x90000003), "Wavelength"); h.put(new Integer(0x90000006), "Power B/C 1"); h.put(new Integer(0x90000007), "Power B/C 2"); h.put(new Integer(0xb0000001), "Filter Set"); h.put(new Integer(0xb0000002), "Filter"); h.put(new Integer(0xd0000004), "Color"); h.put(new Integer(0xd0000005), "Sample Type"); h.put(new Integer(0xd0000006), "Bits Per Sample"); h.put(new Integer(0xd0000007), "Ratio Type"); h.put(new Integer(0xd0000008), "Ratio Track 1"); h.put(new Integer(0xd0000009), "Ratio Track 2"); h.put(new Integer(0xd000000a), "Ratio Channel 1"); h.put(new Integer(0xd000000b), "Ratio Channel 2"); h.put(new Integer(0xd000000c), "Ratio Const. 1"); h.put(new Integer(0xd000000d), "Ratio Const. 2"); h.put(new Integer(0xd000000e), "Ratio Const. 3"); h.put(new Integer(0xd000000f), "Ratio Const. 4"); h.put(new Integer(0xd0000010), "Ratio Const. 5"); h.put(new Integer(0xd0000011), "Ratio Const. 6"); h.put(new Integer(0xd0000012), "Ratio First Images 1"); h.put(new Integer(0xd0000013), "Ratio First Images 2"); h.put(new Integer(0xd0000016), "Spectrum"); h.put(new Integer(0x12000003), "Interval"); return h; } private Integer readEntry() throws IOException { return new Integer(in.readInt()); } private Object readValue() throws IOException { int blockType = in.readInt(); int dataSize = in.readInt(); switch (blockType) { case TYPE_LONG: return new Long(in.readInt()); case TYPE_RATIONAL: return new Double(in.readDouble()); case TYPE_ASCII: String s = in.readString(dataSize).trim(); StringBuffer sb = new StringBuffer(); for (int i=0; i<s.length(); i++) { if (s.charAt(i) >= 10) sb.append(s.charAt(i)); else break; } return sb.toString(); case TYPE_SUBBLOCK: return null; } in.skipBytes(dataSize); return ""; } // -- Helper classes -- class SubBlock { public Hashtable<Integer, Object> blockData; public boolean acquire = true; public SubBlock() { try { read(); } catch (IOException e) { LOGGER.debug("Failed to read sub-block data", e); } } protected int getIntValue(int key) { Object o = blockData.get(new Integer(key)); if (o == null) return -1; return !(o instanceof Number) ? -1 : ((Number) o).intValue(); } protected float getFloatValue(int key) { Object o = blockData.get(new Integer(key)); if (o == null) return -1f; return !(o instanceof Number) ? -1f : ((Number) o).floatValue(); } protected double getDoubleValue(int key) { Object o = blockData.get(new Integer(key)); if (o == null) return -1d; return !(o instanceof Number) ? -1d : ((Number) o).doubleValue(); } protected String getStringValue(int key) { Object o = blockData.get(new Integer(key)); return o == null ? null : o.toString(); } protected void read() throws IOException { blockData = new Hashtable<Integer, Object>(); Integer entry = readEntry(); Object value = readValue(); while (value != null) { if (!blockData.containsKey(entry)) blockData.put(entry, value); entry = readEntry(); value = readValue(); } } public void addToHashtable() { String prefix = this.getClass().getSimpleName() + " #"; int index = 1; while (getSeriesMeta(prefix + index + " Acquire") != null) index++; prefix += index; Integer[] keys = blockData.keySet().toArray(new Integer[0]); for (Integer key : keys) { if (METADATA_KEYS.get(key) != null) { addSeriesMeta(prefix + " " + METADATA_KEYS.get(key), blockData.get(key)); if (METADATA_KEYS.get(key).equals("Bits Per Sample")) { core[getSeries()].bitsPerPixel = Integer.parseInt(blockData.get(key).toString()); } else if (METADATA_KEYS.get(key).equals("User")) { userName = blockData.get(key).toString(); } } } addGlobalMeta(prefix + " Acquire", new Boolean(acquire)); } } class Recording extends SubBlock { public String description; public String name; public String binning; public String startTime; // Objective data public String correction, immersion; public Integer magnification; public Double lensNA; public Boolean iris; protected void read() throws IOException { super.read(); description = getStringValue(RECORDING_DESCRIPTION); name = getStringValue(RECORDING_NAME); binning = getStringValue(RECORDING_CAMERA_BINNING); if (binning != null && binning.indexOf("x") == -1) { if (binning.equals("0")) binning = null; else binning += "x" + binning; } // start time in days since Dec 30 1899 long stamp = (long) (getDoubleValue(RECORDING_SAMPLE_0TIME) * 86400000); if (stamp > 0) { startTime = DateTools.convertDate(stamp, DateTools.MICROSOFT); } zoom = getDoubleValue(RECORDING_ZOOM); String objective = getStringValue(RECORDING_OBJECTIVE); correction = ""; if (objective == null) objective = ""; String[] tokens = objective.split(" "); int next = 0; for (; next<tokens.length; next++) { if (tokens[next].indexOf("/") != -1) break; correction += tokens[next]; } if (next < tokens.length) { String p = tokens[next++]; try { magnification = new Integer(p.substring(0, p.indexOf("/") - 1)); } catch (NumberFormatException e) { } try { lensNA = new Double(p.substring(p.indexOf("/") + 1)); } catch (NumberFormatException e) { } } immersion = next < tokens.length ? tokens[next++] : "Unknown"; iris = Boolean.FALSE; if (next < tokens.length) { iris = new Boolean(tokens[next++].trim().equalsIgnoreCase("iris")); } } } class Laser extends SubBlock { public String medium, type, model; public Double power; protected void read() throws IOException { super.read(); model = getStringValue(LASER_NAME); type = getStringValue(LASER_NAME); if (type == null) type = ""; medium = ""; if (type.startsWith("HeNe")) { medium = "HeNe"; type = "Gas"; } else if (type.startsWith("Argon")) { medium = "Ar"; type = "Gas"; } else if (type.equals("Titanium:Sapphire") || type.equals("Mai Tai")) { medium = "TiSapphire"; type = "SolidState"; } else if (type.equals("YAG")) { medium = ""; type = "SolidState"; } else if (type.equals("Ar/Kr")) { medium = ""; type = "Gas"; } acquire = getIntValue(LASER_ACQUIRE) != 0; power = getDoubleValue(LASER_POWER); } } class Track extends SubBlock { public Double timeIncrement; protected void read() throws IOException { super.read(); timeIncrement = getDoubleValue(TRACK_TIME_BETWEEN_STACKS); acquire = getIntValue(TRACK_ACQUIRE) != 0; } } class DetectionChannel extends SubBlock { public Double pinhole; public Double gain, amplificationGain; public String filter, filterSet; public String channelName; protected void read() throws IOException { super.read(); pinhole = new Double(getDoubleValue(CHANNEL_PINHOLE_DIAMETER)); gain = new Double(getDoubleValue(CHANNEL_DETECTOR_GAIN)); amplificationGain = new Double(getDoubleValue(CHANNEL_AMPLIFIER_GAIN)); filter = getStringValue(CHANNEL_FILTER); if (filter != null) { filter = filter.trim(); if (filter.length() == 0 || filter.equals("None")) { filter = null; } } filterSet = getStringValue(CHANNEL_FILTER_SET); channelName = getStringValue(CHANNEL_NAME); acquire = getIntValue(CHANNEL_ACQUIRE) != 0; } } class IlluminationChannel extends SubBlock { public Integer wavelength; public Double attenuation; public String name; protected void read() throws IOException { super.read(); wavelength = new Integer(getIntValue(ILLUM_CHANNEL_WAVELENGTH)); attenuation = new Double(getDoubleValue(ILLUM_CHANNEL_ATTENUATION)); acquire = getIntValue(ILLUM_CHANNEL_ACQUIRE) != 0; name = getStringValue(ILLUM_CHANNEL_NAME); try { wavelength = new Integer(name); } catch (NumberFormatException e) { } } } class DataChannel extends SubBlock { public String name; protected void read() throws IOException { super.read(); name = getStringValue(DATA_CHANNEL_NAME); for (int i=0; i<name.length(); i++) { if (name.charAt(i) < 10) { name = name.substring(0, i); break; } } acquire = getIntValue(DATA_CHANNEL_ACQUIRE) != 0; } } class BeamSplitter extends SubBlock { public String filter, filterSet; protected void read() throws IOException { super.read(); filter = getStringValue(BEAM_SPLITTER_FILTER); if (filter != null) { filter = filter.trim(); if (filter.length() == 0 || filter.equals("None")) { filter = null; } } filterSet = getStringValue(BEAM_SPLITTER_FILTER_SET); } } class Timer extends SubBlock { } class Marker extends SubBlock { } }
true
true
protected void initMetadata(int series) throws FormatException, IOException { setSeries(series); IFDList ifds = ifdsList.get(series); IFD ifd = ifds.get(0); in.close(); in = new RandomAccessInputStream(getLSMFileFromSeries(series)); in.order(isLittleEndian()); tiffParser = new TiffParser(in); PhotoInterp photo = ifd.getPhotometricInterpretation(); int samples = ifd.getSamplesPerPixel(); core[series].sizeX = (int) ifd.getImageWidth(); core[series].sizeY = (int) ifd.getImageLength(); core[series].rgb = samples > 1 || photo == PhotoInterp.RGB; core[series].interleaved = false; core[series].sizeC = isRGB() ? samples : 1; core[series].pixelType = ifd.getPixelType(); core[series].imageCount = ifds.size(); core[series].sizeZ = getImageCount(); core[series].sizeT = 1; LOGGER.info("Reading LSM metadata for series #{}", series); MetadataStore store = makeFilterMetadata(); int instrument = getEffectiveSeries(series); String imageName = getLSMFileFromSeries(series); if (imageName.indexOf(".") != -1) { imageName = imageName.substring(0, imageName.lastIndexOf(".")); } if (imageName.indexOf(File.separator) != -1) { imageName = imageName.substring(imageName.lastIndexOf(File.separator) + 1); } if (lsmFilenames.length != getSeriesCount()) { imageName += " #" + (getPosition(series) + 1); } // link Instrument and Image store.setImageID(MetadataTools.createLSID("Image", series), series); String instrumentID = MetadataTools.createLSID("Instrument", instrument); store.setInstrumentID(instrumentID, instrument); store.setImageInstrumentRef(instrumentID, series); RandomAccessInputStream ras = getCZTag(ifd); if (ras == null) { imageNames.add(imageName); return; } ras.seek(16); core[series].sizeZ = ras.readInt(); ras.skipBytes(4); core[series].sizeT = ras.readInt(); int dataType = ras.readInt(); switch (dataType) { case 2: addSeriesMeta("DataType", "12 bit unsigned integer"); break; case 5: addSeriesMeta("DataType", "32 bit float"); break; case 0: addSeriesMeta("DataType", "varying data types"); break; default: addSeriesMeta("DataType", "8 bit unsigned integer"); } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { ras.seek(0); addSeriesMeta("MagicNumber ", ras.readInt()); addSeriesMeta("StructureSize", ras.readInt()); addSeriesMeta("DimensionX", ras.readInt()); addSeriesMeta("DimensionY", ras.readInt()); ras.seek(32); addSeriesMeta("ThumbnailX", ras.readInt()); addSeriesMeta("ThumbnailY", ras.readInt()); // pixel sizes are stored in meters, we need them in microns pixelSizeX = ras.readDouble() * 1000000; pixelSizeY = ras.readDouble() * 1000000; pixelSizeZ = ras.readDouble() * 1000000; addSeriesMeta("VoxelSizeX", new Double(pixelSizeX)); addSeriesMeta("VoxelSizeY", new Double(pixelSizeY)); addSeriesMeta("VoxelSizeZ", new Double(pixelSizeZ)); originX = ras.readDouble() * 1000000; originY = ras.readDouble() * 1000000; originZ = ras.readDouble() * 1000000; addSeriesMeta("OriginX", originX); addSeriesMeta("OriginY", originY); addSeriesMeta("OriginZ", originZ); } else ras.seek(88); int scanType = ras.readShort(); switch (scanType) { case 0: addSeriesMeta("ScanType", "x-y-z scan"); core[series].dimensionOrder = "XYZCT"; break; case 1: addSeriesMeta("ScanType", "z scan (x-z plane)"); core[series].dimensionOrder = "XYZCT"; break; case 2: addSeriesMeta("ScanType", "line scan"); core[series].dimensionOrder = "XYZCT"; break; case 3: addSeriesMeta("ScanType", "time series x-y"); core[series].dimensionOrder = "XYTCZ"; break; case 4: addSeriesMeta("ScanType", "time series x-z"); core[series].dimensionOrder = "XYZTC"; break; case 5: addSeriesMeta("ScanType", "time series 'Mean of ROIs'"); core[series].dimensionOrder = "XYTCZ"; break; case 6: addSeriesMeta("ScanType", "time series x-y-z"); core[series].dimensionOrder = "XYZTC"; break; case 7: addSeriesMeta("ScanType", "spline scan"); core[series].dimensionOrder = "XYCTZ"; break; case 8: addSeriesMeta("ScanType", "spline scan x-z"); core[series].dimensionOrder = "XYCZT"; break; case 9: addSeriesMeta("ScanType", "time series spline plane x-z"); core[series].dimensionOrder = "XYTCZ"; break; case 10: addSeriesMeta("ScanType", "point mode"); core[series].dimensionOrder = "XYZCT"; break; default: addSeriesMeta("ScanType", "x-y-z scan"); core[series].dimensionOrder = "XYZCT"; } core[series].indexed = lut != null && lut[series] != null; if (isIndexed()) { core[series].rgb = false; } if (getSizeC() == 0) core[series].sizeC = 1; if (isRGB()) { // shuffle C to front of order string core[series].dimensionOrder = getDimensionOrder().replaceAll("C", ""); core[series].dimensionOrder = getDimensionOrder().replaceAll("XY", "XYC"); } if (getEffectiveSizeC() == 0) { core[series].imageCount = getSizeZ() * getSizeT(); } else { core[series].imageCount = getSizeZ() * getSizeT() * getEffectiveSizeC(); } if (getImageCount() != ifds.size()) { int diff = getImageCount() - ifds.size(); core[series].imageCount = ifds.size(); if (diff % getSizeZ() == 0) { core[series].sizeT -= (diff / getSizeZ()); } else if (diff % getSizeT() == 0) { core[series].sizeZ -= (diff / getSizeT()); } else if (getSizeZ() > 1) { core[series].sizeZ = ifds.size(); core[series].sizeT = 1; } else if (getSizeT() > 1) { core[series].sizeT = ifds.size(); core[series].sizeZ = 1; } } if (getSizeZ() == 0) core[series].sizeZ = getImageCount(); if (getSizeT() == 0) core[series].sizeT = getImageCount() / getSizeZ(); long channelColorsOffset = 0; long timeStampOffset = 0; long eventListOffset = 0; long scanInformationOffset = 0; long channelWavelengthOffset = 0; if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { int spectralScan = ras.readShort(); if (spectralScan != 1) { addSeriesMeta("SpectralScan", "no spectral scan"); } else addSeriesMeta("SpectralScan", "acquired with spectral scan"); int type = ras.readInt(); switch (type) { case 1: addSeriesMeta("DataType2", "calculated data"); break; case 2: addSeriesMeta("DataType2", "animation"); break; default: addSeriesMeta("DataType2", "original scan data"); } long[] overlayOffsets = new long[9]; String[] overlayKeys = new String[] {"VectorOverlay", "InputLut", "OutputLut", "ROI", "BleachROI", "MeanOfRoisOverlay", "TopoIsolineOverlay", "TopoProfileOverlay", "LinescanOverlay"}; overlayOffsets[0] = ras.readInt(); overlayOffsets[1] = ras.readInt(); overlayOffsets[2] = ras.readInt(); channelColorsOffset = ras.readInt(); addSeriesMeta("TimeInterval", ras.readDouble()); ras.skipBytes(4); scanInformationOffset = ras.readInt(); ras.skipBytes(4); timeStampOffset = ras.readInt(); eventListOffset = ras.readInt(); overlayOffsets[3] = ras.readInt(); overlayOffsets[4] = ras.readInt(); ras.skipBytes(4); addSeriesMeta("DisplayAspectX", ras.readDouble()); addSeriesMeta("DisplayAspectY", ras.readDouble()); addSeriesMeta("DisplayAspectZ", ras.readDouble()); addSeriesMeta("DisplayAspectTime", ras.readDouble()); overlayOffsets[5] = ras.readInt(); overlayOffsets[6] = ras.readInt(); overlayOffsets[7] = ras.readInt(); overlayOffsets[8] = ras.readInt(); if (getMetadataOptions().getMetadataLevel() != MetadataLevel.NO_OVERLAYS) { for (int i=0; i<overlayOffsets.length; i++) { parseOverlays(series, overlayOffsets[i], overlayKeys[i], store); } } totalROIs = 0; addSeriesMeta("ToolbarFlags", ras.readInt()); channelWavelengthOffset = ras.readInt(); ras.skipBytes(64); } else ras.skipBytes(182); MetadataTools.setDefaultCreationDate(store, getCurrentFile(), series); if (getSizeC() > 1) { if (!splitPlanes) splitPlanes = isRGB(); core[series].rgb = false; if (splitPlanes) core[series].imageCount *= getSizeC(); } for (int c=0; c<getEffectiveSizeC(); c++) { String lsid = MetadataTools.createLSID("Channel", series, c); store.setChannelID(lsid, series, c); } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { // NB: the Zeiss LSM 5.5 specification indicates that there should be // 15 32-bit integers here; however, there are actually 16 32-bit // integers before the tile position offset. // We have confirmed with Zeiss that this is correct, and the 6.0 // specification was updated to contain the correct information. ras.skipBytes(64); int tilePositionOffset = ras.readInt(); ras.skipBytes(36); int positionOffset = ras.readInt(); // read referenced structures addSeriesMeta("DimensionZ", getSizeZ()); addSeriesMeta("DimensionChannels", getSizeC()); addSeriesMeta("DimensionM", dimensionM); addSeriesMeta("DimensionP", dimensionP); if (positionOffset != 0) { in.seek(positionOffset); int nPositions = in.readInt(); for (int i=0; i<nPositions; i++) { double xPos = originX + in.readDouble() * 1000000; double yPos = originY + in.readDouble() * 1000000; double zPos = originZ + in.readDouble() * 1000000; xCoordinates.add(xPos); yCoordinates.add(yPos); zCoordinates.add(zPos); addGlobalMeta("X position for position #" + (i + 1), xPos); addGlobalMeta("Y position for position #" + (i + 1), yPos); addGlobalMeta("Z position for position #" + (i + 1), zPos); } } if (tilePositionOffset != 0) { in.seek(tilePositionOffset); int nTiles = in.readInt(); for (int i=0; i<nTiles; i++) { double xPos = originX + in.readDouble() * 1000000; double yPos = originY + in.readDouble() * 1000000; double zPos = originZ + in.readDouble() * 1000000; if (xCoordinates.size() > i) { xPos += xCoordinates.get(i); xCoordinates.setElementAt(xPos, i); } if (yCoordinates.size() > i) { yPos += yCoordinates.get(i); yCoordinates.setElementAt(yPos, i); } if (zCoordinates.size() > i) { zPos += zCoordinates.get(i); zCoordinates.setElementAt(zPos, i); } addGlobalMeta("X position for position #" + (i + 1), xPos); addGlobalMeta("Y position for position #" + (i + 1), yPos); addGlobalMeta("Z position for position #" + (i + 1), zPos); } } if (channelColorsOffset != 0) { in.seek(channelColorsOffset + 12); int colorsOffset = in.readInt(); int namesOffset = in.readInt(); // read the color of each channel if (colorsOffset > 0) { in.seek(channelColorsOffset + colorsOffset); lut[getSeries()] = new byte[getSizeC() * 3][256]; core[getSeries()].indexed = true; for (int i=0; i<getSizeC(); i++) { int color = in.readInt(); int red = color & 0xff; int green = (color & 0xff00) >> 8; int blue = (color & 0xff0000) >> 16; for (int j=0; j<256; j++) { lut[getSeries()][i * 3][j] = (byte) ((red / 255.0) * j); lut[getSeries()][i * 3 + 1][j] = (byte) ((green / 255.0) * j); lut[getSeries()][i * 3 + 2][j] = (byte) ((blue / 255.0) * j); } } } // read the name of each channel if (namesOffset > 0) { in.seek(channelColorsOffset + namesOffset + 4); for (int i=0; i<getSizeC(); i++) { if (in.getFilePointer() >= in.length() - 1) break; // we want to read until we find a null char String name = in.readCString(); if (name.length() <= 128) { addSeriesMeta("ChannelName" + i, name); } } } } if (timeStampOffset != 0) { in.seek(timeStampOffset + 8); for (int i=0; i<getSizeT(); i++) { double stamp = in.readDouble(); addSeriesMeta("TimeStamp" + i, stamp); timestamps.add(new Double(stamp)); } } if (eventListOffset != 0) { in.seek(eventListOffset + 4); int numEvents = in.readInt(); in.seek(in.getFilePointer() - 4); in.order(!in.isLittleEndian()); int tmpEvents = in.readInt(); if (numEvents < 0) numEvents = tmpEvents; else numEvents = (int) Math.min(numEvents, tmpEvents); in.order(!in.isLittleEndian()); if (numEvents > 65535) numEvents = 0; for (int i=0; i<numEvents; i++) { if (in.getFilePointer() + 16 <= in.length()) { int size = in.readInt(); double eventTime = in.readDouble(); int eventType = in.readInt(); addSeriesMeta("Event" + i + " Time", eventTime); addSeriesMeta("Event" + i + " Type", eventType); long fp = in.getFilePointer(); int len = size - 16; if (len > 65536) len = 65536; if (len < 0) len = 0; addSeriesMeta("Event" + i + " Description", in.readString(len)); in.seek(fp + size - 16); if (in.getFilePointer() < 0) break; } } } if (scanInformationOffset != 0) { in.seek(scanInformationOffset); nextLaser = nextDetector = 0; nextFilter = nextDichroicChannel = nextDichroic = 0; nextDataChannel = nextDetectChannel = nextIllumChannel = 0; Vector<SubBlock> blocks = new Vector<SubBlock>(); while (in.getFilePointer() < in.length() - 12) { if (in.getFilePointer() < 0) break; int entry = in.readInt(); int blockType = in.readInt(); int dataSize = in.readInt(); if (blockType == TYPE_SUBBLOCK) { SubBlock block = null; switch (entry) { case SUBBLOCK_RECORDING: block = new Recording(); break; case SUBBLOCK_LASER: block = new Laser(); break; case SUBBLOCK_TRACK: block = new Track(); break; case SUBBLOCK_DETECTION_CHANNEL: block = new DetectionChannel(); break; case SUBBLOCK_ILLUMINATION_CHANNEL: block = new IlluminationChannel(); break; case SUBBLOCK_BEAM_SPLITTER: block = new BeamSplitter(); break; case SUBBLOCK_DATA_CHANNEL: block = new DataChannel(); break; case SUBBLOCK_TIMER: block = new Timer(); break; case SUBBLOCK_MARKER: block = new Marker(); break; } if (block != null) { blocks.add(block); } } else if (dataSize + in.getFilePointer() <= in.length() && dataSize > 0) { in.skipBytes(dataSize); } else break; } Vector<SubBlock> nonAcquiredBlocks = new Vector<SubBlock>(); SubBlock[] metadataBlocks = blocks.toArray(new SubBlock[0]); for (SubBlock block : metadataBlocks) { block.addToHashtable(); if (!block.acquire) { nonAcquiredBlocks.add(block); blocks.remove(block); } } for (int i=0; i<blocks.size(); i++) { SubBlock block = blocks.get(i); // every valid IlluminationChannel must be immediately followed by // a valid DataChannel or IlluminationChannel if ((block instanceof IlluminationChannel) && i < blocks.size() - 1) { SubBlock nextBlock = blocks.get(i + 1); if (!(nextBlock instanceof DataChannel) && !(nextBlock instanceof IlluminationChannel)) { ((IlluminationChannel) block).wavelength = null; } } // every valid DetectionChannel must be immediately preceded by // a valid Track or DetectionChannel else if ((block instanceof DetectionChannel) && i > 0) { SubBlock prevBlock = blocks.get(i - 1); if (!(prevBlock instanceof Track) && !(prevBlock instanceof DetectionChannel)) { block.acquire = false; nonAcquiredBlocks.add(block); } } if (block.acquire) populateMetadataStore(block, store, series); } for (SubBlock block : nonAcquiredBlocks) { populateMetadataStore(block, store, series); } } } imageNames.add(imageName); if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { if (userName != null) { String experimenterID = MetadataTools.createLSID("Experimenter", 0); store.setExperimenterID(experimenterID, 0); store.setExperimenterUserName(userName, 0); store.setExperimenterDisplayName(userName, 0); } Double pixX = new Double(pixelSizeX); Double pixY = new Double(pixelSizeY); Double pixZ = new Double(pixelSizeZ); store.setPixelsPhysicalSizeX(pixX, series); store.setPixelsPhysicalSizeY(pixY, series); store.setPixelsPhysicalSizeZ(pixZ, series); double firstStamp = 0; if (timestamps.size() > 0) { firstStamp = timestamps.get(0).doubleValue(); } for (int i=0; i<getImageCount(); i++) { int[] zct = FormatTools.getZCTCoords(this, i); if (zct[2] < timestamps.size()) { double thisStamp = timestamps.get(zct[2]).doubleValue(); store.setPlaneDeltaT(thisStamp - firstStamp, series, i); int index = zct[2] + 1; double nextStamp = index < timestamps.size() ? timestamps.get(index).doubleValue() : thisStamp; if (i == getSizeT() - 1 && zct[2] > 0) { thisStamp = timestamps.get(zct[2] - 1).doubleValue(); } store.setPlaneExposureTime(nextStamp - thisStamp, series, i); } if (xCoordinates.size() > series) { store.setPlanePositionX(xCoordinates.get(series), series, i); store.setPlanePositionY(yCoordinates.get(series), series, i); store.setPlanePositionZ(zCoordinates.get(series), series, i); } } } ras.close(); in.close(); }
protected void initMetadata(int series) throws FormatException, IOException { setSeries(series); IFDList ifds = ifdsList.get(series); IFD ifd = ifds.get(0); in.close(); in = new RandomAccessInputStream(getLSMFileFromSeries(series)); in.order(isLittleEndian()); tiffParser = new TiffParser(in); PhotoInterp photo = ifd.getPhotometricInterpretation(); int samples = ifd.getSamplesPerPixel(); core[series].sizeX = (int) ifd.getImageWidth(); core[series].sizeY = (int) ifd.getImageLength(); core[series].rgb = samples > 1 || photo == PhotoInterp.RGB; core[series].interleaved = false; core[series].sizeC = isRGB() ? samples : 1; core[series].pixelType = ifd.getPixelType(); core[series].imageCount = ifds.size(); core[series].sizeZ = getImageCount(); core[series].sizeT = 1; LOGGER.info("Reading LSM metadata for series #{}", series); MetadataStore store = makeFilterMetadata(); int instrument = getEffectiveSeries(series); String imageName = getLSMFileFromSeries(series); if (imageName.indexOf(".") != -1) { imageName = imageName.substring(0, imageName.lastIndexOf(".")); } if (imageName.indexOf(File.separator) != -1) { imageName = imageName.substring(imageName.lastIndexOf(File.separator) + 1); } if (lsmFilenames.length != getSeriesCount()) { imageName += " #" + (getPosition(series) + 1); } // link Instrument and Image store.setImageID(MetadataTools.createLSID("Image", series), series); String instrumentID = MetadataTools.createLSID("Instrument", instrument); store.setInstrumentID(instrumentID, instrument); store.setImageInstrumentRef(instrumentID, series); RandomAccessInputStream ras = getCZTag(ifd); if (ras == null) { imageNames.add(imageName); return; } ras.seek(16); core[series].sizeZ = ras.readInt(); ras.skipBytes(4); core[series].sizeT = ras.readInt(); int dataType = ras.readInt(); switch (dataType) { case 2: addSeriesMeta("DataType", "12 bit unsigned integer"); break; case 5: addSeriesMeta("DataType", "32 bit float"); break; case 0: addSeriesMeta("DataType", "varying data types"); break; default: addSeriesMeta("DataType", "8 bit unsigned integer"); } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { ras.seek(0); addSeriesMeta("MagicNumber ", ras.readInt()); addSeriesMeta("StructureSize", ras.readInt()); addSeriesMeta("DimensionX", ras.readInt()); addSeriesMeta("DimensionY", ras.readInt()); ras.seek(32); addSeriesMeta("ThumbnailX", ras.readInt()); addSeriesMeta("ThumbnailY", ras.readInt()); // pixel sizes are stored in meters, we need them in microns pixelSizeX = ras.readDouble() * 1000000; pixelSizeY = ras.readDouble() * 1000000; pixelSizeZ = ras.readDouble() * 1000000; addSeriesMeta("VoxelSizeX", new Double(pixelSizeX)); addSeriesMeta("VoxelSizeY", new Double(pixelSizeY)); addSeriesMeta("VoxelSizeZ", new Double(pixelSizeZ)); originX = ras.readDouble() * 1000000; originY = ras.readDouble() * 1000000; originZ = ras.readDouble() * 1000000; addSeriesMeta("OriginX", originX); addSeriesMeta("OriginY", originY); addSeriesMeta("OriginZ", originZ); } else ras.seek(88); int scanType = ras.readShort(); switch (scanType) { case 0: addSeriesMeta("ScanType", "x-y-z scan"); core[series].dimensionOrder = "XYZCT"; break; case 1: addSeriesMeta("ScanType", "z scan (x-z plane)"); core[series].dimensionOrder = "XYZCT"; break; case 2: addSeriesMeta("ScanType", "line scan"); core[series].dimensionOrder = "XYZCT"; break; case 3: addSeriesMeta("ScanType", "time series x-y"); core[series].dimensionOrder = "XYTCZ"; break; case 4: addSeriesMeta("ScanType", "time series x-z"); core[series].dimensionOrder = "XYZTC"; break; case 5: addSeriesMeta("ScanType", "time series 'Mean of ROIs'"); core[series].dimensionOrder = "XYTCZ"; break; case 6: addSeriesMeta("ScanType", "time series x-y-z"); core[series].dimensionOrder = "XYZTC"; break; case 7: addSeriesMeta("ScanType", "spline scan"); core[series].dimensionOrder = "XYCTZ"; break; case 8: addSeriesMeta("ScanType", "spline scan x-z"); core[series].dimensionOrder = "XYCZT"; break; case 9: addSeriesMeta("ScanType", "time series spline plane x-z"); core[series].dimensionOrder = "XYTCZ"; break; case 10: addSeriesMeta("ScanType", "point mode"); core[series].dimensionOrder = "XYZCT"; break; default: addSeriesMeta("ScanType", "x-y-z scan"); core[series].dimensionOrder = "XYZCT"; } core[series].indexed = lut != null && lut[series] != null; if (isIndexed()) { core[series].rgb = false; } if (getSizeC() == 0) core[series].sizeC = 1; if (isRGB()) { // shuffle C to front of order string core[series].dimensionOrder = getDimensionOrder().replaceAll("C", ""); core[series].dimensionOrder = getDimensionOrder().replaceAll("XY", "XYC"); } if (getEffectiveSizeC() == 0) { core[series].imageCount = getSizeZ() * getSizeT(); } else { core[series].imageCount = getSizeZ() * getSizeT() * getEffectiveSizeC(); } if (getImageCount() != ifds.size()) { int diff = getImageCount() - ifds.size(); core[series].imageCount = ifds.size(); if (diff % getSizeZ() == 0) { core[series].sizeT -= (diff / getSizeZ()); } else if (diff % getSizeT() == 0) { core[series].sizeZ -= (diff / getSizeT()); } else if (getSizeZ() > 1) { core[series].sizeZ = ifds.size(); core[series].sizeT = 1; } else if (getSizeT() > 1) { core[series].sizeT = ifds.size(); core[series].sizeZ = 1; } } if (getSizeZ() == 0) core[series].sizeZ = getImageCount(); if (getSizeT() == 0) core[series].sizeT = getImageCount() / getSizeZ(); long channelColorsOffset = 0; long timeStampOffset = 0; long eventListOffset = 0; long scanInformationOffset = 0; long channelWavelengthOffset = 0; if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { int spectralScan = ras.readShort(); if (spectralScan != 1) { addSeriesMeta("SpectralScan", "no spectral scan"); } else addSeriesMeta("SpectralScan", "acquired with spectral scan"); int type = ras.readInt(); switch (type) { case 1: addSeriesMeta("DataType2", "calculated data"); break; case 2: addSeriesMeta("DataType2", "animation"); break; default: addSeriesMeta("DataType2", "original scan data"); } long[] overlayOffsets = new long[9]; String[] overlayKeys = new String[] {"VectorOverlay", "InputLut", "OutputLut", "ROI", "BleachROI", "MeanOfRoisOverlay", "TopoIsolineOverlay", "TopoProfileOverlay", "LinescanOverlay"}; overlayOffsets[0] = ras.readInt(); overlayOffsets[1] = ras.readInt(); overlayOffsets[2] = ras.readInt(); channelColorsOffset = ras.readInt(); addSeriesMeta("TimeInterval", ras.readDouble()); ras.skipBytes(4); scanInformationOffset = ras.readInt(); ras.skipBytes(4); timeStampOffset = ras.readInt(); eventListOffset = ras.readInt(); overlayOffsets[3] = ras.readInt(); overlayOffsets[4] = ras.readInt(); ras.skipBytes(4); addSeriesMeta("DisplayAspectX", ras.readDouble()); addSeriesMeta("DisplayAspectY", ras.readDouble()); addSeriesMeta("DisplayAspectZ", ras.readDouble()); addSeriesMeta("DisplayAspectTime", ras.readDouble()); overlayOffsets[5] = ras.readInt(); overlayOffsets[6] = ras.readInt(); overlayOffsets[7] = ras.readInt(); overlayOffsets[8] = ras.readInt(); if (getMetadataOptions().getMetadataLevel() != MetadataLevel.NO_OVERLAYS) { for (int i=0; i<overlayOffsets.length; i++) { parseOverlays(series, overlayOffsets[i], overlayKeys[i], store); } } totalROIs = 0; addSeriesMeta("ToolbarFlags", ras.readInt()); channelWavelengthOffset = ras.readInt(); ras.skipBytes(64); } else ras.skipBytes(182); MetadataTools.setDefaultCreationDate(store, getCurrentFile(), series); if (getSizeC() > 1) { if (!splitPlanes) splitPlanes = isRGB(); core[series].rgb = false; if (splitPlanes) core[series].imageCount *= getSizeC(); } for (int c=0; c<getEffectiveSizeC(); c++) { String lsid = MetadataTools.createLSID("Channel", series, c); store.setChannelID(lsid, series, c); } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { // NB: the Zeiss LSM 5.5 specification indicates that there should be // 15 32-bit integers here; however, there are actually 16 32-bit // integers before the tile position offset. // We have confirmed with Zeiss that this is correct, and the 6.0 // specification was updated to contain the correct information. ras.skipBytes(64); int tilePositionOffset = ras.readInt(); ras.skipBytes(36); int positionOffset = ras.readInt(); // read referenced structures addSeriesMeta("DimensionZ", getSizeZ()); addSeriesMeta("DimensionChannels", getSizeC()); addSeriesMeta("DimensionM", dimensionM); addSeriesMeta("DimensionP", dimensionP); if (positionOffset != 0) { in.seek(positionOffset); int nPositions = in.readInt(); for (int i=0; i<nPositions; i++) { double xPos = originX + in.readDouble() * 1000000; double yPos = originY + in.readDouble() * 1000000; double zPos = originZ + in.readDouble() * 1000000; xCoordinates.add(xPos); yCoordinates.add(yPos); zCoordinates.add(zPos); addGlobalMeta("X position for position #" + (i + 1), xPos); addGlobalMeta("Y position for position #" + (i + 1), yPos); addGlobalMeta("Z position for position #" + (i + 1), zPos); } } if (tilePositionOffset != 0) { in.seek(tilePositionOffset); int nTiles = in.readInt(); for (int i=0; i<nTiles; i++) { double xPos = originX + in.readDouble() * 1000000; double yPos = originY + in.readDouble() * 1000000; double zPos = originZ + in.readDouble() * 1000000; if (xCoordinates.size() > i) { xPos += xCoordinates.get(i); xCoordinates.setElementAt(xPos, i); } if (yCoordinates.size() > i) { yPos += yCoordinates.get(i); yCoordinates.setElementAt(yPos, i); } if (zCoordinates.size() > i) { zPos += zCoordinates.get(i); zCoordinates.setElementAt(zPos, i); } addGlobalMeta("X position for position #" + (i + 1), xPos); addGlobalMeta("Y position for position #" + (i + 1), yPos); addGlobalMeta("Z position for position #" + (i + 1), zPos); } } if (channelColorsOffset != 0) { in.seek(channelColorsOffset + 12); int colorsOffset = in.readInt(); int namesOffset = in.readInt(); // read the color of each channel if (colorsOffset > 0) { in.seek(channelColorsOffset + colorsOffset); lut[getSeries()] = new byte[getSizeC() * 3][256]; core[getSeries()].indexed = true; for (int i=0; i<getSizeC(); i++) { int color = in.readInt(); int red = color & 0xff; int green = (color & 0xff00) >> 8; int blue = (color & 0xff0000) >> 16; for (int j=0; j<256; j++) { lut[getSeries()][i * 3][j] = (byte) ((red / 255.0) * j); lut[getSeries()][i * 3 + 1][j] = (byte) ((green / 255.0) * j); lut[getSeries()][i * 3 + 2][j] = (byte) ((blue / 255.0) * j); } } } // read the name of each channel if (namesOffset > 0) { in.seek(channelColorsOffset + namesOffset + 4); for (int i=0; i<getSizeC(); i++) { if (in.getFilePointer() >= in.length() - 1) break; // we want to read until we find a null char String name = in.readCString(); if (name.length() <= 128) { addSeriesMeta("ChannelName" + i, name); } } } } if (timeStampOffset != 0) { in.seek(timeStampOffset + 8); for (int i=0; i<getSizeT(); i++) { double stamp = in.readDouble(); addSeriesMeta("TimeStamp" + i, stamp); timestamps.add(new Double(stamp)); } } if (eventListOffset != 0) { in.seek(eventListOffset + 4); int numEvents = in.readInt(); in.seek(in.getFilePointer() - 4); in.order(!in.isLittleEndian()); int tmpEvents = in.readInt(); if (numEvents < 0) numEvents = tmpEvents; else numEvents = (int) Math.min(numEvents, tmpEvents); in.order(!in.isLittleEndian()); if (numEvents > 65535) numEvents = 0; for (int i=0; i<numEvents; i++) { if (in.getFilePointer() + 16 <= in.length()) { int size = in.readInt(); double eventTime = in.readDouble(); int eventType = in.readInt(); addSeriesMeta("Event" + i + " Time", eventTime); addSeriesMeta("Event" + i + " Type", eventType); long fp = in.getFilePointer(); int len = size - 16; if (len > 65536) len = 65536; if (len < 0) len = 0; addSeriesMeta("Event" + i + " Description", in.readString(len)); in.seek(fp + size - 16); if (in.getFilePointer() < 0) break; } } } if (scanInformationOffset != 0) { in.seek(scanInformationOffset); nextLaser = nextDetector = 0; nextFilter = nextDichroicChannel = nextDichroic = 0; nextDataChannel = nextDetectChannel = nextIllumChannel = 0; Vector<SubBlock> blocks = new Vector<SubBlock>(); while (in.getFilePointer() < in.length() - 12) { if (in.getFilePointer() < 0) break; int entry = in.readInt(); int blockType = in.readInt(); int dataSize = in.readInt(); if (blockType == TYPE_SUBBLOCK) { SubBlock block = null; switch (entry) { case SUBBLOCK_RECORDING: block = new Recording(); break; case SUBBLOCK_LASER: block = new Laser(); break; case SUBBLOCK_TRACK: block = new Track(); break; case SUBBLOCK_DETECTION_CHANNEL: block = new DetectionChannel(); break; case SUBBLOCK_ILLUMINATION_CHANNEL: block = new IlluminationChannel(); break; case SUBBLOCK_BEAM_SPLITTER: block = new BeamSplitter(); break; case SUBBLOCK_DATA_CHANNEL: block = new DataChannel(); break; case SUBBLOCK_TIMER: block = new Timer(); break; case SUBBLOCK_MARKER: block = new Marker(); break; } if (block != null) { blocks.add(block); } } else if (dataSize + in.getFilePointer() <= in.length() && dataSize > 0) { in.skipBytes(dataSize); } else break; } Vector<SubBlock> nonAcquiredBlocks = new Vector<SubBlock>(); SubBlock[] metadataBlocks = blocks.toArray(new SubBlock[0]); for (SubBlock block : metadataBlocks) { block.addToHashtable(); if (!block.acquire) { nonAcquiredBlocks.add(block); blocks.remove(block); } } for (int i=0; i<blocks.size(); i++) { SubBlock block = blocks.get(i); // every valid IlluminationChannel must be immediately followed by // a valid DataChannel or IlluminationChannel if ((block instanceof IlluminationChannel) && i < blocks.size() - 1) { SubBlock nextBlock = blocks.get(i + 1); if (!(nextBlock instanceof DataChannel) && !(nextBlock instanceof IlluminationChannel)) { ((IlluminationChannel) block).wavelength = null; } } // every valid DetectionChannel must be immediately preceded by // a valid Track or DetectionChannel else if ((block instanceof DetectionChannel) && i > 0) { SubBlock prevBlock = blocks.get(i - 1); if (!(prevBlock instanceof Track) && !(prevBlock instanceof DetectionChannel)) { block.acquire = false; nonAcquiredBlocks.add(block); } } if (block.acquire) populateMetadataStore(block, store, series); } for (SubBlock block : nonAcquiredBlocks) { populateMetadataStore(block, store, series); } } } imageNames.add(imageName); if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { if (userName != null) { String experimenterID = MetadataTools.createLSID("Experimenter", 0); store.setExperimenterID(experimenterID, 0); store.setExperimenterUserName(userName, 0); store.setExperimenterDisplayName(userName, 0); } Double pixX = new Double(pixelSizeX); Double pixY = new Double(pixelSizeY); Double pixZ = new Double(pixelSizeZ); store.setPixelsPhysicalSizeX(pixX, series); store.setPixelsPhysicalSizeY(pixY, series); store.setPixelsPhysicalSizeZ(pixZ, series); double firstStamp = 0; if (timestamps.size() > 0) { firstStamp = timestamps.get(0).doubleValue(); } for (int i=0; i<getImageCount(); i++) { int[] zct = FormatTools.getZCTCoords(this, i); if (zct[2] < timestamps.size()) { double thisStamp = timestamps.get(zct[2]).doubleValue(); store.setPlaneDeltaT(thisStamp - firstStamp, series, i); int index = zct[2] + 1; double nextStamp = index < timestamps.size() ? timestamps.get(index).doubleValue() : thisStamp; if (i == getSizeT() - 1 && zct[2] > 0) { thisStamp = timestamps.get(zct[2] - 1).doubleValue(); } store.setPlaneExposureTime(nextStamp - thisStamp, series, i); } if (xCoordinates.size() > series) { store.setPlanePositionX(xCoordinates.get(series), series, i); store.setPlanePositionY(yCoordinates.get(series), series, i); store.setPlanePositionZ(zCoordinates.get(series), series, i); } } } ras.close(); }
diff --git a/ctomlabviewer/src/java/gov/nih/nci/caxchange/ctom/viewer/actions/StudySearchAction.java b/ctomlabviewer/src/java/gov/nih/nci/caxchange/ctom/viewer/actions/StudySearchAction.java index 3450495c..f4d62724 100644 --- a/ctomlabviewer/src/java/gov/nih/nci/caxchange/ctom/viewer/actions/StudySearchAction.java +++ b/ctomlabviewer/src/java/gov/nih/nci/caxchange/ctom/viewer/actions/StudySearchAction.java @@ -1,354 +1,354 @@ /** * Copyright Notice. Copyright 2008 ScenPro, Inc ("caBIG(TM) * Participant").caXchange was created with NCI funding and is part of the * caBIG(TM) initiative. The software subject to this notice and license includes * both human readable source code form and machine readable, binary, object * code form (the "caBIG(TM) Software"). This caBIG(TM) Software License (the * "License") is between caBIG(TM) Participant and You. "You (or "Your") shall mean * a person or an entity, and all other entities that control, are controlled * by, or are under common control with the entity. "Control" for purposes of * this definition means (i) the direct or indirect power to cause the direction * or management of such entity, whether by contract or otherwise, or (ii) * ownership of fifty percent (50%) or more of the outstanding shares, or (iii) * beneficial ownership of such entity. License. Provided that You agree to the * conditions described below, caBIG(TM) Participant grants You a non-exclusive, * worldwide, perpetual, fully-paid-up, no-charge, irrevocable, transferable and * royalty-free right and license in its rights in the caBIG(TM) Software, * including any copyright or patent rights therein, to (i) use, install, * disclose, access, operate, execute, reproduce, copy, modify, translate, * market, publicly display, publicly perform, and prepare derivative works of * the caBIG(TM) Software in any manner and for any purpose, and to have or permit * others to do so; (ii) make, have made, use, practice, sell, and offer for * sale, import, and/or otherwise dispose of caBIG(TM) Software (or portions * thereof); (iii) distribute and have distributed to and by third parties the * caBIG(TM) Software and any modifications and derivative works thereof; and (iv) * sublicense the foregoing rights set out in (i), (ii) and (iii) to third * parties, including the right to license such rights to further third parties. * For sake of clarity, and not by way of limitation, caBIG(TM) Participant shall * have no right of accounting or right of payment from You or Your sublicensees * for the rights granted under this License. This License is granted at no * charge to You. Your downloading, copying, modifying, displaying, distributing * or use of caBIG(TM) Software constitutes acceptance of all of the terms and * conditions of this Agreement. If you do not agree to such terms and * conditions, you have no right to download, copy, modify, display, distribute * or use the caBIG(TM) Software. 1. Your redistributions of the source code for * the caBIG(TM) Software must retain the above copyright notice, this list of * conditions and the disclaimer and limitation of liability of Article 6 below. * Your redistributions in object code form must reproduce the above copyright * notice, this list of conditions and the disclaimer of Article 6 in the * documentation and/or other materials provided with the distribution, if any. * 2. Your end-user documentation included with the redistribution, if any, must * include the following acknowledgment: "This product includes software * developed by ScenPro, Inc." If You do not include such end-user * documentation, You shall include this acknowledgment in the caBIG(TM) Software * itself, wherever such third-party acknowledgments normally appear. 3. You may * not use the names "ScenPro, Inc", "The National Cancer Institute", "NCI", * "Cancer Bioinformatics Grid" or "caBIG(TM)" to endorse or promote products * derived from this caBIG(TM) Software. This License does not authorize You to use * any trademarks, service marks, trade names, logos or product names of either * caBIG(TM) Participant, NCI or caBIG(TM), except as required to comply with the * terms of this License. 4. For sake of clarity, and not by way of limitation, * You may incorporate this caBIG(TM) Software into Your proprietary programs and * into any third party proprietary programs. However, if You incorporate the * caBIG(TM) Software into third party proprietary programs, You agree that You are * solely responsible for obtaining any permission from such third parties * required to incorporate the caBIG(TM) Software into such third party proprietary * programs and for informing Your sublicensees, including without limitation * Your end-users, of their obligation to secure any required permissions from * such third parties before incorporating the caBIG(TM) Software into such third * party proprietary software programs. In the event that You fail to obtain * such permissions, You agree to indemnify caBIG(TM) Participant for any claims * against caBIG(TM) Participant by such third parties, except to the extent * prohibited by law, resulting from Your failure to obtain such permissions. 5. * For sake of clarity, and not by way of limitation, You may add Your own * copyright statement to Your modifications and to the derivative works, and * You may provide additional or different license terms and conditions in Your * sublicenses of modifications of the caBIG(TM) Software, or any derivative works * of the caBIG(TM) Software as a whole, provided Your use, reproduction, and * distribution of the Work otherwise complies with the conditions stated in * this License. 6. THIS caBIG(TM) SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED * OR IMPLIED WARRANTIES (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE) * ARE DISCLAIMED. IN NO EVENT SHALL THE ScenPro, Inc OR ITS AFFILIATES 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 caBIG(TM) SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package gov.nih.nci.caxchange.ctom.viewer.actions; import gov.nih.nci.caxchange.ctom.viewer.DAO.StudySearchDAO; import gov.nih.nci.caxchange.ctom.viewer.constants.DisplayConstants; import gov.nih.nci.caxchange.ctom.viewer.constants.ForwardConstants; import gov.nih.nci.caxchange.ctom.viewer.forms.LoginForm; import gov.nih.nci.caxchange.ctom.viewer.forms.StudySearchForm; import gov.nih.nci.caxchange.ctom.viewer.util.CommonUtil; import gov.nih.nci.caxchange.ctom.viewer.viewobjects.SearchResult; import gov.nih.nci.caxchange.ctom.viewer.viewobjects.StudySearchResult; import gov.nih.nci.logging.api.user.UserInfoHelper; import gov.nih.nci.security.exceptions.CSException; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.actions.DispatchAction; /** * This class performs the study search action. The search action calls the * searchObjects method with the user entered search criteria and queries the * database. If the search returns a non null result set; it forwards the user * to study search page and displays the results. * * @author asharma */ public class StudySearchAction extends DispatchAction { private static final Logger logDB = Logger.getLogger(StudySearchAction.class); private static final String CONFIG_FILE = "/baseURL.properties"; /* * (non-Javadoc) * * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, * org.apache.struts.action.ActionForm, * javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ public ActionForward doStudySearch(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { ActionErrors errors = new ActionErrors(); ActionMessages messages = new ActionMessages(); // gets the session object from HttpRequest HttpSession session = request.getSession(); // search form StudySearchForm sForm = (StudySearchForm) form; UserInfoHelper.setUserInfo(((LoginForm) session .getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId(), session.getId()); try { StudySearchDAO studySearchDAO = new StudySearchDAO(); // search based on the given search criteria SearchResult searchResult = studySearchDAO.getStudySearchResults(sForm.getStudyID(), sForm.getStudyTitle(), session); sForm.setStudiesList(searchResult.getSearchResultObjects()); // if the search returned nothing/null; display message if (searchResult.getSearchResultObjects() == null || searchResult.getSearchResultObjects().isEmpty()) { - errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( - DisplayConstants.ERROR_ID, - "The search criteria returned zero results")); - saveErrors(request, errors); +// errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( +// DisplayConstants.ERROR_ID, +// "The search criteria returned zero results")); +// saveErrors(request, errors); if (logDB.isDebugEnabled()) logDB .debug(session.getId() + "|" + ((LoginForm) session .getAttribute(DisplayConstants.LOGIN_OBJECT)) .getLoginId() + "|" + sForm.getFormName() + "|search|Failure|No Records found for " + sForm.getFormName() + " object|" + form.toString() + "|"); return (mapping .findForward(ForwardConstants.LOAD_STUDY_SEARCH_SUCCESS)); } // if search result is not null; forward to searchresults page if (searchResult.getSearchResultMessage() != null && !(searchResult.getSearchResultMessage().trim() .equalsIgnoreCase(""))) { messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage( DisplayConstants.MESSAGE_ID, searchResult .getSearchResultMessage())); saveMessages(request, messages); } //session.setAttribute(DisplayConstants.SEARCH_RESULT_STUDY, // searchResult); //session.setAttribute("studiesList", sForm.getStudiesList()); } catch (CSException cse) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( DisplayConstants.ERROR_ID, cse.getMessage())); saveErrors(request, errors); if (logDB.isDebugEnabled()) logDB.debug(session.getId() + "|" + ((LoginForm) session .getAttribute(DisplayConstants.LOGIN_OBJECT)) .getLoginId() + "|" + sForm.getFormName() + "|search|Failure|Error Searching the " + sForm.getFormName() + " object|" + form.toString() + "|" + cse.getMessage()); } catch (Exception e) { logDB.error(e.getMessage()); } // if search result is not null; forward to searchresults page session.setAttribute(DisplayConstants.CURRENT_FORM, sForm); if (logDB.isDebugEnabled()) logDB.debug(session.getId() + "|" + ((LoginForm) session .getAttribute(DisplayConstants.LOGIN_OBJECT)) .getLoginId() + "|" + sForm.getFormName() + "|search|Success|Success in searching " + sForm.getFormName() + " object|" + form.toString() + "|"); return (mapping.findForward(ForwardConstants.LOAD_STUDY_SEARCH_SUCCESS)); } /** * Forwards the control to the Participant Search page * * @param mapping * @param form * @param request * @param response * @return */ public ActionForward loadParticipant(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { // gets the session object from HttpRequest HttpSession session = request.getSession(); //clear the session attributes with previous participant data CommonUtil util = new CommonUtil(); util.clearParticipantSessionData(session); // search form StudySearchForm sForm = (StudySearchForm) form; List<StudySearchResult> studiesList = sForm.getStudiesList(); int index = Integer.parseInt(sForm.getIndex()) - 1; if (studiesList != null && !studiesList.isEmpty()) { StudySearchResult ssr = studiesList.get(index); // change the title to include patient information String titleString = "Study: " + ssr.getStudyId() + " [" + ssr.getStudyId() + "]"; session.setAttribute("studyId", ssr.getStudyId()); session.setAttribute("studyTitle", titleString); session.setAttribute("pageTitle", titleString); sForm.setIndex(""); session.setAttribute(DisplayConstants.CURRENT_TABLE_ID, DisplayConstants.PARTICIPANTSEARCH_ID); return (mapping .findForward(ForwardConstants.LOAD_PART_SEARCH_SUCCESS)); } return (mapping.findForward(ForwardConstants.LOAD_STUDY_SEARCH_SUCCESS)); } /** * Forwards the control to the Healthcare site details page * * @param mapping * @param form * @param request * @param response * @return */ public ActionForward showHealthCareSite(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { // gets the session object from HttpRequest HttpSession session = request.getSession(); // search form StudySearchForm sForm = (StudySearchForm) form; List<StudySearchResult> studiesList = sForm.getStudiesList(); int index = Integer.parseInt(sForm.getIndex()) - 1; if (studiesList != null && !studiesList.isEmpty()) { StudySearchResult ssr = studiesList.get(index); // change the title to include study information String titleString = "Study: " + ssr.getStudyId() + " [" + ssr.getStudyId() + "]"; session.setAttribute("studyId", ssr.getStudyId()); session.setAttribute("ID", ssr.getId()); session.setAttribute("pageTitle", titleString); sForm.setIndex(""); session.setAttribute(DisplayConstants.CURRENT_TABLE_ID, DisplayConstants.STUDYSEARCH_ID); return (mapping .findForward(ForwardConstants.LOAD_HEALTHCARESITE_SUCCESS)); } return (mapping.findForward(ForwardConstants.LOAD_STUDY_SEARCH_SUCCESS)); } /** * Forwards the control to the PI details page * * @param mapping * @param form * @param request * @param response * @return */ public ActionForward showPI(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { ActionErrors errors = new ActionErrors(); ActionMessages messages = new ActionMessages(); // gets the session object from HttpRequest HttpSession session = request.getSession(); // search form StudySearchForm sForm = (StudySearchForm) form; List<StudySearchResult> studiesList = sForm.getStudiesList(); int index = Integer.parseInt(sForm.getIndex())- 1; if (studiesList != null && !studiesList.isEmpty()) { StudySearchResult ssr = studiesList.get(index); // change the title to include study information String titleString = "Study: " + ssr.getStudyId() + " [" + ssr.getStudyId() + "]"; session.setAttribute("studyId", ssr.getStudyId()); session.setAttribute("ID", ssr.getId()); session.setAttribute("pageTitle", titleString); sForm.setIndex(""); session.setAttribute(DisplayConstants.CURRENT_TABLE_ID, DisplayConstants.STUDYSEARCH_ID); return (mapping .findForward(ForwardConstants.LOAD_PI_SUCCESS)); } return (mapping.findForward(ForwardConstants.LOAD_STUDY_SEARCH_SUCCESS)); } }
true
true
public ActionForward doStudySearch(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { ActionErrors errors = new ActionErrors(); ActionMessages messages = new ActionMessages(); // gets the session object from HttpRequest HttpSession session = request.getSession(); // search form StudySearchForm sForm = (StudySearchForm) form; UserInfoHelper.setUserInfo(((LoginForm) session .getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId(), session.getId()); try { StudySearchDAO studySearchDAO = new StudySearchDAO(); // search based on the given search criteria SearchResult searchResult = studySearchDAO.getStudySearchResults(sForm.getStudyID(), sForm.getStudyTitle(), session); sForm.setStudiesList(searchResult.getSearchResultObjects()); // if the search returned nothing/null; display message if (searchResult.getSearchResultObjects() == null || searchResult.getSearchResultObjects().isEmpty()) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( DisplayConstants.ERROR_ID, "The search criteria returned zero results")); saveErrors(request, errors); if (logDB.isDebugEnabled()) logDB .debug(session.getId() + "|" + ((LoginForm) session .getAttribute(DisplayConstants.LOGIN_OBJECT)) .getLoginId() + "|" + sForm.getFormName() + "|search|Failure|No Records found for " + sForm.getFormName() + " object|" + form.toString() + "|"); return (mapping .findForward(ForwardConstants.LOAD_STUDY_SEARCH_SUCCESS)); } // if search result is not null; forward to searchresults page if (searchResult.getSearchResultMessage() != null && !(searchResult.getSearchResultMessage().trim() .equalsIgnoreCase(""))) { messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage( DisplayConstants.MESSAGE_ID, searchResult .getSearchResultMessage())); saveMessages(request, messages); } //session.setAttribute(DisplayConstants.SEARCH_RESULT_STUDY, // searchResult); //session.setAttribute("studiesList", sForm.getStudiesList()); } catch (CSException cse) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( DisplayConstants.ERROR_ID, cse.getMessage())); saveErrors(request, errors); if (logDB.isDebugEnabled()) logDB.debug(session.getId() + "|" + ((LoginForm) session .getAttribute(DisplayConstants.LOGIN_OBJECT)) .getLoginId() + "|" + sForm.getFormName() + "|search|Failure|Error Searching the " + sForm.getFormName() + " object|" + form.toString() + "|" + cse.getMessage()); } catch (Exception e) { logDB.error(e.getMessage()); } // if search result is not null; forward to searchresults page session.setAttribute(DisplayConstants.CURRENT_FORM, sForm); if (logDB.isDebugEnabled()) logDB.debug(session.getId() + "|" + ((LoginForm) session .getAttribute(DisplayConstants.LOGIN_OBJECT)) .getLoginId() + "|" + sForm.getFormName() + "|search|Success|Success in searching " + sForm.getFormName() + " object|" + form.toString() + "|"); return (mapping.findForward(ForwardConstants.LOAD_STUDY_SEARCH_SUCCESS)); }
public ActionForward doStudySearch(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { ActionErrors errors = new ActionErrors(); ActionMessages messages = new ActionMessages(); // gets the session object from HttpRequest HttpSession session = request.getSession(); // search form StudySearchForm sForm = (StudySearchForm) form; UserInfoHelper.setUserInfo(((LoginForm) session .getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId(), session.getId()); try { StudySearchDAO studySearchDAO = new StudySearchDAO(); // search based on the given search criteria SearchResult searchResult = studySearchDAO.getStudySearchResults(sForm.getStudyID(), sForm.getStudyTitle(), session); sForm.setStudiesList(searchResult.getSearchResultObjects()); // if the search returned nothing/null; display message if (searchResult.getSearchResultObjects() == null || searchResult.getSearchResultObjects().isEmpty()) { // errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( // DisplayConstants.ERROR_ID, // "The search criteria returned zero results")); // saveErrors(request, errors); if (logDB.isDebugEnabled()) logDB .debug(session.getId() + "|" + ((LoginForm) session .getAttribute(DisplayConstants.LOGIN_OBJECT)) .getLoginId() + "|" + sForm.getFormName() + "|search|Failure|No Records found for " + sForm.getFormName() + " object|" + form.toString() + "|"); return (mapping .findForward(ForwardConstants.LOAD_STUDY_SEARCH_SUCCESS)); } // if search result is not null; forward to searchresults page if (searchResult.getSearchResultMessage() != null && !(searchResult.getSearchResultMessage().trim() .equalsIgnoreCase(""))) { messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage( DisplayConstants.MESSAGE_ID, searchResult .getSearchResultMessage())); saveMessages(request, messages); } //session.setAttribute(DisplayConstants.SEARCH_RESULT_STUDY, // searchResult); //session.setAttribute("studiesList", sForm.getStudiesList()); } catch (CSException cse) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( DisplayConstants.ERROR_ID, cse.getMessage())); saveErrors(request, errors); if (logDB.isDebugEnabled()) logDB.debug(session.getId() + "|" + ((LoginForm) session .getAttribute(DisplayConstants.LOGIN_OBJECT)) .getLoginId() + "|" + sForm.getFormName() + "|search|Failure|Error Searching the " + sForm.getFormName() + " object|" + form.toString() + "|" + cse.getMessage()); } catch (Exception e) { logDB.error(e.getMessage()); } // if search result is not null; forward to searchresults page session.setAttribute(DisplayConstants.CURRENT_FORM, sForm); if (logDB.isDebugEnabled()) logDB.debug(session.getId() + "|" + ((LoginForm) session .getAttribute(DisplayConstants.LOGIN_OBJECT)) .getLoginId() + "|" + sForm.getFormName() + "|search|Success|Success in searching " + sForm.getFormName() + " object|" + form.toString() + "|"); return (mapping.findForward(ForwardConstants.LOAD_STUDY_SEARCH_SUCCESS)); }
diff --git a/src/java/org/apache/nutch/fetcher/Fetcher.java b/src/java/org/apache/nutch/fetcher/Fetcher.java index 017d1971..32303149 100644 --- a/src/java/org/apache/nutch/fetcher/Fetcher.java +++ b/src/java/org/apache/nutch/fetcher/Fetcher.java @@ -1,428 +1,428 @@ /** * Copyright 2005 The Apache Software Foundation * * 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.apache.nutch.fetcher; import java.io.IOException; import java.io.File; import org.apache.hadoop.io.*; import org.apache.hadoop.fs.*; import org.apache.hadoop.conf.*; import org.apache.hadoop.util.LogFormatter; import org.apache.hadoop.mapred.*; import org.apache.nutch.crawl.CrawlDatum; import org.apache.nutch.crawl.SignatureFactory; import org.apache.nutch.metadata.Metadata; import org.apache.nutch.net.*; import org.apache.nutch.protocol.*; import org.apache.nutch.parse.*; import org.apache.nutch.util.*; import java.util.logging.*; /** The fetcher. Most of the work is done by plugins. */ public class Fetcher extends Configured implements MapRunnable { public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.fetcher.Fetcher"); public static final String SIGNATURE_KEY = "nutch.content.digest"; public static final String SEGMENT_NAME_KEY = "nutch.segment.name"; public static final String SCORE_KEY = "nutch.crawl.score"; public static class InputFormat extends SequenceFileInputFormat { /** Don't split inputs, to keep things polite. */ public FileSplit[] getSplits(FileSystem fs, JobConf job, int nSplits) throws IOException { File[] files = listFiles(fs, job); FileSplit[] splits = new FileSplit[files.length]; for (int i = 0; i < files.length; i++) { splits[i] = new FileSplit(files[i], 0, fs.getLength(files[i])); } return splits; } } private RecordReader input; private OutputCollector output; private Reporter reporter; private String segmentName; private int activeThreads; private int maxRedirect; private long start = System.currentTimeMillis(); // start time of fetcher run private long lastRequestStart = start; private long bytes; // total bytes fetched private int pages; // total pages fetched private int errors; // total pages errored private boolean storingContent; private boolean parsing; private class FetcherThread extends Thread { private Configuration conf; private URLFilters urlFilters; private ParseUtil parseUtil; private UrlNormalizer normalizer; private ProtocolFactory protocolFactory; public FetcherThread(Configuration conf) { this.setDaemon(true); // don't hang JVM on exit this.setName("FetcherThread"); // use an informative name this.conf = conf; this.urlFilters = new URLFilters(conf); this.parseUtil = new ParseUtil(conf); this.protocolFactory = new ProtocolFactory(conf); this.normalizer = new UrlNormalizerFactory(conf).getNormalizer(); } public void run() { synchronized (Fetcher.this) {activeThreads++;} // count threads try { UTF8 key = new UTF8(); CrawlDatum datum = new CrawlDatum(); while (true) { if (LogFormatter.hasLoggedSevere()) // something bad happened break; // exit try { // get next entry from input if (!input.next(key, datum)) { break; // at eof, exit } } catch (IOException e) { e.printStackTrace(); LOG.severe("fetcher caught:"+e.toString()); break; } synchronized (Fetcher.this) { lastRequestStart = System.currentTimeMillis(); } // url may be changed through redirects. UTF8 url = new UTF8(); url.set(key); try { LOG.info("fetching " + url); // fetch the page boolean redirecting; int redirectCount = 0; do { redirecting = false; LOG.fine("redirectCount=" + redirectCount); Protocol protocol = this.protocolFactory.getProtocol(url.toString()); ProtocolOutput output = protocol.getProtocolOutput(url, datum); ProtocolStatus status = output.getStatus(); Content content = output.getContent(); ParseStatus pstatus = null; switch(status.getCode()) { case ProtocolStatus.SUCCESS: // got a page pstatus = output(url, datum, content, CrawlDatum.STATUS_FETCH_SUCCESS); updateStatus(content.getContent().length); if (pstatus != null && pstatus.isSuccess() && pstatus.getMinorCode() == ParseStatus.SUCCESS_REDIRECT) { String newUrl = pstatus.getMessage(); newUrl = normalizer.normalize(newUrl); newUrl = this.urlFilters.filter(newUrl); if (newUrl != null && !newUrl.equals(url.toString())) { url = new UTF8(newUrl); redirecting = true; redirectCount++; LOG.fine(" - content redirect to " + url); } else { LOG.fine(" - content redirect skipped: " + - (url.equals(newUrl.toString()) ? "to same url" : "filtered")); + (newUrl != null ? "to same url" : "filtered")); } } break; case ProtocolStatus.MOVED: // redirect case ProtocolStatus.TEMP_MOVED: String newUrl = status.getMessage(); newUrl = normalizer.normalize(newUrl); newUrl = this.urlFilters.filter(newUrl); if (newUrl != null && !newUrl.equals(url.toString())) { url = new UTF8(newUrl); redirecting = true; redirectCount++; LOG.fine(" - protocol redirect to " + url); } else { LOG.fine(" - protocol redirect skipped: " + - (url.equals(newUrl.toString()) ? "to same url" : "filtered")); + (newUrl != null ? "to same url" : "filtered")); } break; case ProtocolStatus.EXCEPTION: logError(url, status.getMessage()); case ProtocolStatus.RETRY: // retry datum.setRetriesSinceFetch(datum.getRetriesSinceFetch()+1); output(url, datum, null, CrawlDatum.STATUS_FETCH_RETRY); break; case ProtocolStatus.GONE: // gone case ProtocolStatus.NOTFOUND: case ProtocolStatus.ACCESS_DENIED: case ProtocolStatus.ROBOTS_DENIED: case ProtocolStatus.NOTMODIFIED: output(url, datum, null, CrawlDatum.STATUS_FETCH_GONE); break; default: LOG.warning("Unknown ProtocolStatus: " + status.getCode()); output(url, datum, null, CrawlDatum.STATUS_FETCH_GONE); } if (redirecting && redirectCount >= maxRedirect) { LOG.info(" - redirect count exceeded " + url); output(url, datum, null, CrawlDatum.STATUS_FETCH_GONE); } } while (redirecting && (redirectCount < maxRedirect)); } catch (Throwable t) { // unexpected exception logError(url, t.toString()); output(url, datum, null, CrawlDatum.STATUS_FETCH_GONE); } } } catch (Throwable e) { e.printStackTrace(); LOG.severe("fetcher caught:"+e.toString()); } finally { synchronized (Fetcher.this) {activeThreads--;} // count threads } } private void logError(UTF8 url, String message) { LOG.info("fetch of " + url + " failed with: " + message); synchronized (Fetcher.this) { // record failure errors++; } } private ParseStatus output(UTF8 key, CrawlDatum datum, Content content, int status) { datum.setStatus(status); datum.setFetchTime(System.currentTimeMillis()); if (content == null) { String url = key.toString(); content = new Content(url, url, new byte[0], "", new Metadata(), this.conf); } Metadata metadata = content.getMetadata(); // add segment to metadata metadata.set(SEGMENT_NAME_KEY, segmentName); // add score to metadata metadata.set(SCORE_KEY, Float.toString(datum.getScore())); Parse parse = null; if (parsing && status == CrawlDatum.STATUS_FETCH_SUCCESS) { ParseStatus parseStatus; try { parse = this.parseUtil.parse(content); parseStatus = parse.getData().getStatus(); } catch (Exception e) { parseStatus = new ParseStatus(e); } if (!parseStatus.isSuccess()) { LOG.warning("Error parsing: " + key + ": " + parseStatus); parse = parseStatus.getEmptyParse(getConf()); } // Calculate page signature. For non-parsing fetchers this will // be done in ParseSegment byte[] signature = SignatureFactory.getSignature(getConf()).calculate(content, parse); metadata.set(SIGNATURE_KEY, StringUtil.toHexString(signature)); datum.setSignature(signature); // Ensure segment name and score are in parseData metadata parse.getData().getContentMeta().set(SEGMENT_NAME_KEY, segmentName); parse.getData().getContentMeta().set(SCORE_KEY, Float.toString(datum.getScore())); parse.getData().getContentMeta().set(SIGNATURE_KEY, StringUtil.toHexString(signature)); } try { output.collect (key, new FetcherOutput(datum, storingContent ? content : null, parse != null ? new ParseImpl(parse) : null)); } catch (IOException e) { e.printStackTrace(); LOG.severe("fetcher caught:"+e.toString()); } if (parse != null) return parse.getData().getStatus(); else return null; } } public Fetcher() { super(null); } public Fetcher(Configuration conf) { super(conf); } private synchronized void updateStatus(int bytesInPage) throws IOException { pages++; bytes += bytesInPage; } private void reportStatus() throws IOException { String status; synchronized (this) { long elapsed = (System.currentTimeMillis() - start)/1000; status = pages+" pages, "+errors+" errors, " + Math.round(((float)pages*10)/elapsed)/10.0+" pages/s, " + Math.round(((((float)bytes)*8)/1024)/elapsed)+" kb/s, "; } reporter.setStatus(status); } public void configure(JobConf job) { setConf(job); this.segmentName = job.get(SEGMENT_NAME_KEY); this.storingContent = isStoringContent(job); this.parsing = isParsing(job); if (job.getBoolean("fetcher.verbose", false)) { LOG.setLevel(Level.FINE); } } public void close() {} public static boolean isParsing(Configuration conf) { return conf.getBoolean("fetcher.parse", true); } public static boolean isStoringContent(Configuration conf) { return conf.getBoolean("fetcher.store.content", true); } public void run(RecordReader input, OutputCollector output, Reporter reporter) throws IOException { this.input = input; this.output = output; this.reporter = reporter; this.maxRedirect = getConf().getInt("http.redirect.max", 3); int threadCount = getConf().getInt("fetcher.threads.fetch", 10); LOG.info("Fetcher: threads: " + threadCount); for (int i = 0; i < threadCount; i++) { // spawn threads new FetcherThread(getConf()).start(); } // select a timeout that avoids a task timeout long timeout = getConf().getInt("mapred.task.timeout", 10*60*1000)/2; do { // wait for threads to exit try { Thread.sleep(1000); } catch (InterruptedException e) {} reportStatus(); // some requests seem to hang, despite all intentions synchronized (this) { if ((System.currentTimeMillis() - lastRequestStart) > timeout) { LOG.warning("Aborting with "+activeThreads+" hung threads."); return; } } } while (activeThreads > 0); } public void fetch(File segment, int threads, boolean parsing) throws IOException { LOG.info("Fetcher: starting"); LOG.info("Fetcher: segment: " + segment); JobConf job = new NutchJob(getConf()); job.setJobName("fetch " + segment); job.setInt("fetcher.threads.fetch", threads); job.set(SEGMENT_NAME_KEY, segment.getName()); job.setBoolean("fetcher.parse", parsing); // for politeness, don't permit parallel execution of a single task job.setBoolean("mapred.speculative.execution", false); job.setInputDir(new File(segment, CrawlDatum.GENERATE_DIR_NAME)); job.setInputFormat(InputFormat.class); job.setInputKeyClass(UTF8.class); job.setInputValueClass(CrawlDatum.class); job.setMapRunnerClass(Fetcher.class); job.setOutputDir(segment); job.setOutputFormat(FetcherOutputFormat.class); job.setOutputKeyClass(UTF8.class); job.setOutputValueClass(FetcherOutput.class); JobClient.runJob(job); LOG.info("Fetcher: done"); } /** Run the fetcher. */ public static void main(String[] args) throws Exception { String usage = "Usage: Fetcher <segment> [-threads n] [-noParsing]"; if (args.length < 1) { System.err.println(usage); System.exit(-1); } File segment = new File(args[0]); Configuration conf = NutchConfiguration.create(); int threads = conf.getInt("fetcher.threads.fetch", 10); boolean parsing = true; for (int i = 1; i < args.length; i++) { // parse command line if (args[i].equals("-threads")) { // found -threads option threads = Integer.parseInt(args[++i]); } else if (args[i].equals("-noParsing")) parsing = false; } conf.setInt("fetcher.threads.fetch", threads); if (!parsing) { conf.setBoolean("fetcher.parse", parsing); } Fetcher fetcher = new Fetcher(conf); // make a Fetcher fetcher.fetch(segment, threads, parsing); // run the Fetcher } }
false
true
public void run() { synchronized (Fetcher.this) {activeThreads++;} // count threads try { UTF8 key = new UTF8(); CrawlDatum datum = new CrawlDatum(); while (true) { if (LogFormatter.hasLoggedSevere()) // something bad happened break; // exit try { // get next entry from input if (!input.next(key, datum)) { break; // at eof, exit } } catch (IOException e) { e.printStackTrace(); LOG.severe("fetcher caught:"+e.toString()); break; } synchronized (Fetcher.this) { lastRequestStart = System.currentTimeMillis(); } // url may be changed through redirects. UTF8 url = new UTF8(); url.set(key); try { LOG.info("fetching " + url); // fetch the page boolean redirecting; int redirectCount = 0; do { redirecting = false; LOG.fine("redirectCount=" + redirectCount); Protocol protocol = this.protocolFactory.getProtocol(url.toString()); ProtocolOutput output = protocol.getProtocolOutput(url, datum); ProtocolStatus status = output.getStatus(); Content content = output.getContent(); ParseStatus pstatus = null; switch(status.getCode()) { case ProtocolStatus.SUCCESS: // got a page pstatus = output(url, datum, content, CrawlDatum.STATUS_FETCH_SUCCESS); updateStatus(content.getContent().length); if (pstatus != null && pstatus.isSuccess() && pstatus.getMinorCode() == ParseStatus.SUCCESS_REDIRECT) { String newUrl = pstatus.getMessage(); newUrl = normalizer.normalize(newUrl); newUrl = this.urlFilters.filter(newUrl); if (newUrl != null && !newUrl.equals(url.toString())) { url = new UTF8(newUrl); redirecting = true; redirectCount++; LOG.fine(" - content redirect to " + url); } else { LOG.fine(" - content redirect skipped: " + (url.equals(newUrl.toString()) ? "to same url" : "filtered")); } } break; case ProtocolStatus.MOVED: // redirect case ProtocolStatus.TEMP_MOVED: String newUrl = status.getMessage(); newUrl = normalizer.normalize(newUrl); newUrl = this.urlFilters.filter(newUrl); if (newUrl != null && !newUrl.equals(url.toString())) { url = new UTF8(newUrl); redirecting = true; redirectCount++; LOG.fine(" - protocol redirect to " + url); } else { LOG.fine(" - protocol redirect skipped: " + (url.equals(newUrl.toString()) ? "to same url" : "filtered")); } break; case ProtocolStatus.EXCEPTION: logError(url, status.getMessage()); case ProtocolStatus.RETRY: // retry datum.setRetriesSinceFetch(datum.getRetriesSinceFetch()+1); output(url, datum, null, CrawlDatum.STATUS_FETCH_RETRY); break; case ProtocolStatus.GONE: // gone case ProtocolStatus.NOTFOUND: case ProtocolStatus.ACCESS_DENIED: case ProtocolStatus.ROBOTS_DENIED: case ProtocolStatus.NOTMODIFIED: output(url, datum, null, CrawlDatum.STATUS_FETCH_GONE); break; default: LOG.warning("Unknown ProtocolStatus: " + status.getCode()); output(url, datum, null, CrawlDatum.STATUS_FETCH_GONE); } if (redirecting && redirectCount >= maxRedirect) { LOG.info(" - redirect count exceeded " + url); output(url, datum, null, CrawlDatum.STATUS_FETCH_GONE); } } while (redirecting && (redirectCount < maxRedirect)); } catch (Throwable t) { // unexpected exception logError(url, t.toString()); output(url, datum, null, CrawlDatum.STATUS_FETCH_GONE); } } } catch (Throwable e) { e.printStackTrace(); LOG.severe("fetcher caught:"+e.toString()); } finally { synchronized (Fetcher.this) {activeThreads--;} // count threads } }
public void run() { synchronized (Fetcher.this) {activeThreads++;} // count threads try { UTF8 key = new UTF8(); CrawlDatum datum = new CrawlDatum(); while (true) { if (LogFormatter.hasLoggedSevere()) // something bad happened break; // exit try { // get next entry from input if (!input.next(key, datum)) { break; // at eof, exit } } catch (IOException e) { e.printStackTrace(); LOG.severe("fetcher caught:"+e.toString()); break; } synchronized (Fetcher.this) { lastRequestStart = System.currentTimeMillis(); } // url may be changed through redirects. UTF8 url = new UTF8(); url.set(key); try { LOG.info("fetching " + url); // fetch the page boolean redirecting; int redirectCount = 0; do { redirecting = false; LOG.fine("redirectCount=" + redirectCount); Protocol protocol = this.protocolFactory.getProtocol(url.toString()); ProtocolOutput output = protocol.getProtocolOutput(url, datum); ProtocolStatus status = output.getStatus(); Content content = output.getContent(); ParseStatus pstatus = null; switch(status.getCode()) { case ProtocolStatus.SUCCESS: // got a page pstatus = output(url, datum, content, CrawlDatum.STATUS_FETCH_SUCCESS); updateStatus(content.getContent().length); if (pstatus != null && pstatus.isSuccess() && pstatus.getMinorCode() == ParseStatus.SUCCESS_REDIRECT) { String newUrl = pstatus.getMessage(); newUrl = normalizer.normalize(newUrl); newUrl = this.urlFilters.filter(newUrl); if (newUrl != null && !newUrl.equals(url.toString())) { url = new UTF8(newUrl); redirecting = true; redirectCount++; LOG.fine(" - content redirect to " + url); } else { LOG.fine(" - content redirect skipped: " + (newUrl != null ? "to same url" : "filtered")); } } break; case ProtocolStatus.MOVED: // redirect case ProtocolStatus.TEMP_MOVED: String newUrl = status.getMessage(); newUrl = normalizer.normalize(newUrl); newUrl = this.urlFilters.filter(newUrl); if (newUrl != null && !newUrl.equals(url.toString())) { url = new UTF8(newUrl); redirecting = true; redirectCount++; LOG.fine(" - protocol redirect to " + url); } else { LOG.fine(" - protocol redirect skipped: " + (newUrl != null ? "to same url" : "filtered")); } break; case ProtocolStatus.EXCEPTION: logError(url, status.getMessage()); case ProtocolStatus.RETRY: // retry datum.setRetriesSinceFetch(datum.getRetriesSinceFetch()+1); output(url, datum, null, CrawlDatum.STATUS_FETCH_RETRY); break; case ProtocolStatus.GONE: // gone case ProtocolStatus.NOTFOUND: case ProtocolStatus.ACCESS_DENIED: case ProtocolStatus.ROBOTS_DENIED: case ProtocolStatus.NOTMODIFIED: output(url, datum, null, CrawlDatum.STATUS_FETCH_GONE); break; default: LOG.warning("Unknown ProtocolStatus: " + status.getCode()); output(url, datum, null, CrawlDatum.STATUS_FETCH_GONE); } if (redirecting && redirectCount >= maxRedirect) { LOG.info(" - redirect count exceeded " + url); output(url, datum, null, CrawlDatum.STATUS_FETCH_GONE); } } while (redirecting && (redirectCount < maxRedirect)); } catch (Throwable t) { // unexpected exception logError(url, t.toString()); output(url, datum, null, CrawlDatum.STATUS_FETCH_GONE); } } } catch (Throwable e) { e.printStackTrace(); LOG.severe("fetcher caught:"+e.toString()); } finally { synchronized (Fetcher.this) {activeThreads--;} // count threads } }
diff --git a/bundles/org.eclipse.osgi/resolver/src/org/eclipse/osgi/internal/module/ResolverImpl.java b/bundles/org.eclipse.osgi/resolver/src/org/eclipse/osgi/internal/module/ResolverImpl.java index 08db59fb..72c46bf6 100644 --- a/bundles/org.eclipse.osgi/resolver/src/org/eclipse/osgi/internal/module/ResolverImpl.java +++ b/bundles/org.eclipse.osgi/resolver/src/org/eclipse/osgi/internal/module/ResolverImpl.java @@ -1,1525 +1,1525 @@ /******************************************************************************* * Copyright (c) 2004, 2007 IBM Corporation 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: IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.osgi.internal.module; import java.util.*; import org.eclipse.osgi.framework.adaptor.FrameworkAdaptor; import org.eclipse.osgi.framework.debug.Debug; import org.eclipse.osgi.framework.debug.FrameworkDebugOptions; import org.eclipse.osgi.internal.resolver.BundleDescriptionImpl; import org.eclipse.osgi.internal.resolver.ExportPackageDescriptionImpl; import org.eclipse.osgi.service.resolver.*; import org.eclipse.osgi.util.ManifestElement; import org.osgi.framework.*; public class ResolverImpl implements org.eclipse.osgi.service.resolver.Resolver { // Debug fields private static final String RESOLVER = FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME + "/resolver"; //$NON-NLS-1$ private static final String OPTION_DEBUG = RESOLVER + "/debug";//$NON-NLS-1$ private static final String OPTION_WIRING = RESOLVER + "/wiring"; //$NON-NLS-1$ private static final String OPTION_IMPORTS = RESOLVER + "/imports"; //$NON-NLS-1$ private static final String OPTION_REQUIRES = RESOLVER + "/requires"; //$NON-NLS-1$ private static final String OPTION_GENERICS = RESOLVER + "/generics"; //$NON-NLS-1$ private static final String OPTION_GROUPING = RESOLVER + "/grouping"; //$NON-NLS-1$ private static final String OPTION_CYCLES = RESOLVER + "/cycles"; //$NON-NLS-1$ public static boolean DEBUG = false; public static boolean DEBUG_WIRING = false; public static boolean DEBUG_IMPORTS = false; public static boolean DEBUG_REQUIRES = false; public static boolean DEBUG_GENERICS = false; public static boolean DEBUG_GROUPING = false; public static boolean DEBUG_CYCLES = false; private static String[][] CURRENT_EES; // The State associated with this resolver private State state; // Used to check permissions for import/export, provide/require, host/fragment private PermissionChecker permissionChecker; // Set of bundles that are pending removal private MappedList removalPending = new MappedList(); // Indicates whether this resolver has been initialized private boolean initialized = false; // Repository for exports private VersionHashMap resolverExports = null; // Repository for bundles private VersionHashMap resolverBundles = null; // Repository for generics private VersionHashMap resolverGenerics = null; // List of unresolved bundles private ArrayList unresolvedBundles = null; // Keys are BundleDescriptions, values are ResolverBundles private HashMap bundleMapping = null; private GroupingChecker groupingChecker; private Comparator selectionPolicy; private boolean developmentMode = false; public ResolverImpl(BundleContext context, boolean checkPermissions) { this.permissionChecker = new PermissionChecker(context, checkPermissions, this); } PermissionChecker getPermissionChecker() { return permissionChecker; } // Initializes the resolver private void initialize() { resolverExports = new VersionHashMap(this); resolverBundles = new VersionHashMap(this); resolverGenerics = new VersionHashMap(this); unresolvedBundles = new ArrayList(); bundleMapping = new HashMap(); BundleDescription[] bundles = state.getBundles(); groupingChecker = new GroupingChecker(); ArrayList fragmentBundles = new ArrayList(); // Add each bundle to the resolver's internal state for (int i = 0; i < bundles.length; i++) initResolverBundle(bundles[i], fragmentBundles, false); // Add each removal pending bundle to the resolver's internal state Object[] removedBundles = removalPending.getAllValues(); for (int i = 0; i < removedBundles.length; i++) initResolverBundle((BundleDescription) removedBundles[i], fragmentBundles, true); // Iterate over the resolved fragments and attach them to their hosts for (Iterator iter = fragmentBundles.iterator(); iter.hasNext();) { ResolverBundle fragment = (ResolverBundle) iter.next(); BundleDescription[] hosts = ((HostSpecification) fragment.getHost().getVersionConstraint()).getHosts(); for (int i = 0; i < hosts.length; i++) { ResolverBundle host = (ResolverBundle) bundleMapping.get(hosts[i]); if (host != null) // Do not add fragment exports here because they would have been added by the host above. host.attachFragment(fragment, false); } } rewireBundles(); // Reconstruct wirings setDebugOptions(); initialized = true; } private void initResolverBundle(BundleDescription bundleDesc, ArrayList fragmentBundles, boolean pending) { ResolverBundle bundle = new ResolverBundle(bundleDesc, this); bundleMapping.put(bundleDesc, bundle); if (!pending || bundleDesc.isResolved()) { resolverExports.put(bundle.getExportPackages()); resolverBundles.put(bundle.getName(), bundle); resolverGenerics.put(bundle.getGenericCapabilities()); } if (bundleDesc.isResolved()) { bundle.setState(ResolverBundle.RESOLVED); if (bundleDesc.getHost() != null) fragmentBundles.add(bundle); } else { if (!pending) unresolvedBundles.add(bundle); } } // Re-wire previously resolved bundles private void rewireBundles() { ArrayList visited = new ArrayList(bundleMapping.size()); for (Iterator iter = bundleMapping.values().iterator(); iter.hasNext();) { ResolverBundle rb = (ResolverBundle) iter.next(); if (!rb.getBundle().isResolved() || rb.isFragment()) continue; rewireBundle(rb, visited); } } private void rewireBundle(ResolverBundle rb, ArrayList visited) { if (visited.contains(rb)) return; visited.add(rb); // Wire requires to bundles BundleConstraint[] requires = rb.getRequires(); for (int i = 0; i < requires.length; i++) { rewireRequire(requires[i], visited); } // Wire imports to exports ResolverImport[] imports = rb.getImportPackages(); for (int i = 0; i < imports.length; i++) { rewireImport(imports[i], visited); } // Wire generics GenericConstraint[] genericRequires = rb.getGenericRequires(); for (int i = 0; i < genericRequires.length; i++) rewireGeneric(genericRequires[i], visited); } private void rewireGeneric(GenericConstraint constraint, ArrayList visited) { if (constraint.getMatchingCapabilities() != null) return; GenericDescription[] suppliers = ((GenericSpecification) constraint.getVersionConstraint()).getSuppliers(); if (suppliers == null) return; Object[] matches = resolverGenerics.get(constraint.getName()); for (int i = 0; i < matches.length; i++) { GenericCapability match = (GenericCapability) matches[i]; for (int j = 0; j < suppliers.length; j++) if (match.getBaseDescription() == suppliers[j]) constraint.setMatchingCapability(match); } GenericCapability[] matchingCapabilities = constraint.getMatchingCapabilities(); if (matchingCapabilities != null) for (int i = 0; i < matchingCapabilities.length; i++) rewireBundle(matchingCapabilities[i].getResolverBundle(), visited); } private void rewireRequire(BundleConstraint req, ArrayList visited) { if (req.getSelectedSupplier() != null) return; ResolverBundle matchingBundle = (ResolverBundle) bundleMapping.get(req.getVersionConstraint().getSupplier()); req.addPossibleSupplier(matchingBundle); if (matchingBundle == null && !req.isOptional()) { System.err.println("Could not find matching bundle for " + req.getVersionConstraint()); //$NON-NLS-1$ // TODO log error!! } if (matchingBundle != null) { rewireBundle(matchingBundle, visited); } } private void rewireImport(ResolverImport imp, ArrayList visited) { if (imp.isDynamic() || imp.getSelectedSupplier() != null) return; // Re-wire 'imp' ResolverExport matchingExport = null; ExportPackageDescription importSupplier = (ExportPackageDescription) imp.getVersionConstraint().getSupplier(); ResolverBundle exporter = importSupplier == null ? null : (ResolverBundle) bundleMapping.get(importSupplier.getExporter()); Object[] matches = resolverExports.get(imp.getName()); for (int j = 0; j < matches.length; j++) { ResolverExport export = (ResolverExport) matches[j]; if (export.getExporter() == exporter && importSupplier == export.getExportPackageDescription()) { matchingExport = export; break; } } imp.addPossibleSupplier(matchingExport); // Check if we wired to a reprovided package (in which case the ResolverExport doesn't exist) if (matchingExport == null && exporter != null) { ResolverExport reprovidedExport = new ResolverExport(exporter, importSupplier); if (exporter.getExport(imp.getName()) == null) { exporter.addExport(reprovidedExport); resolverExports.put(reprovidedExport.getName(), reprovidedExport); } imp.addPossibleSupplier(reprovidedExport); } // If we still have a null wire and it's not optional, then we have an error if (imp.getSelectedSupplier() == null && !imp.isOptional()) { System.err.println("Could not find matching export for " + imp.getVersionConstraint()); //$NON-NLS-1$ // TODO log error!! } if (imp.getSelectedSupplier() != null) { rewireBundle(((ResolverExport) imp.getSelectedSupplier()).getExporter(), visited); } } // Checks a bundle to make sure it is valid. If this method returns false for // a given bundle, then that bundle will not even be considered for resolution private boolean isResolvable(BundleDescription bundle, Dictionary[] platformProperties, ArrayList rejectedSingletons) { // check if this is a rejected singleton if (rejectedSingletons.contains(bundle)) return false; // Check for singletons if (bundle.isSingleton()) { Object[] sameName = resolverBundles.get(bundle.getName()); if (sameName.length > 1) // Need to check if one is already resolved for (int i = 0; i < sameName.length; i++) { if (sameName[i] == bundle || !((ResolverBundle) sameName[i]).getBundle().isSingleton()) continue; // Ignore the bundle we are resolving and non-singletons if (((ResolverBundle) sameName[i]).getBundle().isResolved()) { rejectedSingletons.add(bundle); return false; // Must fail since there is already a resolved bundle } } } // check the required execution environment String[] ees = bundle.getExecutionEnvironments(); boolean matchedEE = ees.length == 0; if (!matchedEE) for (int i = 0; i < ees.length && !matchedEE; i++) for (int j = 0; j < CURRENT_EES.length && !matchedEE; j++) for (int k = 0; k < CURRENT_EES[j].length && !matchedEE; k++) if (CURRENT_EES[j][k].equals(ees[i])) { ((BundleDescriptionImpl) bundle).setEquinoxEE(j); matchedEE = true; } if (!matchedEE) { StringBuffer bundleEE = new StringBuffer(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT.length() + 20); bundleEE.append(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT).append(": "); //$NON-NLS-1$ for (int i = 0; i < ees.length; i++) { if (i > 0) bundleEE.append(","); //$NON-NLS-1$ bundleEE.append(ees[i]); } state.addResolverError(bundle, ResolverError.MISSING_EXECUTION_ENVIRONMENT, bundleEE.toString(), null); return false; } // check the platform filter String platformFilter = bundle.getPlatformFilter(); if (platformFilter == null) return true; if (platformProperties == null) return false; try { Filter filter = FrameworkUtil.createFilter(platformFilter); for (int i = 0; i < platformProperties.length; i++) if (filter.match(platformProperties[i])) return true; } catch (InvalidSyntaxException e) { // return false below } state.addResolverError(bundle, ResolverError.PLATFORM_FILTER, platformFilter, null); return false; } // Attach fragment to its host private void attachFragment(ResolverBundle bundle, ArrayList rejectedSingletons) { if (!bundle.isFragment() || !bundle.isResolvable() || rejectedSingletons.contains(bundle.getBundle())) return; // no need to select singletons now; it will be done when we select the rest of the singleton bundles (bug 152042) // find all available hosts to attach to. boolean foundMatch = false; BundleConstraint hostConstraint = bundle.getHost(); Object[] hosts = resolverBundles.get(hostConstraint.getVersionConstraint().getName()); for (int i = 0; i < hosts.length; i++) if (((ResolverBundle) hosts[i]).isResolvable() && hostConstraint.isSatisfiedBy((ResolverBundle) hosts[i])) { foundMatch = true; resolverExports.put(((ResolverBundle) hosts[i]).attachFragment(bundle, true)); } if (!foundMatch) state.addResolverError(bundle.getBundle(), ResolverError.MISSING_FRAGMENT_HOST, bundle.getHost().getVersionConstraint().toString(), bundle.getHost().getVersionConstraint()); } public synchronized void resolve(BundleDescription[] reRefresh, Dictionary[] platformProperties) { if (DEBUG) ResolverImpl.log("*** BEGIN RESOLUTION ***"); //$NON-NLS-1$ if (state == null) throw new IllegalStateException("RESOLVER_NO_STATE"); //$NON-NLS-1$ if (!initialized) initialize(); developmentMode = platformProperties.length == 0 ? false : org.eclipse.osgi.framework.internal.core.Constants.DEVELOPMENT_MODE.equals(platformProperties[0].get(org.eclipse.osgi.framework.internal.core.Constants.OSGI_RESOLVER_MODE)); reRefresh = addDevConstraints(reRefresh); // Unresolve all the supplied bundles and their dependents if (reRefresh != null) for (int i = 0; i < reRefresh.length; i++) { ResolverBundle rb = (ResolverBundle) bundleMapping.get(reRefresh[i]); if (rb != null) unresolveBundle(rb, false); } // reorder exports and bundles after unresolving the bundles resolverExports.reorder(); resolverBundles.reorder(); resolverGenerics.reorder(); // always get the latest EEs getCurrentEEs(platformProperties); // keep a list of rejected singltons ArrayList rejectedSingletons = new ArrayList(); boolean resolveOptional = platformProperties.length == 0 ? false : "true".equals(platformProperties[0].get("osgi.resolveOptional")); //$NON-NLS-1$//$NON-NLS-2$ ResolverBundle[] currentlyResolved = null; if (resolveOptional) { BundleDescription[] resolvedBundles = state.getResolvedBundles(); currentlyResolved = new ResolverBundle[resolvedBundles.length]; for (int i = 0; i < resolvedBundles.length; i++) currentlyResolved[i] = (ResolverBundle) bundleMapping.get(resolvedBundles[i]); } // attempt to resolve all unresolved bundles ResolverBundle[] bundles = (ResolverBundle[]) unresolvedBundles.toArray(new ResolverBundle[unresolvedBundles.size()]); resolveBundles(bundles, platformProperties, rejectedSingletons); if (selectSingletons(bundles, rejectedSingletons)) { // a singleton was unresolved as a result of selecting a different version // try to resolve unresolved bundles again; this will attempt to use the selected singleton bundles = (ResolverBundle[]) unresolvedBundles.toArray(new ResolverBundle[unresolvedBundles.size()]); resolveBundles(bundles, platformProperties, rejectedSingletons); } for (Iterator rejected = rejectedSingletons.iterator(); rejected.hasNext();) { BundleDescription reject = (BundleDescription) rejected.next(); BundleDescription sameName = state.getBundle(reject.getSymbolicName(), null); state.addResolverError(reject, ResolverError.SINGLETON_SELECTION, sameName.toString(), null); } if (resolveOptional) resolveOptionalConstraints(currentlyResolved); if (DEBUG) ResolverImpl.log("*** END RESOLUTION ***"); //$NON-NLS-1$ } private BundleDescription[] addDevConstraints(BundleDescription[] reRefresh) { if (!developmentMode) return reRefresh; // we don't care about this unless we are in development mode // when in develoment mode we need to reRefresh hosts of unresolved fragments that add new constraints // and reRefresh and unresolved bundles that have dependents HashSet additionalRefresh = new HashSet(); ResolverBundle[] unresolved = (ResolverBundle[]) unresolvedBundles.toArray(new ResolverBundle[unresolvedBundles.size()]); for (int i = 0; i < unresolved.length; i++) { addUnresolvedWithDependents(unresolved[i], additionalRefresh); addHostsFromFragmentConstraints(unresolved[i], additionalRefresh); } if (additionalRefresh.size() == 0) return reRefresh; // no new bundles found to refresh // add the original reRefresh bundles to the set if (reRefresh != null) for (int i = 0; i < reRefresh.length; i++) additionalRefresh.add(reRefresh[i]); return (BundleDescription[]) additionalRefresh.toArray(new BundleDescription[additionalRefresh.size()]); } private void addUnresolvedWithDependents(ResolverBundle unresolved, HashSet additionalRefresh) { BundleDescription[] dependents = unresolved.getBundle().getDependents(); if (dependents.length > 0) additionalRefresh.add(unresolved.getBundle()); } private void addHostsFromFragmentConstraints(ResolverBundle unresolved, Set additionalRefresh) { if (!unresolved.isFragment()) return; ImportPackageSpecification[] newImports = unresolved.getBundle().getImportPackages(); BundleSpecification[] newRequires = unresolved.getBundle().getRequiredBundles(); if (newImports.length == 0 && newRequires.length == 0) return; // the fragment does not have its own constraints BundleConstraint hostConstraint = unresolved.getHost(); Object[] hosts = resolverBundles.get(hostConstraint.getVersionConstraint().getName()); for (int j = 0; j < hosts.length; j++) if (hostConstraint.isSatisfiedBy((ResolverBundle) hosts[j]) && ((ResolverBundle) hosts[j]).isResolved()) // we found a host that is resolved; // add it to the set of bundle to refresh so we can ensure this fragment is allowed to resolve additionalRefresh.add(((ResolverBundle) hosts[j]).getBundle()); } private void resolveOptionalConstraints(ResolverBundle[] bundles) { for (int i = 0; i < bundles.length; i++) { if (bundles[i] != null) resolveOptionalConstraints(bundles[i]); } } // TODO this does not do proper uses constraint verification. private void resolveOptionalConstraints(ResolverBundle bundle) { BundleConstraint[] requires = bundle.getRequires(); ArrayList cycle = new ArrayList(); boolean resolvedOptional = false; for (int i = 0; i < requires.length; i++) if (requires[i].isOptional() && requires[i].getSelectedSupplier() == null) { cycle.clear(); resolveRequire(requires[i], cycle); if (requires[i].getSelectedSupplier() != null) resolvedOptional = true; } ResolverImport[] imports = bundle.getImportPackages(); for (int i = 0; i < imports.length; i++) if (imports[i].isOptional() && imports[i].getSelectedSupplier() == null) { cycle.clear(); resolveImport(imports[i], cycle); if (imports[i].getSelectedSupplier() != null) resolvedOptional = true; } if (resolvedOptional) { state.resolveBundle(bundle.getBundle(), false, null, null, null, null); stateResolveConstraints(bundle); stateResolveBundle(bundle); } } private void getCurrentEEs(Dictionary[] platformProperties) { CURRENT_EES = new String[platformProperties.length][]; for (int i = 0; i < platformProperties.length; i++) { String eeSpecs = (String) platformProperties[i].get(Constants.FRAMEWORK_EXECUTIONENVIRONMENT); CURRENT_EES[i] = ManifestElement.getArrayFromList(eeSpecs, ","); //$NON-NLS-1$ } } private void resolveBundles(ResolverBundle[] bundles, Dictionary[] platformProperties, ArrayList rejectedSingletons) { // First check that all the meta-data is valid for each unresolved bundle // This will reset the resolvable flag for each bundle for (int i = 0; i < bundles.length; i++) { state.removeResolverErrors(bundles[i].getBundle()); // if in development mode then make all bundles resolvable // we still want to call isResolvable here to populate any possible ResolverErrors for the bundle bundles[i].setResolvable(isResolvable(bundles[i].getBundle(), platformProperties, rejectedSingletons) || developmentMode); bundles[i].clearRefs(); } resolveBundles0(bundles, platformProperties, rejectedSingletons); if (DEBUG_WIRING) printWirings(); // set the resolved status of the bundles in the State stateResolveBundles(bundles); } private void resolveBundles0(ResolverBundle[] bundles, Dictionary[] platformProperties, ArrayList rejectedSingletons) { // First attach all fragments to the matching hosts for (int i = 0; i < bundles.length; i++) attachFragment(bundles[i], rejectedSingletons); // Lists of cyclic dependencies recording during resolving ArrayList cycle = new ArrayList(1); // start small // Attempt to resolve all unresolved bundles for (int i = 0; i < bundles.length; i++) { if (DEBUG) ResolverImpl.log("** RESOLVING " + bundles[i] + " **"); //$NON-NLS-1$ //$NON-NLS-2$ cycle.clear(); resolveBundle(bundles[i], cycle); // Check for any bundles involved in a cycle. // if any bundles in the cycle are not resolved then we need to resolve the resolvable ones checkCycle(cycle); } // Resolve all fragments that are still attached to at least one host. if (unresolvedBundles.size() > 0) { ResolverBundle[] unresolved = (ResolverBundle[]) unresolvedBundles.toArray(new ResolverBundle[unresolvedBundles.size()]); for (int i = 0; i < unresolved.length; i++) resolveFragment(unresolved[i]); } checkUsesConstraints(bundles, platformProperties, rejectedSingletons); } private void checkUsesConstraints(ResolverBundle[] bundles, Dictionary[] platformProperties, ArrayList rejectedSingletons) { ResolverConstraint[] multipleSuppliers = getMultipleSuppliers(bundles); ArrayList conflictingConstraints = findBestCombination(bundles, multipleSuppliers); Set conflictedBundles = null; if (conflictingConstraints != null) { for (Iterator conflicts = conflictingConstraints.iterator(); conflicts.hasNext();) { ResolverConstraint conflict = (ResolverConstraint) conflicts.next(); if (conflict.isOptional()) { conflict.clearPossibleSuppliers(); continue; } conflictedBundles = new HashSet(conflictingConstraints.size()); ResolverBundle conflictedBundle; if (conflict.isFromFragment()) conflictedBundle = (ResolverBundle) bundleMapping.get(conflict.getVersionConstraint().getBundle()); else conflictedBundle = conflict.getBundle(); if (conflictedBundle != null) { conflictedBundles.add(conflictedBundle); int type = conflict instanceof ResolverImport ? ResolverError.IMPORT_PACKAGE_USES_CONFLICT : ResolverError.REQUIRE_BUNDLE_USES_CONFLICT; state.addResolverError(conflictedBundle.getBundle(), type, conflict.getVersionConstraint().toString(), conflict.getVersionConstraint()); conflictedBundle.setResolvable(false); conflictedBundle.clearRefs(); setBundleUnresolved(conflictedBundle, false, developmentMode); } } if (conflictedBundles != null && conflictedBundles.size() > 0) { ArrayList remainingUnresolved = new ArrayList(); for (int i = 0; i < bundles.length; i++) { if (!conflictedBundles.contains(bundles[i])) { setBundleUnresolved(bundles[i], false, developmentMode); remainingUnresolved.add(bundles[i]); } } resolveBundles0((ResolverBundle[]) remainingUnresolved.toArray(new ResolverBundle[remainingUnresolved.size()]), platformProperties, rejectedSingletons); } } } private ArrayList findBestCombination(ResolverBundle[] bundles, ResolverConstraint[] multipleSuppliers) { int[] bestCombination = new int[multipleSuppliers.length]; ArrayList conflictingBundles = null; if (multipleSuppliers.length > 0) { conflictingBundles = findBestCombination(bundles, multipleSuppliers, bestCombination); for (int i = 0; i < bestCombination.length; i++) multipleSuppliers[i].setSelectedSupplier(bestCombination[i]); } else { conflictingBundles = getConflicts(bundles); } // do not need to keep uses data in memory groupingChecker.clear(); return conflictingBundles; } private void getCombination(ResolverConstraint[] multipleSuppliers, int[] combination) { for (int i = 0; i < combination.length; i++) combination[i] = multipleSuppliers[i].getSelectedSupplierIndex(); } private ArrayList findBestCombination(ResolverBundle[] bundles, ResolverConstraint[] multipleSuppliers, int[] bestCombination) { // first tryout all zeros ArrayList bestConflicts = getConflicts(bundles); if (bestConflicts == null) return null; // the first selected have no conflicts; return without iterating over all combinations // now iterate over every possible combination until either zero conflicts are found // or we have run out of combinations // if all combinations are tried then return the combination with the lowest number of conflicts int bestConflictCount = getConflictCount(bestConflicts); while (bestConflictCount != 0 && getNextCombination(multipleSuppliers)) { ArrayList conflicts = getConflicts(bundles); int conflictCount = getConflictCount(conflicts); if (conflictCount < bestConflictCount) { bestConflictCount = conflictCount; bestConflicts = conflicts; getCombination(multipleSuppliers, bestCombination); } } return bestConflicts; } private boolean getNextCombination(ResolverConstraint[] multipleSuppliers) { if (multipleSuppliers[0].selectNextSupplier()) return true; // the current slot has a next supplier multipleSuppliers[0].setSelectedSupplier(0); // reset first slot int current = 1; while (current < multipleSuppliers.length) { if (multipleSuppliers[current].selectNextSupplier()) return true; multipleSuppliers[current].setSelectedSupplier(0); // reset the current slot current++; // move to the next slot } return false; } // only count non-optional conflicts private int getConflictCount(ArrayList conflicts) { if (conflicts == null || conflicts.size() == 0) return 0; int result = 0; for (Iterator iConflicts = conflicts.iterator(); iConflicts.hasNext();) if (!((ResolverConstraint) iConflicts.next()).isOptional()) result += 1; return result; } private ArrayList getConflicts(ResolverBundle[] bundles) { groupingChecker.clear(); ArrayList conflicts = null; bundlesLoop: for (int i = 0; i < bundles.length; i++) { BundleConstraint[] requires = bundles[i].getRequires(); for (int j = 0; j < requires.length; j++) { ResolverBundle selectedSupplier = (ResolverBundle) requires[j].getSelectedSupplier(); ResolverExport conflict = selectedSupplier == null ? null : groupingChecker.isConsistent(bundles[i], selectedSupplier); if (conflict != null) { if (conflicts == null) conflicts = new ArrayList(1); conflicts.add(requires[j]); // continue on for optonal conflicts because we don't count them if (!requires[j].isOptional()) continue bundlesLoop; } } ResolverImport[] imports = bundles[i].getImportPackages(); for (int j = 0; j < imports.length; j++) { ResolverExport selectedSupplier = (ResolverExport) imports[j].getSelectedSupplier(); ResolverExport conflict = selectedSupplier == null ? null : groupingChecker.isConsistent(bundles[i], selectedSupplier); if (conflict != null) { if (conflicts == null) conflicts = new ArrayList(1); conflicts.add(imports[j]); // continue on for optional conflicts because we don't count them if (!imports[j].isOptional()) continue bundlesLoop; } } } return conflicts; } // get a list of resolver constraints that have multiple suppliers private ResolverConstraint[] getMultipleSuppliers(ResolverBundle[] bundles) { ArrayList multipleSuppliers = new ArrayList(1); for (int i = 0; i < bundles.length; i++) { BundleConstraint[] requires = bundles[i].getRequires(); for (int j = 0; j < requires.length; j++) if (requires[j].getNumPossibleSuppliers() > 1) multipleSuppliers.add(requires[j]); ResolverImport[] imports = bundles[i].getImportPackages(); for (int j = 0; j < imports.length; j++) { if (imports[j].getNumPossibleSuppliers() > 1) { Integer eeProfile = (Integer) ((ResolverExport) imports[j].getSelectedSupplier()).getExportPackageDescription().getDirective(ExportPackageDescriptionImpl.EQUINOX_EE); if (eeProfile.intValue() < 0) { // this is a normal package; always add it multipleSuppliers.add(imports[j]); } else { // this is a system bunde export // If other exporters of this package also require the system bundle // then this package does not need to be added to the mix // this is an optimization for bundles like org.eclipse.xerces // that export lots of packages also exported by the system bundle on J2SE 1.4 VersionSupplier[] suppliers = imports[j].getPossibleSuppliers(); for (int suppliersIndex = 1; suppliersIndex < suppliers.length; suppliersIndex++) { Integer ee = (Integer) ((ResolverExport) suppliers[suppliersIndex]).getExportPackageDescription().getDirective(ExportPackageDescriptionImpl.EQUINOX_EE); if (ee.intValue() >= 0) continue; if (((ResolverExport) suppliers[suppliersIndex]).getExporter().getRequire(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME) == null) if (((ResolverExport) suppliers[suppliersIndex]).getExporter().getRequire(Constants.SYSTEM_BUNDLE_SYMBOLICNAME) == null) { multipleSuppliers.add(imports[j]); break; } } } } } } return (ResolverConstraint[]) multipleSuppliers.toArray(new ResolverConstraint[multipleSuppliers.size()]); } private void checkCycle(ArrayList cycle) { int cycleSize = cycle.size(); if (cycleSize == 0) return; for (int i = cycleSize - 1; i >= 0; i--) { ResolverBundle cycleBundle = (ResolverBundle) cycle.get(i); if (!cycleBundle.isResolvable()) cycle.remove(i); // remove this from the list of bundles that need reresolved // Check that we haven't wired to any dropped exports ResolverImport[] imports = cycleBundle.getImportPackages(); for (int j = 0; j < imports.length; j++) { // check for dropped exports while (imports[j].getSelectedSupplier() != null) { ResolverExport importSupplier = (ResolverExport) imports[j].getSelectedSupplier(); if (importSupplier.isDropped()) imports[j].selectNextSupplier(); else break; } if (!imports[j].isDynamic() && !imports[j].isOptional() && imports[j].getSelectedSupplier() == null) { cycleBundle.setResolvable(false); cycleBundle.clearRefs(); state.addResolverError(imports[j].getVersionConstraint().getBundle(), ResolverError.MISSING_IMPORT_PACKAGE, imports[j].getVersionConstraint().toString(), imports[j].getVersionConstraint()); cycle.remove(i); } } } boolean reresolveCycle = cycle.size() != cycleSize; //we removed an unresolvable bundle; must reresolve remaining cycle if (reresolveCycle) { for (int i = 0; i < cycle.size(); i++) { ResolverBundle cycleBundle = (ResolverBundle) cycle.get(i); cycleBundle.clearWires(); cycleBundle.clearRefs(); } ArrayList innerCycle = new ArrayList(cycle.size()); for (int i = 0; i < cycle.size(); i++) resolveBundle((ResolverBundle) cycle.get(i), innerCycle); checkCycle(innerCycle); } else { for (int i = 0; i < cycle.size(); i++) { if (DEBUG || DEBUG_CYCLES) ResolverImpl.log("Pushing " + cycle.get(i) + " to RESOLVED"); //$NON-NLS-1$ //$NON-NLS-2$ setBundleResolved((ResolverBundle) cycle.get(i)); } } } private boolean selectSingletons(ResolverBundle[] bundles, ArrayList rejectedSingletons) { if (developmentMode) return false; // do no want to unresolve singletons in development mode boolean result = false; for (int i = 0; i < bundles.length; i++) { BundleDescription bundleDesc = bundles[i].getBundle(); if (!bundleDesc.isSingleton() || !bundleDesc.isResolved() || rejectedSingletons.contains(bundleDesc)) continue; Object[] sameName = resolverBundles.get(bundleDesc.getName()); if (sameName.length > 1) { // Need to make a selection based off of num dependents for (int j = 0; j < sameName.length; j++) { BundleDescription sameNameDesc = ((VersionSupplier) sameName[j]).getBundle(); ResolverBundle sameNameBundle = (ResolverBundle) sameName[j]; if (sameName[j] == bundles[i] || !sameNameDesc.isSingleton() || !sameNameDesc.isResolved() || rejectedSingletons.contains(sameNameDesc)) continue; // Ignore the bundle we are selecting, non-singletons, and non-resolved result = true; boolean rejectedPolicy = selectionPolicy != null ? selectionPolicy.compare(sameNameDesc, bundleDesc) < 0 : sameNameDesc.getVersion().compareTo(bundleDesc.getVersion()) > 0; if (rejectedPolicy && sameNameBundle.getRefs() >= bundles[i].getRefs()) { // this bundle is not selected; add it to the rejected list if (!rejectedSingletons.contains(bundles[i].getBundle())) rejectedSingletons.add(bundles[i].getBundle()); break; } // we did not select the sameNameDesc; add the bundle to the rejected list if (!rejectedSingletons.contains(sameNameDesc)) rejectedSingletons.add(sameNameDesc); } } } // unresolve the rejected singletons for (Iterator rejects = rejectedSingletons.iterator(); rejects.hasNext();) unresolveBundle((ResolverBundle) bundleMapping.get(rejects.next()), false); return result; } private void resolveFragment(ResolverBundle fragment) { if (!fragment.isFragment()) return; if (fragment.getHost().getNumPossibleSuppliers() > 0) if (!developmentMode || state.getResolverErrors(fragment.getBundle()).length == 0) setBundleResolved(fragment); } // This method will attempt to resolve the supplied bundle and any bundles that it is dependent on private boolean resolveBundle(ResolverBundle bundle, ArrayList cycle) { if (bundle.isFragment()) return false; if (!bundle.isResolvable()) { if (DEBUG) ResolverImpl.log(" - " + bundle + " is unresolvable"); //$NON-NLS-1$ //$NON-NLS-2$ return false; } if (bundle.getState() == ResolverBundle.RESOLVED) { // 'bundle' is already resolved so just return if (DEBUG) ResolverImpl.log(" - " + bundle + " already resolved"); //$NON-NLS-1$ //$NON-NLS-2$ return true; } else if (bundle.getState() == ResolverBundle.UNRESOLVED) { // 'bundle' is UNRESOLVED so move to RESOLVING bundle.clearWires(); setBundleResolving(bundle); } boolean failed = false; if (!failed) { GenericConstraint[] genericRequires = bundle.getGenericRequires(); for (int i = 0; i < genericRequires.length; i++) { if (!resolveGenericReq(genericRequires[i], cycle)) { if (DEBUG || DEBUG_GENERICS) ResolverImpl.log("** GENERICS " + genericRequires[i].getVersionConstraint().getName() + "[" + genericRequires[i].getBundleDescription() + "] failed to resolve"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ state.addResolverError(genericRequires[i].getVersionConstraint().getBundle(), ResolverError.MISSING_GENERIC_CAPABILITY, genericRequires[i].getVersionConstraint().toString(), genericRequires[i].getVersionConstraint()); if (genericRequires[i].isFromFragment()) { if (!developmentMode) // only detach fragments when not in devmode resolverExports.remove(bundle.detachFragment((ResolverBundle) bundleMapping.get(genericRequires[i].getVersionConstraint().getBundle()), null)); continue; } if (!developmentMode) { // fail fast; otherwise we want to attempt to resolver other constraints in dev mode failed = true; break; } } } } if (!failed) { // Iterate thru required bundles of 'bundle' trying to find matching bundles. BundleConstraint[] requires = bundle.getRequires(); for (int i = 0; i < requires.length; i++) { if (!resolveRequire(requires[i], cycle)) { if (DEBUG || DEBUG_REQUIRES) ResolverImpl.log("** REQUIRE " + requires[i].getVersionConstraint().getName() + "[" + requires[i].getBundleDescription() + "] failed to resolve"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ state.addResolverError(requires[i].getVersionConstraint().getBundle(), ResolverError.MISSING_REQUIRE_BUNDLE, requires[i].getVersionConstraint().toString(), requires[i].getVersionConstraint()); // If the require has failed to resolve and it is from a fragment, then remove the fragment from the host if (requires[i].isFromFragment()) { if (!developmentMode) // only detach fragments when not in devmode resolverExports.remove(bundle.detachFragment((ResolverBundle) bundleMapping.get(requires[i].getVersionConstraint().getBundle()), requires[i])); continue; } if (!developmentMode) { // fail fast; otherwise we want to attempt to resolver other constraints in dev mode failed = true; break; } } } } if (!failed) { // Iterate thru imports of 'bundle' trying to find matching exports. ResolverImport[] imports = bundle.getImportPackages(); for (int i = 0; i < imports.length; i++) { // Only resolve non-dynamic imports here if (!imports[i].isDynamic() && !resolveImport(imports[i], cycle)) { if (DEBUG || DEBUG_IMPORTS) ResolverImpl.log("** IMPORT " + imports[i].getName() + "[" + imports[i].getBundleDescription() + "] failed to resolve"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // If the import has failed to resolve and it is from a fragment, then remove the fragment from the host state.addResolverError(imports[i].getVersionConstraint().getBundle(), ResolverError.MISSING_IMPORT_PACKAGE, imports[i].getVersionConstraint().toString(), imports[i].getVersionConstraint()); if (imports[i].isFromFragment()) { if (!developmentMode) // only detach fragments when not in devmode - resolverExports.remove(bundle.detachFragment((ResolverBundle) bundleMapping.get(imports[i].getBundleDescription()), imports[i])); + resolverExports.remove(bundle.detachFragment((ResolverBundle) bundleMapping.get(imports[i].getVersionConstraint().getBundle()), imports[i])); continue; } if (!developmentMode) { // fail fast; otherwise we want to attempt to resolver other constraints in dev mode failed = true; break; } } } } // check that fragment constraints are met by the constraints that got resolved to the host checkFragmentConstraints(bundle); // do some extra checking when in development mode to see if other resolver error occurred if (developmentMode && !failed && state.getResolverErrors(bundle.getBundle()).length > 0) failed = true; // Need to check that all mandatory imports are wired. If they are then // set the bundle RESOLVED, otherwise set it back to UNRESOLVED if (failed) { setBundleUnresolved(bundle, false, developmentMode); if (DEBUG) ResolverImpl.log(bundle + " NOT RESOLVED"); //$NON-NLS-1$ } else if (!cycle.contains(bundle)) { setBundleResolved(bundle); if (DEBUG) ResolverImpl.log(bundle + " RESOLVED"); //$NON-NLS-1$ } if (bundle.getState() == ResolverBundle.UNRESOLVED) bundle.setResolvable(false); // Set it to unresolvable so we don't attempt to resolve it again in this round return bundle.getState() != ResolverBundle.UNRESOLVED; } private void checkFragmentConstraints(ResolverBundle bundle) { // get all currently attached fragments and ensure that any constraints // they have do not conflict with the constraints resolved to by the host ResolverBundle[] fragments = bundle.getFragments(); for (int i = 0; i < fragments.length; i++) { BundleDescription fragment = fragments[i].getBundle(); if (bundle.constraintsConflict(fragment, fragment.getImportPackages(), fragment.getRequiredBundles(), fragment.getGenericRequires()) && !developmentMode) // found some conflicts; detach the fragment resolverExports.remove(bundle.detachFragment(fragments[i], null)); } } private boolean resolveGenericReq(GenericConstraint constraint, ArrayList cycle) { if (DEBUG_REQUIRES) ResolverImpl.log("Trying to resolve: " + constraint.getBundle() + ", " + constraint.getVersionConstraint()); //$NON-NLS-1$ //$NON-NLS-2$ GenericCapability[] matchingCapabilities = constraint.getMatchingCapabilities(); if (matchingCapabilities != null) { // Check for unrecorded cyclic dependency for (int i = 0; i < matchingCapabilities.length; i++) if (matchingCapabilities[i].getResolverBundle().getState() == ResolverBundle.RESOLVING) if (!cycle.contains(constraint.getBundle())) cycle.add(constraint.getBundle()); if (DEBUG_REQUIRES) ResolverImpl.log(" - already wired"); //$NON-NLS-1$ return true; // Already wired (due to grouping dependencies) so just return } Object[] capabilities = resolverGenerics.get(constraint.getVersionConstraint().getName()); boolean result = false; for (int i = 0; i < capabilities.length; i++) { GenericCapability capability = (GenericCapability) capabilities[i]; if (DEBUG_GENERICS) ResolverImpl.log("CHECKING GENERICS: " + capability.getBaseDescription()); //$NON-NLS-1$ // Check if capability matches if (constraint.isSatisfiedBy(capability)) { capability.getResolverBundle().addRef(constraint.getBundle()); if (result && (((GenericSpecification) constraint.getVersionConstraint()).getResolution() & GenericSpecification.RESOLUTION_MULTIPLE) == 0) continue; // found a match already and this is not a multiple constraint constraint.setMatchingCapability(capability); // Wire to the capability if (constraint.getBundle() == capability.getResolverBundle()) { result = true; // Wired to ourselves continue; } VersionSupplier[] capabilityHosts = capability.isFromFragment() ? capability.getResolverBundle().getHost().getPossibleSuppliers() : new ResolverBundle[] {capability.getResolverBundle()}; boolean foundResolvedMatch = false; for (int j = 0; capabilityHosts != null && j < capabilityHosts.length; j++) { ResolverBundle capabilitySupplier = (ResolverBundle) capabilityHosts[j]; if (capabilitySupplier == constraint.getBundle()) { // the capability is from a fragment attached to this host do not recursively resolve the host again foundResolvedMatch = true; continue; } // if in dev mode then allow a constraint to resolve to an unresolved bundle if (capabilitySupplier.getState() == ResolverBundle.RESOLVED || (resolveBundle(capabilitySupplier, cycle) || developmentMode)) { foundResolvedMatch |= !capability.isFromFragment() ? true : capability.getResolverBundle().getHost().getPossibleSuppliers() != null; // Check cyclic dependencies if (capabilitySupplier.getState() == ResolverBundle.RESOLVING) if (!cycle.contains(capabilitySupplier)) cycle.add(capabilitySupplier); } } if (!foundResolvedMatch) { constraint.removeMatchingCapability(capability); continue; // constraint hasn't resolved } if (DEBUG_GENERICS) ResolverImpl.log("Found match: " + capability.getBaseDescription() + ". Wiring"); //$NON-NLS-1$ //$NON-NLS-2$ result = true; } } return result ? true : (((GenericSpecification) constraint.getVersionConstraint()).getResolution() & GenericSpecification.RESOLUTION_OPTIONAL) != 0; } // Resolve the supplied import. Returns true if the import can be resolved, false otherwise private boolean resolveRequire(BundleConstraint req, ArrayList cycle) { if (DEBUG_REQUIRES) ResolverImpl.log("Trying to resolve: " + req.getBundle() + ", " + req.getVersionConstraint()); //$NON-NLS-1$ //$NON-NLS-2$ if (req.getSelectedSupplier() != null) { // Check for unrecorded cyclic dependency if (!cycle.contains(req.getBundle())) { cycle.add(req.getBundle()); if (DEBUG_CYCLES) ResolverImpl.log("require-bundle cycle: " + req.getBundle() + " -> " + req.getSelectedSupplier()); //$NON-NLS-1$ //$NON-NLS-2$ } if (DEBUG_REQUIRES) ResolverImpl.log(" - already wired"); //$NON-NLS-1$ return true; // Already wired (due to grouping dependencies) so just return } Object[] bundles = resolverBundles.get(req.getVersionConstraint().getName()); boolean result = false; for (int i = 0; i < bundles.length; i++) { ResolverBundle bundle = (ResolverBundle) bundles[i]; if (DEBUG_REQUIRES) ResolverImpl.log("CHECKING: " + bundle.getBundle()); //$NON-NLS-1$ // Check if export matches if (req.isSatisfiedBy(bundle)) { bundle.addRef(req.getBundle()); // first add the possible supplier; this is done before resolving the supplier bundle to prevent endless cycle loops. req.addPossibleSupplier(bundle); if (req.getBundle() != bundle) { // if in dev mode then allow a constraint to resolve to an unresolved bundle if (bundle.getState() != ResolverBundle.RESOLVED && !resolveBundle(bundle, cycle) && !developmentMode) { req.removePossibleSupplier(bundle); continue; // Bundle hasn't resolved } } // Check cyclic dependencies if (req.getBundle() != bundle) { if (bundle.getState() == ResolverBundle.RESOLVING) // If the bundle is RESOLVING, we have a cyclic dependency if (!cycle.contains(req.getBundle())) { cycle.add(req.getBundle()); if (DEBUG_CYCLES) ResolverImpl.log("require-bundle cycle: " + req.getBundle() + " -> " + req.getSelectedSupplier()); //$NON-NLS-1$ //$NON-NLS-2$ } } if (DEBUG_REQUIRES) ResolverImpl.log("Found match: " + bundle.getBundle() + ". Wiring"); //$NON-NLS-1$ //$NON-NLS-2$ result = true; } } if (result || req.isOptional()) return true; // If the req is optional then just return true return false; } // Resolve the supplied import. Returns true if the import can be resolved, false otherwise private boolean resolveImport(ResolverImport imp, ArrayList cycle) { if (DEBUG_IMPORTS) ResolverImpl.log("Trying to resolve: " + imp.getBundle() + ", " + imp.getName()); //$NON-NLS-1$ //$NON-NLS-2$ if (imp.getSelectedSupplier() != null) { // Check for unrecorded cyclic dependency if (!cycle.contains(imp.getBundle())) { cycle.add(imp.getBundle()); if (DEBUG_CYCLES) ResolverImpl.log("import-package cycle: " + imp.getBundle() + " -> " + imp.getSelectedSupplier() + " from " + imp.getSelectedSupplier().getBundle()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } if (DEBUG_IMPORTS) ResolverImpl.log(" - already wired"); //$NON-NLS-1$ return true; // Already wired (due to grouping dependencies) so just return } boolean result = false; Object[] exports = resolverExports.get(imp.getName()); exportsloop: for (int i = 0; i < exports.length; i++) { ResolverExport export = (ResolverExport) exports[i]; if (DEBUG_IMPORTS) ResolverImpl.log("CHECKING: " + export.getExporter().getBundle() + ", " + export.getName()); //$NON-NLS-1$ //$NON-NLS-2$ // Check if export matches if (imp.isSatisfiedBy(export)) { int originalState = export.getExporter().getState(); if (imp.isDynamic() && originalState != ResolverBundle.RESOLVED) continue; // Must not attempt to resolve an exporter when dynamic if (imp.getBundle() == export.getExporter() && !export.getExportPackageDescription().isRoot()) continue; // Can't wire to our own re-export export.getExporter().addRef(imp.getBundle()); // first add the possible supplier; this is done before resolving the supplier bundle to prevent endless cycle loops. imp.addPossibleSupplier(export); ResolverExport[] importerExps = null; if (imp.getBundle() != export.getExporter()) { // Save the exports of this package from the importer in case we need to add them back importerExps = imp.getBundle().getExports(imp.getName()); for (int j = 0; j < importerExps.length; j++) { if (importerExps[j].getExportPackageDescription().isRoot() && !export.getExportPackageDescription().isRoot()) continue exportsloop; // to prevent imports from getting wired to re-exports if we offer a root export if (importerExps[j].getExportPackageDescription().isRoot()) // do not drop reexports when import wins resolverExports.remove(importerExps[j]); // Import wins, remove export } // if in dev mode then allow a constraint to resolve to an unresolved bundle if ((originalState != ResolverBundle.RESOLVED && !resolveBundle(export.getExporter(), cycle) && !developmentMode) || export.isDropped()) { // remove the possible supplier imp.removePossibleSupplier(export); // add back the exports of this package from the importer for (int j = 0; j < importerExps.length; j++) resolverExports.put(importerExps[j].getName(), importerExps[j]); continue; // Bundle hasn't resolved || export has not been selected and is unavailable } } else if (export.isDropped()) continue; // we already found a possible import that satisifies us; our export is dropped // Record any cyclic dependencies if (imp.getBundle() != export.getExporter()) if (export.getExporter().getState() == ResolverBundle.RESOLVING) { // If the exporter is RESOLVING, we have a cyclic dependency if (!cycle.contains(imp.getBundle())) { cycle.add(imp.getBundle()); if (DEBUG_CYCLES) ResolverImpl.log("import-package cycle: " + imp.getBundle() + " -> " + imp.getSelectedSupplier() + " from " + imp.getSelectedSupplier().getBundle()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } if (DEBUG_IMPORTS) ResolverImpl.log("Found match: " + export.getExporter() + ". Wiring " + imp.getBundle() + ":" + imp.getName()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ result = true; } } if (result) return true; if (resolveImportReprovide(imp, cycle)) return true; if (imp.isOptional()) return true; // If the import is optional then just return true return false; } // Check if the import can be resolved to a re-exported package (has no export object to match to) private boolean resolveImportReprovide(ResolverImport imp, ArrayList cycle) { String bsn = ((ImportPackageSpecification) imp.getVersionConstraint()).getBundleSymbolicName(); // If no symbolic name specified then just return (since this is a // re-export an import not specifying a bsn will wire to the root) if (bsn == null) return false; if (DEBUG_IMPORTS) ResolverImpl.log("Checking reprovides: " + imp.getName()); //$NON-NLS-1$ // Find bundle with specified bsn Object[] bundles = resolverBundles.get(bsn); for (int i = 0; i < bundles.length; i++) if (resolveBundle((ResolverBundle) bundles[i], cycle)) if (resolveImportReprovide0(imp, (ResolverBundle) bundles[i], (ResolverBundle) bundles[i], cycle, new ArrayList(5))) return true; return false; } private boolean resolveImportReprovide0(ResolverImport imp, ResolverBundle reexporter, ResolverBundle rb, ArrayList cycle, ArrayList visited) { if (visited.contains(rb)) return false; // make sure we don't endless recurse cycles visited.add(rb); BundleConstraint[] requires = rb.getRequires(); for (int i = 0; i < requires.length; i++) { if (!((BundleSpecification) requires[i].getVersionConstraint()).isExported()) continue; // Skip require if it doesn't re-export the packages // Check exports to see if we've found the root if (requires[i].getSelectedSupplier() == null) continue; ResolverExport[] exports = ((ResolverBundle) requires[i].getSelectedSupplier()).getExports(imp.getName()); for (int j = 0; j < exports.length; j++) { Map directives = exports[j].getExportPackageDescription().getDirectives(); directives.remove(Constants.USES_DIRECTIVE); ExportPackageDescription epd = state.getFactory().createExportPackageDescription(exports[j].getName(), exports[j].getVersion(), directives, exports[j].getExportPackageDescription().getAttributes(), false, reexporter.getBundle()); if (imp.getVersionConstraint().isSatisfiedBy(epd)) { // Create reexport and add to bundle and resolverExports if (DEBUG_IMPORTS) ResolverImpl.log(" - Creating re-export for reprovide: " + reexporter + ":" + epd.getName()); //$NON-NLS-1$ //$NON-NLS-2$ ResolverExport re = new ResolverExport(reexporter, epd); reexporter.addExport(re); resolverExports.put(re.getName(), re); // Resolve import imp.addPossibleSupplier(re); return true; } } // Check requires of matching bundle (recurse down the chain) if (resolveImportReprovide0(imp, reexporter, (ResolverBundle) requires[i].getSelectedSupplier(), cycle, visited)) return true; } return false; } // Move a bundle to UNRESOLVED private void setBundleUnresolved(ResolverBundle bundle, boolean removed, boolean isDevMode) { if (bundle.getState() == ResolverBundle.UNRESOLVED) return; if (bundle.getBundle().isResolved()) { resolverExports.remove(bundle.getExportPackages()); if (removed) resolverGenerics.remove(bundle.getGenericCapabilities()); bundle.initialize(false); if (!removed) resolverExports.put(bundle.getExportPackages()); } if (!removed) unresolvedBundles.add(bundle); if (!isDevMode) bundle.detachAllFragments(); bundle.setState(ResolverBundle.UNRESOLVED); } // Move a bundle to RESOLVED private void setBundleResolved(ResolverBundle bundle) { if (bundle.getState() == ResolverBundle.RESOLVED) return; unresolvedBundles.remove(bundle); bundle.setState(ResolverBundle.RESOLVED); } // Move a bundle to RESOLVING private void setBundleResolving(ResolverBundle bundle) { if (bundle.getState() == ResolverBundle.RESOLVING) return; unresolvedBundles.remove(bundle); bundle.setState(ResolverBundle.RESOLVING); } // Resolves the bundles in the State private void stateResolveBundles(ResolverBundle[] resolvedBundles) { for (int i = 0; i < resolvedBundles.length; i++) { if (!resolvedBundles[i].getBundle().isResolved()) stateResolveBundle(resolvedBundles[i]); } } private void stateResolveConstraints(ResolverBundle rb) { ResolverImport[] imports = rb.getImportPackages(); for (int i = 0; i < imports.length; i++) { ResolverExport export = (ResolverExport) imports[i].getSelectedSupplier(); BaseDescription supplier = export == null ? null : export.getExportPackageDescription(); state.resolveConstraint(imports[i].getVersionConstraint(), supplier); } BundleConstraint[] requires = rb.getRequires(); for (int i = 0; i < requires.length; i++) { ResolverBundle bundle = (ResolverBundle) requires[i].getSelectedSupplier(); BaseDescription supplier = bundle == null ? null : bundle.getBundle(); state.resolveConstraint(requires[i].getVersionConstraint(), supplier); } GenericConstraint[] genericRequires = rb.getGenericRequires(); for (int i = 0; i < genericRequires.length; i++) { GenericCapability[] matchingCapabilities = genericRequires[i].getMatchingCapabilities(); if (matchingCapabilities == null) state.resolveConstraint(genericRequires[i].getVersionConstraint(), null); else for (int j = 0; j < matchingCapabilities.length; j++) state.resolveConstraint(genericRequires[i].getVersionConstraint(), matchingCapabilities[j].getBaseDescription()); } } private void stateResolveFragConstraints(ResolverBundle rb) { ResolverBundle host = (ResolverBundle) rb.getHost().getSelectedSupplier(); ImportPackageSpecification[] imports = rb.getBundle().getImportPackages(); for (int i = 0; i < imports.length; i++) { ResolverImport hostImport = host == null ? null : host.getImport(imports[i].getName()); ResolverExport export = (ResolverExport) (hostImport == null ? null : hostImport.getSelectedSupplier()); BaseDescription supplier = export == null ? null : export.getExportPackageDescription(); state.resolveConstraint(imports[i], supplier); } BundleSpecification[] requires = rb.getBundle().getRequiredBundles(); for (int i = 0; i < requires.length; i++) { BundleConstraint hostRequire = host == null ? null : host.getRequire(requires[i].getName()); ResolverBundle bundle = (ResolverBundle) (hostRequire == null ? null : hostRequire.getSelectedSupplier()); BaseDescription supplier = bundle == null ? null : bundle.getBundle(); state.resolveConstraint(requires[i], supplier); } } private void stateResolveBundle(ResolverBundle rb) { // if in dev mode then we want to tell the state about the constraints we were able to resolve if (!rb.isResolved() && !developmentMode) return; if (rb.isFragment()) stateResolveFragConstraints(rb); else stateResolveConstraints(rb); // Gather selected exports ResolverExport[] exports = rb.getSelectedExports(); ArrayList selectedExports = new ArrayList(exports.length); for (int i = 0; i < exports.length; i++) { selectedExports.add(exports[i].getExportPackageDescription()); } ExportPackageDescription[] selectedExportsArray = (ExportPackageDescription[]) selectedExports.toArray(new ExportPackageDescription[selectedExports.size()]); // Gather exports that have been wired to ResolverImport[] imports = rb.getImportPackages(); ArrayList exportsWiredTo = new ArrayList(imports.length); for (int i = 0; i < imports.length; i++) if (imports[i].getSelectedSupplier() != null) exportsWiredTo.add(imports[i].getSelectedSupplier().getBaseDescription()); ExportPackageDescription[] exportsWiredToArray = (ExportPackageDescription[]) exportsWiredTo.toArray(new ExportPackageDescription[exportsWiredTo.size()]); // Gather bundles that have been wired to BundleConstraint[] requires = rb.getRequires(); ArrayList bundlesWiredTo = new ArrayList(requires.length); for (int i = 0; i < requires.length; i++) if (requires[i].getSelectedSupplier() != null) bundlesWiredTo.add(requires[i].getSelectedSupplier().getBaseDescription()); BundleDescription[] bundlesWiredToArray = (BundleDescription[]) bundlesWiredTo.toArray(new BundleDescription[bundlesWiredTo.size()]); BundleDescription[] hostBundles = null; if (rb.isFragment()) { VersionSupplier[] matchingBundles = rb.getHost().getPossibleSuppliers(); if (matchingBundles != null && matchingBundles.length > 0) { hostBundles = new BundleDescription[matchingBundles.length]; for (int i = 0; i < matchingBundles.length; i++) { hostBundles[i] = matchingBundles[i].getBundle(); if (rb.isNewFragmentExports() && hostBundles[i].isResolved()) { // update the host's set of selected exports ResolverExport[] hostExports = ((ResolverBundle) matchingBundles[i]).getSelectedExports(); ExportPackageDescription[] hostExportsArray = new ExportPackageDescription[hostExports.length]; for (int j = 0; j < hostExports.length; j++) hostExportsArray[j] = hostExports[j].getExportPackageDescription(); state.resolveBundle(hostBundles[i], true, null, hostExportsArray, hostBundles[i].getResolvedRequires(), hostBundles[i].getResolvedImports()); } } } } // Resolve the bundle in the state state.resolveBundle(rb.getBundle(), rb.isResolved(), hostBundles, selectedExportsArray, bundlesWiredToArray, exportsWiredToArray); } // Resolve dynamic import public synchronized ExportPackageDescription resolveDynamicImport(BundleDescription importingBundle, String requestedPackage) { if (state == null) throw new IllegalStateException("RESOLVER_NO_STATE"); //$NON-NLS-1$ // Make sure the resolver is initialized if (!initialized) initialize(); ResolverBundle rb = (ResolverBundle) bundleMapping.get(importingBundle); if (rb.getExport(requestedPackage) != null) return null; // do not allow dynamic wires for packages which this bundle exports ResolverImport[] resolverImports = rb.getImportPackages(); // Check through the ResolverImports of this bundle. // If there is a matching one then pass it into resolveImport() boolean found = false; for (int j = 0; j < resolverImports.length; j++) { // Make sure it is a dynamic import if (!resolverImports[j].isDynamic()) continue; String importName = resolverImports[j].getName(); // If the import uses a wildcard, then temporarily replace this with the requested package if (importName.equals("*") || //$NON-NLS-1$ (importName.endsWith(".*") && requestedPackage.startsWith(importName.substring(0, importName.length() - 2)))) { //$NON-NLS-1$ resolverImports[j].setName(requestedPackage); } // Resolve the import if (requestedPackage.equals(resolverImports[j].getName())) { found = true; // populate the grouping checker with current imports groupingChecker.populateRoots(resolverImports[j].getBundle()); if (resolveImport(resolverImports[j], new ArrayList())) { found = false; while (!found && resolverImports[j].getSelectedSupplier() != null) { if (groupingChecker.isDynamicConsistent(resolverImports[j].getBundle(), (ResolverExport) resolverImports[j].getSelectedSupplier()) != null) resolverImports[j].selectNextSupplier(); // not consistent; try the next else found = true; // found a valid wire } resolverImports[j].setName(null); if (!found) { // not found or there was a conflict; reset the suppliers and return null resolverImports[j].setPossibleSuppliers(null); return null; } // If the import resolved then return it's matching export if (DEBUG_IMPORTS) ResolverImpl.log("Resolved dynamic import: " + rb + ":" + resolverImports[j].getName() + " -> " + ((ResolverExport) resolverImports[j].getSelectedSupplier()).getExporter() + ":" + requestedPackage); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ ExportPackageDescription matchingExport = ((ResolverExport) resolverImports[j].getSelectedSupplier()).getExportPackageDescription(); // If it is a wildcard import then clear the wire, so other // exported packages can be found for it if (importName.endsWith("*")) //$NON-NLS-1$ resolverImports[j].setPossibleSuppliers(null); return matchingExport; } } // Reset the import package name resolverImports[j].setName(null); } // this is to support adding dynamic imports on the fly. if (!found) { Map directives = new HashMap(1); directives.put(Constants.RESOLUTION_DIRECTIVE, ImportPackageSpecification.RESOLUTION_DYNAMIC); ImportPackageSpecification packageSpec = state.getFactory().createImportPackageSpecification(requestedPackage, null, null, null, directives, null, importingBundle); ResolverImport newImport = new ResolverImport(rb, packageSpec); if (resolveImport(newImport, new ArrayList())) { while (newImport.getSelectedSupplier() != null) { if (groupingChecker.isDynamicConsistent(rb, (ResolverExport) newImport.getSelectedSupplier()) != null) newImport.selectNextSupplier(); else break; } return ((ResolverExport) newImport.getSelectedSupplier()).getExportPackageDescription(); } } if (DEBUG || DEBUG_IMPORTS) ResolverImpl.log("Failed to resolve dynamic import: " + requestedPackage); //$NON-NLS-1$ return null; // Couldn't resolve the import, so return null } public void bundleAdded(BundleDescription bundle) { if (!initialized) return; boolean alreadyThere = false; for (int i = 0; i < unresolvedBundles.size(); i++) { ResolverBundle rb = (ResolverBundle) unresolvedBundles.get(i); if (rb.getBundle() == bundle) { alreadyThere = true; } } if (!alreadyThere) { ResolverBundle rb = new ResolverBundle(bundle, this); bundleMapping.put(bundle, rb); unresolvedBundles.add(rb); resolverExports.put(rb.getExportPackages()); resolverBundles.put(rb.getName(), rb); resolverGenerics.put(rb.getGenericCapabilities()); } } public void bundleRemoved(BundleDescription bundle, boolean pending) { // check if there are any dependants if (pending) removalPending.put(new Long(bundle.getBundleId()), bundle); if (!initialized) return; ResolverBundle rb = (ResolverBundle) bundleMapping.get(bundle); if (rb == null) return; if (!pending) { bundleMapping.remove(bundle); groupingChecker.remove(rb); } if (!pending || !bundle.isResolved()) { resolverExports.remove(rb.getExportPackages()); resolverBundles.remove(rb); resolverGenerics.remove(rb.getGenericCapabilities()); } unresolvedBundles.remove(rb); } private void unresolveBundle(ResolverBundle bundle, boolean removed) { if (bundle == null) return; // check the removed list if unresolving then remove from the removed list Object[] removedBundles = removalPending.remove(new Long(bundle.getBundle().getBundleId())); for (int i = 0; i < removedBundles.length; i++) { ResolverBundle re = (ResolverBundle) bundleMapping.get(removedBundles[i]); unresolveBundle(re, true); state.removeBundleComplete((BundleDescription) removedBundles[i]); resolverExports.remove(re.getExportPackages()); resolverBundles.remove(re); resolverGenerics.remove(re.getGenericCapabilities()); bundleMapping.remove(removedBundles[i]); groupingChecker.remove(re); // the bundle is removed if (removedBundles[i] == bundle.getBundle()) removed = true; } if (!bundle.getBundle().isResolved() && !developmentMode) return; // if not removed then add to the list of unresolvedBundles, // passing false for devmode because we need all fragments detached setBundleUnresolved(bundle, removed, false); // Get bundles dependent on 'bundle' BundleDescription[] dependents = bundle.getBundle().getDependents(); state.resolveBundle(bundle.getBundle(), false, null, null, null, null); // Unresolve dependents of 'bundle' for (int i = 0; i < dependents.length; i++) unresolveBundle((ResolverBundle) bundleMapping.get(dependents[i]), false); } public void bundleUpdated(BundleDescription newDescription, BundleDescription existingDescription, boolean pending) { bundleRemoved(existingDescription, pending); bundleAdded(newDescription); } public void flush() { resolverExports = null; resolverBundles = null; resolverGenerics = null; unresolvedBundles = null; bundleMapping = null; Object[] removed = removalPending.getAllValues(); for (int i = 0; i < removed.length; i++) state.removeBundleComplete((BundleDescription) removed[i]); removalPending.clear(); initialized = false; } public State getState() { return state; } public void setState(State newState) { state = newState; flush(); } private void setDebugOptions() { FrameworkDebugOptions options = FrameworkDebugOptions.getDefault(); // may be null if debugging is not enabled if (options == null) return; DEBUG = options.getBooleanOption(OPTION_DEBUG, false); DEBUG_WIRING = options.getBooleanOption(OPTION_WIRING, false); DEBUG_IMPORTS = options.getBooleanOption(OPTION_IMPORTS, false); DEBUG_REQUIRES = options.getBooleanOption(OPTION_REQUIRES, false); DEBUG_GENERICS = options.getBooleanOption(OPTION_GENERICS, false); DEBUG_GROUPING = options.getBooleanOption(OPTION_GROUPING, false); DEBUG_CYCLES = options.getBooleanOption(OPTION_CYCLES, false); } // LOGGING METHODS private void printWirings() { ResolverImpl.log("****** Result Wirings ******"); //$NON-NLS-1$ Object[] bundles = resolverBundles.getAllValues(); for (int j = 0; j < bundles.length; j++) { ResolverBundle rb = (ResolverBundle) bundles[j]; if (rb.getBundle().isResolved()) { continue; } ResolverImpl.log(" * WIRING for " + rb); //$NON-NLS-1$ // Require bundles BundleConstraint[] requireBundles = rb.getRequires(); if (requireBundles.length == 0) { ResolverImpl.log(" (r) no requires"); //$NON-NLS-1$ } else { for (int i = 0; i < requireBundles.length; i++) { if (requireBundles[i].getSelectedSupplier() == null) { ResolverImpl.log(" (r) " + rb.getBundle() + " -> NULL!!!"); //$NON-NLS-1$ //$NON-NLS-2$ } else { ResolverImpl.log(" (r) " + rb.getBundle() + " -> " + requireBundles[i].getSelectedSupplier()); //$NON-NLS-1$ //$NON-NLS-2$ } } } // Hosts BundleConstraint hostSpec = rb.getHost(); if (hostSpec != null) { VersionSupplier[] hosts = hostSpec.getPossibleSuppliers(); if (hosts != null) for (int i = 0; i < hosts.length; i++) { ResolverImpl.log(" (h) " + rb.getBundle() + " -> " + hosts[i].getBundle()); //$NON-NLS-1$ //$NON-NLS-2$ } } // Imports ResolverImport[] imports = rb.getImportPackages(); if (imports.length == 0) { ResolverImpl.log(" (w) no imports"); //$NON-NLS-1$ continue; } for (int i = 0; i < imports.length; i++) { if (imports[i].isDynamic() && imports[i].getSelectedSupplier() == null) { ResolverImpl.log(" (w) " + imports[i].getBundle() + ":" + imports[i].getName() + " -> DYNAMIC"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } else if (imports[i].isOptional() && imports[i].getSelectedSupplier() == null) { ResolverImpl.log(" (w) " + imports[i].getBundle() + ":" + imports[i].getName() + " -> OPTIONAL (could not be wired)"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } else if (imports[i].getSelectedSupplier() == null) { ResolverImpl.log(" (w) " + imports[i].getBundle() + ":" + imports[i].getName() + " -> NULL!!!"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } else { ResolverImpl.log(" (w) " + imports[i].getBundle() + ":" + imports[i].getName() + " -> " + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ ((ResolverExport) imports[i].getSelectedSupplier()).getExporter() + ":" + imports[i].getSelectedSupplier().getName()); //$NON-NLS-1$ } } } } static void log(String message) { Debug.println(message); } VersionHashMap getResolverExports() { return resolverExports; } public void setSelectionPolicy(Comparator selectionPolicy) { this.selectionPolicy = selectionPolicy; } public Comparator getSelectionPolicy() { return selectionPolicy; } }
true
true
private boolean resolveBundle(ResolverBundle bundle, ArrayList cycle) { if (bundle.isFragment()) return false; if (!bundle.isResolvable()) { if (DEBUG) ResolverImpl.log(" - " + bundle + " is unresolvable"); //$NON-NLS-1$ //$NON-NLS-2$ return false; } if (bundle.getState() == ResolverBundle.RESOLVED) { // 'bundle' is already resolved so just return if (DEBUG) ResolverImpl.log(" - " + bundle + " already resolved"); //$NON-NLS-1$ //$NON-NLS-2$ return true; } else if (bundle.getState() == ResolverBundle.UNRESOLVED) { // 'bundle' is UNRESOLVED so move to RESOLVING bundle.clearWires(); setBundleResolving(bundle); } boolean failed = false; if (!failed) { GenericConstraint[] genericRequires = bundle.getGenericRequires(); for (int i = 0; i < genericRequires.length; i++) { if (!resolveGenericReq(genericRequires[i], cycle)) { if (DEBUG || DEBUG_GENERICS) ResolverImpl.log("** GENERICS " + genericRequires[i].getVersionConstraint().getName() + "[" + genericRequires[i].getBundleDescription() + "] failed to resolve"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ state.addResolverError(genericRequires[i].getVersionConstraint().getBundle(), ResolverError.MISSING_GENERIC_CAPABILITY, genericRequires[i].getVersionConstraint().toString(), genericRequires[i].getVersionConstraint()); if (genericRequires[i].isFromFragment()) { if (!developmentMode) // only detach fragments when not in devmode resolverExports.remove(bundle.detachFragment((ResolverBundle) bundleMapping.get(genericRequires[i].getVersionConstraint().getBundle()), null)); continue; } if (!developmentMode) { // fail fast; otherwise we want to attempt to resolver other constraints in dev mode failed = true; break; } } } } if (!failed) { // Iterate thru required bundles of 'bundle' trying to find matching bundles. BundleConstraint[] requires = bundle.getRequires(); for (int i = 0; i < requires.length; i++) { if (!resolveRequire(requires[i], cycle)) { if (DEBUG || DEBUG_REQUIRES) ResolverImpl.log("** REQUIRE " + requires[i].getVersionConstraint().getName() + "[" + requires[i].getBundleDescription() + "] failed to resolve"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ state.addResolverError(requires[i].getVersionConstraint().getBundle(), ResolverError.MISSING_REQUIRE_BUNDLE, requires[i].getVersionConstraint().toString(), requires[i].getVersionConstraint()); // If the require has failed to resolve and it is from a fragment, then remove the fragment from the host if (requires[i].isFromFragment()) { if (!developmentMode) // only detach fragments when not in devmode resolverExports.remove(bundle.detachFragment((ResolverBundle) bundleMapping.get(requires[i].getVersionConstraint().getBundle()), requires[i])); continue; } if (!developmentMode) { // fail fast; otherwise we want to attempt to resolver other constraints in dev mode failed = true; break; } } } } if (!failed) { // Iterate thru imports of 'bundle' trying to find matching exports. ResolverImport[] imports = bundle.getImportPackages(); for (int i = 0; i < imports.length; i++) { // Only resolve non-dynamic imports here if (!imports[i].isDynamic() && !resolveImport(imports[i], cycle)) { if (DEBUG || DEBUG_IMPORTS) ResolverImpl.log("** IMPORT " + imports[i].getName() + "[" + imports[i].getBundleDescription() + "] failed to resolve"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // If the import has failed to resolve and it is from a fragment, then remove the fragment from the host state.addResolverError(imports[i].getVersionConstraint().getBundle(), ResolverError.MISSING_IMPORT_PACKAGE, imports[i].getVersionConstraint().toString(), imports[i].getVersionConstraint()); if (imports[i].isFromFragment()) { if (!developmentMode) // only detach fragments when not in devmode resolverExports.remove(bundle.detachFragment((ResolverBundle) bundleMapping.get(imports[i].getBundleDescription()), imports[i])); continue; } if (!developmentMode) { // fail fast; otherwise we want to attempt to resolver other constraints in dev mode failed = true; break; } } } } // check that fragment constraints are met by the constraints that got resolved to the host checkFragmentConstraints(bundle); // do some extra checking when in development mode to see if other resolver error occurred if (developmentMode && !failed && state.getResolverErrors(bundle.getBundle()).length > 0) failed = true; // Need to check that all mandatory imports are wired. If they are then // set the bundle RESOLVED, otherwise set it back to UNRESOLVED if (failed) { setBundleUnresolved(bundle, false, developmentMode); if (DEBUG) ResolverImpl.log(bundle + " NOT RESOLVED"); //$NON-NLS-1$ } else if (!cycle.contains(bundle)) { setBundleResolved(bundle); if (DEBUG) ResolverImpl.log(bundle + " RESOLVED"); //$NON-NLS-1$ } if (bundle.getState() == ResolverBundle.UNRESOLVED) bundle.setResolvable(false); // Set it to unresolvable so we don't attempt to resolve it again in this round return bundle.getState() != ResolverBundle.UNRESOLVED; }
private boolean resolveBundle(ResolverBundle bundle, ArrayList cycle) { if (bundle.isFragment()) return false; if (!bundle.isResolvable()) { if (DEBUG) ResolverImpl.log(" - " + bundle + " is unresolvable"); //$NON-NLS-1$ //$NON-NLS-2$ return false; } if (bundle.getState() == ResolverBundle.RESOLVED) { // 'bundle' is already resolved so just return if (DEBUG) ResolverImpl.log(" - " + bundle + " already resolved"); //$NON-NLS-1$ //$NON-NLS-2$ return true; } else if (bundle.getState() == ResolverBundle.UNRESOLVED) { // 'bundle' is UNRESOLVED so move to RESOLVING bundle.clearWires(); setBundleResolving(bundle); } boolean failed = false; if (!failed) { GenericConstraint[] genericRequires = bundle.getGenericRequires(); for (int i = 0; i < genericRequires.length; i++) { if (!resolveGenericReq(genericRequires[i], cycle)) { if (DEBUG || DEBUG_GENERICS) ResolverImpl.log("** GENERICS " + genericRequires[i].getVersionConstraint().getName() + "[" + genericRequires[i].getBundleDescription() + "] failed to resolve"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ state.addResolverError(genericRequires[i].getVersionConstraint().getBundle(), ResolverError.MISSING_GENERIC_CAPABILITY, genericRequires[i].getVersionConstraint().toString(), genericRequires[i].getVersionConstraint()); if (genericRequires[i].isFromFragment()) { if (!developmentMode) // only detach fragments when not in devmode resolverExports.remove(bundle.detachFragment((ResolverBundle) bundleMapping.get(genericRequires[i].getVersionConstraint().getBundle()), null)); continue; } if (!developmentMode) { // fail fast; otherwise we want to attempt to resolver other constraints in dev mode failed = true; break; } } } } if (!failed) { // Iterate thru required bundles of 'bundle' trying to find matching bundles. BundleConstraint[] requires = bundle.getRequires(); for (int i = 0; i < requires.length; i++) { if (!resolveRequire(requires[i], cycle)) { if (DEBUG || DEBUG_REQUIRES) ResolverImpl.log("** REQUIRE " + requires[i].getVersionConstraint().getName() + "[" + requires[i].getBundleDescription() + "] failed to resolve"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ state.addResolverError(requires[i].getVersionConstraint().getBundle(), ResolverError.MISSING_REQUIRE_BUNDLE, requires[i].getVersionConstraint().toString(), requires[i].getVersionConstraint()); // If the require has failed to resolve and it is from a fragment, then remove the fragment from the host if (requires[i].isFromFragment()) { if (!developmentMode) // only detach fragments when not in devmode resolverExports.remove(bundle.detachFragment((ResolverBundle) bundleMapping.get(requires[i].getVersionConstraint().getBundle()), requires[i])); continue; } if (!developmentMode) { // fail fast; otherwise we want to attempt to resolver other constraints in dev mode failed = true; break; } } } } if (!failed) { // Iterate thru imports of 'bundle' trying to find matching exports. ResolverImport[] imports = bundle.getImportPackages(); for (int i = 0; i < imports.length; i++) { // Only resolve non-dynamic imports here if (!imports[i].isDynamic() && !resolveImport(imports[i], cycle)) { if (DEBUG || DEBUG_IMPORTS) ResolverImpl.log("** IMPORT " + imports[i].getName() + "[" + imports[i].getBundleDescription() + "] failed to resolve"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // If the import has failed to resolve and it is from a fragment, then remove the fragment from the host state.addResolverError(imports[i].getVersionConstraint().getBundle(), ResolverError.MISSING_IMPORT_PACKAGE, imports[i].getVersionConstraint().toString(), imports[i].getVersionConstraint()); if (imports[i].isFromFragment()) { if (!developmentMode) // only detach fragments when not in devmode resolverExports.remove(bundle.detachFragment((ResolverBundle) bundleMapping.get(imports[i].getVersionConstraint().getBundle()), imports[i])); continue; } if (!developmentMode) { // fail fast; otherwise we want to attempt to resolver other constraints in dev mode failed = true; break; } } } } // check that fragment constraints are met by the constraints that got resolved to the host checkFragmentConstraints(bundle); // do some extra checking when in development mode to see if other resolver error occurred if (developmentMode && !failed && state.getResolverErrors(bundle.getBundle()).length > 0) failed = true; // Need to check that all mandatory imports are wired. If they are then // set the bundle RESOLVED, otherwise set it back to UNRESOLVED if (failed) { setBundleUnresolved(bundle, false, developmentMode); if (DEBUG) ResolverImpl.log(bundle + " NOT RESOLVED"); //$NON-NLS-1$ } else if (!cycle.contains(bundle)) { setBundleResolved(bundle); if (DEBUG) ResolverImpl.log(bundle + " RESOLVED"); //$NON-NLS-1$ } if (bundle.getState() == ResolverBundle.UNRESOLVED) bundle.setResolvable(false); // Set it to unresolvable so we don't attempt to resolve it again in this round return bundle.getState() != ResolverBundle.UNRESOLVED; }
diff --git a/Slick/src/org/newdawn/slick/BigImage.java b/Slick/src/org/newdawn/slick/BigImage.java index 6be7792..60e60b3 100644 --- a/Slick/src/org/newdawn/slick/BigImage.java +++ b/Slick/src/org/newdawn/slick/BigImage.java @@ -1,768 +1,768 @@ package org.newdawn.slick; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.IntBuffer; import org.lwjgl.BufferUtils; import org.newdawn.slick.opengl.ImageData; import org.newdawn.slick.opengl.ImageDataFactory; import org.newdawn.slick.opengl.LoadableImageData; import org.newdawn.slick.opengl.Texture; import org.newdawn.slick.opengl.renderer.SGL; import org.newdawn.slick.opengl.renderer.Renderer; import org.newdawn.slick.util.OperationNotSupportedException; import org.newdawn.slick.util.ResourceLoader; /** * An image implementation that handles loaded images that are larger than the * maximum texture size supported by the card. In most cases it makes sense * to make sure all of your image resources are less than 512x512 in size when * using OpenGL. However, in the rare circumstances where this isn't possible * this implementation can be used to draw a tiled version of the image built * from several smaller textures. * * This implementation does come with limitations and some performance impact * however - so use only when absolutely required. * * TODO: The code in here isn't pretty, really needs revisiting with a comment stick. * * @author kevin */ public class BigImage extends Image { /** The renderer to use for all GL operations */ protected static SGL GL = Renderer.get(); /** * Get the maximum size of an image supported by the underlying * hardware. * * @return The maximum size of the textures supported by the underlying * hardware. */ public static final int getMaxSingleImageSize() { IntBuffer buffer = BufferUtils.createIntBuffer(16); GL.glGetInteger(SGL.GL_MAX_TEXTURE_SIZE, buffer); return buffer.get(0); } /** The last image that we put into "in use" mode */ private static Image lastBind; /** The images building up this sub-image */ private Image[][] images; /** The number of images on the xaxis */ private int xcount; /** The number of images on the yaxis */ private int ycount; /** The real width of the whole image - maintained even when scaled */ private int realWidth; /** The real hieght of the whole image - maintained even when scaled */ private int realHeight; /** * Create a new big image. Empty contructor for cloning only */ private BigImage() { inited = true; } /** * Create a new big image by loading it from the specified reference * * @param ref The reference to the image to load * @throws SlickException Indicates we were unable to locate the resource */ public BigImage(String ref) throws SlickException { this(ref, Image.FILTER_NEAREST); } /** * Create a new big image by loading it from the specified reference * * @param ref The reference to the image to load * @param filter The image filter to apply (@see #Image.FILTER_NEAREST) * @throws SlickException Indicates we were unable to locate the resource */ public BigImage(String ref,int filter) throws SlickException { build(ref, filter, getMaxSingleImageSize()); } /** * Create a new big image by loading it from the specified reference * * @param ref The reference to the image to load * @param filter The image filter to apply (@see #Image.FILTER_NEAREST) * @param tileSize The maximum size of the tiles to use to build the bigger image * @throws SlickException Indicates we were unable to locate the resource */ public BigImage(String ref, int filter, int tileSize) throws SlickException { build(ref, filter, tileSize); } /** * Create a new big image by loading it from the specified image data * * @param data The pixelData to use to create the image * @param imageBuffer The buffer containing texture data * @param filter The image filter to apply (@see #Image.FILTER_NEAREST) */ public BigImage(LoadableImageData data, ByteBuffer imageBuffer, int filter) { build(data, imageBuffer, filter, getMaxSingleImageSize()); } /** * Create a new big image by loading it from the specified image data * * @param data The pixelData to use to create the image * @param imageBuffer The buffer containing texture data * @param filter The image filter to apply (@see #Image.FILTER_NEAREST) * @param tileSize The maximum size of the tiles to use to build the bigger image */ public BigImage(LoadableImageData data, ByteBuffer imageBuffer, int filter, int tileSize) { build(data, imageBuffer, filter, tileSize); } /** * Get a sub tile of this big image. Useful for debugging * * @param x The x tile index * @param y The y tile index * @return The image used for this tile */ public Image getTile(int x, int y) { return images[x][y]; } /** * Create a new big image by loading it from the specified reference * * @param ref The reference to the image to load * @param filter The image filter to apply (@see #Image.FILTER_NEAREST) * @param tileSize The maximum size of the tiles to use to build the bigger image * @throws SlickException Indicates we were unable to locate the resource */ private void build(String ref, int filter, int tileSize) throws SlickException { try { final LoadableImageData data = ImageDataFactory.getImageDataFor(ref); final ByteBuffer imageBuffer = data.loadImage(ResourceLoader.getResourceAsStream(ref), false, null); build(data, imageBuffer, filter, tileSize); } catch (IOException e) { throw new SlickException("Failed to load: "+ref, e); } } /** * Create an big image from a image data source. * * @param data The pixelData to use to create the image * @param imageBuffer The buffer containing texture data * @param filter The filter to use when scaling this image * @param tileSize The maximum size of the tiles to use to build the bigger image */ private void build(final LoadableImageData data, final ByteBuffer imageBuffer, int filter, int tileSize) { final int dataWidth = data.getTexWidth(); final int dataHeight = data.getTexHeight(); realWidth = width = data.getWidth(); realHeight = height = data.getHeight(); if ((dataWidth <= tileSize) && (dataHeight <= tileSize)) { images = new Image[1][1]; ImageData tempData = new ImageData() { public int getDepth() { return data.getDepth(); } public int getHeight() { return dataHeight; } public ByteBuffer getImageBufferData() { return imageBuffer; } public int getTexHeight() { return dataHeight; } public int getTexWidth() { return dataWidth; } public int getWidth() { return dataWidth; } }; images[0][0] = new Image(tempData, filter); xcount = 1; ycount = 1; inited = true; return; } xcount = ((realWidth-1) / tileSize) + 1; ycount = ((realHeight-1) / tileSize) + 1; images = new Image[xcount][ycount]; int components = data.getDepth() / 8; for (int x=0;x<xcount;x++) { for (int y=0;y<ycount;y++) { int finalX = ((x+1) * tileSize); int finalY = ((y+1) * tileSize); - final int imageWidth = realWidth < finalX ? realWidth % tileSize : tileSize; - final int imageHeight = realHeight < finalY ? realHeight % tileSize : tileSize; + final int imageWidth = tileSize; + final int imageHeight = tileSize; final int xSize = imageWidth; final int ySize = imageHeight; final ByteBuffer subBuffer = BufferUtils.createByteBuffer(tileSize*tileSize*components); int xo = x*tileSize*components; byte[] byteData = new byte[xSize*components]; for (int i=0;i<ySize;i++) { int yo = (((y * tileSize) + i) * dataWidth) * components; imageBuffer.position(yo+xo); imageBuffer.get(byteData, 0, xSize*components); subBuffer.put(byteData); } subBuffer.flip(); ImageData imgData = new ImageData() { public int getDepth() { return data.getDepth(); } public int getHeight() { return imageHeight; } public int getWidth() { return imageWidth; } public ByteBuffer getImageBufferData() { return subBuffer; } public int getTexHeight() { return ySize; } public int getTexWidth() { return xSize; } }; images[x][y] = new Image(imgData, filter); } } inited = true; } /** * Not supported in BigImage * * @see org.newdawn.slick.Image#bind() */ public void bind() { throw new OperationNotSupportedException("Can't bind big images yet"); } /** * Not supported in BigImage * * @see org.newdawn.slick.Image#copy() */ public Image copy() { throw new OperationNotSupportedException("Can't copy big images yet"); } /** * @see org.newdawn.slick.Image#draw() */ public void draw() { draw(0,0); } /** * @see org.newdawn.slick.Image#draw(float, float, org.newdawn.slick.Color) */ public void draw(float x, float y, Color filter) { draw(x,y,width,height,filter); } /** * @see org.newdawn.slick.Image#draw(float, float, float, org.newdawn.slick.Color) */ public void draw(float x, float y, float scale, Color filter) { draw(x,y,width*scale,height*scale,filter); } /** * @see org.newdawn.slick.Image#draw(float, float, float, float, org.newdawn.slick.Color) */ public void draw(float x, float y, float width, float height, Color filter) { float sx = width / realWidth; float sy = height / realHeight; GL.glTranslatef(x,y,0); GL.glScalef(sx,sy,1); float xp = 0; float yp = 0; for (int tx=0;tx<xcount;tx++) { yp = 0; for (int ty=0;ty<ycount;ty++) { Image image = images[tx][ty]; image.draw(xp,yp,image.getWidth(), image.getHeight(), filter); yp += image.getHeight(); if (ty == ycount - 1) { xp += image.getWidth(); } } } GL.glScalef(1.0f/sx,1.0f/sy,1); GL.glTranslatef(-x,-y,0); } /** * @see org.newdawn.slick.Image#draw(float, float, float, float, float, float, float, float) */ public void draw(float x, float y, float x2, float y2, float srcx, float srcy, float srcx2, float srcy2) { int srcwidth = (int) (srcx2 - srcx); int srcheight = (int) (srcy2 - srcy); Image subImage = getSubImage((int) srcx,(int) srcy,srcwidth,srcheight); int width = (int) (x2 - x); int height = (int) (y2 - y); subImage.draw(x,y,width,height); } /** * @see org.newdawn.slick.Image#draw(float, float, float, float, float, float) */ public void draw(float x, float y, float srcx, float srcy, float srcx2, float srcy2) { int srcwidth = (int) (srcx2 - srcx); int srcheight = (int) (srcy2 - srcy); draw(x,y,srcwidth,srcheight,srcx,srcy,srcx2,srcy2); } /** * @see org.newdawn.slick.Image#draw(float, float, float, float) */ public void draw(float x, float y, float width, float height) { draw(x,y,width,height,Color.white); } /** * @see org.newdawn.slick.Image#draw(float, float, float) */ public void draw(float x, float y, float scale) { draw(x,y,scale,Color.white); } /** * @see org.newdawn.slick.Image#draw(float, float) */ public void draw(float x, float y) { draw(x,y,Color.white); } /** * @see org.newdawn.slick.Image#drawEmbedded(float, float, float, float) */ public void drawEmbedded(float x, float y, float width, float height) { float sx = width / realWidth; float sy = height / realHeight; float xp = 0; float yp = 0; for (int tx=0;tx<xcount;tx++) { yp = 0; for (int ty=0;ty<ycount;ty++) { Image image = images[tx][ty]; if ((lastBind == null) || (image.getTexture() != lastBind.getTexture())) { if (lastBind != null) { lastBind.endUse(); } lastBind = image; lastBind.startUse(); } image.drawEmbedded(xp+x,yp+y,image.getWidth(), image.getHeight()); yp += image.getHeight(); if (ty == ycount - 1) { xp += image.getWidth(); } } } } /** * @see org.newdawn.slick.Image#drawFlash(float, float, float, float) */ public void drawFlash(float x, float y, float width, float height) { float sx = width / realWidth; float sy = height / realHeight; GL.glTranslatef(x,y,0); GL.glScalef(sx,sy,1); float xp = 0; float yp = 0; for (int tx=0;tx<xcount;tx++) { yp = 0; for (int ty=0;ty<ycount;ty++) { Image image = images[tx][ty]; image.drawFlash(xp,yp,image.getWidth(), image.getHeight()); yp += image.getHeight(); if (ty == ycount - 1) { xp += image.getWidth(); } } } GL.glScalef(1.0f/sx,1.0f/sy,1); GL.glTranslatef(-x,-y,0); } /** * @see org.newdawn.slick.Image#drawFlash(float, float) */ public void drawFlash(float x, float y) { drawFlash(x,y,width,height); } /** * Not supported in BigImage * * @see org.newdawn.slick.Image#endUse() */ public void endUse() { if (lastBind != null) { lastBind.endUse(); } lastBind = null; } /** * Not supported in BigImage * * @see org.newdawn.slick.Image#startUse() */ public void startUse() { } /** * Not supported in BigImage * * @see org.newdawn.slick.Image#ensureInverted() */ public void ensureInverted() { throw new OperationNotSupportedException("Doesn't make sense for tiled operations"); } /** * Not supported in BigImage * * @see org.newdawn.slick.Image#getColor(int, int) */ public Color getColor(int x, int y) { throw new OperationNotSupportedException("Can't use big images as buffers"); } /** * @see org.newdawn.slick.Image#getFlippedCopy(boolean, boolean) */ public Image getFlippedCopy(boolean flipHorizontal, boolean flipVertical) { BigImage image = new BigImage(); image.images = images; image.xcount = xcount; image.ycount = ycount; image.width = width; image.height = height; image.realWidth = realWidth; image.realHeight = realHeight; if (flipHorizontal) { Image[][] images = image.images; image.images = new Image[xcount][ycount]; for (int x=0;x<xcount;x++) { for (int y=0;y<ycount;y++) { image.images[x][y] = images[xcount-1-x][y].getFlippedCopy(true, false); } } } if (flipVertical) { Image[][] images = image.images; image.images = new Image[xcount][ycount]; for (int x=0;x<xcount;x++) { for (int y=0;y<ycount;y++) { image.images[x][y] = images[x][ycount-1-y].getFlippedCopy(false, true); } } } return image; } /** * Not supported in BigImage * * @see org.newdawn.slick.Image#getGraphics() */ public Graphics getGraphics() throws SlickException { throw new OperationNotSupportedException("Can't use big images as offscreen buffers"); } /** * @see org.newdawn.slick.Image#getScaledCopy(float) */ public Image getScaledCopy(float scale) { return getScaledCopy((int) (scale * width), (int) (scale * height)); } /** * @see org.newdawn.slick.Image#getScaledCopy(int, int) */ public Image getScaledCopy(int width, int height) { BigImage image = new BigImage(); image.images = images; image.xcount = xcount; image.ycount = ycount; image.width = width; image.height = height; image.realWidth = realWidth; image.realHeight = realHeight; return image; } /** * @see org.newdawn.slick.Image#getSubImage(int, int, int, int) */ public Image getSubImage(int x, int y, int width, int height) { BigImage image = new BigImage(); image.width = width; image.height = height; image.realWidth = width; image.realHeight = height; image.images = new Image[this.xcount][this.ycount]; float xp = 0; float yp = 0; int x2 = x+width; int y2 = y+height; int startx = 0; int starty = 0; boolean foundStart = false; for (int xt=0;xt<xcount;xt++) { yp = 0; starty = 0; foundStart = false; for (int yt=0;yt<ycount;yt++) { Image current = images[xt][yt]; int xp2 = (int) (xp + current.getWidth()); int yp2 = (int) (yp + current.getHeight()); // if the top corner of the subimage is inside the area // we want or the bottom corrent of the image is, then consider using the // image // this image contributes to the sub image we're attempt to retrieve int targetX1 = (int) Math.max(x, xp); int targetY1 = (int) Math.max(y, yp); int targetX2 = Math.min(x2, xp2); int targetY2 = Math.min(y2, yp2); int targetWidth = targetX2 - targetX1; int targetHeight = targetY2 - targetY1; if ((targetWidth > 0) && (targetHeight > 0)) { Image subImage = current.getSubImage((int) (targetX1 - xp), (int) (targetY1 - yp), (targetX2 - targetX1), (targetY2 - targetY1)); foundStart = true; image.images[startx][starty] = subImage; starty++; image.ycount = Math.max(image.ycount, starty); } yp += current.getHeight(); if (yt == ycount - 1) { xp += current.getWidth(); } } if (foundStart) { startx++; image.xcount++; } } return image; } /** * Not supported in BigImage * * @see org.newdawn.slick.Image#getTexture() */ public Texture getTexture() { throw new OperationNotSupportedException("Can't use big images as offscreen buffers"); } /** * @see org.newdawn.slick.Image#initImpl() */ protected void initImpl() { throw new OperationNotSupportedException("Can't use big images as offscreen buffers"); } /** * @see org.newdawn.slick.Image#reinit() */ protected void reinit() { throw new OperationNotSupportedException("Can't use big images as offscreen buffers"); } /** * Not supported in BigImage * * @see org.newdawn.slick.Image#setTexture(org.newdawn.slick.opengl.Texture) */ public void setTexture(Texture texture) { throw new OperationNotSupportedException("Can't use big images as offscreen buffers"); } /** * Get a sub-image that builds up this image. Note that the offsets * used will depend on the maximum texture size on the OpenGL hardware * * @param offsetX The x position of the image to return * @param offsetY The y position of the image to return * @return The image at the specified offset into the big image */ public Image getSubImage(int offsetX, int offsetY) { return images[offsetX][offsetY]; } /** * Get a count of the number images that build this image up horizontally * * @return The number of sub-images across the big image */ public int getHorizontalImageCount() { return xcount; } /** * Get a count of the number images that build this image up vertically * * @return The number of sub-images down the big image */ public int getVerticalImageCount() { return ycount; } /** * @see org.newdawn.slick.Image#toString() */ public String toString() { return "[BIG IMAGE]"; } /** * Destroy the image and release any native resources. * Calls on a destroyed image have undefined results */ public void destroy() throws SlickException { for (int tx=0;tx<xcount;tx++) { for (int ty=0;ty<ycount;ty++) { Image image = images[tx][ty]; image.destroy(); } } } /** * @see org.newdawn.slick.Image#draw(float, float, float, float, float, float, float, float, org.newdawn.slick.Color) */ public void draw(float x, float y, float x2, float y2, float srcx, float srcy, float srcx2, float srcy2, Color filter) { int srcwidth = (int) (srcx2 - srcx); int srcheight = (int) (srcy2 - srcy); Image subImage = getSubImage((int) srcx,(int) srcy,srcwidth,srcheight); int width = (int) (x2 - x); int height = (int) (y2 - y); subImage.draw(x,y,width,height,filter); } /** * @see org.newdawn.slick.Image#drawCentered(float, float) */ public void drawCentered(float x, float y) { throw new UnsupportedOperationException(); } /** * @see org.newdawn.slick.Image#drawEmbedded(float, float, float, float, float, float, float, float, org.newdawn.slick.Color) */ public void drawEmbedded(float x, float y, float x2, float y2, float srcx, float srcy, float srcx2, float srcy2, Color filter) { throw new UnsupportedOperationException(); } /** * @see org.newdawn.slick.Image#drawEmbedded(float, float, float, float, float, float, float, float) */ public void drawEmbedded(float x, float y, float x2, float y2, float srcx, float srcy, float srcx2, float srcy2) { throw new UnsupportedOperationException(); } /** * @see org.newdawn.slick.Image#drawFlash(float, float, float, float, org.newdawn.slick.Color) */ public void drawFlash(float x, float y, float width, float height, Color col) { throw new UnsupportedOperationException(); } /** * @see org.newdawn.slick.Image#drawSheared(float, float, float, float) */ public void drawSheared(float x, float y, float hshear, float vshear) { throw new UnsupportedOperationException(); } }
true
true
private void build(final LoadableImageData data, final ByteBuffer imageBuffer, int filter, int tileSize) { final int dataWidth = data.getTexWidth(); final int dataHeight = data.getTexHeight(); realWidth = width = data.getWidth(); realHeight = height = data.getHeight(); if ((dataWidth <= tileSize) && (dataHeight <= tileSize)) { images = new Image[1][1]; ImageData tempData = new ImageData() { public int getDepth() { return data.getDepth(); } public int getHeight() { return dataHeight; } public ByteBuffer getImageBufferData() { return imageBuffer; } public int getTexHeight() { return dataHeight; } public int getTexWidth() { return dataWidth; } public int getWidth() { return dataWidth; } }; images[0][0] = new Image(tempData, filter); xcount = 1; ycount = 1; inited = true; return; } xcount = ((realWidth-1) / tileSize) + 1; ycount = ((realHeight-1) / tileSize) + 1; images = new Image[xcount][ycount]; int components = data.getDepth() / 8; for (int x=0;x<xcount;x++) { for (int y=0;y<ycount;y++) { int finalX = ((x+1) * tileSize); int finalY = ((y+1) * tileSize); final int imageWidth = realWidth < finalX ? realWidth % tileSize : tileSize; final int imageHeight = realHeight < finalY ? realHeight % tileSize : tileSize; final int xSize = imageWidth; final int ySize = imageHeight; final ByteBuffer subBuffer = BufferUtils.createByteBuffer(tileSize*tileSize*components); int xo = x*tileSize*components; byte[] byteData = new byte[xSize*components]; for (int i=0;i<ySize;i++) { int yo = (((y * tileSize) + i) * dataWidth) * components; imageBuffer.position(yo+xo); imageBuffer.get(byteData, 0, xSize*components); subBuffer.put(byteData); } subBuffer.flip(); ImageData imgData = new ImageData() { public int getDepth() { return data.getDepth(); } public int getHeight() { return imageHeight; } public int getWidth() { return imageWidth; } public ByteBuffer getImageBufferData() { return subBuffer; } public int getTexHeight() { return ySize; } public int getTexWidth() { return xSize; } }; images[x][y] = new Image(imgData, filter); } } inited = true; }
private void build(final LoadableImageData data, final ByteBuffer imageBuffer, int filter, int tileSize) { final int dataWidth = data.getTexWidth(); final int dataHeight = data.getTexHeight(); realWidth = width = data.getWidth(); realHeight = height = data.getHeight(); if ((dataWidth <= tileSize) && (dataHeight <= tileSize)) { images = new Image[1][1]; ImageData tempData = new ImageData() { public int getDepth() { return data.getDepth(); } public int getHeight() { return dataHeight; } public ByteBuffer getImageBufferData() { return imageBuffer; } public int getTexHeight() { return dataHeight; } public int getTexWidth() { return dataWidth; } public int getWidth() { return dataWidth; } }; images[0][0] = new Image(tempData, filter); xcount = 1; ycount = 1; inited = true; return; } xcount = ((realWidth-1) / tileSize) + 1; ycount = ((realHeight-1) / tileSize) + 1; images = new Image[xcount][ycount]; int components = data.getDepth() / 8; for (int x=0;x<xcount;x++) { for (int y=0;y<ycount;y++) { int finalX = ((x+1) * tileSize); int finalY = ((y+1) * tileSize); final int imageWidth = tileSize; final int imageHeight = tileSize; final int xSize = imageWidth; final int ySize = imageHeight; final ByteBuffer subBuffer = BufferUtils.createByteBuffer(tileSize*tileSize*components); int xo = x*tileSize*components; byte[] byteData = new byte[xSize*components]; for (int i=0;i<ySize;i++) { int yo = (((y * tileSize) + i) * dataWidth) * components; imageBuffer.position(yo+xo); imageBuffer.get(byteData, 0, xSize*components); subBuffer.put(byteData); } subBuffer.flip(); ImageData imgData = new ImageData() { public int getDepth() { return data.getDepth(); } public int getHeight() { return imageHeight; } public int getWidth() { return imageWidth; } public ByteBuffer getImageBufferData() { return subBuffer; } public int getTexHeight() { return ySize; } public int getTexWidth() { return xSize; } }; images[x][y] = new Image(imgData, filter); } } inited = true; }
diff --git a/src/com/lala/wordrank/WordRank.java b/src/com/lala/wordrank/WordRank.java index aef48e3..b6c79f7 100644 --- a/src/com/lala/wordrank/WordRank.java +++ b/src/com/lala/wordrank/WordRank.java @@ -1,41 +1,39 @@ package com.lala.wordrank; import java.io.File; import org.bukkit.event.Event.Priority; import org.bukkit.event.Event.Type; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import com.nijiko.permissions.PermissionHandler; import com.nijikokun.bukkit.Permissions.Permissions; public class WordRank extends JavaPlugin{ public static PermissionHandler permissionHandler; public static File data; private final W w = new W(this); public void onEnable(){ data = getDataFolder(); getServer().getPluginManager().registerEvent(Type.PLAYER_CHAT, new Chat(this), Priority.Normal, this); Config.loadPluginSettings(); getCommand("w").setExecutor(w); setupPermissions(); System.out.println("[WordRank] Enabled!"); } public void onDisable(){ System.out.println("[WordRank] Disabled!"); } private void setupPermissions() { if (permissionHandler != null) { return; } Plugin permissionsPlugin = this.getServer().getPluginManager().getPlugin("Permissions"); if (permissionsPlugin == null) { - System.out.println("Permissions not detected, disabling WordRank!"); - Plugin plugin = this.getServer().getPluginManager().getPlugin("WordRank"); - this.getServer().getPluginManager().disablePlugin(plugin); + System.out.println("Permissions not detected, expect errors!"); return; } permissionHandler = ((Permissions) permissionsPlugin).getHandler(); } }
true
true
private void setupPermissions() { if (permissionHandler != null) { return; } Plugin permissionsPlugin = this.getServer().getPluginManager().getPlugin("Permissions"); if (permissionsPlugin == null) { System.out.println("Permissions not detected, disabling WordRank!"); Plugin plugin = this.getServer().getPluginManager().getPlugin("WordRank"); this.getServer().getPluginManager().disablePlugin(plugin); return; } permissionHandler = ((Permissions) permissionsPlugin).getHandler(); }
private void setupPermissions() { if (permissionHandler != null) { return; } Plugin permissionsPlugin = this.getServer().getPluginManager().getPlugin("Permissions"); if (permissionsPlugin == null) { System.out.println("Permissions not detected, expect errors!"); return; } permissionHandler = ((Permissions) permissionsPlugin).getHandler(); }
diff --git a/src/main/java/com/almuramc/helprequest/RequestGUI.java b/src/main/java/com/almuramc/helprequest/RequestGUI.java index f5659a9..755d56b 100644 --- a/src/main/java/com/almuramc/helprequest/RequestGUI.java +++ b/src/main/java/com/almuramc/helprequest/RequestGUI.java @@ -1,215 +1,215 @@ package com.almuramc.helprequest; import com.almuramc.helprequest.customs.DirectionButton; import com.almuramc.helprequest.customs.FixedTextField; import com.almuramc.helprequest.customs.NSButton; import com.almuramc.helprequest.customs.StateButton; import java.util.List; import org.getspout.spoutapi.gui.GenericButton; import org.getspout.spoutapi.gui.GenericLabel; import org.getspout.spoutapi.gui.GenericPopup; import org.getspout.spoutapi.gui.GenericTextField; import org.getspout.spoutapi.gui.WidgetAnchor; import org.getspout.spoutapi.player.SpoutPlayer; public class RequestGUI extends GenericPopup { private List<FilledRequest> isDisplaying; private int state, currentOne; private GenericTextField title = new FixedTextField(); private GenericTextField description = new FixedTextField(); private GenericLabel time = new GenericLabel(), location = new GenericLabel(), username = new GenericLabel(); private GenericButton dname = new StateButton(this); private GenericButton ns = new NSButton(this); private HelpRequest main; private SpoutPlayer player; private boolean inNewMode; public RequestGUI(HelpRequest main, SpoutPlayer who) { super(); //Get which requests the opened window should show this.main = main; player = who; state = 0; inNewMode = false; //Create the widgets which are there every time GenericLabel usernameL = new GenericLabel("Username: "); GenericLabel timeL = new GenericLabel("Time: "); GenericLabel locationL = new GenericLabel("Location: "); GenericLabel titleL = new GenericLabel("Title: "); GenericLabel descriptionL = new GenericLabel("Description: "); DirectionButton next = new DirectionButton(this, 1, ">"); DirectionButton prev = new DirectionButton(this, -1, "<"); DirectionButton close = new DirectionButton(this, 0, "Close"); usernameL.setHeight(15).setWidth(GenericLabel.getStringWidth(usernameL.getText())); usernameL.setAnchor(WidgetAnchor.TOP_LEFT); usernameL.shiftXPos(30).shiftYPos(10); timeL.setHeight(15).setWidth(GenericLabel.getStringWidth(timeL.getText())); timeL.setAnchor(WidgetAnchor.TOP_LEFT); timeL.shiftXPos(30).shiftYPos(25); locationL.setHeight(15).setWidth(GenericLabel.getStringWidth(locationL.getText())); locationL.setAnchor(WidgetAnchor.TOP_LEFT); locationL.shiftXPos(30).shiftYPos(40); titleL.setHeight(15).setWidth(GenericLabel.getStringWidth(titleL.getText())); titleL.setAnchor(WidgetAnchor.TOP_LEFT); titleL.shiftXPos(30).shiftYPos(55); descriptionL.setHeight(15).setWidth(GenericLabel.getStringWidth(descriptionL.getText())); descriptionL.setAnchor(WidgetAnchor.CENTER_LEFT); descriptionL.shiftXPos(30).shiftYPos(-35); username.setHeight(15).setWidth(80); username.setAnchor(WidgetAnchor.TOP_LEFT); username.shiftXPos(100).shiftYPos(10); time.setHeight(15).setWidth(80); time.setAnchor(WidgetAnchor.TOP_LEFT); time.shiftXPos(100).shiftYPos(25); location.setHeight(15).setWidth(80); location.setAnchor(WidgetAnchor.TOP_LEFT); location.shiftXPos(100).shiftYPos(40); title.setHeight(15).setWidth(80); title.setAnchor(WidgetAnchor.TOP_LEFT); title.shiftXPos(100).shiftYPos(55); - description.setMaximumLines(7); + description.setMaximumLines(9); description.setMaximumCharacters(1000); description.setHeight(110).setWidth(300); description.setAnchor(WidgetAnchor.CENTER_LEFT); description.shiftXPos(100).shiftYPos(-35); dname.setHeight(15).setWidth(100); dname.setAnchor(WidgetAnchor.TOP_CENTER); dname.shiftXPos(60).shiftYPos(10); ns.setHeight(15).setWidth(50); ns.setAnchor(WidgetAnchor.BOTTOM_CENTER); ns.shiftXPos(-140).shiftYPos(-45); prev.setHeight(15).setWidth(15); prev.setAnchor(WidgetAnchor.BOTTOM_CENTER); prev.shiftXPos(-80).shiftYPos(-45); next.setHeight(15).setWidth(15); next.setAnchor(WidgetAnchor.BOTTOM_CENTER); next.shiftXPos(-60).shiftYPos(-45); close.setHeight(15).setWidth(50); close.setAnchor(WidgetAnchor.BOTTOM_CENTER); close.shiftXPos(-40).shiftYPos(-45); attachWidget(main, usernameL).attachWidget(main, timeL).attachWidget(main, titleL).attachWidget(main, locationL).attachWidget(main, titleL).attachWidget(main, descriptionL); attachWidget(main, username).attachWidget(main, time).attachWidget(main, location).attachWidget(main, title).attachWidget(main, description); attachWidget(main, dname); attachWidget(main, ns); attachWidget(main, close); attachWidget(main, next).attachWidget(main, prev); refreshForState(); who.getMainScreen().attachPopupScreen(this); } private void refreshForState() { isDisplaying = main.getRequestsFor(player.getName(), state); switch (state) { case 0: dname.setText("Opened requests"); dname.setDirty(true); break; case 1: dname.setText("Closed requests"); dname.setDirty(true); break; case 2: dname.setText("Help requests"); dname.setDirty(true); break; } currentOne = 0; time.setText(""); location.setText("").setDirty(true); username.setText("").setDirty(true); title.setText("").setPlaceholder("").setDirty(true); description.setText("").setPlaceholder("").setDirty(true); if(!(isDisplaying.isEmpty())) { updateCurrentPage(); } } public void updateCurrentPage() { FilledRequest current = isDisplaying.get(currentOne); time.setText(current.getTime()); location.setText(current.getLocation()); username.setText(current.getUsername()); title.setText(current.getTitle()); description.setText(current.getDescription()); inNewMode = false; ns.setText("Create").setDirty(true); } public void onStateChange() { state++; if (state == 3) { state = 0; } if (state == 2 && !player.hasPermission("helprequest.moderate")) { state = 0; } refreshForState(); } public void onNS() { if(inNewMode) { //Saving inNewMode = false; FilledRequest fr = new FilledRequest(title.getText(), description.getText(), player); main.addRequest(fr); refreshForState(); } else { //Free stuff, get ready for editing time.setText(""); location.setText(""); username.setText(""); title.setText("").setPlaceholder("Title here"); description.setText("").setPlaceholder("Description here"); inNewMode = true; } } public void onDirection(int dir) { if(dir == -1) { currentOne--; if(currentOne == -1) { currentOne++; return; } else { updateCurrentPage(); } } if(dir == 0 && state != 1 && !isDisplaying.isEmpty()) { FilledRequest fr = isDisplaying.get(currentOne); main.closeRequest(fr); refreshForState(); } if(dir == 1) { currentOne++; if(currentOne > isDisplaying.size() - 1) { currentOne--; return; } else { updateCurrentPage(); } } } }
true
true
public RequestGUI(HelpRequest main, SpoutPlayer who) { super(); //Get which requests the opened window should show this.main = main; player = who; state = 0; inNewMode = false; //Create the widgets which are there every time GenericLabel usernameL = new GenericLabel("Username: "); GenericLabel timeL = new GenericLabel("Time: "); GenericLabel locationL = new GenericLabel("Location: "); GenericLabel titleL = new GenericLabel("Title: "); GenericLabel descriptionL = new GenericLabel("Description: "); DirectionButton next = new DirectionButton(this, 1, ">"); DirectionButton prev = new DirectionButton(this, -1, "<"); DirectionButton close = new DirectionButton(this, 0, "Close"); usernameL.setHeight(15).setWidth(GenericLabel.getStringWidth(usernameL.getText())); usernameL.setAnchor(WidgetAnchor.TOP_LEFT); usernameL.shiftXPos(30).shiftYPos(10); timeL.setHeight(15).setWidth(GenericLabel.getStringWidth(timeL.getText())); timeL.setAnchor(WidgetAnchor.TOP_LEFT); timeL.shiftXPos(30).shiftYPos(25); locationL.setHeight(15).setWidth(GenericLabel.getStringWidth(locationL.getText())); locationL.setAnchor(WidgetAnchor.TOP_LEFT); locationL.shiftXPos(30).shiftYPos(40); titleL.setHeight(15).setWidth(GenericLabel.getStringWidth(titleL.getText())); titleL.setAnchor(WidgetAnchor.TOP_LEFT); titleL.shiftXPos(30).shiftYPos(55); descriptionL.setHeight(15).setWidth(GenericLabel.getStringWidth(descriptionL.getText())); descriptionL.setAnchor(WidgetAnchor.CENTER_LEFT); descriptionL.shiftXPos(30).shiftYPos(-35); username.setHeight(15).setWidth(80); username.setAnchor(WidgetAnchor.TOP_LEFT); username.shiftXPos(100).shiftYPos(10); time.setHeight(15).setWidth(80); time.setAnchor(WidgetAnchor.TOP_LEFT); time.shiftXPos(100).shiftYPos(25); location.setHeight(15).setWidth(80); location.setAnchor(WidgetAnchor.TOP_LEFT); location.shiftXPos(100).shiftYPos(40); title.setHeight(15).setWidth(80); title.setAnchor(WidgetAnchor.TOP_LEFT); title.shiftXPos(100).shiftYPos(55); description.setMaximumLines(7); description.setMaximumCharacters(1000); description.setHeight(110).setWidth(300); description.setAnchor(WidgetAnchor.CENTER_LEFT); description.shiftXPos(100).shiftYPos(-35); dname.setHeight(15).setWidth(100); dname.setAnchor(WidgetAnchor.TOP_CENTER); dname.shiftXPos(60).shiftYPos(10); ns.setHeight(15).setWidth(50); ns.setAnchor(WidgetAnchor.BOTTOM_CENTER); ns.shiftXPos(-140).shiftYPos(-45); prev.setHeight(15).setWidth(15); prev.setAnchor(WidgetAnchor.BOTTOM_CENTER); prev.shiftXPos(-80).shiftYPos(-45); next.setHeight(15).setWidth(15); next.setAnchor(WidgetAnchor.BOTTOM_CENTER); next.shiftXPos(-60).shiftYPos(-45); close.setHeight(15).setWidth(50); close.setAnchor(WidgetAnchor.BOTTOM_CENTER); close.shiftXPos(-40).shiftYPos(-45); attachWidget(main, usernameL).attachWidget(main, timeL).attachWidget(main, titleL).attachWidget(main, locationL).attachWidget(main, titleL).attachWidget(main, descriptionL); attachWidget(main, username).attachWidget(main, time).attachWidget(main, location).attachWidget(main, title).attachWidget(main, description); attachWidget(main, dname); attachWidget(main, ns); attachWidget(main, close); attachWidget(main, next).attachWidget(main, prev); refreshForState(); who.getMainScreen().attachPopupScreen(this); }
public RequestGUI(HelpRequest main, SpoutPlayer who) { super(); //Get which requests the opened window should show this.main = main; player = who; state = 0; inNewMode = false; //Create the widgets which are there every time GenericLabel usernameL = new GenericLabel("Username: "); GenericLabel timeL = new GenericLabel("Time: "); GenericLabel locationL = new GenericLabel("Location: "); GenericLabel titleL = new GenericLabel("Title: "); GenericLabel descriptionL = new GenericLabel("Description: "); DirectionButton next = new DirectionButton(this, 1, ">"); DirectionButton prev = new DirectionButton(this, -1, "<"); DirectionButton close = new DirectionButton(this, 0, "Close"); usernameL.setHeight(15).setWidth(GenericLabel.getStringWidth(usernameL.getText())); usernameL.setAnchor(WidgetAnchor.TOP_LEFT); usernameL.shiftXPos(30).shiftYPos(10); timeL.setHeight(15).setWidth(GenericLabel.getStringWidth(timeL.getText())); timeL.setAnchor(WidgetAnchor.TOP_LEFT); timeL.shiftXPos(30).shiftYPos(25); locationL.setHeight(15).setWidth(GenericLabel.getStringWidth(locationL.getText())); locationL.setAnchor(WidgetAnchor.TOP_LEFT); locationL.shiftXPos(30).shiftYPos(40); titleL.setHeight(15).setWidth(GenericLabel.getStringWidth(titleL.getText())); titleL.setAnchor(WidgetAnchor.TOP_LEFT); titleL.shiftXPos(30).shiftYPos(55); descriptionL.setHeight(15).setWidth(GenericLabel.getStringWidth(descriptionL.getText())); descriptionL.setAnchor(WidgetAnchor.CENTER_LEFT); descriptionL.shiftXPos(30).shiftYPos(-35); username.setHeight(15).setWidth(80); username.setAnchor(WidgetAnchor.TOP_LEFT); username.shiftXPos(100).shiftYPos(10); time.setHeight(15).setWidth(80); time.setAnchor(WidgetAnchor.TOP_LEFT); time.shiftXPos(100).shiftYPos(25); location.setHeight(15).setWidth(80); location.setAnchor(WidgetAnchor.TOP_LEFT); location.shiftXPos(100).shiftYPos(40); title.setHeight(15).setWidth(80); title.setAnchor(WidgetAnchor.TOP_LEFT); title.shiftXPos(100).shiftYPos(55); description.setMaximumLines(9); description.setMaximumCharacters(1000); description.setHeight(110).setWidth(300); description.setAnchor(WidgetAnchor.CENTER_LEFT); description.shiftXPos(100).shiftYPos(-35); dname.setHeight(15).setWidth(100); dname.setAnchor(WidgetAnchor.TOP_CENTER); dname.shiftXPos(60).shiftYPos(10); ns.setHeight(15).setWidth(50); ns.setAnchor(WidgetAnchor.BOTTOM_CENTER); ns.shiftXPos(-140).shiftYPos(-45); prev.setHeight(15).setWidth(15); prev.setAnchor(WidgetAnchor.BOTTOM_CENTER); prev.shiftXPos(-80).shiftYPos(-45); next.setHeight(15).setWidth(15); next.setAnchor(WidgetAnchor.BOTTOM_CENTER); next.shiftXPos(-60).shiftYPos(-45); close.setHeight(15).setWidth(50); close.setAnchor(WidgetAnchor.BOTTOM_CENTER); close.shiftXPos(-40).shiftYPos(-45); attachWidget(main, usernameL).attachWidget(main, timeL).attachWidget(main, titleL).attachWidget(main, locationL).attachWidget(main, titleL).attachWidget(main, descriptionL); attachWidget(main, username).attachWidget(main, time).attachWidget(main, location).attachWidget(main, title).attachWidget(main, description); attachWidget(main, dname); attachWidget(main, ns); attachWidget(main, close); attachWidget(main, next).attachWidget(main, prev); refreshForState(); who.getMainScreen().attachPopupScreen(this); }
diff --git a/Mastermind/src/com/example/mastermind/Game.java b/Mastermind/src/com/example/mastermind/Game.java index fc75851..ff07c81 100644 --- a/Mastermind/src/com/example/mastermind/Game.java +++ b/Mastermind/src/com/example/mastermind/Game.java @@ -1,240 +1,243 @@ package com.example.mastermind; import java.util.ArrayList; import java.util.Random; import android.app.Activity; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; public class Game { private Context context; private String[] colors = {"red", "orange", "yellow", "green", "blue", "violet", "blank"}; //private ArrayList<String> answer = new ArrayList<String>(); //private ArrayList<String> guesses = new ArrayList<String>(); private String[] answer; private String[] guesses; private Integer round = 0; private Integer choice = 0; private Result result = new Result(); private Boolean solved = false; private Boolean gameOver = false; private Boolean optionDup = false, optionBlank = false; private Integer numGuesses = 0, guessLength = 0; private ButtonColorManager bcm; public Game(Context context) { this.context = context; bcm = new ButtonColorManager(this.context); } public String[] getColors() { return colors; } public void setColors(String[] colors) { this.colors = colors; } public String[] getAnswer() { return answer; } public void setAnswer(String[] answer) { this.answer = answer; } public String[] getGuesses() { return guesses; } public void setGuesses(String[] guesses) { this.guesses = guesses; } public Integer getRound() { return round; } public void setRound(Integer round) { this.round = round; } public Integer getChoice() { return choice; } public void setChoice(Integer choice) { this.choice = choice; } public Result getResult() { return result; } public void setResult(Result result) { this.result = result; } public Boolean getSolved() { return solved; } public void setSolved(Boolean solved) { this.solved = solved; } public Boolean getGameOver() { return gameOver; } public void setGameOver(Boolean gameOver) { this.gameOver = gameOver; } // game utilities private int getRandomInt(Integer min, Integer max) { Random random = new Random(); int myInt = random.nextInt(max) + min; return myInt; //return Math.floor(Math.random() * (max - min + 1)) + min; } private void chooseAnswer(Boolean dup, Boolean blank) { ArrayList<Integer> available = new ArrayList<Integer>(); int max = (blank)? 7 : 6; for (int i=0;i<max;i++) { available.add(i); } int chosen; for (int i=0; i<guessLength; i++) { chosen = getRandomInt(1, available.size()); int indexToGet = available.get(chosen-1); this.answer[i] = this.colors[indexToGet]; if (!dup) { //available.splice(chosen-1, 1); available.remove(chosen-1); } } } public void startGame(Integer numGuesses, Integer guessLength, Integer numChoices, Boolean allowDupes, Boolean allowBlanks) { this.numGuesses = numGuesses; this.guessLength = guessLength; this.optionDup = allowDupes; this.optionBlank = allowBlanks; this.round = 0; this.choice = 0; this.answer = new String[guessLength]; this.guesses = new String[guessLength]; chooseAnswer(optionDup, optionBlank); clearHints(); this.solved = false; this.gameOver = false; this.result = new Result(); } private void clearHints() { // TODO Hmmm, need a hint class? } public void nextRound() { if (solved || gameOver) { return; } else { //increment the round this.round += 1; //display the next round (happens in gameactivity on submit currently //reset some variables this.choice = 0; // initialize the guesses for (int i=0; i<guessLength; i++) { this.guesses[i] = ""; } this.result = new Result(); clearHints(); } } // this is for apk<11 // TODO for now, infer that the first available position is what they want to populate public void userChoice(Integer colorViewId, ViewGroup currentGuessRow) { if (solved || gameOver) { // Button to play again Toast.makeText(context, "Game over. Play again?", Toast.LENGTH_LONG).show(); } else if (choice>=guessLength) { Toast.makeText(context, "You've filled up your guess. Hit the submit button.", Toast.LENGTH_LONG).show(); } else { // we always allow duplicates in the guesses clearHints(); // TODO any way to get this on evaluate? String colorName = bcm.getColorNameFromViewId(colorViewId); guesses[choice] = colorName; // put that color in the current guess position (choice) View currentChoice = currentGuessRow.getChildAt(choice); int colorId = bcm.getColorIdFromViewId(colorViewId); bcm.setBackground(currentChoice, colorId); // increment the choice choice += 1; } } // this is for apk>=11 public void userChoice(Integer colorViewId, Integer guessPositionId) { if (solved || gameOver) { // Button to play again Toast.makeText(context, "Game over. Play again?", Toast.LENGTH_LONG).show(); } else if (choice>=guessLength) { Toast.makeText(context, "You've filled up your guess. Hit the submit button.", Toast.LENGTH_LONG).show(); } else { // we always allow duplicates in the guesses clearHints(); String colorName = bcm.getColorNameFromViewId(colorViewId); GameActivity parent = (GameActivity) context; int i; for (i=1; i<=guessLength;i++) { ViewGroup guessRow = (ViewGroup) parent.findViewById(R.id.game_guessRow1); if (guessPositionId == guessRow.getChildAt(i-1).getId()) { break; } } int guessPosition = i-1; guesses[guessPosition] = colorName; choice += 1; } } public void evaluate() { int i, j, k; String[] answerCopy = answer.clone(); clearHints(); if (solved||gameOver) { //shouldn't happen because submit button should disappear return; } // process all the possible blacks first for (i=answerCopy.length; i>0; i--) { if (guesses[i-1] == answerCopy[i-1]) { result.setBlack(result.getBlack()+1); guesses[i-1] = ""; answerCopy[i-1] = ""; } } // then process any remaining whites for (j = guessLength - result.getBlack(); j>0; j--) { String colorToFind = guesses[j-1]; + if (colorToFind == "") { + continue; + } for (k=0; k<answerCopy.length; k++) { if (answerCopy[k] == colorToFind) { result.setWhite(result.getWhite()+1); // don't mess up the position of answers, just replace match with "" answerCopy[k] = ""; break; } } } } }
true
true
public void evaluate() { int i, j, k; String[] answerCopy = answer.clone(); clearHints(); if (solved||gameOver) { //shouldn't happen because submit button should disappear return; } // process all the possible blacks first for (i=answerCopy.length; i>0; i--) { if (guesses[i-1] == answerCopy[i-1]) { result.setBlack(result.getBlack()+1); guesses[i-1] = ""; answerCopy[i-1] = ""; } } // then process any remaining whites for (j = guessLength - result.getBlack(); j>0; j--) { String colorToFind = guesses[j-1]; for (k=0; k<answerCopy.length; k++) { if (answerCopy[k] == colorToFind) { result.setWhite(result.getWhite()+1); // don't mess up the position of answers, just replace match with "" answerCopy[k] = ""; break; } } } }
public void evaluate() { int i, j, k; String[] answerCopy = answer.clone(); clearHints(); if (solved||gameOver) { //shouldn't happen because submit button should disappear return; } // process all the possible blacks first for (i=answerCopy.length; i>0; i--) { if (guesses[i-1] == answerCopy[i-1]) { result.setBlack(result.getBlack()+1); guesses[i-1] = ""; answerCopy[i-1] = ""; } } // then process any remaining whites for (j = guessLength - result.getBlack(); j>0; j--) { String colorToFind = guesses[j-1]; if (colorToFind == "") { continue; } for (k=0; k<answerCopy.length; k++) { if (answerCopy[k] == colorToFind) { result.setWhite(result.getWhite()+1); // don't mess up the position of answers, just replace match with "" answerCopy[k] = ""; break; } } } }
diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/util/BuildCleanupListener.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/util/BuildCleanupListener.java index ea59be8c9..d4dcc7ee3 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/util/BuildCleanupListener.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/util/BuildCleanupListener.java @@ -1,154 +1,153 @@ /******************************************************************************* * 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 Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.team.internal.ccvs.core.util; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IResourceDeltaVisitor; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.team.core.RepositoryProvider; import org.eclipse.team.core.TeamException; import org.eclipse.team.internal.ccvs.core.*; import org.eclipse.team.internal.ccvs.core.CVSException; import org.eclipse.team.internal.ccvs.core.CVSProviderPlugin; import org.eclipse.team.internal.ccvs.core.ICVSFolder; import org.eclipse.team.internal.ccvs.core.ICVSRunnable; import org.eclipse.team.internal.ccvs.core.Policy; import org.eclipse.team.internal.ccvs.core.resources.CVSWorkspaceRoot; import org.eclipse.team.internal.ccvs.core.resources.EclipseSynchronizer; /** * Cleanup any CVS folders that were copied by a builder. This will also clean up * CVS folders that were copied by the user since the last auto-build. */ public class BuildCleanupListener implements IResourceDeltaVisitor, IResourceChangeListener { public static IResource getResourceFor(IProject container, IResource destination, IPath originating) { switch(destination.getType()) { case IResource.FILE : return container.getFile(originating); case IResource.FOLDER: return container.getFolder(originating); case IResource.PROJECT: return ResourcesPlugin.getWorkspace().getRoot().getProject(originating.toString()); } return destination; } /** * @see IResourceDeltaVisitor#visit(IResourceDelta) */ public boolean visit(IResourceDelta delta) throws CoreException { IResource resource = delta.getResource(); boolean movedFrom = (delta.getFlags() & IResourceDelta.MOVED_FROM) > 0; switch (delta.getKind()) { case IResourceDelta.ADDED : // make sure the added resource isn't a phantom if (resource.exists()) { if (EclipseSynchronizer.getInstance().wasPhantom(resource)) { EclipseSynchronizer.getInstance().resourcesRecreated(new IResource[] { resource }, null); } if (resource.getType() == IResource.FOLDER) { handleOrphanedSubtree((IContainer)resource); } } break; case IResourceDelta.CHANGED : // This state means there is a resource before and after but changes were made by deleting and moving. // For files, we shouldn'd do anything. // For folders, we should purge the CVS info if (movedFrom && resource.getType() == IResource.FOLDER && resource.exists()) { // When folders are moved, purge the CVS folders return ! handleOrphanedSubtree((IContainer)resource); } break; } return true; } /* * Determine if the container is an orphaned subtree. * If it is, handle it and return true. * Otherwise, return false */ private boolean handleOrphanedSubtree(IContainer container) { try { if (CVSWorkspaceRoot.isOrphanedSubtree(container)) { ICVSFolder mFolder = CVSWorkspaceRoot.getCVSFolderFor(container); mFolder.unmanage(null); return true; } } catch (CVSException e) { CVSProviderPlugin.log(e); } return false; } public void resourceChanged(IResourceChangeEvent event) { try { IResourceDelta root = event.getDelta(); IResourceDelta[] projectDeltas = root.getAffectedChildren(); for (int i = 0; i < projectDeltas.length; i++) { final IResourceDelta delta = projectDeltas[i]; IResource resource = delta.getResource(); if (resource.getType() == IResource.PROJECT) { // If the project is not accessible, don't process it if (!resource.isAccessible()) continue; - if ((delta.getFlags() & IResourceDelta.OPEN) != 0) continue; } RepositoryProvider provider = RepositoryProvider.getProvider(resource.getProject(), CVSProviderPlugin.getTypeId()); // Make sure that the project is a CVS folder. ICVSFolder folder = CVSWorkspaceRoot.getCVSFolderFor(resource.getProject()); if (provider != null) { try { if (! folder.isCVSFolder()) { RepositoryProvider.unmap(resource.getProject()); provider = null; } } catch (TeamException e) { CVSProviderPlugin.log(e); } } // if a project is moved the originating project will not be associated with the CVS provider // however listeners will probably still be interested in the move delta. if ((delta.getFlags() & IResourceDelta.MOVED_TO) > 0) { IResource destination = getResourceFor(resource.getProject(), resource, delta.getMovedToPath()); provider = RepositoryProvider.getProvider(destination.getProject()); } if(provider!=null) { // Traverse the delta is a runnable so that files are only written at the end folder.run(new ICVSRunnable() { public void run(IProgressMonitor monitor) throws CVSException { try { delta.accept(BuildCleanupListener.this); } catch (CoreException e) { Util.logError(CVSMessages.ResourceDeltaVisitor_visitError, e); } } }, Policy.monitorFor(null)); } } } catch (CVSException e) { Util.logError(CVSMessages.ResourceDeltaVisitor_visitError, e); } } }
true
true
public void resourceChanged(IResourceChangeEvent event) { try { IResourceDelta root = event.getDelta(); IResourceDelta[] projectDeltas = root.getAffectedChildren(); for (int i = 0; i < projectDeltas.length; i++) { final IResourceDelta delta = projectDeltas[i]; IResource resource = delta.getResource(); if (resource.getType() == IResource.PROJECT) { // If the project is not accessible, don't process it if (!resource.isAccessible()) continue; if ((delta.getFlags() & IResourceDelta.OPEN) != 0) continue; } RepositoryProvider provider = RepositoryProvider.getProvider(resource.getProject(), CVSProviderPlugin.getTypeId()); // Make sure that the project is a CVS folder. ICVSFolder folder = CVSWorkspaceRoot.getCVSFolderFor(resource.getProject()); if (provider != null) { try { if (! folder.isCVSFolder()) { RepositoryProvider.unmap(resource.getProject()); provider = null; } } catch (TeamException e) { CVSProviderPlugin.log(e); } } // if a project is moved the originating project will not be associated with the CVS provider // however listeners will probably still be interested in the move delta. if ((delta.getFlags() & IResourceDelta.MOVED_TO) > 0) { IResource destination = getResourceFor(resource.getProject(), resource, delta.getMovedToPath()); provider = RepositoryProvider.getProvider(destination.getProject()); } if(provider!=null) { // Traverse the delta is a runnable so that files are only written at the end folder.run(new ICVSRunnable() { public void run(IProgressMonitor monitor) throws CVSException { try { delta.accept(BuildCleanupListener.this); } catch (CoreException e) { Util.logError(CVSMessages.ResourceDeltaVisitor_visitError, e); } } }, Policy.monitorFor(null)); } } } catch (CVSException e) { Util.logError(CVSMessages.ResourceDeltaVisitor_visitError, e); } }
public void resourceChanged(IResourceChangeEvent event) { try { IResourceDelta root = event.getDelta(); IResourceDelta[] projectDeltas = root.getAffectedChildren(); for (int i = 0; i < projectDeltas.length; i++) { final IResourceDelta delta = projectDeltas[i]; IResource resource = delta.getResource(); if (resource.getType() == IResource.PROJECT) { // If the project is not accessible, don't process it if (!resource.isAccessible()) continue; } RepositoryProvider provider = RepositoryProvider.getProvider(resource.getProject(), CVSProviderPlugin.getTypeId()); // Make sure that the project is a CVS folder. ICVSFolder folder = CVSWorkspaceRoot.getCVSFolderFor(resource.getProject()); if (provider != null) { try { if (! folder.isCVSFolder()) { RepositoryProvider.unmap(resource.getProject()); provider = null; } } catch (TeamException e) { CVSProviderPlugin.log(e); } } // if a project is moved the originating project will not be associated with the CVS provider // however listeners will probably still be interested in the move delta. if ((delta.getFlags() & IResourceDelta.MOVED_TO) > 0) { IResource destination = getResourceFor(resource.getProject(), resource, delta.getMovedToPath()); provider = RepositoryProvider.getProvider(destination.getProject()); } if(provider!=null) { // Traverse the delta is a runnable so that files are only written at the end folder.run(new ICVSRunnable() { public void run(IProgressMonitor monitor) throws CVSException { try { delta.accept(BuildCleanupListener.this); } catch (CoreException e) { Util.logError(CVSMessages.ResourceDeltaVisitor_visitError, e); } } }, Policy.monitorFor(null)); } } } catch (CVSException e) { Util.logError(CVSMessages.ResourceDeltaVisitor_visitError, e); } }
diff --git a/src/main/java/com/redhat/ceylon/js/repl/SimpleJsonEncoder.java b/src/main/java/com/redhat/ceylon/js/repl/SimpleJsonEncoder.java index 4770a1f..33c6329 100644 --- a/src/main/java/com/redhat/ceylon/js/repl/SimpleJsonEncoder.java +++ b/src/main/java/com/redhat/ceylon/js/repl/SimpleJsonEncoder.java @@ -1,68 +1,68 @@ package com.redhat.ceylon.js.repl; import java.util.List; import java.util.Map; /** A dead simple JSON encoder. Encoders maps into objects; knows how to encode lists and maps, * and turns anything else into a properly encoded string. * The top-level object must always be a Map. * * @author Enrique Zamudio */ public class SimpleJsonEncoder { public String encode(Map<String, Object> map) { StringBuilder sb = new StringBuilder(); encodeMap(map, sb); return sb.toString(); } public void encodeString(String s, StringBuilder sb) { sb.append('"'); sb.append(s.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\\\"").replaceAll("'", "\\\\'")); sb.append('"'); } @SuppressWarnings("unchecked") public void encodeList(List<Object> list, StringBuilder sb) { sb.append('['); boolean first = true; for (Object item : list) { if (!first) { sb.append(','); } if (item instanceof List) { encodeList((List<Object>)item, sb); } else if (item instanceof Map) { encodeMap((Map<String, Object>)item, sb); } else { encodeString(item.toString(), sb); } first=false; } sb.append(']'); } @SuppressWarnings("unchecked") public void encodeMap(Map<String, Object> map, StringBuilder sb) { sb.append('{'); boolean first = true; for (Map.Entry<String, Object> entry : map.entrySet()) { if (!first) { sb.append(','); } encodeString(entry.getKey(), sb); - sb.append('='); + sb.append(':'); if (entry.getValue() instanceof List) { encodeList((List<Object>)entry.getValue(), sb); } else if (entry.getValue() instanceof Map) { encodeMap((Map<String, Object>)entry.getValue(), sb); } else { encodeString(entry.getValue().toString(), sb); } first = false; } sb.append('}'); } }
true
true
public void encodeMap(Map<String, Object> map, StringBuilder sb) { sb.append('{'); boolean first = true; for (Map.Entry<String, Object> entry : map.entrySet()) { if (!first) { sb.append(','); } encodeString(entry.getKey(), sb); sb.append('='); if (entry.getValue() instanceof List) { encodeList((List<Object>)entry.getValue(), sb); } else if (entry.getValue() instanceof Map) { encodeMap((Map<String, Object>)entry.getValue(), sb); } else { encodeString(entry.getValue().toString(), sb); } first = false; } sb.append('}'); }
public void encodeMap(Map<String, Object> map, StringBuilder sb) { sb.append('{'); boolean first = true; for (Map.Entry<String, Object> entry : map.entrySet()) { if (!first) { sb.append(','); } encodeString(entry.getKey(), sb); sb.append(':'); if (entry.getValue() instanceof List) { encodeList((List<Object>)entry.getValue(), sb); } else if (entry.getValue() instanceof Map) { encodeMap((Map<String, Object>)entry.getValue(), sb); } else { encodeString(entry.getValue().toString(), sb); } first = false; } sb.append('}'); }
diff --git a/src/com/wwsean08/clear/PreviewCommand.java b/src/com/wwsean08/clear/PreviewCommand.java index aa7fbe8..e8c28a8 100644 --- a/src/com/wwsean08/clear/PreviewCommand.java +++ b/src/com/wwsean08/clear/PreviewCommand.java @@ -1,143 +1,145 @@ package com.wwsean08.clear; import java.util.ArrayList; import java.util.HashMap; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Server; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; public class PreviewCommand implements CommandExecutor{ Clear plugin; Server server; private HashMap<Player, ItemStack[]> originalInventory; public PreviewCommand(Clear instance){ plugin = instance; server = Bukkit.getServer(); originalInventory = new HashMap<Player, ItemStack[]>(); } @Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if(commandLabel.equalsIgnoreCase("preview")){ if(sender instanceof Player){ if(args.length == 0){ Player player = (Player) sender; unpreview(player); } if(args.length == 1){ Player player = (Player) sender; - Player affected = server.matchPlayer(args[0]).get(0); - if(affected!=null){ - if(plugin.usesSP){ - if(player.hasPermission("clear.other")){ + if(server.matchPlayer(args[0]) != null){ + Player affected = server.matchPlayer(args[0]).get(0); + if(affected!=null){ + if(plugin.usesSP){ + if(player.hasPermission("clear.other")){ + preview(player, affected); + ClearRunnable run = new ClearRunnable(this, player); + server.getScheduler().scheduleSyncDelayedTask(plugin, run, 6000); + } + }else if(player.isOp()){ preview(player, affected); ClearRunnable run = new ClearRunnable(this, player); server.getScheduler().scheduleSyncDelayedTask(plugin, run, 6000); + }else{ + sender.sendMessage("You do not have permission to use this command"); + plugin.log.warning(plugin.PREFIX + player.getDisplayName() + " Attempted to preview another players inventory"); } - }else if(player.isOp()){ - preview(player, affected); - ClearRunnable run = new ClearRunnable(this, player); - server.getScheduler().scheduleSyncDelayedTask(plugin, run, 6000); - }else{ - sender.sendMessage("You do not have permission to use this command"); - plugin.log.warning(plugin.PREFIX + player.getDisplayName() + " Attempted to preview another players inventory"); } } } } else{ if(args.length == 0){ sender.sendMessage(ChatColor.GRAY + "Error: I need a name of who to preview"); }else{ Player player = server.getPlayer(args[0]); ArrayList<String> contains = preview(player); sender.sendMessage(ChatColor.GRAY + "Here is the inventory of " + player.getDisplayName()); for(String s : contains){ sender.sendMessage(s); } } } } else if(commandLabel.equalsIgnoreCase("unpreview") || commandLabel.equalsIgnoreCase("revert")){ if(sender instanceof Player){ Player player = (Player) sender; unpreview(player); } } return true; } /** * is used to display a players inventory from the server console * @param player the player whose inventory is being previewed * @return a list of items to display to the server console */ public ArrayList<String> preview(Player player) { ArrayList<String> inventoryList = new ArrayList<String>(); ArrayList<Integer> itemNumbers = new ArrayList<Integer>(); HashMap<Integer, Integer> ammount = new HashMap<Integer, Integer>(); PlayerInventory inv = player.getInventory(); ItemStack[] contents = inv.getContents(); //loop thru the contents of the inventory in order to make our array list of items for(ItemStack a : contents){ if(a != null){ Integer value = a.getTypeId(); if(itemNumbers.contains(Integer.valueOf(value))){ int i = ammount.get(value); i += a.getAmount(); ammount.put(value, i); }else{ itemNumbers.add(value); ammount.put(value, a.getAmount()); } } } //build an array list of strings with the ammount they have and the item for(Integer i : itemNumbers){ StringBuilder out = new StringBuilder(); out.append(ammount.get(i) + "x "); for(int j = 0; j < plugin.items.size(); j++){ if(plugin.items.get(j).getItem() == i.intValue()){ out.append(plugin.items.get(j).getOutput()); break; } } inventoryList.add(out.toString()); } return inventoryList; } /** * Allows an admin to preview a players inventory * @param previewer The admin that will be previewing the inventory * @param previewee The player whose inventory we want to preview */ public void preview(Player previewer, Player previewee){ ItemStack[] preview = previewee.getInventory().getContents(); if(!originalInventory.containsKey(previewer)) originalInventory.put(previewer, previewer.getInventory().getContents()); previewer.getInventory().setContents(preview); ClearRunnable runner = new ClearRunnable(this, previewer); server.getScheduler().scheduleSyncDelayedTask(plugin, runner, 6000); previewer.sendMessage("You are now previewing " + previewee.getDisplayName()); } /** * Restores the content of an admins inventory if they are previewing one * @param previewer the admin who is getting their inventory back */ public void unpreview(Player previewer){ if(originalInventory.containsKey(previewer)){ previewer.getInventory().clear(); previewer.getInventory().setContents(originalInventory.get(previewer)); originalInventory.remove(previewer); previewer.sendMessage("Your inventory has been restored"); } } }
false
true
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if(commandLabel.equalsIgnoreCase("preview")){ if(sender instanceof Player){ if(args.length == 0){ Player player = (Player) sender; unpreview(player); } if(args.length == 1){ Player player = (Player) sender; Player affected = server.matchPlayer(args[0]).get(0); if(affected!=null){ if(plugin.usesSP){ if(player.hasPermission("clear.other")){ preview(player, affected); ClearRunnable run = new ClearRunnable(this, player); server.getScheduler().scheduleSyncDelayedTask(plugin, run, 6000); } }else if(player.isOp()){ preview(player, affected); ClearRunnable run = new ClearRunnable(this, player); server.getScheduler().scheduleSyncDelayedTask(plugin, run, 6000); }else{ sender.sendMessage("You do not have permission to use this command"); plugin.log.warning(plugin.PREFIX + player.getDisplayName() + " Attempted to preview another players inventory"); } } } } else{ if(args.length == 0){ sender.sendMessage(ChatColor.GRAY + "Error: I need a name of who to preview"); }else{ Player player = server.getPlayer(args[0]); ArrayList<String> contains = preview(player); sender.sendMessage(ChatColor.GRAY + "Here is the inventory of " + player.getDisplayName()); for(String s : contains){ sender.sendMessage(s); } } } } else if(commandLabel.equalsIgnoreCase("unpreview") || commandLabel.equalsIgnoreCase("revert")){ if(sender instanceof Player){ Player player = (Player) sender; unpreview(player); } } return true; }
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if(commandLabel.equalsIgnoreCase("preview")){ if(sender instanceof Player){ if(args.length == 0){ Player player = (Player) sender; unpreview(player); } if(args.length == 1){ Player player = (Player) sender; if(server.matchPlayer(args[0]) != null){ Player affected = server.matchPlayer(args[0]).get(0); if(affected!=null){ if(plugin.usesSP){ if(player.hasPermission("clear.other")){ preview(player, affected); ClearRunnable run = new ClearRunnable(this, player); server.getScheduler().scheduleSyncDelayedTask(plugin, run, 6000); } }else if(player.isOp()){ preview(player, affected); ClearRunnable run = new ClearRunnable(this, player); server.getScheduler().scheduleSyncDelayedTask(plugin, run, 6000); }else{ sender.sendMessage("You do not have permission to use this command"); plugin.log.warning(plugin.PREFIX + player.getDisplayName() + " Attempted to preview another players inventory"); } } } } } else{ if(args.length == 0){ sender.sendMessage(ChatColor.GRAY + "Error: I need a name of who to preview"); }else{ Player player = server.getPlayer(args[0]); ArrayList<String> contains = preview(player); sender.sendMessage(ChatColor.GRAY + "Here is the inventory of " + player.getDisplayName()); for(String s : contains){ sender.sendMessage(s); } } } } else if(commandLabel.equalsIgnoreCase("unpreview") || commandLabel.equalsIgnoreCase("revert")){ if(sender instanceof Player){ Player player = (Player) sender; unpreview(player); } } return true; }
diff --git a/ecologylab/generic/ClassAndCollectionIterator.java b/ecologylab/generic/ClassAndCollectionIterator.java index 4041fcb2..dfada483 100644 --- a/ecologylab/generic/ClassAndCollectionIterator.java +++ b/ecologylab/generic/ClassAndCollectionIterator.java @@ -1,87 +1,87 @@ package ecologylab.generic; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import ecologylab.xml.FieldAccessor; /** * Iterates through a Collection of things, and then through an Iterator * of such (nested) Collections of things. * Provides flat access to all members. * * @author andruid * * @param <I> Class that we iterate over. * @param <O> Class of objects that are applied in the context of what we iterate over. * This typically starts as this, but shifts as we iterate through * the nested Collection of Iterators. */ public class ClassAndCollectionIterator<I extends FieldAccessor, O extends Iterable<I>> implements Iterator<O> { private Iterator<I> iterator; private Iterator<O> collection; private O root; private O currentObject; public ClassAndCollectionIterator(O firstObject) { root = firstObject; this.iterator = firstObject.iterator(); } public O next() { try { if (collection != null) return nextInCollection(); if (iterator.hasNext()) { I firstNext = iterator.next(); if(firstNext.isCollection()) { collection = (Iterator<O>) firstNext.getField().get(root); return nextInCollection(); } O next = (O) firstNext.getField().get(root); currentObject = next; - return currentObject; + return next; } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; } private O nextInCollection() { if (!collection.hasNext()) { collection = null; return next(); } O next = collection.next(); currentObject = next; return next; } public O currentObject() { return currentObject; } public void remove() { throw new UnsupportedOperationException(); } public boolean hasNext() { return iterator.hasNext() || (collection != null && collection.hasNext()); } }
true
true
public O next() { try { if (collection != null) return nextInCollection(); if (iterator.hasNext()) { I firstNext = iterator.next(); if(firstNext.isCollection()) { collection = (Iterator<O>) firstNext.getField().get(root); return nextInCollection(); } O next = (O) firstNext.getField().get(root); currentObject = next; return currentObject; } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; }
public O next() { try { if (collection != null) return nextInCollection(); if (iterator.hasNext()) { I firstNext = iterator.next(); if(firstNext.isCollection()) { collection = (Iterator<O>) firstNext.getField().get(root); return nextInCollection(); } O next = (O) firstNext.getField().get(root); currentObject = next; return next; } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; }
diff --git a/webui/portal/src/main/java/org/exoplatform/portal/webui/navigation/PageNavigationUtils.java b/webui/portal/src/main/java/org/exoplatform/portal/webui/navigation/PageNavigationUtils.java index 8d934744c8..bb4e9f1a3b 100644 --- a/webui/portal/src/main/java/org/exoplatform/portal/webui/navigation/PageNavigationUtils.java +++ b/webui/portal/src/main/java/org/exoplatform/portal/webui/navigation/PageNavigationUtils.java @@ -1,131 +1,131 @@ /* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero 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 org.exoplatform.portal.webui.navigation; import java.util.ArrayList; import java.util.List; import org.exoplatform.container.ExoContainer; import org.exoplatform.portal.config.UserPortalConfigService; import org.exoplatform.portal.config.model.PageNavigation; import org.exoplatform.portal.config.model.PageNode; import org.exoplatform.webui.application.WebuiRequestContext; /** * Created by The eXo Platform SARL * Author : Nhu Dinh Thuan * [email protected] * Jun 27, 2007 */ public class PageNavigationUtils { public static void removeNode(List<PageNode> list, String uri) { if(list == null) return; for(PageNode pageNode: list){ if(pageNode.getUri().equalsIgnoreCase(uri)) { list.remove(pageNode); return; } } } public static PageNode[] searchPageNodesByUri(PageNode node, String uri){ if(node.getUri().equals(uri) ) return new PageNode[] {null, node}; if(node.getChildren() == null) return null; List<PageNode> children = node.getChildren(); for(PageNode ele : children) { PageNode[] returnNodes = searchPageNodesByUri(ele, uri); if(returnNodes != null) { if(returnNodes[0] == null) returnNodes[0] = node; return returnNodes; } } return null; } public static PageNode[] searchPageNodesByUri(PageNavigation nav, String uri){ if(nav.getNodes() == null) return null; List<PageNode> nodes = nav.getNodes(); for(PageNode ele : nodes) { PageNode [] returnNodes = searchPageNodesByUri(ele, uri); if(returnNodes != null) return returnNodes; } return null; } public static PageNode searchPageNodeByUri(PageNode node, String uri){ if(node.getUri().equals(uri) ) return node; if(node.getChildren() == null) return null; List<PageNode> children = node.getChildren(); for(PageNode ele : children) { PageNode returnNode = searchPageNodeByUri(ele, uri); if(returnNode != null) return returnNode; } return null; } public static PageNode searchPageNodeByUri(PageNavigation nav, String uri){ if(nav.getNodes() == null) return null; List<PageNode> nodes = nav.getNodes(); for(PageNode ele : nodes) { PageNode returnNode = searchPageNodeByUri(ele, uri); if(returnNode != null) return returnNode; } return null; } public static Object searchParentNode(PageNavigation nav, String uri){ if(nav.getNodes() == null) return null; int last = uri.lastIndexOf("/"); String parentUri = ""; if (last > -1) parentUri = uri.substring(0, uri.lastIndexOf("/")); for(PageNode ele : nav.getNodes()) { if( ele.getUri().equals(uri)) return nav; } if(parentUri.equals("")) return null; return searchPageNodeByUri(nav, parentUri); } public static PageNavigation filter(PageNavigation nav, String userName) throws Exception { PageNavigation filter = nav.clone(); filter.setNodes(new ArrayList<PageNode>()); // if(nav.getNodes() == null || nav.getNodes().size() < 1) return null; for(PageNode node: nav.getNodes()){ PageNode newNode = filter(node, userName); if(newNode != null ) filter.addNode(newNode); } return filter; } public static PageNode filter(PageNode node, String userName) throws Exception { WebuiRequestContext context = WebuiRequestContext.getCurrentInstance() ; ExoContainer container = context.getApplication().getApplicationServiceContainer() ; UserPortalConfigService userService = (UserPortalConfigService)container.getComponentInstanceOfType(UserPortalConfigService.class); if(!node.isDisplay() || (node.getPageReference() != null && userService.getPage(node.getPageReference(), userName) == null)) return null; PageNode copyNode = node.clone(); copyNode.setChildren(new ArrayList<PageNode>()); List<PageNode> children = node.getChildren(); if(children == null || children.size() == 0) return copyNode; for(PageNode child: children){ PageNode newNode = filter(child, userName); if(newNode != null ) copyNode.getChildren().add(newNode); } - if(copyNode.getChildren().size() == 0) return null; + if((copyNode.getChildren().size() == 0) && (copyNode.getPageReference() == null)) return null; return copyNode; } }
true
true
public static PageNode filter(PageNode node, String userName) throws Exception { WebuiRequestContext context = WebuiRequestContext.getCurrentInstance() ; ExoContainer container = context.getApplication().getApplicationServiceContainer() ; UserPortalConfigService userService = (UserPortalConfigService)container.getComponentInstanceOfType(UserPortalConfigService.class); if(!node.isDisplay() || (node.getPageReference() != null && userService.getPage(node.getPageReference(), userName) == null)) return null; PageNode copyNode = node.clone(); copyNode.setChildren(new ArrayList<PageNode>()); List<PageNode> children = node.getChildren(); if(children == null || children.size() == 0) return copyNode; for(PageNode child: children){ PageNode newNode = filter(child, userName); if(newNode != null ) copyNode.getChildren().add(newNode); } if(copyNode.getChildren().size() == 0) return null; return copyNode; }
public static PageNode filter(PageNode node, String userName) throws Exception { WebuiRequestContext context = WebuiRequestContext.getCurrentInstance() ; ExoContainer container = context.getApplication().getApplicationServiceContainer() ; UserPortalConfigService userService = (UserPortalConfigService)container.getComponentInstanceOfType(UserPortalConfigService.class); if(!node.isDisplay() || (node.getPageReference() != null && userService.getPage(node.getPageReference(), userName) == null)) return null; PageNode copyNode = node.clone(); copyNode.setChildren(new ArrayList<PageNode>()); List<PageNode> children = node.getChildren(); if(children == null || children.size() == 0) return copyNode; for(PageNode child: children){ PageNode newNode = filter(child, userName); if(newNode != null ) copyNode.getChildren().add(newNode); } if((copyNode.getChildren().size() == 0) && (copyNode.getPageReference() == null)) return null; return copyNode; }
diff --git a/TeaLeaf/src/com/tealeaf/EditTextView.java b/TeaLeaf/src/com/tealeaf/EditTextView.java index fd936da..aa3c241 100644 --- a/TeaLeaf/src/com/tealeaf/EditTextView.java +++ b/TeaLeaf/src/com/tealeaf/EditTextView.java @@ -1,319 +1,319 @@ package com.tealeaf; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Typeface; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextWatcher; import android.util.AttributeSet; import android.util.TypedValue; import android.view.Display; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.AbsoluteLayout; import android.widget.EditText; import android.widget.TextView; import com.tealeaf.event.Event; import com.tealeaf.event.InputKeyboardFocusNextEvent; import com.tealeaf.event.InputKeyboardKeyUpEvent; import com.tealeaf.event.InputKeyboardSubmitEvent; import java.util.Map; import org.json.JSONObject; public class EditTextView extends EditText { private static EditTextView instance; private Activity activity; private boolean registerTextChange = true; private OnTouchListener currentTouchListener = null; private OnGlobalLayoutListener onGlobalLayoutListener; private boolean isOpened = false; public enum InputName { DEFAULT, NUMBER, PHONE, PASSWORD, CAPITAL } public EditTextView(Activity activity) { super(activity); init(); } public EditTextView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { this.setCursorVisible(true); this.setTextColor(Color.BLACK); this.setBackgroundColor(Color.TRANSPARENT); this.setVisibility(View.GONE); this.setSingleLine(true); } public static EditTextView Get(final Activity activity) { if (instance == null && activity != null) { instance = (EditTextView)activity.getLayoutInflater().inflate(R.layout.edit_text_view, null); instance.activity = activity; instance.addTextChangedListener(new TextWatcher() { private String beforeText = ""; @Override public void afterTextChanged(Editable s) { // propagate text changes to JS to update views if (instance.registerTextChange) { logger.log("KeyUp textChange in TextEditView"); EventQueue.pushEvent(new InputKeyboardKeyUpEvent(s.toString(), beforeText, instance.getSelectionStart())); } else { instance.registerTextChange = true; } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { beforeText = s.toString(); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } }); instance.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { EventQueue.pushEvent(new InputKeyboardSubmitEvent(0, instance.getText().toString())); instance.hideKeyboard(); } else if (actionId == EditorInfo.IME_ACTION_NEXT) { EventQueue.pushEvent(new InputKeyboardFocusNextEvent(true)); } return false; } }); //register for focus NativeShim.RegisterCallable("editText.focus", new TeaLeafCallable() { public JSONObject call(final JSONObject obj) { activity.runOnUiThread(new Runnable() { public void run() { try { instance.registerTextChange = false; instance.setVisibility(View.VISIBLE); instance.requestFocus(); instance.currentTouchListener = TeaLeaf.get().glView.getOnTouchListener(); TeaLeaf.get().glView.setOnTouchListener(instance.getScreenCaptureListener()); //set x, y, width and height int x = obj.optInt("x", 0); int y = obj.optInt("y", 0); int width = obj.optInt("width", 0); int height = obj.optInt("height", 0); AbsoluteLayout.LayoutParams layoutParams = new AbsoluteLayout.LayoutParams(width, height, x, y); instance.setLayoutParams(layoutParams); //font size int fontSize = (int)(obj.optInt("fontSize", 16) * .9f); instance.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSize); //text String text = obj.optString("text", ""); instance.setText(text); //font color String fontColor = obj.optString("fontColor", "#000000"); instance.setTextColor(Color.parseColor(fontColor)); //font family String font = obj.optString("font", "helvetica"); TextManager textManager = TeaLeaf.get().glView.getTextureLoader().getTextManager(); Typeface tf = textManager.getTypeface(font); instance.setTypeface(tf); //hint text String hint = obj.optString("hint", ""); instance.setHint(hint); //hint text color String hintColor = obj.optString("hintColor", "#999999"); instance.setHintTextColor(Color.parseColor(hintColor)); //max length int maxLength = obj.optInt("maxLength", -1); if (maxLength == -1) { instance.setFilters(new InputFilter[] {}); } else { instance.setFilters(new InputFilter[] { new InputFilter.LengthFilter(maxLength) }); } //input type String inputType = obj.optString("inputType", ""); int type; InputName inputName = InputName.DEFAULT; inputName = InputName.valueOf(inputType.toUpperCase().trim()); boolean hasForward = obj.optBoolean("hasForward", false); - String inputReturnButton = obj.optString("inputReturnButton", "done"); + String inputReturnButton = obj.optString("inputReturnType", "done"); if (inputReturnButton.equals("done")) { instance.setImeOptions(EditorInfo.IME_ACTION_DONE); } else if (inputReturnButton.equals("next")) { instance.setImeOptions(EditorInfo.IME_ACTION_NEXT); } else if (inputReturnButton.equals("search")) { instance.setImeOptions(EditorInfo.IME_ACTION_SEARCH); } else if (inputReturnButton.equals("send")) { instance.setImeOptions(EditorInfo.IME_ACTION_SEND); } else if (inputReturnButton.equals("go")) { instance.setImeOptions(EditorInfo.IME_ACTION_GO); } else { int action = hasForward ? EditorInfo.IME_ACTION_NEXT : EditorInfo.IME_ACTION_DONE; if (inputReturnButton.equals("default")) { instance.setImeOptions(action); } else { instance.setImeActionLabel(inputReturnButton, action); } } //cursor pos int cursorPos = obj.optInt("cursorPos", instance.length()); instance.setSelection(cursorPos < 0 || cursorPos > instance.length() ? instance.getText().length() : cursorPos); switch (inputName) { case NUMBER: type = InputType.TYPE_CLASS_NUMBER; break; case PHONE: type = InputType.TYPE_CLASS_PHONE; break; case PASSWORD: type = InputType.TYPE_TEXT_VARIATION_PASSWORD; break; case CAPITAL: type = InputType.TYPE_TEXT_FLAG_CAP_WORDS; break; default: type = InputType.TYPE_CLASS_TEXT; break; } //for auto correct use this flag -> InputType.TYPE_TEXT_FLAG_AUTO_CORRECT instance.setInputType(type | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); //padding int paddingLeft = obj.optInt("paddingLeft", 0); int paddingRight = obj.optInt("paddingRight", 0); instance.setPadding(paddingLeft, 0, paddingRight, 0); InputMethodManager imm = (InputMethodManager) instance.activity.getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(instance, 0); instance.setListenerToRootView(); } catch (Exception e) { logger.log(e); } } }); return obj; } }); //register for clear focus NativeShim.RegisterCallable("editText.clearFocus", new TeaLeafCallable() { public JSONObject call(final JSONObject obj) { activity.runOnUiThread(new Runnable() { public void run() { TeaLeaf.get().glView.setOnTouchListener(instance.currentTouchListener); instance.hideKeyboard(); instance.setVisibility(View.GONE); instance.removeListenerToRootView(); } }); return obj; } }); instance.onGlobalLayoutListener = new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { View group = (View)TeaLeaf.get().getGroup(); // get visible area of the view Rect r = new Rect(); group.getWindowVisibleDisplayFrame(r); // get display height Display display = instance.activity.getWindow().getWindowManager().getDefaultDisplay(); int height = display.getHeight(); // if our visible height is less than 75% normal, assume keyboard on screen int visibleHeight = r.bottom - r.top; if (visibleHeight < .75 * height && !instance.isOpened) { instance.isOpened = true; } else if(instance.isOpened){ EventQueue.pushEvent(new Event("editText.onFinishEditing")); } } }; } return instance; } public void setListenerToRootView() { View activityRootView = (View)TeaLeaf.get().getGroup(); activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(this.onGlobalLayoutListener); } public void removeListenerToRootView() { View activityRootView = (View)TeaLeaf.get().getGroup(); activityRootView.getViewTreeObserver().removeGlobalOnLayoutListener(this.onGlobalLayoutListener); } private void hideKeyboard() { isOpened = false; InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(this.getWindowToken(), 0); } public OnTouchListener getScreenCaptureListener() { return new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { EventQueue.pushEvent(new Event("editText.onFinishEditing")); return false; } }; } }
true
true
public static EditTextView Get(final Activity activity) { if (instance == null && activity != null) { instance = (EditTextView)activity.getLayoutInflater().inflate(R.layout.edit_text_view, null); instance.activity = activity; instance.addTextChangedListener(new TextWatcher() { private String beforeText = ""; @Override public void afterTextChanged(Editable s) { // propagate text changes to JS to update views if (instance.registerTextChange) { logger.log("KeyUp textChange in TextEditView"); EventQueue.pushEvent(new InputKeyboardKeyUpEvent(s.toString(), beforeText, instance.getSelectionStart())); } else { instance.registerTextChange = true; } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { beforeText = s.toString(); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } }); instance.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { EventQueue.pushEvent(new InputKeyboardSubmitEvent(0, instance.getText().toString())); instance.hideKeyboard(); } else if (actionId == EditorInfo.IME_ACTION_NEXT) { EventQueue.pushEvent(new InputKeyboardFocusNextEvent(true)); } return false; } }); //register for focus NativeShim.RegisterCallable("editText.focus", new TeaLeafCallable() { public JSONObject call(final JSONObject obj) { activity.runOnUiThread(new Runnable() { public void run() { try { instance.registerTextChange = false; instance.setVisibility(View.VISIBLE); instance.requestFocus(); instance.currentTouchListener = TeaLeaf.get().glView.getOnTouchListener(); TeaLeaf.get().glView.setOnTouchListener(instance.getScreenCaptureListener()); //set x, y, width and height int x = obj.optInt("x", 0); int y = obj.optInt("y", 0); int width = obj.optInt("width", 0); int height = obj.optInt("height", 0); AbsoluteLayout.LayoutParams layoutParams = new AbsoluteLayout.LayoutParams(width, height, x, y); instance.setLayoutParams(layoutParams); //font size int fontSize = (int)(obj.optInt("fontSize", 16) * .9f); instance.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSize); //text String text = obj.optString("text", ""); instance.setText(text); //font color String fontColor = obj.optString("fontColor", "#000000"); instance.setTextColor(Color.parseColor(fontColor)); //font family String font = obj.optString("font", "helvetica"); TextManager textManager = TeaLeaf.get().glView.getTextureLoader().getTextManager(); Typeface tf = textManager.getTypeface(font); instance.setTypeface(tf); //hint text String hint = obj.optString("hint", ""); instance.setHint(hint); //hint text color String hintColor = obj.optString("hintColor", "#999999"); instance.setHintTextColor(Color.parseColor(hintColor)); //max length int maxLength = obj.optInt("maxLength", -1); if (maxLength == -1) { instance.setFilters(new InputFilter[] {}); } else { instance.setFilters(new InputFilter[] { new InputFilter.LengthFilter(maxLength) }); } //input type String inputType = obj.optString("inputType", ""); int type; InputName inputName = InputName.DEFAULT; inputName = InputName.valueOf(inputType.toUpperCase().trim()); boolean hasForward = obj.optBoolean("hasForward", false); String inputReturnButton = obj.optString("inputReturnButton", "done"); if (inputReturnButton.equals("done")) { instance.setImeOptions(EditorInfo.IME_ACTION_DONE); } else if (inputReturnButton.equals("next")) { instance.setImeOptions(EditorInfo.IME_ACTION_NEXT); } else if (inputReturnButton.equals("search")) { instance.setImeOptions(EditorInfo.IME_ACTION_SEARCH); } else if (inputReturnButton.equals("send")) { instance.setImeOptions(EditorInfo.IME_ACTION_SEND); } else if (inputReturnButton.equals("go")) { instance.setImeOptions(EditorInfo.IME_ACTION_GO); } else { int action = hasForward ? EditorInfo.IME_ACTION_NEXT : EditorInfo.IME_ACTION_DONE; if (inputReturnButton.equals("default")) { instance.setImeOptions(action); } else { instance.setImeActionLabel(inputReturnButton, action); } } //cursor pos int cursorPos = obj.optInt("cursorPos", instance.length()); instance.setSelection(cursorPos < 0 || cursorPos > instance.length() ? instance.getText().length() : cursorPos); switch (inputName) { case NUMBER: type = InputType.TYPE_CLASS_NUMBER; break; case PHONE: type = InputType.TYPE_CLASS_PHONE; break; case PASSWORD: type = InputType.TYPE_TEXT_VARIATION_PASSWORD; break; case CAPITAL: type = InputType.TYPE_TEXT_FLAG_CAP_WORDS; break; default: type = InputType.TYPE_CLASS_TEXT; break; } //for auto correct use this flag -> InputType.TYPE_TEXT_FLAG_AUTO_CORRECT instance.setInputType(type | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); //padding int paddingLeft = obj.optInt("paddingLeft", 0); int paddingRight = obj.optInt("paddingRight", 0); instance.setPadding(paddingLeft, 0, paddingRight, 0); InputMethodManager imm = (InputMethodManager) instance.activity.getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(instance, 0); instance.setListenerToRootView(); } catch (Exception e) { logger.log(e); } } }); return obj; } }); //register for clear focus NativeShim.RegisterCallable("editText.clearFocus", new TeaLeafCallable() { public JSONObject call(final JSONObject obj) { activity.runOnUiThread(new Runnable() { public void run() { TeaLeaf.get().glView.setOnTouchListener(instance.currentTouchListener); instance.hideKeyboard(); instance.setVisibility(View.GONE); instance.removeListenerToRootView(); } }); return obj; } }); instance.onGlobalLayoutListener = new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { View group = (View)TeaLeaf.get().getGroup(); // get visible area of the view Rect r = new Rect(); group.getWindowVisibleDisplayFrame(r); // get display height Display display = instance.activity.getWindow().getWindowManager().getDefaultDisplay(); int height = display.getHeight(); // if our visible height is less than 75% normal, assume keyboard on screen int visibleHeight = r.bottom - r.top; if (visibleHeight < .75 * height && !instance.isOpened) { instance.isOpened = true; } else if(instance.isOpened){ EventQueue.pushEvent(new Event("editText.onFinishEditing")); } } }; } return instance; }
public static EditTextView Get(final Activity activity) { if (instance == null && activity != null) { instance = (EditTextView)activity.getLayoutInflater().inflate(R.layout.edit_text_view, null); instance.activity = activity; instance.addTextChangedListener(new TextWatcher() { private String beforeText = ""; @Override public void afterTextChanged(Editable s) { // propagate text changes to JS to update views if (instance.registerTextChange) { logger.log("KeyUp textChange in TextEditView"); EventQueue.pushEvent(new InputKeyboardKeyUpEvent(s.toString(), beforeText, instance.getSelectionStart())); } else { instance.registerTextChange = true; } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { beforeText = s.toString(); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } }); instance.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { EventQueue.pushEvent(new InputKeyboardSubmitEvent(0, instance.getText().toString())); instance.hideKeyboard(); } else if (actionId == EditorInfo.IME_ACTION_NEXT) { EventQueue.pushEvent(new InputKeyboardFocusNextEvent(true)); } return false; } }); //register for focus NativeShim.RegisterCallable("editText.focus", new TeaLeafCallable() { public JSONObject call(final JSONObject obj) { activity.runOnUiThread(new Runnable() { public void run() { try { instance.registerTextChange = false; instance.setVisibility(View.VISIBLE); instance.requestFocus(); instance.currentTouchListener = TeaLeaf.get().glView.getOnTouchListener(); TeaLeaf.get().glView.setOnTouchListener(instance.getScreenCaptureListener()); //set x, y, width and height int x = obj.optInt("x", 0); int y = obj.optInt("y", 0); int width = obj.optInt("width", 0); int height = obj.optInt("height", 0); AbsoluteLayout.LayoutParams layoutParams = new AbsoluteLayout.LayoutParams(width, height, x, y); instance.setLayoutParams(layoutParams); //font size int fontSize = (int)(obj.optInt("fontSize", 16) * .9f); instance.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSize); //text String text = obj.optString("text", ""); instance.setText(text); //font color String fontColor = obj.optString("fontColor", "#000000"); instance.setTextColor(Color.parseColor(fontColor)); //font family String font = obj.optString("font", "helvetica"); TextManager textManager = TeaLeaf.get().glView.getTextureLoader().getTextManager(); Typeface tf = textManager.getTypeface(font); instance.setTypeface(tf); //hint text String hint = obj.optString("hint", ""); instance.setHint(hint); //hint text color String hintColor = obj.optString("hintColor", "#999999"); instance.setHintTextColor(Color.parseColor(hintColor)); //max length int maxLength = obj.optInt("maxLength", -1); if (maxLength == -1) { instance.setFilters(new InputFilter[] {}); } else { instance.setFilters(new InputFilter[] { new InputFilter.LengthFilter(maxLength) }); } //input type String inputType = obj.optString("inputType", ""); int type; InputName inputName = InputName.DEFAULT; inputName = InputName.valueOf(inputType.toUpperCase().trim()); boolean hasForward = obj.optBoolean("hasForward", false); String inputReturnButton = obj.optString("inputReturnType", "done"); if (inputReturnButton.equals("done")) { instance.setImeOptions(EditorInfo.IME_ACTION_DONE); } else if (inputReturnButton.equals("next")) { instance.setImeOptions(EditorInfo.IME_ACTION_NEXT); } else if (inputReturnButton.equals("search")) { instance.setImeOptions(EditorInfo.IME_ACTION_SEARCH); } else if (inputReturnButton.equals("send")) { instance.setImeOptions(EditorInfo.IME_ACTION_SEND); } else if (inputReturnButton.equals("go")) { instance.setImeOptions(EditorInfo.IME_ACTION_GO); } else { int action = hasForward ? EditorInfo.IME_ACTION_NEXT : EditorInfo.IME_ACTION_DONE; if (inputReturnButton.equals("default")) { instance.setImeOptions(action); } else { instance.setImeActionLabel(inputReturnButton, action); } } //cursor pos int cursorPos = obj.optInt("cursorPos", instance.length()); instance.setSelection(cursorPos < 0 || cursorPos > instance.length() ? instance.getText().length() : cursorPos); switch (inputName) { case NUMBER: type = InputType.TYPE_CLASS_NUMBER; break; case PHONE: type = InputType.TYPE_CLASS_PHONE; break; case PASSWORD: type = InputType.TYPE_TEXT_VARIATION_PASSWORD; break; case CAPITAL: type = InputType.TYPE_TEXT_FLAG_CAP_WORDS; break; default: type = InputType.TYPE_CLASS_TEXT; break; } //for auto correct use this flag -> InputType.TYPE_TEXT_FLAG_AUTO_CORRECT instance.setInputType(type | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); //padding int paddingLeft = obj.optInt("paddingLeft", 0); int paddingRight = obj.optInt("paddingRight", 0); instance.setPadding(paddingLeft, 0, paddingRight, 0); InputMethodManager imm = (InputMethodManager) instance.activity.getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(instance, 0); instance.setListenerToRootView(); } catch (Exception e) { logger.log(e); } } }); return obj; } }); //register for clear focus NativeShim.RegisterCallable("editText.clearFocus", new TeaLeafCallable() { public JSONObject call(final JSONObject obj) { activity.runOnUiThread(new Runnable() { public void run() { TeaLeaf.get().glView.setOnTouchListener(instance.currentTouchListener); instance.hideKeyboard(); instance.setVisibility(View.GONE); instance.removeListenerToRootView(); } }); return obj; } }); instance.onGlobalLayoutListener = new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { View group = (View)TeaLeaf.get().getGroup(); // get visible area of the view Rect r = new Rect(); group.getWindowVisibleDisplayFrame(r); // get display height Display display = instance.activity.getWindow().getWindowManager().getDefaultDisplay(); int height = display.getHeight(); // if our visible height is less than 75% normal, assume keyboard on screen int visibleHeight = r.bottom - r.top; if (visibleHeight < .75 * height && !instance.isOpened) { instance.isOpened = true; } else if(instance.isOpened){ EventQueue.pushEvent(new Event("editText.onFinishEditing")); } } }; } return instance; }
diff --git a/src/uk/me/parabola/imgfmt/sys/BlockManager.java b/src/uk/me/parabola/imgfmt/sys/BlockManager.java index 28505273..42cab5f9 100644 --- a/src/uk/me/parabola/imgfmt/sys/BlockManager.java +++ b/src/uk/me/parabola/imgfmt/sys/BlockManager.java @@ -1,65 +1,67 @@ /* * Copyright (C) 2007 Steve Ratcliffe * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * 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. * * * Author: Steve Ratcliffe * Create date: 25-Oct-2007 */ package uk.me.parabola.imgfmt.sys; import uk.me.parabola.imgfmt.ExitException; import uk.me.parabola.log.Logger; /** * This is used to allocate blocks for files in the filesystem/archive. * * @author Steve Ratcliffe */ class BlockManager { private static final Logger log = Logger.getLogger(BlockManager.class); private int currentBlock; private final int blockSize; private int maxBlock = 0xfffe; BlockManager(int blockSize, int initialBlock) { this.blockSize = blockSize; this.currentBlock = initialBlock; } /** * Well the algorithm is pretty simple - you just get the next unused block * number. * * @return A block number that is free to be used. */ public int allocate() { int n = currentBlock++; if (maxBlock > 0 && n > maxBlock) { log.error("overflowed directory with max block " + maxBlock + ", current=" + n); - throw new ExitException("Directory overflow. This is a bug in mkgmap"); + throw new ExitException( + "There is not enough room in a single garmin map for all the input data\n" + + " The .osm file should be split into smaller pieces first."); } return n; } public int getBlockSize() { return blockSize; } public int getMaxBlock() { return maxBlock; } public void setMaxBlock(int maxBlock) { this.maxBlock = maxBlock; } }
true
true
public int allocate() { int n = currentBlock++; if (maxBlock > 0 && n > maxBlock) { log.error("overflowed directory with max block " + maxBlock + ", current=" + n); throw new ExitException("Directory overflow. This is a bug in mkgmap"); } return n; }
public int allocate() { int n = currentBlock++; if (maxBlock > 0 && n > maxBlock) { log.error("overflowed directory with max block " + maxBlock + ", current=" + n); throw new ExitException( "There is not enough room in a single garmin map for all the input data\n" + " The .osm file should be split into smaller pieces first."); } return n; }
diff --git a/src/cytoscape/data/ImportHandler.java b/src/cytoscape/data/ImportHandler.java index 0077e9310..e33c5e0fb 100644 --- a/src/cytoscape/data/ImportHandler.java +++ b/src/cytoscape/data/ImportHandler.java @@ -1,516 +1,518 @@ /* Copyright (c) 2006, 2007, The Cytoscape Consortium (www.cytoscape.org) The Cytoscape Consortium is: - Institute for Systems Biology - University of California San Diego - Memorial Sloan-Kettering Cancer Center - Institut Pasteur - Agilent Technologies This library 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 any later version. This library 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. The software and documentation provided hereunder is on an "as is" basis, and the Institute for Systems Biology and the Whitehead Institute have no obligations to provide maintenance, support, updates, enhancements or modifications. In no event shall the Institute for Systems Biology and the Whitehead Institute be liable to any party for direct, indirect, special, incidental or consequential damages, including lost profits, arising out of the use of this software and its documentation, even if the Institute for Systems Biology and the Whitehead Institute have been advised of the possibility of such damage. 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 library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ package cytoscape.data; import cytoscape.data.readers.GraphReader; import cytoscape.task.TaskMonitor; import cytoscape.task.ui.JTask; import cytoscape.util.CyFileFilter; import cytoscape.util.GMLFileFilter; import cytoscape.util.ProxyHandler; import cytoscape.util.SIFFileFilter; import cytoscape.util.XGMMLFileFilter; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.net.Proxy; import java.net.URL; import java.net.URLConnection; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Central registry for all Cytoscape import classes. * * @author Cytoscape Development Team. */ public class ImportHandler { /** * Filter Type: NETWORK. */ public static String GRAPH_NATURE = "NETWORK"; /** * Filter Type: NODE. */ public static String NODE_NATURE = "NODE"; /** * Filter Type: EDGE. */ public static String EDGE_NATURE = "EDGE"; /** * Filer Type: PROPERTIES. */ public static String PROPERTIES_NATURE = "PROPERTIES"; /** * Set of all registered CyFileFilter Objects. */ protected static Set cyFileFilters = new HashSet(); /** * Constructor. */ public ImportHandler() { // By default, register SIF, XGMML and GML File Filters init(); } /** * Initialize ImportHandler. */ private void init() { addFilter(new SIFFileFilter()); addFilter(new XGMMLFileFilter()); addFilter(new GMLFileFilter()); } /** * Registers a new CyFileFilter. * * @param cff CyFileFilter. * @return true indicates filter was added successfully. */ public boolean addFilter(CyFileFilter cff) { Set check = cff.getExtensionSet(); for (Iterator it = check.iterator(); it.hasNext();) { String extension = (String) it.next(); if (getAllExtensions().contains(extension) && !extension.equals("xml")) { return false; } } cyFileFilters.add(cff); return true; } /** * Registers an Array of CyFileFilter Objects. * * @param cff Array of CyFileFilter Objects. * @return true indicates all filters were added successfully. */ public boolean addFilter(CyFileFilter[] cff) { //first check if suffixes are unique boolean flag = true; for (int j = 0; (j < cff.length) && (flag == true); j++) { flag = addFilter(cff[j]); } return flag; } /** * Gets the GraphReader that is capable of reading the specified file. * * @param fileName File name or null if no reader is capable of reading the file. * @return GraphReader capable of reading the specified file. */ public GraphReader getReader(String fileName) { // check if fileType is available CyFileFilter cff; for (Iterator it = cyFileFilters.iterator(); it.hasNext();) { cff = (CyFileFilter) it.next(); if (cff.accept(fileName)) { return cff.getReader(fileName); } } return null; } /** * Gets the GraphReader that is capable of reading URL. * * @param url -- the URL string * @return GraphReader capable of reading the specified URL. */ public GraphReader getReader(URL url) { // check if fileType is available CyFileFilter cff; // Open up the connection Proxy pProxyServer = ProxyHandler.getProxyServer(); URLConnection conn = null; try { if (pProxyServer == null) conn = url.openConnection(); else conn = url.openConnection(pProxyServer); } catch (IOException ioe) { System.out.println("Unable to open "+url); return null; } // Ensure we are reading the real content from url, // and not some out-of-date cached content: conn.setUseCaches(false); // Get the content-type String contentType = conn.getContentType(); + if ( contentType == null ) + contentType = ""; // System.out.println("Content-type: "+contentType); int cend = contentType.indexOf(';'); if (cend >= 0) contentType = contentType.substring(0, cend); for (Iterator it = cyFileFilters.iterator(); it.hasNext();) { cff = (CyFileFilter) it.next(); if (cff.accept(url, contentType)) { // System.out.println("Found reader: "+cff.getDescription()); GraphReader reader = cff.getReader(url, conn); // Does the reader support the url,connection constructor? if (reader != null) { // Yes, return it return reader; } // No, see if we can find another one that does } } // If the content type is text/plain or text/html or text/xml // then write a temp file and handle things that way if (contentType.contains("text/html") || contentType.contains("text/plain") || contentType.contains("text/xml")) { File tmpFile = null; try { tmpFile = downloadFromURL(url, null); } catch (Exception e) { System.out.println("Failed to download from URL: "+url); } if (tmpFile != null) { return getReader(tmpFile.getAbsolutePath()); } } // System.out.println("No reader for: "+url.toString()); return null; } /** * Gets descriptions for all registered filters, which are of the type: fileNature. * * @param fileNature type: GRAPH_NATURE, NODE_NATURE, EDGE_NATURE, etc. * @return Collection of String descriptions, e.g. "XGMML files" */ public Collection getAllTypes(String fileNature) { Collection ans = new HashSet(); CyFileFilter cff; for (Iterator it = cyFileFilters.iterator(); it.hasNext();) { cff = (CyFileFilter) it.next(); //if statement to check if nature equals fileNature if (cff.getFileNature().equals(fileNature)) { cff.setExtensionListInDescription(false); ans.add(cff.getDescription()); cff.setExtensionListInDescription(true); } } return ans; } /** * Gets a collection of all registered file extensions. * * @return Collection of Strings, e.g. "xgmml", "sif", etc. */ public Collection getAllExtensions() { Collection ans = new HashSet(); for (Iterator it = cyFileFilters.iterator(); it.hasNext();) { ans.addAll(((CyFileFilter) (it.next())).getExtensionSet()); } return ans; } /** * Gets a collection of all registered filter descriptions. * Descriptions are of the form: "{File Description} ({file extensions})". * For example: "GML files (*.gml)" * * @return Collection of Strings, e.g. "GML files (*.gml)", etc. */ public Collection getAllDescriptions() { Collection ans = new HashSet(); for (Iterator it = cyFileFilters.iterator(); it.hasNext();) { ans.add(((CyFileFilter) it.next()).getDescription()); } return ans; } /** * Gets the name of the filter which is capable of reading the specified file. * * @param fileName File Name. * @return name of filter capable of reading the specified file. */ public String getFileType(String fileName) { CyFileFilter cff; String ans = null; for (Iterator it = cyFileFilters.iterator(); it.hasNext();) { cff = (CyFileFilter) it.next(); if (cff.accept(fileName)) { cff.setExtensionListInDescription(false); ans = (cff.getDescription()); cff.setExtensionListInDescription(true); } } return ans; } /** * Gets a list of all registered filters plus a catch-all super set filter. * * @return List of CyFileFilter Objects. */ public List getAllFilters() { List ans = new ArrayList(); for (Iterator it = cyFileFilters.iterator(); it.hasNext();) { ans.add((CyFileFilter) it.next()); } if (ans.size() > 1) { String[] allTypes = concatAllExtensions(ans); ans.add(new CyFileFilter(allTypes, "All Natures")); } return ans; } /** * Gets a list of all registered filters, which are of type: fileNature, * plus a catch-all super set filter. * * @param fileNature type: GRAPH_NATURE, NODE_NATURE, EDGE_NATURE, etc. * @return List of CyFileFilter Objects. */ public List getAllFilters(String fileNature) { List ans = new ArrayList(); CyFileFilter cff; for (Iterator it = cyFileFilters.iterator(); it.hasNext();) { cff = (CyFileFilter) it.next(); //if statement to check if nature equals fileNature if (cff.getFileNature().equals(fileNature)) { ans.add(cff); } } if (ans.size() > 1) { String[] allTypes = concatAllExtensions(ans); ans.add(new CyFileFilter(allTypes, "All " + fileNature.toLowerCase() + " files", fileNature)); } return ans; } /** * Unregisters all registered File Filters (except default file filters.) * Resets everything with a clean slate. */ public void resetImportHandler() { cyFileFilters = new HashSet(); init(); } /** * Creates a String array of all extensions */ private String[] concatAllExtensions(List cffs) { Set ans = new HashSet(); for (Iterator it = cffs.iterator(); it.hasNext();) { ans.addAll(((CyFileFilter) (it.next())).getExtensionSet()); } String[] stringAns = (String[]) ans.toArray(new String[0]); return stringAns; } private String extractExtensionFromContentType(String ct) { Pattern p = Pattern.compile("^\\w+/([\\w|-]+);*.*"); Matcher m = p.matcher(ct); if (m.matches()) return m.group(1); else return "txt"; } // Create a temp file for URL download private File createTempFile(URLConnection conn, URL url) throws IOException { File tmpFile = null; String tmpDir = System.getProperty("java.io.tmpdir"); String pURLstr = url.toString(); // Try if we can determine the network type from URLstr // test the URL against the various file extensions, // if one matches, then extract the basename Collection theExts = getAllExtensions(); for (Iterator it = theExts.iterator(); it.hasNext();) { String theExt = (String) it.next(); if (pURLstr.endsWith(theExt)) { tmpFile = new File(tmpDir + System.getProperty("file.separator") + pURLstr.substring(pURLstr.lastIndexOf("/") + 1)); break; } } // if none of the extensions match, then use the the content type as // a suffix and create a temp file. if (tmpFile == null) { String ct = "." + extractExtensionFromContentType(conn.getContentType()); tmpFile = File.createTempFile("url.download.", ct, new File(tmpDir)); } if (tmpFile == null) return null; else tmpFile.deleteOnExit(); return tmpFile; } /** * Download a temporary file from the given URL. The file will be saved in the * temporary directory and will be deleted after Cytoscape exits. * @param u -- the URL string, TaskMonitor if any * @return -- a temporary file downloaded from the given URL. */ public File downloadFromURL(URL url, TaskMonitor taskMonitor) throws IOException, FileNotFoundException { Proxy pProxyServer = ProxyHandler.getProxyServer(); URLConnection conn = null; if (pProxyServer == null) conn = url.openConnection(); else conn = url.openConnection(pProxyServer); // Ensure we are reading the real content from url, // and not some out-of-date cached content: conn.setUseCaches(false); // create the temp file File tmpFile = createTempFile(conn, url); // This is needed for the progress monitor int maxCount = conn.getContentLength(); // -1 if unknown int progressCount = 0; // now write the temp file BufferedWriter out = null; BufferedReader in = null; out = new BufferedWriter(new FileWriter(tmpFile)); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine = null; double percent = 0.0d; while ((inputLine = in.readLine()) != null) { progressCount += inputLine.length(); // Report on Progress if (taskMonitor != null) { percent = ((double) progressCount / maxCount) * 100.0; if (maxCount == -1) { // file size unknown percent = -1; } JTask jTask = (JTask) taskMonitor; if (jTask.haltRequested()) { //abort tmpFile = null; taskMonitor.setStatus("Canceling the download task ..."); taskMonitor.setPercentCompleted(100); break; } taskMonitor.setPercentCompleted((int) percent); } out.write(inputLine); out.newLine(); } in.close(); out.close(); return tmpFile; } // End of downloadFromURL() }
true
true
public GraphReader getReader(URL url) { // check if fileType is available CyFileFilter cff; // Open up the connection Proxy pProxyServer = ProxyHandler.getProxyServer(); URLConnection conn = null; try { if (pProxyServer == null) conn = url.openConnection(); else conn = url.openConnection(pProxyServer); } catch (IOException ioe) { System.out.println("Unable to open "+url); return null; } // Ensure we are reading the real content from url, // and not some out-of-date cached content: conn.setUseCaches(false); // Get the content-type String contentType = conn.getContentType(); // System.out.println("Content-type: "+contentType); int cend = contentType.indexOf(';'); if (cend >= 0) contentType = contentType.substring(0, cend); for (Iterator it = cyFileFilters.iterator(); it.hasNext();) { cff = (CyFileFilter) it.next(); if (cff.accept(url, contentType)) { // System.out.println("Found reader: "+cff.getDescription()); GraphReader reader = cff.getReader(url, conn); // Does the reader support the url,connection constructor? if (reader != null) { // Yes, return it return reader; } // No, see if we can find another one that does } } // If the content type is text/plain or text/html or text/xml // then write a temp file and handle things that way if (contentType.contains("text/html") || contentType.contains("text/plain") || contentType.contains("text/xml")) { File tmpFile = null; try { tmpFile = downloadFromURL(url, null); } catch (Exception e) { System.out.println("Failed to download from URL: "+url); } if (tmpFile != null) { return getReader(tmpFile.getAbsolutePath()); } } // System.out.println("No reader for: "+url.toString()); return null; }
public GraphReader getReader(URL url) { // check if fileType is available CyFileFilter cff; // Open up the connection Proxy pProxyServer = ProxyHandler.getProxyServer(); URLConnection conn = null; try { if (pProxyServer == null) conn = url.openConnection(); else conn = url.openConnection(pProxyServer); } catch (IOException ioe) { System.out.println("Unable to open "+url); return null; } // Ensure we are reading the real content from url, // and not some out-of-date cached content: conn.setUseCaches(false); // Get the content-type String contentType = conn.getContentType(); if ( contentType == null ) contentType = ""; // System.out.println("Content-type: "+contentType); int cend = contentType.indexOf(';'); if (cend >= 0) contentType = contentType.substring(0, cend); for (Iterator it = cyFileFilters.iterator(); it.hasNext();) { cff = (CyFileFilter) it.next(); if (cff.accept(url, contentType)) { // System.out.println("Found reader: "+cff.getDescription()); GraphReader reader = cff.getReader(url, conn); // Does the reader support the url,connection constructor? if (reader != null) { // Yes, return it return reader; } // No, see if we can find another one that does } } // If the content type is text/plain or text/html or text/xml // then write a temp file and handle things that way if (contentType.contains("text/html") || contentType.contains("text/plain") || contentType.contains("text/xml")) { File tmpFile = null; try { tmpFile = downloadFromURL(url, null); } catch (Exception e) { System.out.println("Failed to download from URL: "+url); } if (tmpFile != null) { return getReader(tmpFile.getAbsolutePath()); } } // System.out.println("No reader for: "+url.toString()); return null; }
diff --git a/src/gamesincommon/GamesInCommon.java b/src/gamesincommon/GamesInCommon.java index 68933e0..eccc363 100644 --- a/src/gamesincommon/GamesInCommon.java +++ b/src/gamesincommon/GamesInCommon.java @@ -1,299 +1,311 @@ package gamesincommon; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import com.github.koraktor.steamcondenser.exceptions.SteamCondenserException; import com.github.koraktor.steamcondenser.steam.community.SteamGame; import com.github.koraktor.steamcondenser.steam.community.SteamId; public class GamesInCommon { Connection connection = null; private Logger logger; public GamesInCommon() { // initialise logger logger = Logger.getLogger(GamesInCommon.class.getName()); logger.setLevel(Level.ALL); // initialise database connector connection = InitialDBCheck(); if (connection == null) { throw new RuntimeException("Connection could not be establised to local database."); } } public Logger getLogger() { return logger; } /** * Creates local database, if necessary, and creates tables for all enum entries. * * @return A Connection object to the database. */ private Connection InitialDBCheck() { // newDB is TRUE if the database is about to be created by DriverManager.getConnection(); File dbFile = new File("gamedata.db"); boolean newDB = (!(dbFile).exists()); Connection result = null; try { Class.forName("org.sqlite.JDBC"); // attempt to connect to the database result = DriverManager.getConnection("jdbc:sqlite:gamedata.db"); // check all tables from the information schema Statement statement = result.createStatement(); ResultSet resultSet = null; // and copy resultset to List object to enable random access List<String> tableList = new ArrayList<String>(); // skip if new database, as it'll all be new anyway if (!newDB) { // query db resultSet = statement.executeQuery("SELECT name FROM sqlite_master WHERE type='table';"); // copy to tableList while (resultSet.next()) { tableList.add(resultSet.getString("name")); } } else { logger.log(Level.INFO, "New database created."); } // check all filtertypes have a corresponding table, create if one if not present // skip check and create if the database is new for (FilterType filter : FilterType.values()) { boolean filterFound = false; if (!newDB) { for (String tableName : tableList) { if (tableName.equals(filter.getValue())) { filterFound = true; } } } // if the tableList is traversed and the filter was not found, create a table for it if (!filterFound) { statement.executeUpdate("CREATE TABLE [" + filter.getValue() + "] ( AppID VARCHAR( 16 ) PRIMARY KEY ON CONFLICT FAIL," + "Name VARCHAR( 64 )," + "HasProperty BOOLEAN NOT NULL ON CONFLICT FAIL );"); } } } catch (ClassNotFoundException | SQLException e) { logger.log(Level.SEVERE, e.getMessage(), e); } return result; } /** * Finds common games between an arbitrarily long list of users * * @param users * A list of names to find common games for. * @return A collection of games common to all users */ public Collection<SteamGame> findCommonGames(List<SteamId> users) { List<Collection<SteamGame>> userGames = new ArrayList<Collection<SteamGame>>(); for (SteamId name : users) { try { userGames.add(getGames(name)); logger.log(Level.INFO, "Added user " + name.getNickname() + " (" + name.getSteamId64() + ")."); } catch (SteamCondenserException e) { logger.log(Level.SEVERE, e.getMessage()); return null; } } Collection<SteamGame> commonGames = mergeSets(userGames); logger.log(Level.INFO, "Search complete."); return commonGames; } public SteamId checkSteamId(String nameToCheck) throws SteamCondenserException { try { return SteamId.create(nameToCheck); } catch (SteamCondenserException e1) { try { return SteamId.create(Long.parseLong(nameToCheck)); } catch (SteamCondenserException | NumberFormatException e2) { throw e1; } } } /** * Finds all games from the given steam user. * * @param sId * The SteamId of the user to get games from. * @return A set of all games for the give user. * @throws SteamCondenserException */ public Collection<SteamGame> getGames(SteamId sId) throws SteamCondenserException { return sId.getGames().values(); } /** * Returns games that match one or more of the given filter types * * @param gameList * Collection of games to be filtered. * @param filterList * Collection of filters to apply. * @return A collection of games matching one or more of filters. */ public Collection<SteamGame> filterGames(Collection<SteamGame> gameList, List<FilterType> filterList) { Collection<SteamGame> result = new HashSet<SteamGame>(); // get list of tables Statement s = null; for (SteamGame game : gameList) { ResultSet tableSet = null; // first run a query through the local db try { s = connection.createStatement(); tableSet = s.executeQuery("SELECT name FROM sqlite_master WHERE type='table';"); } catch (SQLException e1) { logger.log(Level.SEVERE, e1.getMessage(), e1); } // filtersToCheck tells the following webcheck loop which filters need checking and insertion into the DB Map<FilterType, Boolean> filtersToCheck = new HashMap<FilterType, Boolean>(); // default to "needs checking" boolean needsWebCheck = true; try { // query the table that matches the filter while (tableSet.next()) { - ResultSet rSet = null;; + ResultSet rSet = null; + ; // if the game is not already in the result Collection if (!result.contains(game)) { for (FilterType filter : filterList) { if (filter.getValue().equals((tableSet.getString("name")))) { s = connection.createStatement(); rSet = s.executeQuery("SELECT * FROM [" + tableSet.getString("name") + "] WHERE AppID = '" + game.getAppId() + "'"); } // if rSet.next() indicates a match if ((rSet != null) && (rSet.next())) { // if the game passes the filter and is not already in the result collection, add it if (rSet.getBoolean("HasProperty")) { result.add(game); } // if there's an entry in the database, no need to check anywhere else filtersToCheck.put(filter, false); needsWebCheck = false; logger.log(Level.INFO, "[SQL] Checked game '" + game.getName() + "'"); rSet.close(); } else { // "needs checking" - filtersToCheck.put(filter, true); + filtersToCheck.put(filter, true); } } } if (rSet != null) { rSet.close(); } } if (tableSet != null) { tableSet.close(); } } catch (SQLException e2) { logger.log(Level.SEVERE, e2.getMessage(), e2); } // if any games need checking, we'll need to send requests to the steampowered.com website for data if (needsWebCheck) { // foundProperties records whether it has or does not have each of the filters HashMap<FilterType, Boolean> foundProperties = new HashMap<FilterType, Boolean>(); try (BufferedReader br = new BufferedReader(new InputStreamReader(new URL( "http://store.steampowered.com/api/appdetails/?appids=" + game.getAppId()).openStream()));) { // Read lines in until there are no more to be read, run filter on each line looking for specified package IDs. String line; while (((line = br.readLine()) != null) && (!result.contains(game))) { for (FilterType filter : filterList) { // default false until set to true foundProperties.put(filter, false); if (line.contains("\"" + filter.getValue() + "\"")) { result.add(game); // success - add to foundProperties as TRUE foundProperties.put(filter, true); } } } // if we have any filters that needed data, match them up with foundProperties and insert them into the database + // IF filterToCheck -> true INSERT INTO DB foundProperties.value(); for (Map.Entry<FilterType, Boolean> filterToCheck : filtersToCheck.entrySet()) { if (filterToCheck.getValue().equals(new Boolean(true))) { for (Map.Entry<FilterType, Boolean> entry : foundProperties.entrySet()) { - // SQL takes booleans as 1 or 0 intead of TRUE or FALSE - int boolVal = (entry.getValue().equals(new Boolean(true))) ? 1 : 0; - connection.createStatement().executeUpdate( - "INSERT INTO [" + entry.getKey().toString() + "] (AppID, Name, HasProperty) VALUES ('" - + game.getAppId() + "','" + sanitiseInputString(game.getName()) + "', " + boolVal + ")"); + // END OF ALL WHACK-A-MOLE GAMES + s = connection.createStatement(); + ResultSet checkSet = s.executeQuery("SELECT * FROM [" + entry.getKey().toString() + "] WHERE AppID='" + + game.getAppId() + "';"); + if (checkSet.next()) { + // if checkSet returns a value, skip + } else { + // SQL takes booleans as 1 or 0 intead of TRUE or FALSE + int boolVal = (entry.getValue().equals(new Boolean(true))) ? 1 : 0; + connection.createStatement() + .executeUpdate( + "INSERT INTO [" + entry.getKey().toString() + "] (AppID, Name, HasProperty) VALUES ('" + + game.getAppId() + "','" + sanitiseInputString(game.getName()) + "', " + + boolVal + ")"); + } } } } logger.log(Level.INFO, "[WEB] Checked game '" + game.getName() + "'"); } catch (IOException | SQLException e3) { logger.log(Level.SEVERE, e3.getMessage(), e3); } } } return result; } /** * Merges multiple user game sets together to keep all games that are the same. * * @param userGames * A list of user game sets. * @return A set containing all common games. */ public Collection<SteamGame> mergeSets(List<Collection<SteamGame>> userGames) { if (userGames.size() == 0) { return null; } Collection<SteamGame> result = new ArrayList<SteamGame>(); int size = 0; int index = 0; for (int i = 0; i < userGames.size(); i++) { if (userGames.get(i).size() > size) { size = userGames.get(i).size(); index = i; } } result.addAll(userGames.get(index)); for (int i = 0; i < userGames.size(); i++) { result.retainAll(userGames.get(i)); } return result; } public String sanitiseInputString(String input) { return input.replace("'", "''"); } }
false
true
public Collection<SteamGame> filterGames(Collection<SteamGame> gameList, List<FilterType> filterList) { Collection<SteamGame> result = new HashSet<SteamGame>(); // get list of tables Statement s = null; for (SteamGame game : gameList) { ResultSet tableSet = null; // first run a query through the local db try { s = connection.createStatement(); tableSet = s.executeQuery("SELECT name FROM sqlite_master WHERE type='table';"); } catch (SQLException e1) { logger.log(Level.SEVERE, e1.getMessage(), e1); } // filtersToCheck tells the following webcheck loop which filters need checking and insertion into the DB Map<FilterType, Boolean> filtersToCheck = new HashMap<FilterType, Boolean>(); // default to "needs checking" boolean needsWebCheck = true; try { // query the table that matches the filter while (tableSet.next()) { ResultSet rSet = null;; // if the game is not already in the result Collection if (!result.contains(game)) { for (FilterType filter : filterList) { if (filter.getValue().equals((tableSet.getString("name")))) { s = connection.createStatement(); rSet = s.executeQuery("SELECT * FROM [" + tableSet.getString("name") + "] WHERE AppID = '" + game.getAppId() + "'"); } // if rSet.next() indicates a match if ((rSet != null) && (rSet.next())) { // if the game passes the filter and is not already in the result collection, add it if (rSet.getBoolean("HasProperty")) { result.add(game); } // if there's an entry in the database, no need to check anywhere else filtersToCheck.put(filter, false); needsWebCheck = false; logger.log(Level.INFO, "[SQL] Checked game '" + game.getName() + "'"); rSet.close(); } else { // "needs checking" filtersToCheck.put(filter, true); } } } if (rSet != null) { rSet.close(); } } if (tableSet != null) { tableSet.close(); } } catch (SQLException e2) { logger.log(Level.SEVERE, e2.getMessage(), e2); } // if any games need checking, we'll need to send requests to the steampowered.com website for data if (needsWebCheck) { // foundProperties records whether it has or does not have each of the filters HashMap<FilterType, Boolean> foundProperties = new HashMap<FilterType, Boolean>(); try (BufferedReader br = new BufferedReader(new InputStreamReader(new URL( "http://store.steampowered.com/api/appdetails/?appids=" + game.getAppId()).openStream()));) { // Read lines in until there are no more to be read, run filter on each line looking for specified package IDs. String line; while (((line = br.readLine()) != null) && (!result.contains(game))) { for (FilterType filter : filterList) { // default false until set to true foundProperties.put(filter, false); if (line.contains("\"" + filter.getValue() + "\"")) { result.add(game); // success - add to foundProperties as TRUE foundProperties.put(filter, true); } } } // if we have any filters that needed data, match them up with foundProperties and insert them into the database for (Map.Entry<FilterType, Boolean> filterToCheck : filtersToCheck.entrySet()) { if (filterToCheck.getValue().equals(new Boolean(true))) { for (Map.Entry<FilterType, Boolean> entry : foundProperties.entrySet()) { // SQL takes booleans as 1 or 0 intead of TRUE or FALSE int boolVal = (entry.getValue().equals(new Boolean(true))) ? 1 : 0; connection.createStatement().executeUpdate( "INSERT INTO [" + entry.getKey().toString() + "] (AppID, Name, HasProperty) VALUES ('" + game.getAppId() + "','" + sanitiseInputString(game.getName()) + "', " + boolVal + ")"); } } } logger.log(Level.INFO, "[WEB] Checked game '" + game.getName() + "'"); } catch (IOException | SQLException e3) { logger.log(Level.SEVERE, e3.getMessage(), e3); } } } return result; }
public Collection<SteamGame> filterGames(Collection<SteamGame> gameList, List<FilterType> filterList) { Collection<SteamGame> result = new HashSet<SteamGame>(); // get list of tables Statement s = null; for (SteamGame game : gameList) { ResultSet tableSet = null; // first run a query through the local db try { s = connection.createStatement(); tableSet = s.executeQuery("SELECT name FROM sqlite_master WHERE type='table';"); } catch (SQLException e1) { logger.log(Level.SEVERE, e1.getMessage(), e1); } // filtersToCheck tells the following webcheck loop which filters need checking and insertion into the DB Map<FilterType, Boolean> filtersToCheck = new HashMap<FilterType, Boolean>(); // default to "needs checking" boolean needsWebCheck = true; try { // query the table that matches the filter while (tableSet.next()) { ResultSet rSet = null; ; // if the game is not already in the result Collection if (!result.contains(game)) { for (FilterType filter : filterList) { if (filter.getValue().equals((tableSet.getString("name")))) { s = connection.createStatement(); rSet = s.executeQuery("SELECT * FROM [" + tableSet.getString("name") + "] WHERE AppID = '" + game.getAppId() + "'"); } // if rSet.next() indicates a match if ((rSet != null) && (rSet.next())) { // if the game passes the filter and is not already in the result collection, add it if (rSet.getBoolean("HasProperty")) { result.add(game); } // if there's an entry in the database, no need to check anywhere else filtersToCheck.put(filter, false); needsWebCheck = false; logger.log(Level.INFO, "[SQL] Checked game '" + game.getName() + "'"); rSet.close(); } else { // "needs checking" filtersToCheck.put(filter, true); } } } if (rSet != null) { rSet.close(); } } if (tableSet != null) { tableSet.close(); } } catch (SQLException e2) { logger.log(Level.SEVERE, e2.getMessage(), e2); } // if any games need checking, we'll need to send requests to the steampowered.com website for data if (needsWebCheck) { // foundProperties records whether it has or does not have each of the filters HashMap<FilterType, Boolean> foundProperties = new HashMap<FilterType, Boolean>(); try (BufferedReader br = new BufferedReader(new InputStreamReader(new URL( "http://store.steampowered.com/api/appdetails/?appids=" + game.getAppId()).openStream()));) { // Read lines in until there are no more to be read, run filter on each line looking for specified package IDs. String line; while (((line = br.readLine()) != null) && (!result.contains(game))) { for (FilterType filter : filterList) { // default false until set to true foundProperties.put(filter, false); if (line.contains("\"" + filter.getValue() + "\"")) { result.add(game); // success - add to foundProperties as TRUE foundProperties.put(filter, true); } } } // if we have any filters that needed data, match them up with foundProperties and insert them into the database // IF filterToCheck -> true INSERT INTO DB foundProperties.value(); for (Map.Entry<FilterType, Boolean> filterToCheck : filtersToCheck.entrySet()) { if (filterToCheck.getValue().equals(new Boolean(true))) { for (Map.Entry<FilterType, Boolean> entry : foundProperties.entrySet()) { // END OF ALL WHACK-A-MOLE GAMES s = connection.createStatement(); ResultSet checkSet = s.executeQuery("SELECT * FROM [" + entry.getKey().toString() + "] WHERE AppID='" + game.getAppId() + "';"); if (checkSet.next()) { // if checkSet returns a value, skip } else { // SQL takes booleans as 1 or 0 intead of TRUE or FALSE int boolVal = (entry.getValue().equals(new Boolean(true))) ? 1 : 0; connection.createStatement() .executeUpdate( "INSERT INTO [" + entry.getKey().toString() + "] (AppID, Name, HasProperty) VALUES ('" + game.getAppId() + "','" + sanitiseInputString(game.getName()) + "', " + boolVal + ")"); } } } } logger.log(Level.INFO, "[WEB] Checked game '" + game.getName() + "'"); } catch (IOException | SQLException e3) { logger.log(Level.SEVERE, e3.getMessage(), e3); } } } return result; }
diff --git a/src/barsan/opengl/rendering/Shader.java b/src/barsan/opengl/rendering/Shader.java index a149040..8dfa7f5 100644 --- a/src/barsan/opengl/rendering/Shader.java +++ b/src/barsan/opengl/rendering/Shader.java @@ -1,345 +1,352 @@ /** * YETI Engine Copyright (c) 2012-2013, Andrei B�rsan 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. * * 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 barsan.opengl.rendering; import java.lang.reflect.Array; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.media.opengl.GL2; import javax.media.opengl.GL2GL3; import javax.media.opengl.GL3; import barsan.opengl.Yeti; import barsan.opengl.math.Matrix3; import barsan.opengl.math.Matrix4; import barsan.opengl.math.Vector2; import barsan.opengl.math.Vector3; import barsan.opengl.rendering.materials.BumpComponent; import barsan.opengl.rendering.materials.ShadowReceiver; import barsan.opengl.util.Color; /** * Shader wrapper class that facilitates material interactions with the underlying * GPU program. * * @note It caches all the uniform locations, indexed by their name, in a * HashMap to limit the number of native calls being performed (VisualVM showed * this as one of the top 10 time consumers). * * @author Andrei B�rsan */ public class Shader { public static final String A_POSITION = "vVertex"; public static final String A_NORMAL = "vNormal"; public static final String A_TEXCOORD = "vTexCoord"; private static final List<String> groks = Arrays.asList("No errors."); // Utility buffers static final IntBuffer i_buff = IntBuffer.allocate(8); static final ByteBuffer b_buff = ByteBuffer.allocate(1024); static final int[] result = new int[1]; public static HashMap<String, Shader> compileBulk(GL2GL3 gl, String[] vertexData, String[] fragmentData) { assert vertexData.length == fragmentData.length; HashMap<String, Shader> result = new HashMap<>(vertexData.length); // TODO: implement return result; } /* pp */ int handle = -1; /* pp */ String name = ""; private HashMap<String, Integer> uLocCache = new HashMap<>(); public Shader(GL2GL3 gl, String name, String vertexSrc, String fragmentSrc) { this(gl, name, vertexSrc, fragmentSrc, null, new String[] { A_POSITION, A_NORMAL }); } public Shader(GL2GL3 gl, String name, String vertexSrc, String fragmentSrc, String geometrySrc) { this(gl, name, vertexSrc, fragmentSrc, geometrySrc, new String[] { A_POSITION, A_NORMAL }); } public int getHandle() { return handle; } public Shader(GL2GL3 gl, String name, String vertexSrc, String fragmentSrc, String geometrySrc, String[] args) { int vertex = gl.glCreateShader(GL2.GL_VERTEX_SHADER); int fragment = gl.glCreateShader(GL2.GL_FRAGMENT_SHADER); int geometry = 0; boolean hasGeometry = (geometrySrc != null); gl.glShaderSource(vertex, 1, new String[] { vertexSrc }, (int[])null, 0); gl.glCompileShader(vertex); checkShader("Vertex shader [" + name + "]", vertex); if(hasGeometry) { geometry = gl.glCreateShader(GL3.GL_GEOMETRY_SHADER); gl.glShaderSource(geometry, 1, new String[] { geometrySrc }, (int[])null, 0); gl.glCompileShader(geometry); checkShader("Geometry shader [" + name + "]", geometry); } // The null int[] is required -> otherwise the source code somehow // gets corrupted and causes strange errors. gl.glShaderSource(fragment, 1, new String[] { fragmentSrc }, (int[])null, 0); gl.glCompileShader(fragment); checkShader("Fragment shader [" + name + "]", fragment); int shaderProgram = gl.glCreateProgram(); gl.glAttachShader(shaderProgram, vertex); gl.glAttachShader(shaderProgram, fragment); if(hasGeometry) { gl.glAttachShader(shaderProgram, geometry); } // Maybe pre-bind attributes here? gl.glLinkProgram(shaderProgram); checkProgram("Shader [" + name + "]", shaderProgram); gl.glValidateProgram(shaderProgram); gl.glDeleteShader(vertex); gl.glDeleteShader(fragment); if(hasGeometry) { gl.glDeleteShader(geometry); } this.name = name; this.handle = shaderProgram; } public int getAttribLocation(String name) { GL2GL3 gl = Yeti.get().gl; return gl.glGetAttribLocation(handle, name); } public boolean setUMatrix4(String uniformName, Matrix4 matrix) { GL2GL3 gl = Yeti.get().gl; int pos = grabUniform(uniformName); if(pos == -1) return false; gl.glUniformMatrix4fv(pos, 1, false, matrix.getData(), 0); return true; } public boolean setUMatrix4a(String uniformName, Matrix4[] matrix) { GL2GL3 gl = Yeti.get().gl; int pos = grabUniform(uniformName); if(pos == -1) return false; float[] buffer = new float[matrix.length * 16]; for(int i = 0; i < matrix.length; i++) { System.arraycopy(matrix[i].getData(), 0, buffer, 16 * i, 16); } gl.glUniformMatrix4fv(pos, matrix.length, false, buffer, 0); return true; } public boolean setUVector2f(String uniformName, Vector2 value) { return setUVector2f(uniformName, value.x, value.y); } public boolean setUVector2f(String uniformName, float x, float y) { GL2GL3 gl = Yeti.get().gl; int pos = grabUniform(uniformName); if(pos == -1) return false; gl.glUniform2f(pos, x, y); return true; } public boolean setUVector3f(String uniformName, Vector3 value) { GL2GL3 gl = Yeti.get().gl; int pos = grabUniform(uniformName); if(pos == -1) return false; gl.glUniform3f(pos, value.x, value.y, value.z); return true; } public boolean setUVector3f(String uniformName, Color value) { GL2GL3 gl = Yeti.get().gl; int pos = grabUniform(uniformName); if(pos == -1) return false; gl.glUniform3f(pos, value.r, value.g, value.b); return true; } public boolean setUVector4f(String uniformName, float[] value) { GL2GL3 gl = Yeti.get().gl; int pos = grabUniform(uniformName); if(pos == -1) return false; gl.glUniform4fv(pos, 1, value, 0); return true; } public boolean setUMatrix3(String uniformName, Matrix3 matrix) { GL2GL3 gl = Yeti.get().gl; int pos = grabUniform(uniformName); if(pos == -1) return false; gl.glUniformMatrix3fv(pos, 1, false, matrix.getData(), 0); return true; } public boolean setU1i(String uniformName, boolean value) { return setU1i(uniformName, (value) ? 1 : 0); } public boolean setU1i(String uniformName, int value) { GL2GL3 gl = Yeti.get().gl; int pos = grabUniform(uniformName); gl.glUniform1i(pos, value); return true; } public boolean setU1f(String uniformName, float value) { GL2GL3 gl = Yeti.get().gl; int pos = grabUniform(uniformName); if(pos == -1) return false; gl.glUniform1f(pos, value); return true; } /** * Called to release the native resource. */ public void dispose() { GL2GL3 gl = Yeti.get().gl; gl.glDeleteShader(handle); } /** * Helper method to get a handle to a uniform. First checks whether that value * was already looked up, in which case it grabs it from the cache instead of * performing a native call, avoiding the associated overhead. */ private int grabUniform(String uniformName) { GL2GL3 gl = Yeti.get().gl; int pos; if(uLocCache.containsKey(uniformName)) { pos = uLocCache.get(uniformName); } else { pos = gl.glGetUniformLocation(handle, uniformName); uLocCache.put(uniformName, pos); if(pos == -1) { Yeti.debug("Uniform not found: %s (in shader %s)", uniformName, name); } } return pos; } private void checkShader(String message, int handle) { check(message, handle, false); } private void checkProgram(String message, int handle) { check(message, handle, true); } /** * Checks whether the entity (shader or shader program, specified by the * isProgram parameter) compiled successfully. If an error occurred, crashes * the engine to prompt the programmer to fix the error as soon as possible. * * If warnings are detected, they are printed out. */ private void check(String message, int handle, boolean isProgram) { GL3 gl = Yeti.get().gl; IntBuffer buff = IntBuffer.allocate(1); String logContents = "Empty log"; boolean logEmpty = true; if(isProgram) { gl.glGetProgramiv(handle, GL2.GL_INFO_LOG_LENGTH, buff); } else { gl.glGetShaderiv(handle, GL2.GL_INFO_LOG_LENGTH, buff); } if(buff.remaining() != 1) { Yeti.screwed("Ba edy ce plm de driver ai?"); } int l = buff.get(); if(l > 1) { logEmpty = false; if(isProgram) { gl.glGetProgramInfoLog(handle, l, i_buff, b_buff); } else { gl.glGetShaderInfoLog(handle, l, i_buff, b_buff); } - logContents = new String(b_buff.array(), 0, i_buff.get()); + if(i_buff.remaining() == 0) { + // Attempt to use the already-found version for drivers that don't + // populate the int buffer + logContents = new String(b_buff.array(), 0, l); + } + else { + logContents = new String(b_buff.array(), 0, i_buff.get()); + } } if(isProgram) { gl.glGetProgramiv(handle, GL2.GL_LINK_STATUS, result, 0); } else { gl.glGetShaderiv(handle, GL2.GL_COMPILE_STATUS, result, 0); } String action = isProgram ? "link" : "compile"; String actionPT = isProgram ? "linked" : "compiled"; if(result[0] == GL2.GL_FALSE) { Yeti.screwed(message + " failed to " + action + "!\n\t" + logContents); return; } if(!logEmpty) { if( ! groks.contains(logContents.trim())) { // Some drivers do fill the log even though there are no actual // warnings. We don't want to treat the a message like "No errors." // as a warning! Yeti.warn(message + " " + actionPT + " with warnings!\n\t" + logContents); } } } }
true
true
private void check(String message, int handle, boolean isProgram) { GL3 gl = Yeti.get().gl; IntBuffer buff = IntBuffer.allocate(1); String logContents = "Empty log"; boolean logEmpty = true; if(isProgram) { gl.glGetProgramiv(handle, GL2.GL_INFO_LOG_LENGTH, buff); } else { gl.glGetShaderiv(handle, GL2.GL_INFO_LOG_LENGTH, buff); } if(buff.remaining() != 1) { Yeti.screwed("Ba edy ce plm de driver ai?"); } int l = buff.get(); if(l > 1) { logEmpty = false; if(isProgram) { gl.glGetProgramInfoLog(handle, l, i_buff, b_buff); } else { gl.glGetShaderInfoLog(handle, l, i_buff, b_buff); } logContents = new String(b_buff.array(), 0, i_buff.get()); } if(isProgram) { gl.glGetProgramiv(handle, GL2.GL_LINK_STATUS, result, 0); } else { gl.glGetShaderiv(handle, GL2.GL_COMPILE_STATUS, result, 0); } String action = isProgram ? "link" : "compile"; String actionPT = isProgram ? "linked" : "compiled"; if(result[0] == GL2.GL_FALSE) { Yeti.screwed(message + " failed to " + action + "!\n\t" + logContents); return; } if(!logEmpty) { if( ! groks.contains(logContents.trim())) { // Some drivers do fill the log even though there are no actual // warnings. We don't want to treat the a message like "No errors." // as a warning! Yeti.warn(message + " " + actionPT + " with warnings!\n\t" + logContents); } } }
private void check(String message, int handle, boolean isProgram) { GL3 gl = Yeti.get().gl; IntBuffer buff = IntBuffer.allocate(1); String logContents = "Empty log"; boolean logEmpty = true; if(isProgram) { gl.glGetProgramiv(handle, GL2.GL_INFO_LOG_LENGTH, buff); } else { gl.glGetShaderiv(handle, GL2.GL_INFO_LOG_LENGTH, buff); } if(buff.remaining() != 1) { Yeti.screwed("Ba edy ce plm de driver ai?"); } int l = buff.get(); if(l > 1) { logEmpty = false; if(isProgram) { gl.glGetProgramInfoLog(handle, l, i_buff, b_buff); } else { gl.glGetShaderInfoLog(handle, l, i_buff, b_buff); } if(i_buff.remaining() == 0) { // Attempt to use the already-found version for drivers that don't // populate the int buffer logContents = new String(b_buff.array(), 0, l); } else { logContents = new String(b_buff.array(), 0, i_buff.get()); } } if(isProgram) { gl.glGetProgramiv(handle, GL2.GL_LINK_STATUS, result, 0); } else { gl.glGetShaderiv(handle, GL2.GL_COMPILE_STATUS, result, 0); } String action = isProgram ? "link" : "compile"; String actionPT = isProgram ? "linked" : "compiled"; if(result[0] == GL2.GL_FALSE) { Yeti.screwed(message + " failed to " + action + "!\n\t" + logContents); return; } if(!logEmpty) { if( ! groks.contains(logContents.trim())) { // Some drivers do fill the log even though there are no actual // warnings. We don't want to treat the a message like "No errors." // as a warning! Yeti.warn(message + " " + actionPT + " with warnings!\n\t" + logContents); } } }
diff --git a/uispec4j/src/main/java/org/uispec4j/AbstractSwingUIComponent.java b/uispec4j/src/main/java/org/uispec4j/AbstractSwingUIComponent.java index 1c7666d..35807f5 100644 --- a/uispec4j/src/main/java/org/uispec4j/AbstractSwingUIComponent.java +++ b/uispec4j/src/main/java/org/uispec4j/AbstractSwingUIComponent.java @@ -1,33 +1,33 @@ package org.uispec4j; import org.uispec4j.assertion.Assertion; import org.uispec4j.assertion.testlibrairies.AssertAdapter; import javax.swing.*; /** * Base class for UIComponent implementations that wrap JComponent subclasses. */ public abstract class AbstractSwingUIComponent extends AbstractUIComponent implements TooltipComponent { public abstract JComponent getAwtComponent(); public Assertion tooltipEquals(final String text) { return new Assertion() { public void check() { String actualText = getAwtComponent().getToolTipText(); AssertAdapter.assertEquals(actualText, text); } }; } public Assertion tooltipContains(final String text) { return new Assertion() { public void check() { String actualText = getAwtComponent().getToolTipText(); AssertAdapter.assertNotNull("No tooltip set", actualText); - AssertAdapter.assertTrue("Actual tooltip", actualText.contains(text)); + AssertAdapter.assertTrue("Actual tooltip:" + actualText, actualText.contains(text)); } }; } }
true
true
public Assertion tooltipContains(final String text) { return new Assertion() { public void check() { String actualText = getAwtComponent().getToolTipText(); AssertAdapter.assertNotNull("No tooltip set", actualText); AssertAdapter.assertTrue("Actual tooltip", actualText.contains(text)); } }; }
public Assertion tooltipContains(final String text) { return new Assertion() { public void check() { String actualText = getAwtComponent().getToolTipText(); AssertAdapter.assertNotNull("No tooltip set", actualText); AssertAdapter.assertTrue("Actual tooltip:" + actualText, actualText.contains(text)); } }; }
diff --git a/src/org/mozilla/javascript/Interpreter.java b/src/org/mozilla/javascript/Interpreter.java index f9b1e1f8..167f03b7 100644 --- a/src/org/mozilla/javascript/Interpreter.java +++ b/src/org/mozilla/javascript/Interpreter.java @@ -1,4524 +1,4524 @@ /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * 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. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Patrick Beard * Norris Boyd * Igor Bukanov * Ethan Hugg * Bob Jervis * Terry Lucas * Roger Lawrence * Milen Nankov * Hannes Wallnoefer * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; import java.io.PrintStream; import java.io.Serializable; import java.util.List; import java.util.ArrayList; import org.mozilla.javascript.continuations.Continuation; import org.mozilla.javascript.debug.DebugFrame; public class Interpreter { // Additional interpreter-specific codes private static final int // Stack: ... value1 -> ... value1 value1 Icode_DUP = -1, // Stack: ... value2 value1 -> ... value2 value1 value2 value1 Icode_DUP2 = -2, // Stack: ... value2 value1 -> ... value1 value2 Icode_SWAP = -3, // Stack: ... value1 -> ... Icode_POP = -4, // Store stack top into return register and then pop it Icode_POP_RESULT = -5, // To jump conditionally and pop additional stack value Icode_IFEQ_POP = -6, // various types of ++/-- Icode_VAR_INC_DEC = -7, Icode_NAME_INC_DEC = -8, Icode_PROP_INC_DEC = -9, Icode_ELEM_INC_DEC = -10, Icode_REF_INC_DEC = -11, // load/save scope from/to local Icode_SCOPE_LOAD = -12, Icode_SCOPE_SAVE = -13, Icode_TYPEOFNAME = -14, // helper for function calls Icode_NAME_AND_THIS = -15, Icode_PROP_AND_THIS = -16, Icode_ELEM_AND_THIS = -17, Icode_VALUE_AND_THIS = -18, // Create closure object for nested functions Icode_CLOSURE_EXPR = -19, Icode_CLOSURE_STMT = -20, // Special calls Icode_CALLSPECIAL = -21, // To return undefined value Icode_RETUNDEF = -22, // Exception handling implementation Icode_GOSUB = -23, Icode_STARTSUB = -24, Icode_RETSUB = -25, // To indicating a line number change in icodes. Icode_LINE = -26, // To store shorts and ints inline Icode_SHORTNUMBER = -27, Icode_INTNUMBER = -28, // To create and populate array to hold values for [] and {} literals Icode_LITERAL_NEW = -29, Icode_LITERAL_SET = -30, // Array literal with skipped index like [1,,2] Icode_SPARE_ARRAYLIT = -31, // Load index register to prepare for the following index operation Icode_REG_IND_C0 = -32, Icode_REG_IND_C1 = -33, Icode_REG_IND_C2 = -34, Icode_REG_IND_C3 = -35, Icode_REG_IND_C4 = -36, Icode_REG_IND_C5 = -37, Icode_REG_IND1 = -38, Icode_REG_IND2 = -39, Icode_REG_IND4 = -40, // Load string register to prepare for the following string operation Icode_REG_STR_C0 = -41, Icode_REG_STR_C1 = -42, Icode_REG_STR_C2 = -43, Icode_REG_STR_C3 = -44, Icode_REG_STR1 = -45, Icode_REG_STR2 = -46, Icode_REG_STR4 = -47, // Version of getvar/setvar that read var index directly from bytecode Icode_GETVAR1 = -48, Icode_SETVAR1 = -49, // Load unefined Icode_UNDEF = -50, Icode_ZERO = -51, Icode_ONE = -52, // entrance and exit from .() Icode_ENTERDQ = -53, Icode_LEAVEDQ = -54, Icode_TAIL_CALL = -55, // Clear local to allow GC its context Icode_LOCAL_CLEAR = -56, // Literal get/set Icode_LITERAL_GETTER = -57, Icode_LITERAL_SETTER = -58, // const Icode_SETCONST = -59, Icode_SETCONSTVAR = -60, Icode_SETCONSTVAR1 = -61, // Generator opcodes (along with Token.YIELD) Icode_GENERATOR = -62, Icode_GENERATOR_END = -63, Icode_DEBUGGER = -64, // Last icode MIN_ICODE = -64; // data for parsing private CompilerEnvirons compilerEnv; private boolean itsInFunctionFlag; private InterpreterData itsData; private ScriptOrFnNode scriptOrFn; private int itsICodeTop; private int itsStackDepth; private int itsLineNumber; private int itsDoubleTableTop; private ObjToIntMap itsStrings = new ObjToIntMap(20); private int itsLocalTop; private static final int MIN_LABEL_TABLE_SIZE = 32; private static final int MIN_FIXUP_TABLE_SIZE = 40; private int[] itsLabelTable; private int itsLabelTableTop; // itsFixupTable[i] = (label_index << 32) | fixup_site private long[] itsFixupTable; private int itsFixupTableTop; private ObjArray itsLiteralIds = new ObjArray(); private int itsExceptionTableTop; private static final int EXCEPTION_TRY_START_SLOT = 0; private static final int EXCEPTION_TRY_END_SLOT = 1; private static final int EXCEPTION_HANDLER_SLOT = 2; private static final int EXCEPTION_TYPE_SLOT = 3; private static final int EXCEPTION_LOCAL_SLOT = 4; private static final int EXCEPTION_SCOPE_SLOT = 5; // SLOT_SIZE: space for try start/end, handler, start, handler type, // exception local and scope local private static final int EXCEPTION_SLOT_SIZE = 6; // ECF_ or Expression Context Flags constants: for now only TAIL is available private static final int ECF_TAIL = 1 << 0; /** * Class to hold data corresponding to one interpreted call stack frame. */ private static class CallFrame implements Cloneable, Serializable { static final long serialVersionUID = -2843792508994958978L; CallFrame parentFrame; // amount of stack frames before this one on the interpretation stack int frameIndex; // If true indicates read-only frame that is a part of continuation boolean frozen; InterpretedFunction fnOrScript; InterpreterData idata; // Stack structure // stack[0 <= i < localShift]: arguments and local variables // stack[localShift <= i <= emptyStackTop]: used for local temporaries // stack[emptyStackTop < i < stack.length]: stack data // sDbl[i]: if stack[i] is UniqueTag.DOUBLE_MARK, sDbl[i] holds the number value Object[] stack; int[] stackAttributes; double[] sDbl; CallFrame varSource; // defaults to this unless continuation frame int localShift; int emptyStackTop; DebugFrame debuggerFrame; boolean useActivation; Scriptable thisObj; Scriptable[] scriptRegExps; // The values that change during interpretation Object result; double resultDbl; int pc; int pcPrevBranch; int pcSourceLineStart; Scriptable scope; int savedStackTop; int savedCallOp; CallFrame cloneFrozen() { if (!frozen) Kit.codeBug(); CallFrame copy; try { copy = (CallFrame)clone(); } catch (CloneNotSupportedException ex) { throw new IllegalStateException(); } // clone stack but keep varSource to point to values // from this frame to share variables. copy.stack = (Object[])stack.clone(); copy.stackAttributes = (int[])stackAttributes.clone(); copy.sDbl = (double[])sDbl.clone(); copy.frozen = false; return copy; } } private static final class ContinuationJump implements Serializable { static final long serialVersionUID = 7687739156004308247L; CallFrame capturedFrame; CallFrame branchFrame; Object result; double resultDbl; ContinuationJump(Continuation c, CallFrame current) { this.capturedFrame = (CallFrame)c.getImplementation(); if (this.capturedFrame == null || current == null) { // Continuation and current execution does not share // any frames if there is nothing to capture or // if there is no currently executed frames this.branchFrame = null; } else { // Search for branch frame where parent frame chains starting // from captured and current meet. CallFrame chain1 = this.capturedFrame; CallFrame chain2 = current; // First work parents of chain1 or chain2 until the same // frame depth. int diff = chain1.frameIndex - chain2.frameIndex; if (diff != 0) { if (diff < 0) { // swap to make sure that // chain1.frameIndex > chain2.frameIndex and diff > 0 chain1 = current; chain2 = this.capturedFrame; diff = -diff; } do { chain1 = chain1.parentFrame; } while (--diff != 0); if (chain1.frameIndex != chain2.frameIndex) Kit.codeBug(); } // Now walk parents in parallel until a shared frame is found // or until the root is reached. while (chain1 != chain2 && chain1 != null) { chain1 = chain1.parentFrame; chain2 = chain2.parentFrame; } this.branchFrame = chain1; if (this.branchFrame != null && !this.branchFrame.frozen) Kit.codeBug(); } } } private static CallFrame captureFrameForGenerator(CallFrame frame) { frame.frozen = true; CallFrame result = frame.cloneFrozen(); frame.frozen = false; // now isolate this frame from its previous context result.parentFrame = null; result.frameIndex = 0; return result; } static { // Checks for byte code consistencies, good compiler can eliminate them if (Token.LAST_BYTECODE_TOKEN > 127) { String str = "Violation of Token.LAST_BYTECODE_TOKEN <= 127"; System.err.println(str); throw new IllegalStateException(str); } if (MIN_ICODE < -128) { String str = "Violation of Interpreter.MIN_ICODE >= -128"; System.err.println(str); throw new IllegalStateException(str); } } private static String bytecodeName(int bytecode) { if (!validBytecode(bytecode)) { throw new IllegalArgumentException(String.valueOf(bytecode)); } if (!Token.printICode) { return String.valueOf(bytecode); } if (validTokenCode(bytecode)) { return Token.name(bytecode); } switch (bytecode) { case Icode_DUP: return "DUP"; case Icode_DUP2: return "DUP2"; case Icode_SWAP: return "SWAP"; case Icode_POP: return "POP"; case Icode_POP_RESULT: return "POP_RESULT"; case Icode_IFEQ_POP: return "IFEQ_POP"; case Icode_VAR_INC_DEC: return "VAR_INC_DEC"; case Icode_NAME_INC_DEC: return "NAME_INC_DEC"; case Icode_PROP_INC_DEC: return "PROP_INC_DEC"; case Icode_ELEM_INC_DEC: return "ELEM_INC_DEC"; case Icode_REF_INC_DEC: return "REF_INC_DEC"; case Icode_SCOPE_LOAD: return "SCOPE_LOAD"; case Icode_SCOPE_SAVE: return "SCOPE_SAVE"; case Icode_TYPEOFNAME: return "TYPEOFNAME"; case Icode_NAME_AND_THIS: return "NAME_AND_THIS"; case Icode_PROP_AND_THIS: return "PROP_AND_THIS"; case Icode_ELEM_AND_THIS: return "ELEM_AND_THIS"; case Icode_VALUE_AND_THIS: return "VALUE_AND_THIS"; case Icode_CLOSURE_EXPR: return "CLOSURE_EXPR"; case Icode_CLOSURE_STMT: return "CLOSURE_STMT"; case Icode_CALLSPECIAL: return "CALLSPECIAL"; case Icode_RETUNDEF: return "RETUNDEF"; case Icode_GOSUB: return "GOSUB"; case Icode_STARTSUB: return "STARTSUB"; case Icode_RETSUB: return "RETSUB"; case Icode_LINE: return "LINE"; case Icode_SHORTNUMBER: return "SHORTNUMBER"; case Icode_INTNUMBER: return "INTNUMBER"; case Icode_LITERAL_NEW: return "LITERAL_NEW"; case Icode_LITERAL_SET: return "LITERAL_SET"; case Icode_SPARE_ARRAYLIT: return "SPARE_ARRAYLIT"; case Icode_REG_IND_C0: return "REG_IND_C0"; case Icode_REG_IND_C1: return "REG_IND_C1"; case Icode_REG_IND_C2: return "REG_IND_C2"; case Icode_REG_IND_C3: return "REG_IND_C3"; case Icode_REG_IND_C4: return "REG_IND_C4"; case Icode_REG_IND_C5: return "REG_IND_C5"; case Icode_REG_IND1: return "LOAD_IND1"; case Icode_REG_IND2: return "LOAD_IND2"; case Icode_REG_IND4: return "LOAD_IND4"; case Icode_REG_STR_C0: return "REG_STR_C0"; case Icode_REG_STR_C1: return "REG_STR_C1"; case Icode_REG_STR_C2: return "REG_STR_C2"; case Icode_REG_STR_C3: return "REG_STR_C3"; case Icode_REG_STR1: return "LOAD_STR1"; case Icode_REG_STR2: return "LOAD_STR2"; case Icode_REG_STR4: return "LOAD_STR4"; case Icode_GETVAR1: return "GETVAR1"; case Icode_SETVAR1: return "SETVAR1"; case Icode_UNDEF: return "UNDEF"; case Icode_ZERO: return "ZERO"; case Icode_ONE: return "ONE"; case Icode_ENTERDQ: return "ENTERDQ"; case Icode_LEAVEDQ: return "LEAVEDQ"; case Icode_TAIL_CALL: return "TAIL_CALL"; case Icode_LOCAL_CLEAR: return "LOCAL_CLEAR"; case Icode_LITERAL_GETTER: return "LITERAL_GETTER"; case Icode_LITERAL_SETTER: return "LITERAL_SETTER"; case Icode_SETCONST: return "SETCONST"; case Icode_SETCONSTVAR: return "SETCONSTVAR"; case Icode_SETCONSTVAR1: return "SETCONSTVAR1"; case Icode_GENERATOR: return "GENERATOR"; case Icode_GENERATOR_END: return "GENERATOR_END"; case Icode_DEBUGGER: return "DEBUGGER"; } // icode without name throw new IllegalStateException(String.valueOf(bytecode)); } private static boolean validIcode(int icode) { return MIN_ICODE <= icode && icode <= -1; } private static boolean validTokenCode(int token) { return Token.FIRST_BYTECODE_TOKEN <= token && token <= Token.LAST_BYTECODE_TOKEN; } private static boolean validBytecode(int bytecode) { return validIcode(bytecode) || validTokenCode(bytecode); } public Object compile(CompilerEnvirons compilerEnv, ScriptOrFnNode tree, String encodedSource, boolean returnFunction) { this.compilerEnv = compilerEnv; new NodeTransformer().transform(tree); if (Token.printTrees) { System.out.println(tree.toStringTree(tree)); } if (returnFunction) { tree = tree.getFunctionNode(0); } scriptOrFn = tree; itsData = new InterpreterData(compilerEnv.getLanguageVersion(), scriptOrFn.getSourceName(), encodedSource); itsData.topLevel = true; if (returnFunction) { generateFunctionICode(); } else { generateICodeFromTree(scriptOrFn); } return itsData; } public Script createScriptObject(Object bytecode, Object staticSecurityDomain) { if(bytecode != itsData) { Kit.codeBug(); } return InterpretedFunction.createScript(itsData, staticSecurityDomain); } public Function createFunctionObject(Context cx, Scriptable scope, Object bytecode, Object staticSecurityDomain) { if(bytecode != itsData) { Kit.codeBug(); } return InterpretedFunction.createFunction(cx, scope, itsData, staticSecurityDomain); } private void generateFunctionICode() { itsInFunctionFlag = true; FunctionNode theFunction = (FunctionNode)scriptOrFn; itsData.itsFunctionType = theFunction.getFunctionType(); itsData.itsNeedsActivation = theFunction.requiresActivation(); itsData.itsName = theFunction.getFunctionName(); if (!theFunction.getIgnoreDynamicScope()) { if (compilerEnv.isUseDynamicScope()) { itsData.useDynamicScope = true; } } if (theFunction.isGenerator()) { addIcode(Icode_GENERATOR); addUint16(theFunction.getBaseLineno() & 0xFFFF); } generateICodeFromTree(theFunction.getLastChild()); } private void generateICodeFromTree(Node tree) { generateNestedFunctions(); generateRegExpLiterals(); visitStatement(tree, 0); fixLabelGotos(); // add RETURN_RESULT only to scripts as function always ends with RETURN if (itsData.itsFunctionType == 0) { addToken(Token.RETURN_RESULT); } if (itsData.itsICode.length != itsICodeTop) { // Make itsData.itsICode length exactly itsICodeTop to save memory // and catch bugs with jumps beyond icode as early as possible byte[] tmp = new byte[itsICodeTop]; System.arraycopy(itsData.itsICode, 0, tmp, 0, itsICodeTop); itsData.itsICode = tmp; } if (itsStrings.size() == 0) { itsData.itsStringTable = null; } else { itsData.itsStringTable = new String[itsStrings.size()]; ObjToIntMap.Iterator iter = itsStrings.newIterator(); for (iter.start(); !iter.done(); iter.next()) { String str = (String)iter.getKey(); int index = iter.getValue(); if (itsData.itsStringTable[index] != null) Kit.codeBug(); itsData.itsStringTable[index] = str; } } if (itsDoubleTableTop == 0) { itsData.itsDoubleTable = null; } else if (itsData.itsDoubleTable.length != itsDoubleTableTop) { double[] tmp = new double[itsDoubleTableTop]; System.arraycopy(itsData.itsDoubleTable, 0, tmp, 0, itsDoubleTableTop); itsData.itsDoubleTable = tmp; } if (itsExceptionTableTop != 0 && itsData.itsExceptionTable.length != itsExceptionTableTop) { int[] tmp = new int[itsExceptionTableTop]; System.arraycopy(itsData.itsExceptionTable, 0, tmp, 0, itsExceptionTableTop); itsData.itsExceptionTable = tmp; } itsData.itsMaxVars = scriptOrFn.getParamAndVarCount(); // itsMaxFrameArray: interpret method needs this amount for its // stack and sDbl arrays itsData.itsMaxFrameArray = itsData.itsMaxVars + itsData.itsMaxLocals + itsData.itsMaxStack; itsData.argNames = scriptOrFn.getParamAndVarNames(); itsData.argIsConst = scriptOrFn.getParamAndVarConst(); itsData.argCount = scriptOrFn.getParamCount(); itsData.encodedSourceStart = scriptOrFn.getEncodedSourceStart(); itsData.encodedSourceEnd = scriptOrFn.getEncodedSourceEnd(); if (itsLiteralIds.size() != 0) { itsData.literalIds = itsLiteralIds.toArray(); } if (Token.printICode) dumpICode(itsData); } private void generateNestedFunctions() { int functionCount = scriptOrFn.getFunctionCount(); if (functionCount == 0) return; InterpreterData[] array = new InterpreterData[functionCount]; for (int i = 0; i != functionCount; i++) { FunctionNode def = scriptOrFn.getFunctionNode(i); Interpreter jsi = new Interpreter(); jsi.compilerEnv = compilerEnv; jsi.scriptOrFn = def; jsi.itsData = new InterpreterData(itsData); jsi.generateFunctionICode(); array[i] = jsi.itsData; } itsData.itsNestedFunctions = array; } private void generateRegExpLiterals() { int N = scriptOrFn.getRegexpCount(); if (N == 0) return; Context cx = Context.getContext(); RegExpProxy rep = ScriptRuntime.checkRegExpProxy(cx); Object[] array = new Object[N]; for (int i = 0; i != N; i++) { String string = scriptOrFn.getRegexpString(i); String flags = scriptOrFn.getRegexpFlags(i); array[i] = rep.compileRegExp(cx, string, flags); } itsData.itsRegExpLiterals = array; } private void updateLineNumber(Node node) { int lineno = node.getLineno(); if (lineno != itsLineNumber && lineno >= 0) { if (itsData.firstLinePC < 0) { itsData.firstLinePC = lineno; } itsLineNumber = lineno; addIcode(Icode_LINE); addUint16(lineno & 0xFFFF); } } private RuntimeException badTree(Node node) { throw new RuntimeException(node.toString()); } private void visitStatement(Node node, int initialStackDepth) { int type = node.getType(); Node child = node.getFirstChild(); switch (type) { case Token.FUNCTION: { int fnIndex = node.getExistingIntProp(Node.FUNCTION_PROP); int fnType = scriptOrFn.getFunctionNode(fnIndex). getFunctionType(); // Only function expressions or function expression // statements need closure code creating new function // object on stack as function statements are initialized // at script/function start. // In addition, function expressions can not be present here // at statement level, they must only be present as expressions. if (fnType == FunctionNode.FUNCTION_EXPRESSION_STATEMENT) { addIndexOp(Icode_CLOSURE_STMT, fnIndex); } else { if (fnType != FunctionNode.FUNCTION_STATEMENT) { throw Kit.codeBug(); } } // For function statements or function expression statements // in scripts, we need to ensure that the result of the script // is the function if it is the last statement in the script. // For example, eval("function () {}") should return a // function, not undefined. if (!itsInFunctionFlag) { addIndexOp(Icode_CLOSURE_EXPR, fnIndex); stackChange(1); addIcode(Icode_POP_RESULT); stackChange(-1); } } break; case Token.SCRIPT: case Token.LABEL: case Token.LOOP: case Token.BLOCK: case Token.EMPTY: case Token.WITH: updateLineNumber(node); while (child != null) { visitStatement(child, initialStackDepth); child = child.getNext(); } break; case Token.ENTERWITH: visitExpression(child, 0); addToken(Token.ENTERWITH); stackChange(-1); break; case Token.LEAVEWITH: addToken(Token.LEAVEWITH); break; case Token.LOCAL_BLOCK: { int local = allocLocal(); node.putIntProp(Node.LOCAL_PROP, local); updateLineNumber(node); while (child != null) { visitStatement(child, initialStackDepth); child = child.getNext(); } addIndexOp(Icode_LOCAL_CLEAR, local); releaseLocal(local); } break; case Token.DEBUGGER: addIcode(Icode_DEBUGGER); break; case Token.SWITCH: updateLineNumber(node); // See comments in IRFactory.createSwitch() for description // of SWITCH node { visitExpression(child, 0); for (Node.Jump caseNode = (Node.Jump)child.getNext(); caseNode != null; caseNode = (Node.Jump)caseNode.getNext()) { if (caseNode.getType() != Token.CASE) throw badTree(caseNode); Node test = caseNode.getFirstChild(); addIcode(Icode_DUP); stackChange(1); visitExpression(test, 0); addToken(Token.SHEQ); stackChange(-1); // If true, Icode_IFEQ_POP will jump and remove case // value from stack addGoto(caseNode.target, Icode_IFEQ_POP); stackChange(-1); } addIcode(Icode_POP); stackChange(-1); } break; case Token.TARGET: markTargetLabel(node); break; case Token.IFEQ : case Token.IFNE : { Node target = ((Node.Jump)node).target; visitExpression(child, 0); addGoto(target, type); stackChange(-1); } break; case Token.GOTO: { Node target = ((Node.Jump)node).target; addGoto(target, type); } break; case Token.JSR: { Node target = ((Node.Jump)node).target; addGoto(target, Icode_GOSUB); } break; case Token.FINALLY: { // Account for incomming GOTOSUB address stackChange(1); int finallyRegister = getLocalBlockRef(node); addIndexOp(Icode_STARTSUB, finallyRegister); stackChange(-1); while (child != null) { visitStatement(child, initialStackDepth); child = child.getNext(); } addIndexOp(Icode_RETSUB, finallyRegister); } break; case Token.EXPR_VOID: case Token.EXPR_RESULT: updateLineNumber(node); visitExpression(child, 0); addIcode((type == Token.EXPR_VOID) ? Icode_POP : Icode_POP_RESULT); stackChange(-1); break; case Token.TRY: { Node.Jump tryNode = (Node.Jump)node; int exceptionObjectLocal = getLocalBlockRef(tryNode); int scopeLocal = allocLocal(); addIndexOp(Icode_SCOPE_SAVE, scopeLocal); int tryStart = itsICodeTop; while (child != null) { visitStatement(child, initialStackDepth); child = child.getNext(); } Node catchTarget = tryNode.target; if (catchTarget != null) { int catchStartPC = itsLabelTable[getTargetLabel(catchTarget)]; addExceptionHandler( tryStart, catchStartPC, catchStartPC, false, exceptionObjectLocal, scopeLocal); } Node finallyTarget = tryNode.getFinally(); if (finallyTarget != null) { int finallyStartPC = itsLabelTable[getTargetLabel(finallyTarget)]; addExceptionHandler( tryStart, finallyStartPC, finallyStartPC, true, exceptionObjectLocal, scopeLocal); } addIndexOp(Icode_LOCAL_CLEAR, scopeLocal); releaseLocal(scopeLocal); } break; case Token.CATCH_SCOPE: { int localIndex = getLocalBlockRef(node); int scopeIndex = node.getExistingIntProp(Node.CATCH_SCOPE_PROP); String name = child.getString(); child = child.getNext(); visitExpression(child, 0); // load expression object addStringPrefix(name); addIndexPrefix(localIndex); addToken(Token.CATCH_SCOPE); addUint8(scopeIndex != 0 ? 1 : 0); stackChange(-1); } break; case Token.THROW: updateLineNumber(node); visitExpression(child, 0); addToken(Token.THROW); addUint16(itsLineNumber & 0xFFFF); stackChange(-1); break; case Token.RETHROW: updateLineNumber(node); addIndexOp(Token.RETHROW, getLocalBlockRef(node)); break; case Token.RETURN: updateLineNumber(node); if (node.getIntProp(Node.GENERATOR_END_PROP, 0) != 0) { // We're in a generator, so change RETURN to GENERATOR_END addIcode(Icode_GENERATOR_END); addUint16(itsLineNumber & 0xFFFF); } else if (child != null) { visitExpression(child, ECF_TAIL); addToken(Token.RETURN); stackChange(-1); } else { addIcode(Icode_RETUNDEF); } break; case Token.RETURN_RESULT: updateLineNumber(node); addToken(Token.RETURN_RESULT); break; case Token.ENUM_INIT_KEYS: case Token.ENUM_INIT_VALUES : visitExpression(child, 0); addIndexOp(type, getLocalBlockRef(node)); stackChange(-1); break; case Icode_GENERATOR: break; default: throw badTree(node); } if (itsStackDepth != initialStackDepth) { throw Kit.codeBug(); } } private void visitExpression(Node node, int contextFlags) { int type = node.getType(); Node child = node.getFirstChild(); int savedStackDepth = itsStackDepth; switch (type) { case Token.FUNCTION: { int fnIndex = node.getExistingIntProp(Node.FUNCTION_PROP); FunctionNode fn = scriptOrFn.getFunctionNode(fnIndex); // See comments in visitStatement for Token.FUNCTION case if (fn.getFunctionType() != FunctionNode.FUNCTION_EXPRESSION) { throw Kit.codeBug(); } addIndexOp(Icode_CLOSURE_EXPR, fnIndex); stackChange(1); } break; case Token.LOCAL_LOAD: { int localIndex = getLocalBlockRef(node); addIndexOp(Token.LOCAL_LOAD, localIndex); stackChange(1); } break; case Token.COMMA: { Node lastChild = node.getLastChild(); while (child != lastChild) { visitExpression(child, 0); addIcode(Icode_POP); stackChange(-1); child = child.getNext(); } // Preserve tail context flag if any visitExpression(child, contextFlags & ECF_TAIL); } break; case Token.USE_STACK: // Indicates that stack was modified externally, // like placed catch object stackChange(1); break; case Token.REF_CALL: case Token.CALL: case Token.NEW: { if (type == Token.NEW) { visitExpression(child, 0); } else { generateCallFunAndThis(child); } int argCount = 0; while ((child = child.getNext()) != null) { visitExpression(child, 0); ++argCount; } int callType = node.getIntProp(Node.SPECIALCALL_PROP, Node.NON_SPECIALCALL); if (callType != Node.NON_SPECIALCALL) { // embed line number and source filename addIndexOp(Icode_CALLSPECIAL, argCount); addUint8(callType); addUint8(type == Token.NEW ? 1 : 0); addUint16(itsLineNumber & 0xFFFF); } else { if (type == Token.CALL) { if ((contextFlags & ECF_TAIL) != 0) { type = Icode_TAIL_CALL; } } addIndexOp(type, argCount); } // adjust stack if (type == Token.NEW) { // new: f, args -> result stackChange(-argCount); } else { // call: f, thisObj, args -> result // ref_call: f, thisObj, args -> ref stackChange(-1 - argCount); } if (argCount > itsData.itsMaxCalleeArgs) { itsData.itsMaxCalleeArgs = argCount; } } break; case Token.AND: case Token.OR: { visitExpression(child, 0); addIcode(Icode_DUP); stackChange(1); int afterSecondJumpStart = itsICodeTop; int jump = (type == Token.AND) ? Token.IFNE : Token.IFEQ; addGotoOp(jump); stackChange(-1); addIcode(Icode_POP); stackChange(-1); child = child.getNext(); // Preserve tail context flag if any visitExpression(child, contextFlags & ECF_TAIL); resolveForwardGoto(afterSecondJumpStart); } break; case Token.HOOK: { Node ifThen = child.getNext(); Node ifElse = ifThen.getNext(); visitExpression(child, 0); int elseJumpStart = itsICodeTop; addGotoOp(Token.IFNE); stackChange(-1); // Preserve tail context flag if any visitExpression(ifThen, contextFlags & ECF_TAIL); int afterElseJumpStart = itsICodeTop; addGotoOp(Token.GOTO); resolveForwardGoto(elseJumpStart); itsStackDepth = savedStackDepth; // Preserve tail context flag if any visitExpression(ifElse, contextFlags & ECF_TAIL); resolveForwardGoto(afterElseJumpStart); } break; case Token.GETPROP: visitExpression(child, 0); child = child.getNext(); addStringOp(Token.GETPROP, child.getString()); break; case Token.GETELEM: case Token.DELPROP: case Token.BITAND: case Token.BITOR: case Token.BITXOR: case Token.LSH: case Token.RSH: case Token.URSH: case Token.ADD: case Token.SUB: case Token.MOD: case Token.DIV: case Token.MUL: case Token.EQ: case Token.NE: case Token.SHEQ: case Token.SHNE: case Token.IN: case Token.INSTANCEOF: case Token.LE: case Token.LT: case Token.GE: case Token.GT: visitExpression(child, 0); child = child.getNext(); visitExpression(child, 0); addToken(type); stackChange(-1); break; case Token.POS: case Token.NEG: case Token.NOT: case Token.BITNOT: case Token.TYPEOF: case Token.VOID: visitExpression(child, 0); if (type == Token.VOID) { addIcode(Icode_POP); addIcode(Icode_UNDEF); } else { addToken(type); } break; case Token.GET_REF: case Token.DEL_REF: visitExpression(child, 0); addToken(type); break; case Token.SETPROP: case Token.SETPROP_OP: { visitExpression(child, 0); child = child.getNext(); String property = child.getString(); child = child.getNext(); if (type == Token.SETPROP_OP) { addIcode(Icode_DUP); stackChange(1); addStringOp(Token.GETPROP, property); // Compensate for the following USE_STACK stackChange(-1); } visitExpression(child, 0); addStringOp(Token.SETPROP, property); stackChange(-1); } break; case Token.SETELEM: case Token.SETELEM_OP: visitExpression(child, 0); child = child.getNext(); visitExpression(child, 0); child = child.getNext(); if (type == Token.SETELEM_OP) { addIcode(Icode_DUP2); stackChange(2); addToken(Token.GETELEM); stackChange(-1); // Compensate for the following USE_STACK stackChange(-1); } visitExpression(child, 0); addToken(Token.SETELEM); stackChange(-2); break; case Token.SET_REF: case Token.SET_REF_OP: visitExpression(child, 0); child = child.getNext(); if (type == Token.SET_REF_OP) { addIcode(Icode_DUP); stackChange(1); addToken(Token.GET_REF); // Compensate for the following USE_STACK stackChange(-1); } visitExpression(child, 0); addToken(Token.SET_REF); stackChange(-1); break; case Token.SETNAME: { String name = child.getString(); visitExpression(child, 0); child = child.getNext(); visitExpression(child, 0); addStringOp(Token.SETNAME, name); stackChange(-1); } break; case Token.SETCONST: { String name = child.getString(); visitExpression(child, 0); child = child.getNext(); visitExpression(child, 0); addStringOp(Icode_SETCONST, name); stackChange(-1); } break; case Token.TYPEOFNAME: { int index = -1; // use typeofname if an activation frame exists // since the vars all exist there instead of in jregs if (itsInFunctionFlag && !itsData.itsNeedsActivation) index = scriptOrFn.getIndexForNameNode(node); if (index == -1) { addStringOp(Icode_TYPEOFNAME, node.getString()); stackChange(1); } else { addVarOp(Token.GETVAR, index); stackChange(1); addToken(Token.TYPEOF); } } break; case Token.BINDNAME: case Token.NAME: case Token.STRING: addStringOp(type, node.getString()); stackChange(1); break; case Token.INC: case Token.DEC: visitIncDec(node, child); break; case Token.NUMBER: { double num = node.getDouble(); int inum = (int)num; if (inum == num) { if (inum == 0) { addIcode(Icode_ZERO); // Check for negative zero if (1.0 / num < 0.0) { addToken(Token.NEG); } } else if (inum == 1) { addIcode(Icode_ONE); } else if ((short)inum == inum) { addIcode(Icode_SHORTNUMBER); // write short as uin16 bit pattern addUint16(inum & 0xFFFF); } else { addIcode(Icode_INTNUMBER); addInt(inum); } } else { int index = getDoubleIndex(num); addIndexOp(Token.NUMBER, index); } stackChange(1); } break; case Token.GETVAR: { if (itsData.itsNeedsActivation) Kit.codeBug(); int index = scriptOrFn.getIndexForNameNode(node); addVarOp(Token.GETVAR, index); stackChange(1); } break; case Token.SETVAR: { if (itsData.itsNeedsActivation) Kit.codeBug(); int index = scriptOrFn.getIndexForNameNode(child); child = child.getNext(); visitExpression(child, 0); addVarOp(Token.SETVAR, index); } break; case Token.SETCONSTVAR: { if (itsData.itsNeedsActivation) Kit.codeBug(); int index = scriptOrFn.getIndexForNameNode(child); child = child.getNext(); visitExpression(child, 0); addVarOp(Token.SETCONSTVAR, index); } break; case Token.NULL: case Token.THIS: case Token.THISFN: case Token.FALSE: case Token.TRUE: addToken(type); stackChange(1); break; case Token.ENUM_NEXT: case Token.ENUM_ID: addIndexOp(type, getLocalBlockRef(node)); stackChange(1); break; case Token.REGEXP: { int index = node.getExistingIntProp(Node.REGEXP_PROP); addIndexOp(Token.REGEXP, index); stackChange(1); } break; case Token.ARRAYLIT: case Token.OBJECTLIT: visitLiteral(node, child); break; case Token.ARRAYCOMP: visitArrayComprehension(node, child, child.getNext()); break; case Token.REF_SPECIAL: visitExpression(child, 0); addStringOp(type, (String)node.getProp(Node.NAME_PROP)); break; case Token.REF_MEMBER: case Token.REF_NS_MEMBER: case Token.REF_NAME: case Token.REF_NS_NAME: { int memberTypeFlags = node.getIntProp(Node.MEMBER_TYPE_PROP, 0); // generate possible target, possible namespace and member int childCount = 0; do { visitExpression(child, 0); ++childCount; child = child.getNext(); } while (child != null); addIndexOp(type, memberTypeFlags); stackChange(1 - childCount); } break; case Token.DOTQUERY: { int queryPC; updateLineNumber(node); visitExpression(child, 0); addIcode(Icode_ENTERDQ); stackChange(-1); queryPC = itsICodeTop; visitExpression(child.getNext(), 0); addBackwardGoto(Icode_LEAVEDQ, queryPC); } break; case Token.DEFAULTNAMESPACE : case Token.ESCXMLATTR : case Token.ESCXMLTEXT : visitExpression(child, 0); addToken(type); break; case Token.YIELD: if (child != null) { visitExpression(child, 0); } else { addIcode(Icode_UNDEF); stackChange(1); } addToken(Token.YIELD); addUint16(node.getLineno() & 0xFFFF); break; case Token.WITHEXPR: { Node enterWith = node.getFirstChild(); Node with = enterWith.getNext(); visitExpression(enterWith.getFirstChild(), 0); addToken(Token.ENTERWITH); stackChange(-1); visitExpression(with.getFirstChild(), 0); addToken(Token.LEAVEWITH); break; } default: throw badTree(node); } if (savedStackDepth + 1 != itsStackDepth) { Kit.codeBug(); } } private void generateCallFunAndThis(Node left) { // Generate code to place on stack function and thisObj int type = left.getType(); switch (type) { case Token.NAME: { String name = left.getString(); // stack: ... -> ... function thisObj addStringOp(Icode_NAME_AND_THIS, name); stackChange(2); break; } case Token.GETPROP: case Token.GETELEM: { Node target = left.getFirstChild(); visitExpression(target, 0); Node id = target.getNext(); if (type == Token.GETPROP) { String property = id.getString(); // stack: ... target -> ... function thisObj addStringOp(Icode_PROP_AND_THIS, property); stackChange(1); } else { visitExpression(id, 0); // stack: ... target id -> ... function thisObj addIcode(Icode_ELEM_AND_THIS); } break; } default: // Including Token.GETVAR visitExpression(left, 0); // stack: ... value -> ... function thisObj addIcode(Icode_VALUE_AND_THIS); stackChange(1); break; } } private void visitIncDec(Node node, Node child) { int incrDecrMask = node.getExistingIntProp(Node.INCRDECR_PROP); int childType = child.getType(); switch (childType) { case Token.GETVAR : { if (itsData.itsNeedsActivation) Kit.codeBug(); int i = scriptOrFn.getIndexForNameNode(child); addVarOp(Icode_VAR_INC_DEC, i); addUint8(incrDecrMask); stackChange(1); break; } case Token.NAME : { String name = child.getString(); addStringOp(Icode_NAME_INC_DEC, name); addUint8(incrDecrMask); stackChange(1); break; } case Token.GETPROP : { Node object = child.getFirstChild(); visitExpression(object, 0); String property = object.getNext().getString(); addStringOp(Icode_PROP_INC_DEC, property); addUint8(incrDecrMask); break; } case Token.GETELEM : { Node object = child.getFirstChild(); visitExpression(object, 0); Node index = object.getNext(); visitExpression(index, 0); addIcode(Icode_ELEM_INC_DEC); addUint8(incrDecrMask); stackChange(-1); break; } case Token.GET_REF : { Node ref = child.getFirstChild(); visitExpression(ref, 0); addIcode(Icode_REF_INC_DEC); addUint8(incrDecrMask); break; } default : { throw badTree(node); } } } private void visitLiteral(Node node, Node child) { int type = node.getType(); int count; Object[] propertyIds = null; if (type == Token.ARRAYLIT) { count = 0; for (Node n = child; n != null; n = n.getNext()) { ++count; } } else if (type == Token.OBJECTLIT) { propertyIds = (Object[])node.getProp(Node.OBJECT_IDS_PROP); count = propertyIds.length; } else { throw badTree(node); } addIndexOp(Icode_LITERAL_NEW, count); stackChange(2); while (child != null) { int childType = child.getType(); if (childType == Token.GET) { visitExpression(child.getFirstChild(), 0); addIcode(Icode_LITERAL_GETTER); } else if (childType == Token.SET) { visitExpression(child.getFirstChild(), 0); addIcode(Icode_LITERAL_SETTER); } else { visitExpression(child, 0); addIcode(Icode_LITERAL_SET); } stackChange(-1); child = child.getNext(); } if (type == Token.ARRAYLIT) { int[] skipIndexes = (int[])node.getProp(Node.SKIP_INDEXES_PROP); if (skipIndexes == null) { addToken(Token.ARRAYLIT); } else { int index = itsLiteralIds.size(); itsLiteralIds.add(skipIndexes); addIndexOp(Icode_SPARE_ARRAYLIT, index); } } else { int index = itsLiteralIds.size(); itsLiteralIds.add(propertyIds); addIndexOp(Token.OBJECTLIT, index); } stackChange(-1); } private void visitArrayComprehension(Node node, Node initStmt, Node expr) { // A bit of a hack: array comprehensions are implemented using // statement nodes for the iteration, yet they appear in an // expression context. So we pass the current stack depth to // visitStatement so it can check that the depth is not altered // by statements. visitStatement(initStmt, itsStackDepth); visitExpression(expr, 0); } private int getLocalBlockRef(Node node) { Node localBlock = (Node)node.getProp(Node.LOCAL_BLOCK_PROP); return localBlock.getExistingIntProp(Node.LOCAL_PROP); } private int getTargetLabel(Node target) { int label = target.labelId(); if (label != -1) { return label; } label = itsLabelTableTop; if (itsLabelTable == null || label == itsLabelTable.length) { if (itsLabelTable == null) { itsLabelTable = new int[MIN_LABEL_TABLE_SIZE]; }else { int[] tmp = new int[itsLabelTable.length * 2]; System.arraycopy(itsLabelTable, 0, tmp, 0, label); itsLabelTable = tmp; } } itsLabelTableTop = label + 1; itsLabelTable[label] = -1; target.labelId(label); return label; } private void markTargetLabel(Node target) { int label = getTargetLabel(target); if (itsLabelTable[label] != -1) { // Can mark label only once Kit.codeBug(); } itsLabelTable[label] = itsICodeTop; } private void addGoto(Node target, int gotoOp) { int label = getTargetLabel(target); if (!(label < itsLabelTableTop)) Kit.codeBug(); int targetPC = itsLabelTable[label]; if (targetPC != -1) { addBackwardGoto(gotoOp, targetPC); } else { int gotoPC = itsICodeTop; addGotoOp(gotoOp); int top = itsFixupTableTop; if (itsFixupTable == null || top == itsFixupTable.length) { if (itsFixupTable == null) { itsFixupTable = new long[MIN_FIXUP_TABLE_SIZE]; } else { long[] tmp = new long[itsFixupTable.length * 2]; System.arraycopy(itsFixupTable, 0, tmp, 0, top); itsFixupTable = tmp; } } itsFixupTableTop = top + 1; itsFixupTable[top] = ((long)label << 32) | gotoPC; } } private void fixLabelGotos() { for (int i = 0; i < itsFixupTableTop; i++) { long fixup = itsFixupTable[i]; int label = (int)(fixup >> 32); int jumpSource = (int)fixup; int pc = itsLabelTable[label]; if (pc == -1) { // Unlocated label throw Kit.codeBug(); } resolveGoto(jumpSource, pc); } itsFixupTableTop = 0; } private void addBackwardGoto(int gotoOp, int jumpPC) { int fromPC = itsICodeTop; // Ensure that this is a jump backward if (fromPC <= jumpPC) throw Kit.codeBug(); addGotoOp(gotoOp); resolveGoto(fromPC, jumpPC); } private void resolveForwardGoto(int fromPC) { // Ensure that forward jump skips at least self bytecode if (itsICodeTop < fromPC + 3) throw Kit.codeBug(); resolveGoto(fromPC, itsICodeTop); } private void resolveGoto(int fromPC, int jumpPC) { int offset = jumpPC - fromPC; // Ensure that jumps do not overlap if (0 <= offset && offset <= 2) throw Kit.codeBug(); int offsetSite = fromPC + 1; if (offset != (short)offset) { if (itsData.longJumps == null) { itsData.longJumps = new UintMap(); } itsData.longJumps.put(offsetSite, jumpPC); offset = 0; } byte[] array = itsData.itsICode; array[offsetSite] = (byte)(offset >> 8); array[offsetSite + 1] = (byte)offset; } private void addToken(int token) { if (!validTokenCode(token)) throw Kit.codeBug(); addUint8(token); } private void addIcode(int icode) { if (!validIcode(icode)) throw Kit.codeBug(); // Write negative icode as uint8 bits addUint8(icode & 0xFF); } private void addUint8(int value) { if ((value & ~0xFF) != 0) throw Kit.codeBug(); byte[] array = itsData.itsICode; int top = itsICodeTop; if (top == array.length) { array = increaseICodeCapacity(1); } array[top] = (byte)value; itsICodeTop = top + 1; } private void addUint16(int value) { if ((value & ~0xFFFF) != 0) throw Kit.codeBug(); byte[] array = itsData.itsICode; int top = itsICodeTop; if (top + 2 > array.length) { array = increaseICodeCapacity(2); } array[top] = (byte)(value >>> 8); array[top + 1] = (byte)value; itsICodeTop = top + 2; } private void addInt(int i) { byte[] array = itsData.itsICode; int top = itsICodeTop; if (top + 4 > array.length) { array = increaseICodeCapacity(4); } array[top] = (byte)(i >>> 24); array[top + 1] = (byte)(i >>> 16); array[top + 2] = (byte)(i >>> 8); array[top + 3] = (byte)i; itsICodeTop = top + 4; } private int getDoubleIndex(double num) { int index = itsDoubleTableTop; if (index == 0) { itsData.itsDoubleTable = new double[64]; } else if (itsData.itsDoubleTable.length == index) { double[] na = new double[index * 2]; System.arraycopy(itsData.itsDoubleTable, 0, na, 0, index); itsData.itsDoubleTable = na; } itsData.itsDoubleTable[index] = num; itsDoubleTableTop = index + 1; return index; } private void addGotoOp(int gotoOp) { byte[] array = itsData.itsICode; int top = itsICodeTop; if (top + 3 > array.length) { array = increaseICodeCapacity(3); } array[top] = (byte)gotoOp; // Offset would written later itsICodeTop = top + 1 + 2; } private void addVarOp(int op, int varIndex) { switch (op) { case Token.SETCONSTVAR: if (varIndex < 128) { addIcode(Icode_SETCONSTVAR1); addUint8(varIndex); return; } addIndexOp(Icode_SETCONSTVAR, varIndex); return; case Token.GETVAR: case Token.SETVAR: if (varIndex < 128) { addIcode(op == Token.GETVAR ? Icode_GETVAR1 : Icode_SETVAR1); addUint8(varIndex); return; } // fallthrough case Icode_VAR_INC_DEC: addIndexOp(op, varIndex); return; } throw Kit.codeBug(); } private void addStringOp(int op, String str) { addStringPrefix(str); if (validIcode(op)) { addIcode(op); } else { addToken(op); } } private void addIndexOp(int op, int index) { addIndexPrefix(index); if (validIcode(op)) { addIcode(op); } else { addToken(op); } } private void addStringPrefix(String str) { int index = itsStrings.get(str, -1); if (index == -1) { index = itsStrings.size(); itsStrings.put(str, index); } if (index < 4) { addIcode(Icode_REG_STR_C0 - index); } else if (index <= 0xFF) { addIcode(Icode_REG_STR1); addUint8(index); } else if (index <= 0xFFFF) { addIcode(Icode_REG_STR2); addUint16(index); } else { addIcode(Icode_REG_STR4); addInt(index); } } private void addIndexPrefix(int index) { if (index < 0) Kit.codeBug(); if (index < 6) { addIcode(Icode_REG_IND_C0 - index); } else if (index <= 0xFF) { addIcode(Icode_REG_IND1); addUint8(index); } else if (index <= 0xFFFF) { addIcode(Icode_REG_IND2); addUint16(index); } else { addIcode(Icode_REG_IND4); addInt(index); } } private void addExceptionHandler(int icodeStart, int icodeEnd, int handlerStart, boolean isFinally, int exceptionObjectLocal, int scopeLocal) { int top = itsExceptionTableTop; int[] table = itsData.itsExceptionTable; if (table == null) { if (top != 0) Kit.codeBug(); table = new int[EXCEPTION_SLOT_SIZE * 2]; itsData.itsExceptionTable = table; } else if (table.length == top) { table = new int[table.length * 2]; System.arraycopy(itsData.itsExceptionTable, 0, table, 0, top); itsData.itsExceptionTable = table; } table[top + EXCEPTION_TRY_START_SLOT] = icodeStart; table[top + EXCEPTION_TRY_END_SLOT] = icodeEnd; table[top + EXCEPTION_HANDLER_SLOT] = handlerStart; table[top + EXCEPTION_TYPE_SLOT] = isFinally ? 1 : 0; table[top + EXCEPTION_LOCAL_SLOT] = exceptionObjectLocal; table[top + EXCEPTION_SCOPE_SLOT] = scopeLocal; itsExceptionTableTop = top + EXCEPTION_SLOT_SIZE; } private byte[] increaseICodeCapacity(int extraSize) { int capacity = itsData.itsICode.length; int top = itsICodeTop; if (top + extraSize <= capacity) throw Kit.codeBug(); capacity *= 2; if (top + extraSize > capacity) { capacity = top + extraSize; } byte[] array = new byte[capacity]; System.arraycopy(itsData.itsICode, 0, array, 0, top); itsData.itsICode = array; return array; } private void stackChange(int change) { if (change <= 0) { itsStackDepth += change; } else { int newDepth = itsStackDepth + change; if (newDepth > itsData.itsMaxStack) { itsData.itsMaxStack = newDepth; } itsStackDepth = newDepth; } } private int allocLocal() { int localSlot = itsLocalTop; ++itsLocalTop; if (itsLocalTop > itsData.itsMaxLocals) { itsData.itsMaxLocals = itsLocalTop; } return localSlot; } private void releaseLocal(int localSlot) { --itsLocalTop; if (localSlot != itsLocalTop) Kit.codeBug(); } private static int getShort(byte[] iCode, int pc) { return (iCode[pc] << 8) | (iCode[pc + 1] & 0xFF); } private static int getIndex(byte[] iCode, int pc) { return ((iCode[pc] & 0xFF) << 8) | (iCode[pc + 1] & 0xFF); } private static int getInt(byte[] iCode, int pc) { return (iCode[pc] << 24) | ((iCode[pc + 1] & 0xFF) << 16) | ((iCode[pc + 2] & 0xFF) << 8) | (iCode[pc + 3] & 0xFF); } private static int getExceptionHandler(CallFrame frame, boolean onlyFinally) { int[] exceptionTable = frame.idata.itsExceptionTable; if (exceptionTable == null) { // No exception handlers return -1; } // Icode switch in the interpreter increments PC immediately // and it is necessary to subtract 1 from the saved PC // to point it before the start of the next instruction. int pc = frame.pc - 1; // OPT: use binary search int best = -1, bestStart = 0, bestEnd = 0; for (int i = 0; i != exceptionTable.length; i += EXCEPTION_SLOT_SIZE) { int start = exceptionTable[i + EXCEPTION_TRY_START_SLOT]; int end = exceptionTable[i + EXCEPTION_TRY_END_SLOT]; if (!(start <= pc && pc < end)) { continue; } if (onlyFinally && exceptionTable[i + EXCEPTION_TYPE_SLOT] != 1) { continue; } if (best >= 0) { // Since handlers always nest and they never have shared end // although they can share start it is sufficient to compare // handlers ends if (bestEnd < end) { continue; } // Check the above assumption if (bestStart > start) Kit.codeBug(); // should be nested if (bestEnd == end) Kit.codeBug(); // no ens sharing } best = i; bestStart = start; bestEnd = end; } return best; } private static void dumpICode(InterpreterData idata) { if (!Token.printICode) { return; } byte iCode[] = idata.itsICode; int iCodeLength = iCode.length; String[] strings = idata.itsStringTable; PrintStream out = System.out; out.println("ICode dump, for " + idata.itsName + ", length = " + iCodeLength); out.println("MaxStack = " + idata.itsMaxStack); int indexReg = 0; for (int pc = 0; pc < iCodeLength; ) { out.flush(); out.print(" [" + pc + "] "); int token = iCode[pc]; int icodeLength = bytecodeSpan(token); String tname = bytecodeName(token); int old_pc = pc; ++pc; switch (token) { default: if (icodeLength != 1) Kit.codeBug(); out.println(tname); break; case Icode_GOSUB : case Token.GOTO : case Token.IFEQ : case Token.IFNE : case Icode_IFEQ_POP : case Icode_LEAVEDQ : { int newPC = pc + getShort(iCode, pc) - 1; out.println(tname + " " + newPC); pc += 2; break; } case Icode_VAR_INC_DEC : case Icode_NAME_INC_DEC : case Icode_PROP_INC_DEC : case Icode_ELEM_INC_DEC : case Icode_REF_INC_DEC: { int incrDecrType = iCode[pc]; out.println(tname + " " + incrDecrType); ++pc; break; } case Icode_CALLSPECIAL : { int callType = iCode[pc] & 0xFF; boolean isNew = (iCode[pc + 1] != 0); int line = getIndex(iCode, pc+2); out.println(tname+" "+callType+" "+isNew+" "+indexReg+" "+line); pc += 4; break; } case Token.CATCH_SCOPE: { boolean afterFisrtFlag = (iCode[pc] != 0); out.println(tname+" "+afterFisrtFlag); ++pc; } break; case Token.REGEXP : out.println(tname+" "+idata.itsRegExpLiterals[indexReg]); break; case Token.OBJECTLIT : case Icode_SPARE_ARRAYLIT : out.println(tname+" "+idata.literalIds[indexReg]); break; case Icode_CLOSURE_EXPR : case Icode_CLOSURE_STMT : out.println(tname+" "+idata.itsNestedFunctions[indexReg]); break; case Token.CALL : case Icode_TAIL_CALL : case Token.REF_CALL : case Token.NEW : out.println(tname+' '+indexReg); break; case Token.THROW : case Token.YIELD : case Icode_GENERATOR : case Icode_GENERATOR_END : { int line = getIndex(iCode, pc); out.println(tname + " : " + line); pc += 2; break; } case Icode_SHORTNUMBER : { int value = getShort(iCode, pc); out.println(tname + " " + value); pc += 2; break; } case Icode_INTNUMBER : { int value = getInt(iCode, pc); out.println(tname + " " + value); pc += 4; break; } case Token.NUMBER : { double value = idata.itsDoubleTable[indexReg]; out.println(tname + " " + value); break; } case Icode_LINE : { int line = getIndex(iCode, pc); out.println(tname + " : " + line); pc += 2; break; } case Icode_REG_STR1: { String str = strings[0xFF & iCode[pc]]; out.println(tname + " \"" + str + '"'); ++pc; break; } case Icode_REG_STR2: { String str = strings[getIndex(iCode, pc)]; out.println(tname + " \"" + str + '"'); pc += 2; break; } case Icode_REG_STR4: { String str = strings[getInt(iCode, pc)]; out.println(tname + " \"" + str + '"'); pc += 4; break; } case Icode_REG_IND_C0: indexReg = 0; out.println(tname); break; case Icode_REG_IND_C1: indexReg = 1; out.println(tname); break; case Icode_REG_IND_C2: indexReg = 2; out.println(tname); break; case Icode_REG_IND_C3: indexReg = 3; out.println(tname); break; case Icode_REG_IND_C4: indexReg = 4; out.println(tname); break; case Icode_REG_IND_C5: indexReg = 5; out.println(tname); break; case Icode_REG_IND1: { indexReg = 0xFF & iCode[pc]; out.println(tname+" "+indexReg); ++pc; break; } case Icode_REG_IND2: { indexReg = getIndex(iCode, pc); out.println(tname+" "+indexReg); pc += 2; break; } case Icode_REG_IND4: { indexReg = getInt(iCode, pc); out.println(tname+" "+indexReg); pc += 4; break; } case Icode_GETVAR1: case Icode_SETVAR1: case Icode_SETCONSTVAR1: indexReg = iCode[pc]; out.println(tname+" "+indexReg); ++pc; break; } if (old_pc + icodeLength != pc) Kit.codeBug(); } int[] table = idata.itsExceptionTable; if (table != null) { out.println("Exception handlers: " +table.length / EXCEPTION_SLOT_SIZE); for (int i = 0; i != table.length; i += EXCEPTION_SLOT_SIZE) { int tryStart = table[i + EXCEPTION_TRY_START_SLOT]; int tryEnd = table[i + EXCEPTION_TRY_END_SLOT]; int handlerStart = table[i + EXCEPTION_HANDLER_SLOT]; int type = table[i + EXCEPTION_TYPE_SLOT]; int exceptionLocal = table[i + EXCEPTION_LOCAL_SLOT]; int scopeLocal = table[i + EXCEPTION_SCOPE_SLOT]; out.println(" tryStart="+tryStart+" tryEnd="+tryEnd +" handlerStart="+handlerStart +" type="+(type == 0 ? "catch" : "finally") +" exceptionLocal="+exceptionLocal); } } out.flush(); } private static int bytecodeSpan(int bytecode) { switch (bytecode) { case Token.THROW : case Token.YIELD: case Icode_GENERATOR: case Icode_GENERATOR_END: // source line return 1 + 2; case Icode_GOSUB : case Token.GOTO : case Token.IFEQ : case Token.IFNE : case Icode_IFEQ_POP : case Icode_LEAVEDQ : // target pc offset return 1 + 2; case Icode_CALLSPECIAL : // call type // is new // line number return 1 + 1 + 1 + 2; case Token.CATCH_SCOPE: // scope flag return 1 + 1; case Icode_VAR_INC_DEC: case Icode_NAME_INC_DEC: case Icode_PROP_INC_DEC: case Icode_ELEM_INC_DEC: case Icode_REF_INC_DEC: // type of ++/-- return 1 + 1; case Icode_SHORTNUMBER : // short number return 1 + 2; case Icode_INTNUMBER : // int number return 1 + 4; case Icode_REG_IND1: // ubyte index return 1 + 1; case Icode_REG_IND2: // ushort index return 1 + 2; case Icode_REG_IND4: // int index return 1 + 4; case Icode_REG_STR1: // ubyte string index return 1 + 1; case Icode_REG_STR2: // ushort string index return 1 + 2; case Icode_REG_STR4: // int string index return 1 + 4; case Icode_GETVAR1: case Icode_SETVAR1: case Icode_SETCONSTVAR1: // byte var index return 1 + 1; case Icode_LINE : // line number return 1 + 2; } if (!validBytecode(bytecode)) throw Kit.codeBug(); return 1; } static int[] getLineNumbers(InterpreterData data) { UintMap presentLines = new UintMap(); byte[] iCode = data.itsICode; int iCodeLength = iCode.length; for (int pc = 0; pc != iCodeLength;) { int bytecode = iCode[pc]; int span = bytecodeSpan(bytecode); if (bytecode == Icode_LINE) { if (span != 3) Kit.codeBug(); int line = getIndex(iCode, pc + 1); presentLines.put(line, 0); } pc += span; } return presentLines.getKeys(); } static void captureInterpreterStackInfo(RhinoException ex) { Context cx = Context.getCurrentContext(); if (cx == null || cx.lastInterpreterFrame == null) { // No interpreter invocations ex.interpreterStackInfo = null; ex.interpreterLineData = null; return; } // has interpreter frame on the stack CallFrame[] array; if (cx.previousInterpreterInvocations == null || cx.previousInterpreterInvocations.size() == 0) { array = new CallFrame[1]; } else { int previousCount = cx.previousInterpreterInvocations.size(); if (cx.previousInterpreterInvocations.peek() == cx.lastInterpreterFrame) { // It can happen if exception was generated after // frame was pushed to cx.previousInterpreterInvocations // but before assignment to cx.lastInterpreterFrame. // In this case frames has to be ignored. --previousCount; } array = new CallFrame[previousCount + 1]; cx.previousInterpreterInvocations.toArray(array); } array[array.length - 1] = (CallFrame)cx.lastInterpreterFrame; int interpreterFrameCount = 0; for (int i = 0; i != array.length; ++i) { interpreterFrameCount += 1 + array[i].frameIndex; } int[] linePC = new int[interpreterFrameCount]; // Fill linePC with pc positions from all interpreter frames. // Start from the most nested frame int linePCIndex = interpreterFrameCount; for (int i = array.length; i != 0;) { --i; CallFrame frame = array[i]; while (frame != null) { --linePCIndex; linePC[linePCIndex] = frame.pcSourceLineStart; frame = frame.parentFrame; } } if (linePCIndex != 0) Kit.codeBug(); ex.interpreterStackInfo = array; ex.interpreterLineData = linePC; } static String getSourcePositionFromStack(Context cx, int[] linep) { CallFrame frame = (CallFrame)cx.lastInterpreterFrame; InterpreterData idata = frame.idata; if (frame.pcSourceLineStart >= 0) { linep[0] = getIndex(idata.itsICode, frame.pcSourceLineStart); } else { linep[0] = 0; } return idata.itsSourceFile; } static String getPatchedStack(RhinoException ex, String nativeStackTrace) { String tag = "org.mozilla.javascript.Interpreter.interpretLoop"; StringBuffer sb = new StringBuffer(nativeStackTrace.length() + 1000); String lineSeparator = SecurityUtilities.getSystemProperty("line.separator"); CallFrame[] array = (CallFrame[])ex.interpreterStackInfo; int[] linePC = ex.interpreterLineData; int arrayIndex = array.length; int linePCIndex = linePC.length; int offset = 0; while (arrayIndex != 0) { --arrayIndex; int pos = nativeStackTrace.indexOf(tag, offset); if (pos < 0) { break; } // Skip tag length pos += tag.length(); // Skip until the end of line for (; pos != nativeStackTrace.length(); ++pos) { char c = nativeStackTrace.charAt(pos); if (c == '\n' || c == '\r') { break; } } sb.append(nativeStackTrace.substring(offset, pos)); offset = pos; CallFrame frame = array[arrayIndex]; while (frame != null) { if (linePCIndex == 0) Kit.codeBug(); --linePCIndex; InterpreterData idata = frame.idata; sb.append(lineSeparator); sb.append("\tat script"); if (idata.itsName != null && idata.itsName.length() != 0) { sb.append('.'); sb.append(idata.itsName); } sb.append('('); sb.append(idata.itsSourceFile); int pc = linePC[linePCIndex]; if (pc >= 0) { // Include line info only if available sb.append(':'); sb.append(getIndex(idata.itsICode, pc)); } sb.append(')'); frame = frame.parentFrame; } } sb.append(nativeStackTrace.substring(offset)); return sb.toString(); } static List getScriptStack(RhinoException ex) { if (ex.interpreterStackInfo == null) { return null; } List list = new ArrayList(); String lineSeparator = SecurityUtilities.getSystemProperty("line.separator"); CallFrame[] array = (CallFrame[])ex.interpreterStackInfo; int[] linePC = ex.interpreterLineData; int arrayIndex = array.length; int linePCIndex = linePC.length; while (arrayIndex != 0) { --arrayIndex; StringBuffer sb = new StringBuffer(); CallFrame frame = array[arrayIndex]; while (frame != null) { if (linePCIndex == 0) Kit.codeBug(); --linePCIndex; InterpreterData idata = frame.idata; sb.append("\tat "); sb.append(idata.itsSourceFile); int pc = linePC[linePCIndex]; if (pc >= 0) { // Include line info only if available sb.append(':'); sb.append(getIndex(idata.itsICode, pc)); } if (idata.itsName != null && idata.itsName.length() != 0) { sb.append(" ("); sb.append(idata.itsName); sb.append(')'); } sb.append(lineSeparator); frame = frame.parentFrame; } list.add(sb.toString()); } return list; } static String getEncodedSource(InterpreterData idata) { if (idata.encodedSource == null) { return null; } return idata.encodedSource.substring(idata.encodedSourceStart, idata.encodedSourceEnd); } private static void initFunction(Context cx, Scriptable scope, InterpretedFunction parent, int index) { InterpretedFunction fn; fn = InterpretedFunction.createFunction(cx, scope, parent, index); ScriptRuntime.initFunction(cx, scope, fn, fn.idata.itsFunctionType, parent.idata.evalScriptFlag); } static Object interpret(InterpretedFunction ifun, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (!ScriptRuntime.hasTopCall(cx)) Kit.codeBug(); if (cx.interpreterSecurityDomain != ifun.securityDomain) { Object savedDomain = cx.interpreterSecurityDomain; cx.interpreterSecurityDomain = ifun.securityDomain; try { return ifun.securityController.callWithDomain( ifun.securityDomain, cx, ifun, scope, thisObj, args); } finally { cx.interpreterSecurityDomain = savedDomain; } } CallFrame frame = new CallFrame(); initFrame(cx, scope, thisObj, args, null, 0, args.length, ifun, null, frame); return interpretLoop(cx, frame, null); } static class GeneratorState { GeneratorState(int operation, Object value) { this.operation = operation; this.value = value; } int operation; Object value; RuntimeException returnedException; } public static Object resumeGenerator(Context cx, Scriptable scope, int operation, Object savedState, Object value) { CallFrame frame = (CallFrame) savedState; GeneratorState generatorState = new GeneratorState(operation, value); if (operation == NativeGenerator.GENERATOR_CLOSE) { try { return interpretLoop(cx, frame, generatorState); } catch (RuntimeException e) { // Only propagate exceptions other than closingException if (e != value) throw e; } return Undefined.instance; } Object result = interpretLoop(cx, frame, generatorState); if (generatorState.returnedException != null) throw generatorState.returnedException; return result; } public static Object restartContinuation(Continuation c, Context cx, Scriptable scope, Object[] args) { if (!ScriptRuntime.hasTopCall(cx)) { return ScriptRuntime.doTopCall(c, cx, scope, null, args); } Object arg; if (args.length == 0) { arg = Undefined.instance; } else { arg = args[0]; } CallFrame capturedFrame = (CallFrame)c.getImplementation(); if (capturedFrame == null) { // No frames to restart return arg; } ContinuationJump cjump = new ContinuationJump(c, null); cjump.result = arg; return interpretLoop(cx, null, cjump); } private static Object interpretLoop(Context cx, CallFrame frame, Object throwable) { // throwable holds exception object to rethrow or catch // It is also used for continuation restart in which case // it holds ContinuationJump final Object DBL_MRK = UniqueTag.DOUBLE_MARK; final Object undefined = Undefined.instance; final boolean instructionCounting = (cx.instructionThreshold != 0); // arbitrary number to add to instructionCount when calling // other functions final int INVOCATION_COST = 100; // arbitrary exception cost for instruction counting final int EXCEPTION_COST = 100; String stringReg = null; int indexReg = -1; if (cx.lastInterpreterFrame != null) { // save the top frame from the previous interpreterLoop // invocation on the stack if (cx.previousInterpreterInvocations == null) { cx.previousInterpreterInvocations = new ObjArray(); } cx.previousInterpreterInvocations.push(cx.lastInterpreterFrame); } // When restarting continuation throwable is not null and to jump // to the code that rewind continuation state indexReg should be set // to -1. // With the normal call throable == null and indexReg == -1 allows to // catch bugs with using indeReg to access array eleemnts before // initializing indexReg. GeneratorState generatorState = null; if (throwable != null) { if (throwable instanceof GeneratorState) { generatorState = (GeneratorState) throwable; // reestablish this call frame enterFrame(cx, frame, ScriptRuntime.emptyArgs, true); throwable = null; } else if (!(throwable instanceof ContinuationJump)) { // It should be continuation Kit.codeBug(); } } Object interpreterResult = null; double interpreterResultDbl = 0.0; StateLoop: for (;;) { withoutExceptions: try { if (throwable != null) { // Recovering from exception, indexReg contains // the index of handler if (indexReg >= 0) { // Normal exception handler, transfer // control appropriately if (frame.frozen) { // XXX Deal with exceptios!!! frame = frame.cloneFrozen(); } int[] table = frame.idata.itsExceptionTable; frame.pc = table[indexReg + EXCEPTION_HANDLER_SLOT]; if (instructionCounting) { frame.pcPrevBranch = frame.pc; } frame.savedStackTop = frame.emptyStackTop; int scopeLocal = frame.localShift + table[indexReg + EXCEPTION_SCOPE_SLOT]; int exLocal = frame.localShift + table[indexReg + EXCEPTION_LOCAL_SLOT]; frame.scope = (Scriptable)frame.stack[scopeLocal]; frame.stack[exLocal] = throwable; throwable = null; } else { // Continuation restoration ContinuationJump cjump = (ContinuationJump)throwable; // Clear throwable to indicate that exceptions are OK throwable = null; if (cjump.branchFrame != frame) Kit.codeBug(); // Check that we have at least one frozen frame // in the case of detached continuation restoration: // unwind code ensure that if (cjump.capturedFrame == null) Kit.codeBug(); // Need to rewind branchFrame, capturedFrame // and all frames in between int rewindCount = cjump.capturedFrame.frameIndex + 1; if (cjump.branchFrame != null) { rewindCount -= cjump.branchFrame.frameIndex; } int enterCount = 0; CallFrame[] enterFrames = null; CallFrame x = cjump.capturedFrame; for (int i = 0; i != rewindCount; ++i) { if (!x.frozen) Kit.codeBug(); if (isFrameEnterExitRequired(x)) { if (enterFrames == null) { // Allocate enough space to store the rest // of rewind frames in case all of them // would require to enter enterFrames = new CallFrame[rewindCount - i]; } enterFrames[enterCount] = x; ++enterCount; } x = x.parentFrame; } while (enterCount != 0) { // execute enter: walk enterFrames in the reverse // order since they were stored starting from // the capturedFrame, not branchFrame --enterCount; x = enterFrames[enterCount]; enterFrame(cx, x, ScriptRuntime.emptyArgs, true); } // Continuation jump is almost done: capturedFrame // points to the call to the function that captured // continuation, so clone capturedFrame and // emulate return that function with the suplied result frame = cjump.capturedFrame.cloneFrozen(); setCallResult(frame, cjump.result, cjump.resultDbl); // restart the execution } } else { if (generatorState == null && frame.frozen) Kit.codeBug(); } // Use local variables for constant values in frame // for faster access Object[] stack = frame.stack; double[] sDbl = frame.sDbl; Object[] vars = frame.varSource.stack; double[] varDbls = frame.varSource.sDbl; int[] varAttributes = frame.varSource.stackAttributes; byte[] iCode = frame.idata.itsICode; String[] strings = frame.idata.itsStringTable; // Use local for stackTop as well. Since execption handlers // can only exist at statement level where stack is empty, // it is necessary to save/restore stackTop only across // function calls and normal returns. int stackTop = frame.savedStackTop; // Store new frame in cx which is used for error reporting etc. cx.lastInterpreterFrame = frame; Loop: for (;;) { // Exception handler assumes that PC is already incremented // pass the instruction start when it searches the // exception handler int op = iCode[frame.pc++]; jumplessRun: { // Back indent to ease implementation reading switch (op) { case Icode_GENERATOR: { if (!frame.frozen) { // First time encountering this opcode: create new generator // object and return frame.pc--; // we want to come back here when we resume CallFrame generatorFrame = captureFrameForGenerator(frame); generatorFrame.frozen = true; NativeGenerator generator = new NativeGenerator(frame.scope, generatorFrame.fnOrScript, generatorFrame); frame.result = generator; break Loop; } else { // We are now resuming execution. Fall through to YIELD case. } } // fall through... case Token.YIELD: { if (!frame.frozen) { if (generatorState.operation == NativeGenerator.GENERATOR_CLOSE) { // Error: no yields when generator is closing throw ScriptRuntime.typeError0("msg.yield.closing"); } // return to our caller (which should be a method of NativeGenerator) frame.frozen = true; frame.result = stack[stackTop]; frame.resultDbl = sDbl[stackTop]; frame.savedStackTop = stackTop; frame.pc--; // we want to come back here when we resume ScriptRuntime.exitActivationFunction(cx); return (frame.result != DBL_MRK) ? frame.result : ScriptRuntime.wrapNumber(frame.resultDbl); } else { // we are resuming execution frame.frozen = false; int sourceLine = getIndex(iCode, frame.pc); frame.pc += 2; // skip line number data if (generatorState.operation == NativeGenerator.GENERATOR_THROW) { // processing a call to <generator>.throw(exception): must // act as if exception was thrown from resumption point throwable = new JavaScriptException(generatorState.value, frame.idata.itsSourceFile, sourceLine); break withoutExceptions; } if (generatorState.operation == NativeGenerator.GENERATOR_CLOSE) { throwable = generatorState.value; break withoutExceptions; } if (generatorState.operation != NativeGenerator.GENERATOR_SEND) throw Kit.codeBug(); if (op == Token.YIELD) stack[stackTop] = generatorState.value; continue Loop; } } case Icode_GENERATOR_END: { // throw StopIteration frame.frozen = true; Scriptable top = ScriptableObject.getTopLevelScope(frame.scope); Object e = top.get(NativeIterator.STOP_ITERATION, frame.scope); int sourceLine = getIndex(iCode, frame.pc); generatorState.returnedException = new JavaScriptException(e, frame.idata.itsSourceFile, sourceLine); break Loop; } case Token.THROW: { Object value = stack[stackTop]; if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; int sourceLine = getIndex(iCode, frame.pc); throwable = new JavaScriptException(value, frame.idata.itsSourceFile, sourceLine); break withoutExceptions; } case Token.RETHROW: { indexReg += frame.localShift; throwable = stack[indexReg]; break withoutExceptions; } case Token.GE : case Token.LE : case Token.GT : case Token.LT : { --stackTop; Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; boolean valBln; object_compare: { number_compare: { double rDbl, lDbl; if (rhs == DBL_MRK) { rDbl = sDbl[stackTop + 1]; lDbl = stack_double(frame, stackTop); } else if (lhs == DBL_MRK) { rDbl = ScriptRuntime.toNumber(rhs); lDbl = sDbl[stackTop]; } else { break number_compare; } switch (op) { case Token.GE: valBln = (lDbl >= rDbl); break object_compare; case Token.LE: valBln = (lDbl <= rDbl); break object_compare; case Token.GT: valBln = (lDbl > rDbl); break object_compare; case Token.LT: valBln = (lDbl < rDbl); break object_compare; default: throw Kit.codeBug(); } } switch (op) { case Token.GE: valBln = ScriptRuntime.cmp_LE(rhs, lhs); break; case Token.LE: valBln = ScriptRuntime.cmp_LE(lhs, rhs); break; case Token.GT: valBln = ScriptRuntime.cmp_LT(rhs, lhs); break; case Token.LT: valBln = ScriptRuntime.cmp_LT(lhs, rhs); break; default: throw Kit.codeBug(); } } stack[stackTop] = ScriptRuntime.wrapBoolean(valBln); continue Loop; } case Token.IN : case Token.INSTANCEOF : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); boolean valBln; if (op == Token.IN) { valBln = ScriptRuntime.in(lhs, rhs, cx); } else { valBln = ScriptRuntime.instanceOf(lhs, rhs, cx); } stack[stackTop] = ScriptRuntime.wrapBoolean(valBln); continue Loop; } case Token.EQ : case Token.NE : { --stackTop; boolean valBln; Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; if (rhs == DBL_MRK) { if (lhs == DBL_MRK) { valBln = (sDbl[stackTop] == sDbl[stackTop + 1]); } else { valBln = ScriptRuntime.eqNumber(sDbl[stackTop + 1], lhs); } } else { if (lhs == DBL_MRK) { valBln = ScriptRuntime.eqNumber(sDbl[stackTop], rhs); } else { valBln = ScriptRuntime.eq(lhs, rhs); } } valBln ^= (op == Token.NE); stack[stackTop] = ScriptRuntime.wrapBoolean(valBln); continue Loop; } case Token.SHEQ : case Token.SHNE : { --stackTop; Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; boolean valBln; shallow_compare: { double rdbl, ldbl; if (rhs == DBL_MRK) { rdbl = sDbl[stackTop + 1]; if (lhs == DBL_MRK) { ldbl = sDbl[stackTop]; } else if (lhs instanceof Number) { ldbl = ((Number)lhs).doubleValue(); } else { valBln = false; break shallow_compare; } } else if (lhs == DBL_MRK) { ldbl = sDbl[stackTop]; if (rhs == DBL_MRK) { rdbl = sDbl[stackTop + 1]; } else if (rhs instanceof Number) { rdbl = ((Number)rhs).doubleValue(); } else { valBln = false; break shallow_compare; } } else { valBln = ScriptRuntime.shallowEq(lhs, rhs); break shallow_compare; } valBln = (ldbl == rdbl); } valBln ^= (op == Token.SHNE); stack[stackTop] = ScriptRuntime.wrapBoolean(valBln); continue Loop; } case Token.IFNE : if (stack_boolean(frame, stackTop--)) { frame.pc += 2; continue Loop; } break jumplessRun; case Token.IFEQ : if (!stack_boolean(frame, stackTop--)) { frame.pc += 2; continue Loop; } break jumplessRun; case Icode_IFEQ_POP : if (!stack_boolean(frame, stackTop--)) { frame.pc += 2; continue Loop; } stack[stackTop--] = null; break jumplessRun; case Token.GOTO : break jumplessRun; case Icode_GOSUB : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = frame.pc + 2; break jumplessRun; case Icode_STARTSUB : if (stackTop == frame.emptyStackTop + 1) { // Call from Icode_GOSUB: store return PC address in the local indexReg += frame.localShift; stack[indexReg] = stack[stackTop]; sDbl[indexReg] = sDbl[stackTop]; --stackTop; } else { // Call from exception handler: exception object is already stored // in the local if (stackTop != frame.emptyStackTop) Kit.codeBug(); } continue Loop; case Icode_RETSUB : { // indexReg: local to store return address if (instructionCounting) { addInstructionCount(cx, frame, 0); } indexReg += frame.localShift; Object value = stack[indexReg]; if (value != DBL_MRK) { // Invocation from exception handler, restore object to rethrow throwable = value; break withoutExceptions; } // Normal return from GOSUB frame.pc = (int)sDbl[indexReg]; if (instructionCounting) { frame.pcPrevBranch = frame.pc; } continue Loop; } case Icode_POP : stack[stackTop] = null; stackTop--; continue Loop; case Icode_POP_RESULT : frame.result = stack[stackTop]; frame.resultDbl = sDbl[stackTop]; stack[stackTop] = null; --stackTop; continue Loop; case Icode_DUP : stack[stackTop + 1] = stack[stackTop]; sDbl[stackTop + 1] = sDbl[stackTop]; stackTop++; continue Loop; case Icode_DUP2 : stack[stackTop + 1] = stack[stackTop - 1]; sDbl[stackTop + 1] = sDbl[stackTop - 1]; stack[stackTop + 2] = stack[stackTop]; sDbl[stackTop + 2] = sDbl[stackTop]; stackTop += 2; continue Loop; case Icode_SWAP : { Object o = stack[stackTop]; stack[stackTop] = stack[stackTop - 1]; stack[stackTop - 1] = o; double d = sDbl[stackTop]; sDbl[stackTop] = sDbl[stackTop - 1]; sDbl[stackTop - 1] = d; continue Loop; } case Token.RETURN : frame.result = stack[stackTop]; frame.resultDbl = sDbl[stackTop]; --stackTop; break Loop; case Token.RETURN_RESULT : break Loop; case Icode_RETUNDEF : frame.result = undefined; break Loop; case Token.BITNOT : { int rIntValue = stack_int32(frame, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = ~rIntValue; continue Loop; } case Token.BITAND : case Token.BITOR : case Token.BITXOR : case Token.LSH : case Token.RSH : { int rIntValue = stack_int32(frame, stackTop); --stackTop; int lIntValue = stack_int32(frame, stackTop); stack[stackTop] = DBL_MRK; switch (op) { case Token.BITAND: lIntValue &= rIntValue; break; case Token.BITOR: lIntValue |= rIntValue; break; case Token.BITXOR: lIntValue ^= rIntValue; break; case Token.LSH: lIntValue <<= rIntValue; break; case Token.RSH: lIntValue >>= rIntValue; break; } sDbl[stackTop] = lIntValue; continue Loop; } case Token.URSH : { int rIntValue = stack_int32(frame, stackTop) & 0x1F; --stackTop; double lDbl = stack_double(frame, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = ScriptRuntime.toUint32(lDbl) >>> rIntValue; continue Loop; } case Token.NEG : case Token.POS : { double rDbl = stack_double(frame, stackTop); stack[stackTop] = DBL_MRK; if (op == Token.NEG) { rDbl = -rDbl; } sDbl[stackTop] = rDbl; continue Loop; } case Token.ADD : --stackTop; do_add(stack, sDbl, stackTop, cx); continue Loop; case Token.SUB : case Token.MUL : case Token.DIV : case Token.MOD : { double rDbl = stack_double(frame, stackTop); --stackTop; double lDbl = stack_double(frame, stackTop); stack[stackTop] = DBL_MRK; switch (op) { case Token.SUB: lDbl -= rDbl; break; case Token.MUL: lDbl *= rDbl; break; case Token.DIV: lDbl /= rDbl; break; case Token.MOD: lDbl %= rDbl; break; } sDbl[stackTop] = lDbl; continue Loop; } case Token.NOT : stack[stackTop] = ScriptRuntime.wrapBoolean( !stack_boolean(frame, stackTop)); continue Loop; case Token.BINDNAME : stack[++stackTop] = ScriptRuntime.bind(cx, frame.scope, stringReg); continue Loop; case Token.SETNAME : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Scriptable lhs = (Scriptable)stack[stackTop]; stack[stackTop] = ScriptRuntime.setName(lhs, rhs, cx, frame.scope, stringReg); continue Loop; } case Icode_SETCONST: { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Scriptable lhs = (Scriptable)stack[stackTop]; stack[stackTop] = ScriptRuntime.setConst(lhs, rhs, cx, stringReg); continue Loop; } case Token.DELPROP : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.delete(lhs, rhs, cx); continue Loop; } case Token.GETPROP : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getObjectProp(lhs, stringReg, cx); continue Loop; } case Token.SETPROP : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.setObjectProp(lhs, stringReg, rhs, cx); continue Loop; } case Icode_PROP_INC_DEC : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.propIncrDecr(lhs, stringReg, cx, iCode[frame.pc]); ++frame.pc; continue Loop; } case Token.GETELEM : { --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) { lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); } Object value; Object id = stack[stackTop + 1]; if (id != DBL_MRK) { value = ScriptRuntime.getObjectElem(lhs, id, cx); } else { double d = sDbl[stackTop + 1]; value = ScriptRuntime.getObjectIndex(lhs, d, cx); } stack[stackTop] = value; continue Loop; } case Token.SETELEM : { stackTop -= 2; Object rhs = stack[stackTop + 2]; if (rhs == DBL_MRK) { rhs = ScriptRuntime.wrapNumber(sDbl[stackTop + 2]); } Object lhs = stack[stackTop]; if (lhs == DBL_MRK) { lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); } Object value; Object id = stack[stackTop + 1]; if (id != DBL_MRK) { value = ScriptRuntime.setObjectElem(lhs, id, rhs, cx); } else { double d = sDbl[stackTop + 1]; value = ScriptRuntime.setObjectIndex(lhs, d, rhs, cx); } stack[stackTop] = value; continue Loop; } case Icode_ELEM_INC_DEC: { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.elemIncrDecr(lhs, rhs, cx, iCode[frame.pc]); ++frame.pc; continue Loop; } case Token.GET_REF : { Ref ref = (Ref)stack[stackTop]; stack[stackTop] = ScriptRuntime.refGet(ref, cx); continue Loop; } case Token.SET_REF : { Object value = stack[stackTop]; if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Ref ref = (Ref)stack[stackTop]; stack[stackTop] = ScriptRuntime.refSet(ref, value, cx); continue Loop; } case Token.DEL_REF : { Ref ref = (Ref)stack[stackTop]; stack[stackTop] = ScriptRuntime.refDel(ref, cx); continue Loop; } case Icode_REF_INC_DEC : { Ref ref = (Ref)stack[stackTop]; stack[stackTop] = ScriptRuntime.refIncrDecr(ref, cx, iCode[frame.pc]); ++frame.pc; continue Loop; } case Token.LOCAL_LOAD : ++stackTop; indexReg += frame.localShift; stack[stackTop] = stack[indexReg]; sDbl[stackTop] = sDbl[indexReg]; continue Loop; case Icode_LOCAL_CLEAR : indexReg += frame.localShift; stack[indexReg] = null; continue Loop; case Icode_NAME_AND_THIS : // stringReg: name ++stackTop; stack[stackTop] = ScriptRuntime.getNameFunctionAndThis(stringReg, cx, frame.scope); ++stackTop; stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx); continue Loop; case Icode_PROP_AND_THIS: { Object obj = stack[stackTop]; if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]); // stringReg: property stack[stackTop] = ScriptRuntime.getPropFunctionAndThis(obj, stringReg, cx); ++stackTop; stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx); continue Loop; } case Icode_ELEM_AND_THIS: { Object obj = stack[stackTop - 1]; if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop - 1]); Object id = stack[stackTop]; if (id == DBL_MRK) id = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop - 1] = ScriptRuntime.getElemFunctionAndThis(obj, id, cx); stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx); continue Loop; } case Icode_VALUE_AND_THIS : { Object value = stack[stackTop]; if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getValueFunctionAndThis(value, cx); ++stackTop; stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx); continue Loop; } case Icode_CALLSPECIAL : { if (instructionCounting) { cx.instructionCount += INVOCATION_COST; } int callType = iCode[frame.pc] & 0xFF; boolean isNew = (iCode[frame.pc + 1] != 0); int sourceLine = getIndex(iCode, frame.pc + 2); // indexReg: number of arguments if (isNew) { // stack change: function arg0 .. argN -> newResult stackTop -= indexReg; Object function = stack[stackTop]; if (function == DBL_MRK) function = ScriptRuntime.wrapNumber(sDbl[stackTop]); Object[] outArgs = getArgsArray( stack, sDbl, stackTop + 1, indexReg); stack[stackTop] = ScriptRuntime.newSpecial( cx, function, outArgs, frame.scope, callType); } else { // stack change: function thisObj arg0 .. argN -> result stackTop -= 1 + indexReg; // Call code generation ensure that stack here // is ... Callable Scriptable Scriptable functionThis = (Scriptable)stack[stackTop + 1]; Callable function = (Callable)stack[stackTop]; Object[] outArgs = getArgsArray( stack, sDbl, stackTop + 2, indexReg); stack[stackTop] = ScriptRuntime.callSpecial( cx, function, functionThis, outArgs, frame.scope, frame.thisObj, callType, frame.idata.itsSourceFile, sourceLine); } frame.pc += 4; continue Loop; } case Token.CALL : case Icode_TAIL_CALL : case Token.REF_CALL : { if (instructionCounting) { cx.instructionCount += INVOCATION_COST; } // stack change: function thisObj arg0 .. argN -> result // indexReg: number of arguments stackTop -= 1 + indexReg; // CALL generation ensures that fun and funThisObj // are already Scriptable and Callable objects respectively Callable fun = (Callable)stack[stackTop]; Scriptable funThisObj = (Scriptable)stack[stackTop + 1]; if (op == Token.REF_CALL) { Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 2, indexReg); stack[stackTop] = ScriptRuntime.callRef(fun, funThisObj, outArgs, cx); continue Loop; } Scriptable calleeScope = frame.scope; if (frame.useActivation) { calleeScope = ScriptableObject.getTopLevelScope(frame.scope); } if (fun instanceof InterpretedFunction) { InterpretedFunction ifun = (InterpretedFunction)fun; if (frame.fnOrScript.securityDomain == ifun.securityDomain) { CallFrame callParentFrame = frame; CallFrame calleeFrame = new CallFrame(); if (op == Icode_TAIL_CALL) { // In principle tail call can re-use the current // frame and its stack arrays but it is hard to // do properly. Any exceptions that can legally // happen during frame re-initialization including // StackOverflowException during innocent looking // System.arraycopy may leave the current frame // data corrupted leading to undefined behaviour // in the catch code bellow that unwinds JS stack // on exceptions. Then there is issue about frame release // end exceptions there. // To avoid frame allocation a released frame // can be cached for re-use which would also benefit // non-tail calls but it is not clear that this caching // would gain in performance due to potentially // bad iteraction with GC. callParentFrame = frame.parentFrame; // Release the current frame. See Bug #344501 to see why // it is being done here. // TODO: If using the graphical debugger, tail call // optimization will create a "hole" in the context stack. // The correct thing to do may be to disable tail call // optimization if the code is being debugged. exitFrame(cx, frame, null); } initFrame(cx, calleeScope, funThisObj, stack, sDbl, stackTop + 2, indexReg, ifun, callParentFrame, calleeFrame); if (op != Icode_TAIL_CALL) { frame.savedStackTop = stackTop; frame.savedCallOp = op; } frame = calleeFrame; continue StateLoop; } } if (fun instanceof Continuation) { // Jump to the captured continuation ContinuationJump cjump; cjump = new ContinuationJump((Continuation)fun, frame); // continuation result is the first argument if any // of contination call if (indexReg == 0) { cjump.result = undefined; } else { cjump.result = stack[stackTop + 2]; cjump.resultDbl = sDbl[stackTop + 2]; } // Start the real unwind job throwable = cjump; break withoutExceptions; } if (fun instanceof IdFunctionObject) { IdFunctionObject ifun = (IdFunctionObject)fun; if (Continuation.isContinuationConstructor(ifun)) { captureContinuation(cx, frame, stackTop); continue Loop; } } Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 2, indexReg); stack[stackTop] = fun.call(cx, calleeScope, funThisObj, outArgs); continue Loop; } case Token.NEW : { if (instructionCounting) { cx.instructionCount += INVOCATION_COST; } // stack change: function arg0 .. argN -> newResult // indexReg: number of arguments stackTop -= indexReg; Object lhs = stack[stackTop]; if (lhs instanceof InterpretedFunction) { InterpretedFunction f = (InterpretedFunction)lhs; if (frame.fnOrScript.securityDomain == f.securityDomain) { Scriptable newInstance = f.createObject(cx, frame.scope); CallFrame calleeFrame = new CallFrame(); initFrame(cx, frame.scope, newInstance, stack, sDbl, stackTop + 1, indexReg, f, frame, calleeFrame); stack[stackTop] = newInstance; frame.savedStackTop = stackTop; frame.savedCallOp = op; frame = calleeFrame; continue StateLoop; } } if (!(lhs instanceof Function)) { if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); throw ScriptRuntime.notFunctionError(lhs); } Function fun = (Function)lhs; if (fun instanceof IdFunctionObject) { IdFunctionObject ifun = (IdFunctionObject)fun; if (Continuation.isContinuationConstructor(ifun)) { captureContinuation(cx, frame, stackTop); continue Loop; } } Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 1, indexReg); stack[stackTop] = fun.construct(cx, frame.scope, outArgs); continue Loop; } case Token.TYPEOF : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.typeof(lhs); continue Loop; } case Icode_TYPEOFNAME : stack[++stackTop] = ScriptRuntime.typeofName(frame.scope, stringReg); continue Loop; case Token.STRING : stack[++stackTop] = stringReg; continue Loop; case Icode_SHORTNUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = getShort(iCode, frame.pc); frame.pc += 2; continue Loop; case Icode_INTNUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = getInt(iCode, frame.pc); frame.pc += 4; continue Loop; case Token.NUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = frame.idata.itsDoubleTable[indexReg]; continue Loop; case Token.NAME : stack[++stackTop] = ScriptRuntime.name(cx, frame.scope, stringReg); continue Loop; case Icode_NAME_INC_DEC : stack[++stackTop] = ScriptRuntime.nameIncrDecr(frame.scope, stringReg, cx, iCode[frame.pc]); ++frame.pc; continue Loop; case Icode_SETCONSTVAR1: indexReg = iCode[frame.pc++]; // fallthrough case Token.SETCONSTVAR : if (!frame.useActivation) { if ((varAttributes[indexReg] & ScriptableObject.READONLY) == 0) { throw Context.reportRuntimeError1("msg.var.redecl", frame.idata.argNames[indexReg]); } if ((varAttributes[indexReg] & ScriptableObject.UNINITIALIZED_CONST) != 0) { vars[indexReg] = stack[stackTop]; varAttributes[indexReg] &= ~ScriptableObject.UNINITIALIZED_CONST; varDbls[indexReg] = sDbl[stackTop]; } } else { Object val = stack[stackTop]; if (val == DBL_MRK) val = ScriptRuntime.wrapNumber(sDbl[stackTop]); stringReg = frame.idata.argNames[indexReg]; if (frame.scope instanceof ConstProperties) { ConstProperties cp = (ConstProperties)frame.scope; cp.putConst(stringReg, frame.scope, val); } else throw Kit.codeBug(); } continue Loop; case Icode_SETVAR1: indexReg = iCode[frame.pc++]; // fallthrough case Token.SETVAR : if (!frame.useActivation) { if ((varAttributes[indexReg] & ScriptableObject.READONLY) == 0) { vars[indexReg] = stack[stackTop]; varDbls[indexReg] = sDbl[stackTop]; } } else { Object val = stack[stackTop]; if (val == DBL_MRK) val = ScriptRuntime.wrapNumber(sDbl[stackTop]); stringReg = frame.idata.argNames[indexReg]; frame.scope.put(stringReg, frame.scope, val); } continue Loop; case Icode_GETVAR1: indexReg = iCode[frame.pc++]; // fallthrough case Token.GETVAR : ++stackTop; if (!frame.useActivation) { stack[stackTop] = vars[indexReg]; sDbl[stackTop] = varDbls[indexReg]; } else { stringReg = frame.idata.argNames[indexReg]; stack[stackTop] = frame.scope.get(stringReg, frame.scope); } continue Loop; case Icode_VAR_INC_DEC : { // indexReg : varindex ++stackTop; int incrDecrMask = iCode[frame.pc]; if (!frame.useActivation) { stack[stackTop] = DBL_MRK; Object varValue = vars[indexReg]; double d; if (varValue == DBL_MRK) { d = varDbls[indexReg]; } else { d = ScriptRuntime.toNumber(varValue); vars[indexReg] = DBL_MRK; } double d2 = ((incrDecrMask & Node.DECR_FLAG) == 0) ? d + 1.0 : d - 1.0; varDbls[indexReg] = d2; sDbl[stackTop] = ((incrDecrMask & Node.POST_FLAG) == 0) ? d2 : d; } else { String varName = frame.idata.argNames[indexReg]; stack[stackTop] = ScriptRuntime.nameIncrDecr(frame.scope, varName, cx, incrDecrMask); } ++frame.pc; continue Loop; } case Icode_ZERO : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = 0; continue Loop; case Icode_ONE : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = 1; continue Loop; case Token.NULL : stack[++stackTop] = null; continue Loop; case Token.THIS : stack[++stackTop] = frame.thisObj; continue Loop; case Token.THISFN : stack[++stackTop] = frame.fnOrScript; continue Loop; case Token.FALSE : stack[++stackTop] = Boolean.FALSE; continue Loop; case Token.TRUE : stack[++stackTop] = Boolean.TRUE; continue Loop; case Icode_UNDEF : stack[++stackTop] = undefined; continue Loop; case Token.ENTERWITH : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; frame.scope = ScriptRuntime.enterWith(lhs, cx, frame.scope); continue Loop; } case Token.LEAVEWITH : frame.scope = ScriptRuntime.leaveWith(frame.scope); continue Loop; case Token.CATCH_SCOPE : { // stack top: exception object // stringReg: name of exception variable // indexReg: local for exception scope --stackTop; indexReg += frame.localShift; boolean afterFirstScope = (frame.idata.itsICode[frame.pc] != 0); Throwable caughtException = (Throwable)stack[stackTop + 1]; Scriptable lastCatchScope; if (!afterFirstScope) { lastCatchScope = null; } else { lastCatchScope = (Scriptable)stack[indexReg]; } stack[indexReg] = ScriptRuntime.newCatchScope(caughtException, lastCatchScope, stringReg, cx, frame.scope); ++frame.pc; continue Loop; } case Token.ENUM_INIT_KEYS : case Token.ENUM_INIT_VALUES : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; indexReg += frame.localShift; stack[indexReg] = ScriptRuntime.enumInit( lhs, cx, (op == Token.ENUM_INIT_VALUES)); continue Loop; } case Token.ENUM_NEXT : case Token.ENUM_ID : { indexReg += frame.localShift; Object val = stack[indexReg]; ++stackTop; stack[stackTop] = (op == Token.ENUM_NEXT) ? (Object)ScriptRuntime.enumNext(val) : (Object)ScriptRuntime.enumId(val, cx); continue Loop; } case Token.REF_SPECIAL : { //stringReg: name of special property Object obj = stack[stackTop]; if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.specialRef(obj, stringReg, cx); continue Loop; } case Token.REF_MEMBER: { //indexReg: flags Object elem = stack[stackTop]; if (elem == DBL_MRK) elem = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object obj = stack[stackTop]; if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.memberRef(obj, elem, cx, indexReg); continue Loop; } case Token.REF_NS_MEMBER: { //indexReg: flags Object elem = stack[stackTop]; if (elem == DBL_MRK) elem = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object ns = stack[stackTop]; if (ns == DBL_MRK) ns = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object obj = stack[stackTop]; if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.memberRef(obj, ns, elem, cx, indexReg); continue Loop; } case Token.REF_NAME: { //indexReg: flags Object name = stack[stackTop]; if (name == DBL_MRK) name = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.nameRef(name, cx, frame.scope, indexReg); continue Loop; } case Token.REF_NS_NAME: { //indexReg: flags Object name = stack[stackTop]; if (name == DBL_MRK) name = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object ns = stack[stackTop]; if (ns == DBL_MRK) ns = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.nameRef(ns, name, cx, frame.scope, indexReg); continue Loop; } case Icode_SCOPE_LOAD : indexReg += frame.localShift; frame.scope = (Scriptable)stack[indexReg]; continue Loop; case Icode_SCOPE_SAVE : indexReg += frame.localShift; stack[indexReg] = frame.scope; continue Loop; case Icode_CLOSURE_EXPR : stack[++stackTop] = InterpretedFunction.createFunction(cx, frame.scope, frame.fnOrScript, indexReg); continue Loop; case Icode_CLOSURE_STMT : initFunction(cx, frame.scope, frame.fnOrScript, indexReg); continue Loop; case Token.REGEXP : stack[++stackTop] = frame.scriptRegExps[indexReg]; continue Loop; case Icode_LITERAL_NEW : // indexReg: number of values in the literal ++stackTop; stack[stackTop] = new int[indexReg]; ++stackTop; stack[stackTop] = new Object[indexReg]; sDbl[stackTop] = 0; continue Loop; case Icode_LITERAL_SET : { Object value = stack[stackTop]; if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; int i = (int)sDbl[stackTop]; ((Object[])stack[stackTop])[i] = value; sDbl[stackTop] = i + 1; continue Loop; } case Icode_LITERAL_GETTER : { Object value = stack[stackTop]; --stackTop; int i = (int)sDbl[stackTop]; ((Object[])stack[stackTop])[i] = value; ((int[])stack[stackTop - 1])[i] = -1; sDbl[stackTop] = i + 1; continue Loop; } case Icode_LITERAL_SETTER : { Object value = stack[stackTop]; --stackTop; int i = (int)sDbl[stackTop]; ((Object[])stack[stackTop])[i] = value; ((int[])stack[stackTop - 1])[i] = +1; sDbl[stackTop] = i + 1; continue Loop; } case Token.ARRAYLIT : case Icode_SPARE_ARRAYLIT : case Token.OBJECTLIT : { Object[] data = (Object[])stack[stackTop]; --stackTop; int[] getterSetters = (int[])stack[stackTop]; Object val; if (op == Token.OBJECTLIT) { Object[] ids = (Object[])frame.idata.literalIds[indexReg]; val = ScriptRuntime.newObjectLiteral(ids, data, getterSetters, cx, frame.scope); } else { int[] skipIndexces = null; if (op == Icode_SPARE_ARRAYLIT) { skipIndexces = (int[])frame.idata.literalIds[indexReg]; } val = ScriptRuntime.newArrayLiteral(data, skipIndexces, cx, frame.scope); } stack[stackTop] = val; continue Loop; } case Icode_ENTERDQ : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; frame.scope = ScriptRuntime.enterDotQuery(lhs, frame.scope); continue Loop; } case Icode_LEAVEDQ : { boolean valBln = stack_boolean(frame, stackTop); Object x = ScriptRuntime.updateDotQuery(valBln, frame.scope); if (x != null) { stack[stackTop] = x; frame.scope = ScriptRuntime.leaveDotQuery(frame.scope); frame.pc += 2; continue Loop; } // reset stack and PC to code after ENTERDQ --stackTop; break jumplessRun; } case Token.DEFAULTNAMESPACE : { Object value = stack[stackTop]; if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.setDefaultNamespace(value, cx); continue Loop; } case Token.ESCXMLATTR : { Object value = stack[stackTop]; if (value != DBL_MRK) { - stack[stackTop] = "\"" + ScriptRuntime.escapeAttributeValue(value, cx) + "\""; + stack[stackTop] = ScriptRuntime.escapeAttributeValue(value, cx); } continue Loop; } case Token.ESCXMLTEXT : { Object value = stack[stackTop]; if (value != DBL_MRK) { stack[stackTop] = ScriptRuntime.escapeTextValue(value, cx); } continue Loop; } case Icode_DEBUGGER: if (frame.debuggerFrame != null) { frame.debuggerFrame.onDebuggerStatement(cx); } break Loop; case Icode_LINE : frame.pcSourceLineStart = frame.pc; if (frame.debuggerFrame != null) { int line = getIndex(iCode, frame.pc); frame.debuggerFrame.onLineChange(cx, line); } frame.pc += 2; continue Loop; case Icode_REG_IND_C0: indexReg = 0; continue Loop; case Icode_REG_IND_C1: indexReg = 1; continue Loop; case Icode_REG_IND_C2: indexReg = 2; continue Loop; case Icode_REG_IND_C3: indexReg = 3; continue Loop; case Icode_REG_IND_C4: indexReg = 4; continue Loop; case Icode_REG_IND_C5: indexReg = 5; continue Loop; case Icode_REG_IND1: indexReg = 0xFF & iCode[frame.pc]; ++frame.pc; continue Loop; case Icode_REG_IND2: indexReg = getIndex(iCode, frame.pc); frame.pc += 2; continue Loop; case Icode_REG_IND4: indexReg = getInt(iCode, frame.pc); frame.pc += 4; continue Loop; case Icode_REG_STR_C0: stringReg = strings[0]; continue Loop; case Icode_REG_STR_C1: stringReg = strings[1]; continue Loop; case Icode_REG_STR_C2: stringReg = strings[2]; continue Loop; case Icode_REG_STR_C3: stringReg = strings[3]; continue Loop; case Icode_REG_STR1: stringReg = strings[0xFF & iCode[frame.pc]]; ++frame.pc; continue Loop; case Icode_REG_STR2: stringReg = strings[getIndex(iCode, frame.pc)]; frame.pc += 2; continue Loop; case Icode_REG_STR4: stringReg = strings[getInt(iCode, frame.pc)]; frame.pc += 4; continue Loop; default : dumpICode(frame.idata); throw new RuntimeException( "Unknown icode : "+op+" @ pc : "+(frame.pc-1)); } // end of interpreter switch } // end of jumplessRun label block // This should be reachable only for jump implementation // when pc points to encoded target offset if (instructionCounting) { addInstructionCount(cx, frame, 2); } int offset = getShort(iCode, frame.pc); if (offset != 0) { // -1 accounts for pc pointing to jump opcode + 1 frame.pc += offset - 1; } else { frame.pc = frame.idata.longJumps. getExistingInt(frame.pc); } if (instructionCounting) { frame.pcPrevBranch = frame.pc; } continue Loop; } // end of Loop: for exitFrame(cx, frame, null); interpreterResult = frame.result; interpreterResultDbl = frame.resultDbl; if (frame.parentFrame != null) { frame = frame.parentFrame; if (frame.frozen) { frame = frame.cloneFrozen(); } setCallResult( frame, interpreterResult, interpreterResultDbl); interpreterResult = null; // Help GC continue StateLoop; } break StateLoop; } // end of interpreter withoutExceptions: try catch (Throwable ex) { if (throwable != null) { // This is serious bug and it is better to track it ASAP ex.printStackTrace(System.err); throw new IllegalStateException(); } throwable = ex; } // This should be reachable only after above catch or from // finally when it needs to propagate exception or from // explicit throw if (throwable == null) Kit.codeBug(); // Exception type final int EX_CATCH_STATE = 2; // Can execute JS catch final int EX_FINALLY_STATE = 1; // Can execute JS finally final int EX_NO_JS_STATE = 0; // Terminate JS execution int exState; ContinuationJump cjump = null; if (generatorState != null && generatorState.operation == NativeGenerator.GENERATOR_CLOSE && throwable == generatorState.value) { exState = EX_FINALLY_STATE; } else if (throwable instanceof JavaScriptException) { exState = EX_CATCH_STATE; } else if (throwable instanceof EcmaError) { // an offical ECMA error object, exState = EX_CATCH_STATE; } else if (throwable instanceof EvaluatorException) { exState = EX_CATCH_STATE; } else if (throwable instanceof RuntimeException) { exState = EX_FINALLY_STATE; } else if (throwable instanceof Error) { exState = EX_NO_JS_STATE; } else { // It must be ContinuationJump exState = EX_FINALLY_STATE; cjump = (ContinuationJump)throwable; } if (instructionCounting) { try { addInstructionCount(cx, frame, EXCEPTION_COST); } catch (RuntimeException ex) { throwable = ex; exState = EX_FINALLY_STATE; } catch (Error ex) { // Error from instruction counting // => unconditionally terminate JS throwable = ex; cjump = null; exState = EX_NO_JS_STATE; } } if (frame.debuggerFrame != null && throwable instanceof RuntimeException) { // Call debugger only for RuntimeException RuntimeException rex = (RuntimeException)throwable; try { frame.debuggerFrame.onExceptionThrown(cx, rex); } catch (Throwable ex) { // Any exception from debugger // => unconditionally terminate JS throwable = ex; cjump = null; exState = EX_NO_JS_STATE; } } for (;;) { if (exState != EX_NO_JS_STATE) { boolean onlyFinally = (exState != EX_CATCH_STATE); indexReg = getExceptionHandler(frame, onlyFinally); if (indexReg >= 0) { // We caught an exception, restart the loop // with exception pending the processing at the loop // start continue StateLoop; } } // No allowed exception handlers in this frame, unwind // to parent and try to look there exitFrame(cx, frame, throwable); frame = frame.parentFrame; if (frame == null) { break; } if (cjump != null && cjump.branchFrame == frame) { // Continuation branch point was hit, // restart the state loop to reenter continuation indexReg = -1; continue StateLoop; } } // No more frames, rethrow the exception or deal with continuation if (cjump != null) { if (cjump.branchFrame != null) { // The above loop should locate the top frame Kit.codeBug(); } if (cjump.capturedFrame != null) { // Restarting detached continuation indexReg = -1; continue StateLoop; } // Return continuation result to the caller interpreterResult = cjump.result; interpreterResultDbl = cjump.resultDbl; throwable = null; } break StateLoop; } // end of StateLoop: for(;;) // Do cleanups/restorations before the final return or throw if (cx.previousInterpreterInvocations != null && cx.previousInterpreterInvocations.size() != 0) { cx.lastInterpreterFrame = cx.previousInterpreterInvocations.pop(); } else { // It was the last interpreter frame on the stack cx.lastInterpreterFrame = null; // Force GC of the value cx.previousInterpreterInvocations cx.previousInterpreterInvocations = null; } if (throwable != null) { if (throwable instanceof RuntimeException) { throw (RuntimeException)throwable; } else { // Must be instance of Error or code bug throw (Error)throwable; } } return (interpreterResult != DBL_MRK) ? interpreterResult : ScriptRuntime.wrapNumber(interpreterResultDbl); } private static void initFrame(Context cx, Scriptable callerScope, Scriptable thisObj, Object[] args, double[] argsDbl, int argShift, int argCount, InterpretedFunction fnOrScript, CallFrame parentFrame, CallFrame frame) { InterpreterData idata = fnOrScript.idata; boolean useActivation = idata.itsNeedsActivation; DebugFrame debuggerFrame = null; if (cx.debugger != null) { debuggerFrame = cx.debugger.getFrame(cx, idata); if (debuggerFrame != null) { useActivation = true; } } if (useActivation) { // Copy args to new array to pass to enterActivationFunction // or debuggerFrame.onEnter if (argsDbl != null) { args = getArgsArray(args, argsDbl, argShift, argCount); } argShift = 0; argsDbl = null; } Scriptable scope; if (idata.itsFunctionType != 0) { if (!idata.useDynamicScope) { scope = fnOrScript.getParentScope(); } else { scope = callerScope; } if (useActivation) { scope = ScriptRuntime.createFunctionActivation( fnOrScript, scope, args); } } else { scope = callerScope; ScriptRuntime.initScript(fnOrScript, thisObj, cx, scope, fnOrScript.idata.evalScriptFlag); } if (idata.itsNestedFunctions != null) { if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation) Kit.codeBug(); for (int i = 0; i < idata.itsNestedFunctions.length; i++) { InterpreterData fdata = idata.itsNestedFunctions[i]; if (fdata.itsFunctionType == FunctionNode.FUNCTION_STATEMENT) { initFunction(cx, scope, fnOrScript, i); } } } Scriptable[] scriptRegExps = null; if (idata.itsRegExpLiterals != null) { // Wrapped regexps for functions are stored in // InterpretedFunction // but for script which should not contain references to scope // the regexps re-wrapped during each script execution if (idata.itsFunctionType != 0) { scriptRegExps = fnOrScript.functionRegExps; } else { scriptRegExps = fnOrScript.createRegExpWraps(cx, scope); } } // Initialize args, vars, locals and stack int emptyStackTop = idata.itsMaxVars + idata.itsMaxLocals - 1; int maxFrameArray = idata.itsMaxFrameArray; if (maxFrameArray != emptyStackTop + idata.itsMaxStack + 1) Kit.codeBug(); Object[] stack; int[] stackAttributes; double[] sDbl; boolean stackReuse; if (frame.stack != null && maxFrameArray <= frame.stack.length) { // Reuse stacks from old frame stackReuse = true; stack = frame.stack; stackAttributes = frame.stackAttributes; sDbl = frame.sDbl; } else { stackReuse = false; stack = new Object[maxFrameArray]; stackAttributes = new int[maxFrameArray]; sDbl = new double[maxFrameArray]; } int varCount = idata.getParamAndVarCount(); for (int i = 0; i < varCount; i++) { if (idata.getParamOrVarConst(i)) stackAttributes[i] = ScriptableObject.CONST; } int definedArgs = idata.argCount; if (definedArgs > argCount) { definedArgs = argCount; } // Fill the frame structure frame.parentFrame = parentFrame; frame.frameIndex = (parentFrame == null) ? 0 : parentFrame.frameIndex + 1; if(frame.frameIndex > cx.getMaximumInterpreterStackDepth()) { throw Context.reportRuntimeError("Exceeded maximum stack depth"); } frame.frozen = false; frame.fnOrScript = fnOrScript; frame.idata = idata; frame.stack = stack; frame.stackAttributes = stackAttributes; frame.sDbl = sDbl; frame.varSource = frame; frame.localShift = idata.itsMaxVars; frame.emptyStackTop = emptyStackTop; frame.debuggerFrame = debuggerFrame; frame.useActivation = useActivation; frame.thisObj = thisObj; frame.scriptRegExps = scriptRegExps; // Initialize initial values of variables that change during // interpretation. frame.result = Undefined.instance; frame.pc = 0; frame.pcPrevBranch = 0; frame.pcSourceLineStart = idata.firstLinePC; frame.scope = scope; frame.savedStackTop = emptyStackTop; frame.savedCallOp = 0; System.arraycopy(args, argShift, stack, 0, definedArgs); if (argsDbl != null) { System.arraycopy(argsDbl, argShift, sDbl, 0, definedArgs); } for (int i = definedArgs; i != idata.itsMaxVars; ++i) { stack[i] = Undefined.instance; } if (stackReuse) { // Clean the stack part and space beyond stack if any // of the old array to allow to GC objects there for (int i = emptyStackTop + 1; i != stack.length; ++i) { stack[i] = null; } } enterFrame(cx, frame, args, false); } private static boolean isFrameEnterExitRequired(CallFrame frame) { return frame.debuggerFrame != null || frame.idata.itsNeedsActivation; } private static void enterFrame(Context cx, CallFrame frame, Object[] args, boolean continuationRestart) { boolean usesActivation = frame.idata.itsNeedsActivation; boolean isDebugged = frame.debuggerFrame != null; if(usesActivation || isDebugged) { Scriptable scope = frame.scope; if(scope == null) { Kit.codeBug(); } else if (continuationRestart) { // Walk the parent chain of frame.scope until a NativeCall is // found. Normally, frame.scope is a NativeCall when called // from initFrame() for a debugged or activatable function. // However, when called from interpreterLoop() as part of // restarting a continuation, it can also be a NativeWith if // the continuation was captured within a "with" or "catch" // block ("catch" implicitly uses NativeWith to create a scope // to expose the exception variable). for(;;) { if(scope instanceof NativeCall) { break; } else { scope = scope.getParentScope(); if (scope == null || (frame.parentFrame != null && frame.parentFrame.scope == scope)) { // If we get here, we didn't find a NativeCall in // the call chain before reaching parent frame's // scope. This should not be possible. Kit.codeBug(); break; // Never reached, but keeps the static analyzer happy about "scope" not being null 5 lines above. } } } } if (isDebugged) { frame.debuggerFrame.onEnter(cx, scope, frame.thisObj, args); } // Enter activation only when itsNeedsActivation true, // since debugger should not interfere with activation // chaining if (usesActivation) { ScriptRuntime.enterActivationFunction(cx, scope); } } } private static void exitFrame(Context cx, CallFrame frame, Object throwable) { if (frame.idata.itsNeedsActivation) { ScriptRuntime.exitActivationFunction(cx); } if (frame.debuggerFrame != null) { try { if (throwable instanceof Throwable) { frame.debuggerFrame.onExit(cx, true, throwable); } else { Object result; ContinuationJump cjump = (ContinuationJump)throwable; if (cjump == null) { result = frame.result; } else { result = cjump.result; } if (result == UniqueTag.DOUBLE_MARK) { double resultDbl; if (cjump == null) { resultDbl = frame.resultDbl; } else { resultDbl = cjump.resultDbl; } result = ScriptRuntime.wrapNumber(resultDbl); } frame.debuggerFrame.onExit(cx, false, result); } } catch (Throwable ex) { System.err.println( "RHINO USAGE WARNING: onExit terminated with exception"); ex.printStackTrace(System.err); } } } private static void setCallResult(CallFrame frame, Object callResult, double callResultDbl) { if (frame.savedCallOp == Token.CALL) { frame.stack[frame.savedStackTop] = callResult; frame.sDbl[frame.savedStackTop] = callResultDbl; } else if (frame.savedCallOp == Token.NEW) { // If construct returns scriptable, // then it replaces on stack top saved original instance // of the object. if (callResult instanceof Scriptable) { frame.stack[frame.savedStackTop] = callResult; } } else { Kit.codeBug(); } frame.savedCallOp = 0; } private static void captureContinuation(Context cx, CallFrame frame, int stackTop) { Continuation c = new Continuation(); ScriptRuntime.setObjectProtoAndParent( c, ScriptRuntime.getTopCallScope(cx)); // Make sure that all frames upstack frames are frozen CallFrame x = frame.parentFrame; while (x != null && !x.frozen) { x.frozen = true; // Allow to GC unused stack space for (int i = x.savedStackTop + 1; i != x.stack.length; ++i) { // Allow to GC unused stack space x.stack[i] = null; x.stackAttributes[i] = ScriptableObject.EMPTY; } if (x.savedCallOp == Token.CALL) { // the call will always overwrite the stack top with the result x.stack[x.savedStackTop] = null; } else { if (x.savedCallOp != Token.NEW) Kit.codeBug(); // the new operator uses stack top to store the constructed // object so it shall not be cleared: see comments in // setCallResult } x = x.parentFrame; } c.initImplementation(frame.parentFrame); frame.stack[stackTop] = c; } private static int stack_int32(CallFrame frame, int i) { Object x = frame.stack[i]; double value; if (x == UniqueTag.DOUBLE_MARK) { value = frame.sDbl[i]; } else { value = ScriptRuntime.toNumber(x); } return ScriptRuntime.toInt32(value); } private static double stack_double(CallFrame frame, int i) { Object x = frame.stack[i]; if (x != UniqueTag.DOUBLE_MARK) { return ScriptRuntime.toNumber(x); } else { return frame.sDbl[i]; } } private static boolean stack_boolean(CallFrame frame, int i) { Object x = frame.stack[i]; if (x == Boolean.TRUE) { return true; } else if (x == Boolean.FALSE) { return false; } else if (x == UniqueTag.DOUBLE_MARK) { double d = frame.sDbl[i]; return d == d && d != 0.0; } else if (x == null || x == Undefined.instance) { return false; } else if (x instanceof Number) { double d = ((Number)x).doubleValue(); return (d == d && d != 0.0); } else if (x instanceof Boolean) { return ((Boolean)x).booleanValue(); } else { return ScriptRuntime.toBoolean(x); } } private static void do_add(Object[] stack, double[] sDbl, int stackTop, Context cx) { Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; double d; boolean leftRightOrder; if (rhs == UniqueTag.DOUBLE_MARK) { d = sDbl[stackTop + 1]; if (lhs == UniqueTag.DOUBLE_MARK) { sDbl[stackTop] += d; return; } leftRightOrder = true; // fallthrough to object + number code } else if (lhs == UniqueTag.DOUBLE_MARK) { d = sDbl[stackTop]; lhs = rhs; leftRightOrder = false; // fallthrough to object + number code } else { if (lhs instanceof Scriptable || rhs instanceof Scriptable) { stack[stackTop] = ScriptRuntime.add(lhs, rhs, cx); } else if (lhs instanceof String) { String lstr = (String)lhs; String rstr = ScriptRuntime.toString(rhs); stack[stackTop] = lstr.concat(rstr); } else if (rhs instanceof String) { String lstr = ScriptRuntime.toString(lhs); String rstr = (String)rhs; stack[stackTop] = lstr.concat(rstr); } else { double lDbl = (lhs instanceof Number) ? ((Number)lhs).doubleValue() : ScriptRuntime.toNumber(lhs); double rDbl = (rhs instanceof Number) ? ((Number)rhs).doubleValue() : ScriptRuntime.toNumber(rhs); stack[stackTop] = UniqueTag.DOUBLE_MARK; sDbl[stackTop] = lDbl + rDbl; } return; } // handle object(lhs) + number(d) code if (lhs instanceof Scriptable) { rhs = ScriptRuntime.wrapNumber(d); if (!leftRightOrder) { Object tmp = lhs; lhs = rhs; rhs = tmp; } stack[stackTop] = ScriptRuntime.add(lhs, rhs, cx); } else if (lhs instanceof String) { String lstr = (String)lhs; String rstr = ScriptRuntime.toString(d); if (leftRightOrder) { stack[stackTop] = lstr.concat(rstr); } else { stack[stackTop] = rstr.concat(lstr); } } else { double lDbl = (lhs instanceof Number) ? ((Number)lhs).doubleValue() : ScriptRuntime.toNumber(lhs); stack[stackTop] = UniqueTag.DOUBLE_MARK; sDbl[stackTop] = lDbl + d; } } private static Object[] getArgsArray(Object[] stack, double[] sDbl, int shift, int count) { if (count == 0) { return ScriptRuntime.emptyArgs; } Object[] args = new Object[count]; for (int i = 0; i != count; ++i, ++shift) { Object val = stack[shift]; if (val == UniqueTag.DOUBLE_MARK) { val = ScriptRuntime.wrapNumber(sDbl[shift]); } args[i] = val; } return args; } private static void addInstructionCount(Context cx, CallFrame frame, int extra) { cx.instructionCount += frame.pc - frame.pcPrevBranch + extra; if (cx.instructionCount > cx.instructionThreshold) { cx.observeInstructionCount(cx.instructionCount); cx.instructionCount = 0; } } }
true
true
private static Object interpretLoop(Context cx, CallFrame frame, Object throwable) { // throwable holds exception object to rethrow or catch // It is also used for continuation restart in which case // it holds ContinuationJump final Object DBL_MRK = UniqueTag.DOUBLE_MARK; final Object undefined = Undefined.instance; final boolean instructionCounting = (cx.instructionThreshold != 0); // arbitrary number to add to instructionCount when calling // other functions final int INVOCATION_COST = 100; // arbitrary exception cost for instruction counting final int EXCEPTION_COST = 100; String stringReg = null; int indexReg = -1; if (cx.lastInterpreterFrame != null) { // save the top frame from the previous interpreterLoop // invocation on the stack if (cx.previousInterpreterInvocations == null) { cx.previousInterpreterInvocations = new ObjArray(); } cx.previousInterpreterInvocations.push(cx.lastInterpreterFrame); } // When restarting continuation throwable is not null and to jump // to the code that rewind continuation state indexReg should be set // to -1. // With the normal call throable == null and indexReg == -1 allows to // catch bugs with using indeReg to access array eleemnts before // initializing indexReg. GeneratorState generatorState = null; if (throwable != null) { if (throwable instanceof GeneratorState) { generatorState = (GeneratorState) throwable; // reestablish this call frame enterFrame(cx, frame, ScriptRuntime.emptyArgs, true); throwable = null; } else if (!(throwable instanceof ContinuationJump)) { // It should be continuation Kit.codeBug(); } } Object interpreterResult = null; double interpreterResultDbl = 0.0; StateLoop: for (;;) { withoutExceptions: try { if (throwable != null) { // Recovering from exception, indexReg contains // the index of handler if (indexReg >= 0) { // Normal exception handler, transfer // control appropriately if (frame.frozen) { // XXX Deal with exceptios!!! frame = frame.cloneFrozen(); } int[] table = frame.idata.itsExceptionTable; frame.pc = table[indexReg + EXCEPTION_HANDLER_SLOT]; if (instructionCounting) { frame.pcPrevBranch = frame.pc; } frame.savedStackTop = frame.emptyStackTop; int scopeLocal = frame.localShift + table[indexReg + EXCEPTION_SCOPE_SLOT]; int exLocal = frame.localShift + table[indexReg + EXCEPTION_LOCAL_SLOT]; frame.scope = (Scriptable)frame.stack[scopeLocal]; frame.stack[exLocal] = throwable; throwable = null; } else { // Continuation restoration ContinuationJump cjump = (ContinuationJump)throwable; // Clear throwable to indicate that exceptions are OK throwable = null; if (cjump.branchFrame != frame) Kit.codeBug(); // Check that we have at least one frozen frame // in the case of detached continuation restoration: // unwind code ensure that if (cjump.capturedFrame == null) Kit.codeBug(); // Need to rewind branchFrame, capturedFrame // and all frames in between int rewindCount = cjump.capturedFrame.frameIndex + 1; if (cjump.branchFrame != null) { rewindCount -= cjump.branchFrame.frameIndex; } int enterCount = 0; CallFrame[] enterFrames = null; CallFrame x = cjump.capturedFrame; for (int i = 0; i != rewindCount; ++i) { if (!x.frozen) Kit.codeBug(); if (isFrameEnterExitRequired(x)) { if (enterFrames == null) { // Allocate enough space to store the rest // of rewind frames in case all of them // would require to enter enterFrames = new CallFrame[rewindCount - i]; } enterFrames[enterCount] = x; ++enterCount; } x = x.parentFrame; } while (enterCount != 0) { // execute enter: walk enterFrames in the reverse // order since they were stored starting from // the capturedFrame, not branchFrame --enterCount; x = enterFrames[enterCount]; enterFrame(cx, x, ScriptRuntime.emptyArgs, true); } // Continuation jump is almost done: capturedFrame // points to the call to the function that captured // continuation, so clone capturedFrame and // emulate return that function with the suplied result frame = cjump.capturedFrame.cloneFrozen(); setCallResult(frame, cjump.result, cjump.resultDbl); // restart the execution } } else { if (generatorState == null && frame.frozen) Kit.codeBug(); } // Use local variables for constant values in frame // for faster access Object[] stack = frame.stack; double[] sDbl = frame.sDbl; Object[] vars = frame.varSource.stack; double[] varDbls = frame.varSource.sDbl; int[] varAttributes = frame.varSource.stackAttributes; byte[] iCode = frame.idata.itsICode; String[] strings = frame.idata.itsStringTable; // Use local for stackTop as well. Since execption handlers // can only exist at statement level where stack is empty, // it is necessary to save/restore stackTop only across // function calls and normal returns. int stackTop = frame.savedStackTop; // Store new frame in cx which is used for error reporting etc. cx.lastInterpreterFrame = frame; Loop: for (;;) { // Exception handler assumes that PC is already incremented // pass the instruction start when it searches the // exception handler int op = iCode[frame.pc++]; jumplessRun: { // Back indent to ease implementation reading switch (op) { case Icode_GENERATOR: { if (!frame.frozen) { // First time encountering this opcode: create new generator // object and return frame.pc--; // we want to come back here when we resume CallFrame generatorFrame = captureFrameForGenerator(frame); generatorFrame.frozen = true; NativeGenerator generator = new NativeGenerator(frame.scope, generatorFrame.fnOrScript, generatorFrame); frame.result = generator; break Loop; } else { // We are now resuming execution. Fall through to YIELD case. } } // fall through... case Token.YIELD: { if (!frame.frozen) { if (generatorState.operation == NativeGenerator.GENERATOR_CLOSE) { // Error: no yields when generator is closing throw ScriptRuntime.typeError0("msg.yield.closing"); } // return to our caller (which should be a method of NativeGenerator) frame.frozen = true; frame.result = stack[stackTop]; frame.resultDbl = sDbl[stackTop]; frame.savedStackTop = stackTop; frame.pc--; // we want to come back here when we resume ScriptRuntime.exitActivationFunction(cx); return (frame.result != DBL_MRK) ? frame.result : ScriptRuntime.wrapNumber(frame.resultDbl); } else { // we are resuming execution frame.frozen = false; int sourceLine = getIndex(iCode, frame.pc); frame.pc += 2; // skip line number data if (generatorState.operation == NativeGenerator.GENERATOR_THROW) { // processing a call to <generator>.throw(exception): must // act as if exception was thrown from resumption point throwable = new JavaScriptException(generatorState.value, frame.idata.itsSourceFile, sourceLine); break withoutExceptions; } if (generatorState.operation == NativeGenerator.GENERATOR_CLOSE) { throwable = generatorState.value; break withoutExceptions; } if (generatorState.operation != NativeGenerator.GENERATOR_SEND) throw Kit.codeBug(); if (op == Token.YIELD) stack[stackTop] = generatorState.value; continue Loop; } } case Icode_GENERATOR_END: { // throw StopIteration frame.frozen = true; Scriptable top = ScriptableObject.getTopLevelScope(frame.scope); Object e = top.get(NativeIterator.STOP_ITERATION, frame.scope); int sourceLine = getIndex(iCode, frame.pc); generatorState.returnedException = new JavaScriptException(e, frame.idata.itsSourceFile, sourceLine); break Loop; } case Token.THROW: { Object value = stack[stackTop]; if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; int sourceLine = getIndex(iCode, frame.pc); throwable = new JavaScriptException(value, frame.idata.itsSourceFile, sourceLine); break withoutExceptions; } case Token.RETHROW: { indexReg += frame.localShift; throwable = stack[indexReg]; break withoutExceptions; } case Token.GE : case Token.LE : case Token.GT : case Token.LT : { --stackTop; Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; boolean valBln; object_compare: { number_compare: { double rDbl, lDbl; if (rhs == DBL_MRK) { rDbl = sDbl[stackTop + 1]; lDbl = stack_double(frame, stackTop); } else if (lhs == DBL_MRK) { rDbl = ScriptRuntime.toNumber(rhs); lDbl = sDbl[stackTop]; } else { break number_compare; } switch (op) { case Token.GE: valBln = (lDbl >= rDbl); break object_compare; case Token.LE: valBln = (lDbl <= rDbl); break object_compare; case Token.GT: valBln = (lDbl > rDbl); break object_compare; case Token.LT: valBln = (lDbl < rDbl); break object_compare; default: throw Kit.codeBug(); } } switch (op) { case Token.GE: valBln = ScriptRuntime.cmp_LE(rhs, lhs); break; case Token.LE: valBln = ScriptRuntime.cmp_LE(lhs, rhs); break; case Token.GT: valBln = ScriptRuntime.cmp_LT(rhs, lhs); break; case Token.LT: valBln = ScriptRuntime.cmp_LT(lhs, rhs); break; default: throw Kit.codeBug(); } } stack[stackTop] = ScriptRuntime.wrapBoolean(valBln); continue Loop; } case Token.IN : case Token.INSTANCEOF : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); boolean valBln; if (op == Token.IN) { valBln = ScriptRuntime.in(lhs, rhs, cx); } else { valBln = ScriptRuntime.instanceOf(lhs, rhs, cx); } stack[stackTop] = ScriptRuntime.wrapBoolean(valBln); continue Loop; } case Token.EQ : case Token.NE : { --stackTop; boolean valBln; Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; if (rhs == DBL_MRK) { if (lhs == DBL_MRK) { valBln = (sDbl[stackTop] == sDbl[stackTop + 1]); } else { valBln = ScriptRuntime.eqNumber(sDbl[stackTop + 1], lhs); } } else { if (lhs == DBL_MRK) { valBln = ScriptRuntime.eqNumber(sDbl[stackTop], rhs); } else { valBln = ScriptRuntime.eq(lhs, rhs); } } valBln ^= (op == Token.NE); stack[stackTop] = ScriptRuntime.wrapBoolean(valBln); continue Loop; } case Token.SHEQ : case Token.SHNE : { --stackTop; Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; boolean valBln; shallow_compare: { double rdbl, ldbl; if (rhs == DBL_MRK) { rdbl = sDbl[stackTop + 1]; if (lhs == DBL_MRK) { ldbl = sDbl[stackTop]; } else if (lhs instanceof Number) { ldbl = ((Number)lhs).doubleValue(); } else { valBln = false; break shallow_compare; } } else if (lhs == DBL_MRK) { ldbl = sDbl[stackTop]; if (rhs == DBL_MRK) { rdbl = sDbl[stackTop + 1]; } else if (rhs instanceof Number) { rdbl = ((Number)rhs).doubleValue(); } else { valBln = false; break shallow_compare; } } else { valBln = ScriptRuntime.shallowEq(lhs, rhs); break shallow_compare; } valBln = (ldbl == rdbl); } valBln ^= (op == Token.SHNE); stack[stackTop] = ScriptRuntime.wrapBoolean(valBln); continue Loop; } case Token.IFNE : if (stack_boolean(frame, stackTop--)) { frame.pc += 2; continue Loop; } break jumplessRun; case Token.IFEQ : if (!stack_boolean(frame, stackTop--)) { frame.pc += 2; continue Loop; } break jumplessRun; case Icode_IFEQ_POP : if (!stack_boolean(frame, stackTop--)) { frame.pc += 2; continue Loop; } stack[stackTop--] = null; break jumplessRun; case Token.GOTO : break jumplessRun; case Icode_GOSUB : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = frame.pc + 2; break jumplessRun; case Icode_STARTSUB : if (stackTop == frame.emptyStackTop + 1) { // Call from Icode_GOSUB: store return PC address in the local indexReg += frame.localShift; stack[indexReg] = stack[stackTop]; sDbl[indexReg] = sDbl[stackTop]; --stackTop; } else { // Call from exception handler: exception object is already stored // in the local if (stackTop != frame.emptyStackTop) Kit.codeBug(); } continue Loop; case Icode_RETSUB : { // indexReg: local to store return address if (instructionCounting) { addInstructionCount(cx, frame, 0); } indexReg += frame.localShift; Object value = stack[indexReg]; if (value != DBL_MRK) { // Invocation from exception handler, restore object to rethrow throwable = value; break withoutExceptions; } // Normal return from GOSUB frame.pc = (int)sDbl[indexReg]; if (instructionCounting) { frame.pcPrevBranch = frame.pc; } continue Loop; } case Icode_POP : stack[stackTop] = null; stackTop--; continue Loop; case Icode_POP_RESULT : frame.result = stack[stackTop]; frame.resultDbl = sDbl[stackTop]; stack[stackTop] = null; --stackTop; continue Loop; case Icode_DUP : stack[stackTop + 1] = stack[stackTop]; sDbl[stackTop + 1] = sDbl[stackTop]; stackTop++; continue Loop; case Icode_DUP2 : stack[stackTop + 1] = stack[stackTop - 1]; sDbl[stackTop + 1] = sDbl[stackTop - 1]; stack[stackTop + 2] = stack[stackTop]; sDbl[stackTop + 2] = sDbl[stackTop]; stackTop += 2; continue Loop; case Icode_SWAP : { Object o = stack[stackTop]; stack[stackTop] = stack[stackTop - 1]; stack[stackTop - 1] = o; double d = sDbl[stackTop]; sDbl[stackTop] = sDbl[stackTop - 1]; sDbl[stackTop - 1] = d; continue Loop; } case Token.RETURN : frame.result = stack[stackTop]; frame.resultDbl = sDbl[stackTop]; --stackTop; break Loop; case Token.RETURN_RESULT : break Loop; case Icode_RETUNDEF : frame.result = undefined; break Loop; case Token.BITNOT : { int rIntValue = stack_int32(frame, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = ~rIntValue; continue Loop; } case Token.BITAND : case Token.BITOR : case Token.BITXOR : case Token.LSH : case Token.RSH : { int rIntValue = stack_int32(frame, stackTop); --stackTop; int lIntValue = stack_int32(frame, stackTop); stack[stackTop] = DBL_MRK; switch (op) { case Token.BITAND: lIntValue &= rIntValue; break; case Token.BITOR: lIntValue |= rIntValue; break; case Token.BITXOR: lIntValue ^= rIntValue; break; case Token.LSH: lIntValue <<= rIntValue; break; case Token.RSH: lIntValue >>= rIntValue; break; } sDbl[stackTop] = lIntValue; continue Loop; } case Token.URSH : { int rIntValue = stack_int32(frame, stackTop) & 0x1F; --stackTop; double lDbl = stack_double(frame, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = ScriptRuntime.toUint32(lDbl) >>> rIntValue; continue Loop; } case Token.NEG : case Token.POS : { double rDbl = stack_double(frame, stackTop); stack[stackTop] = DBL_MRK; if (op == Token.NEG) { rDbl = -rDbl; } sDbl[stackTop] = rDbl; continue Loop; } case Token.ADD : --stackTop; do_add(stack, sDbl, stackTop, cx); continue Loop; case Token.SUB : case Token.MUL : case Token.DIV : case Token.MOD : { double rDbl = stack_double(frame, stackTop); --stackTop; double lDbl = stack_double(frame, stackTop); stack[stackTop] = DBL_MRK; switch (op) { case Token.SUB: lDbl -= rDbl; break; case Token.MUL: lDbl *= rDbl; break; case Token.DIV: lDbl /= rDbl; break; case Token.MOD: lDbl %= rDbl; break; } sDbl[stackTop] = lDbl; continue Loop; } case Token.NOT : stack[stackTop] = ScriptRuntime.wrapBoolean( !stack_boolean(frame, stackTop)); continue Loop; case Token.BINDNAME : stack[++stackTop] = ScriptRuntime.bind(cx, frame.scope, stringReg); continue Loop; case Token.SETNAME : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Scriptable lhs = (Scriptable)stack[stackTop]; stack[stackTop] = ScriptRuntime.setName(lhs, rhs, cx, frame.scope, stringReg); continue Loop; } case Icode_SETCONST: { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Scriptable lhs = (Scriptable)stack[stackTop]; stack[stackTop] = ScriptRuntime.setConst(lhs, rhs, cx, stringReg); continue Loop; } case Token.DELPROP : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.delete(lhs, rhs, cx); continue Loop; } case Token.GETPROP : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getObjectProp(lhs, stringReg, cx); continue Loop; } case Token.SETPROP : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.setObjectProp(lhs, stringReg, rhs, cx); continue Loop; } case Icode_PROP_INC_DEC : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.propIncrDecr(lhs, stringReg, cx, iCode[frame.pc]); ++frame.pc; continue Loop; } case Token.GETELEM : { --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) { lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); } Object value; Object id = stack[stackTop + 1]; if (id != DBL_MRK) { value = ScriptRuntime.getObjectElem(lhs, id, cx); } else { double d = sDbl[stackTop + 1]; value = ScriptRuntime.getObjectIndex(lhs, d, cx); } stack[stackTop] = value; continue Loop; } case Token.SETELEM : { stackTop -= 2; Object rhs = stack[stackTop + 2]; if (rhs == DBL_MRK) { rhs = ScriptRuntime.wrapNumber(sDbl[stackTop + 2]); } Object lhs = stack[stackTop]; if (lhs == DBL_MRK) { lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); } Object value; Object id = stack[stackTop + 1]; if (id != DBL_MRK) { value = ScriptRuntime.setObjectElem(lhs, id, rhs, cx); } else { double d = sDbl[stackTop + 1]; value = ScriptRuntime.setObjectIndex(lhs, d, rhs, cx); } stack[stackTop] = value; continue Loop; } case Icode_ELEM_INC_DEC: { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.elemIncrDecr(lhs, rhs, cx, iCode[frame.pc]); ++frame.pc; continue Loop; } case Token.GET_REF : { Ref ref = (Ref)stack[stackTop]; stack[stackTop] = ScriptRuntime.refGet(ref, cx); continue Loop; } case Token.SET_REF : { Object value = stack[stackTop]; if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Ref ref = (Ref)stack[stackTop]; stack[stackTop] = ScriptRuntime.refSet(ref, value, cx); continue Loop; } case Token.DEL_REF : { Ref ref = (Ref)stack[stackTop]; stack[stackTop] = ScriptRuntime.refDel(ref, cx); continue Loop; } case Icode_REF_INC_DEC : { Ref ref = (Ref)stack[stackTop]; stack[stackTop] = ScriptRuntime.refIncrDecr(ref, cx, iCode[frame.pc]); ++frame.pc; continue Loop; } case Token.LOCAL_LOAD : ++stackTop; indexReg += frame.localShift; stack[stackTop] = stack[indexReg]; sDbl[stackTop] = sDbl[indexReg]; continue Loop; case Icode_LOCAL_CLEAR : indexReg += frame.localShift; stack[indexReg] = null; continue Loop; case Icode_NAME_AND_THIS : // stringReg: name ++stackTop; stack[stackTop] = ScriptRuntime.getNameFunctionAndThis(stringReg, cx, frame.scope); ++stackTop; stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx); continue Loop; case Icode_PROP_AND_THIS: { Object obj = stack[stackTop]; if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]); // stringReg: property stack[stackTop] = ScriptRuntime.getPropFunctionAndThis(obj, stringReg, cx); ++stackTop; stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx); continue Loop; } case Icode_ELEM_AND_THIS: { Object obj = stack[stackTop - 1]; if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop - 1]); Object id = stack[stackTop]; if (id == DBL_MRK) id = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop - 1] = ScriptRuntime.getElemFunctionAndThis(obj, id, cx); stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx); continue Loop; } case Icode_VALUE_AND_THIS : { Object value = stack[stackTop]; if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getValueFunctionAndThis(value, cx); ++stackTop; stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx); continue Loop; } case Icode_CALLSPECIAL : { if (instructionCounting) { cx.instructionCount += INVOCATION_COST; } int callType = iCode[frame.pc] & 0xFF; boolean isNew = (iCode[frame.pc + 1] != 0); int sourceLine = getIndex(iCode, frame.pc + 2); // indexReg: number of arguments if (isNew) { // stack change: function arg0 .. argN -> newResult stackTop -= indexReg; Object function = stack[stackTop]; if (function == DBL_MRK) function = ScriptRuntime.wrapNumber(sDbl[stackTop]); Object[] outArgs = getArgsArray( stack, sDbl, stackTop + 1, indexReg); stack[stackTop] = ScriptRuntime.newSpecial( cx, function, outArgs, frame.scope, callType); } else { // stack change: function thisObj arg0 .. argN -> result stackTop -= 1 + indexReg; // Call code generation ensure that stack here // is ... Callable Scriptable Scriptable functionThis = (Scriptable)stack[stackTop + 1]; Callable function = (Callable)stack[stackTop]; Object[] outArgs = getArgsArray( stack, sDbl, stackTop + 2, indexReg); stack[stackTop] = ScriptRuntime.callSpecial( cx, function, functionThis, outArgs, frame.scope, frame.thisObj, callType, frame.idata.itsSourceFile, sourceLine); } frame.pc += 4; continue Loop; } case Token.CALL : case Icode_TAIL_CALL : case Token.REF_CALL : { if (instructionCounting) { cx.instructionCount += INVOCATION_COST; } // stack change: function thisObj arg0 .. argN -> result // indexReg: number of arguments stackTop -= 1 + indexReg; // CALL generation ensures that fun and funThisObj // are already Scriptable and Callable objects respectively Callable fun = (Callable)stack[stackTop]; Scriptable funThisObj = (Scriptable)stack[stackTop + 1]; if (op == Token.REF_CALL) { Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 2, indexReg); stack[stackTop] = ScriptRuntime.callRef(fun, funThisObj, outArgs, cx); continue Loop; } Scriptable calleeScope = frame.scope; if (frame.useActivation) { calleeScope = ScriptableObject.getTopLevelScope(frame.scope); } if (fun instanceof InterpretedFunction) { InterpretedFunction ifun = (InterpretedFunction)fun; if (frame.fnOrScript.securityDomain == ifun.securityDomain) { CallFrame callParentFrame = frame; CallFrame calleeFrame = new CallFrame(); if (op == Icode_TAIL_CALL) { // In principle tail call can re-use the current // frame and its stack arrays but it is hard to // do properly. Any exceptions that can legally // happen during frame re-initialization including // StackOverflowException during innocent looking // System.arraycopy may leave the current frame // data corrupted leading to undefined behaviour // in the catch code bellow that unwinds JS stack // on exceptions. Then there is issue about frame release // end exceptions there. // To avoid frame allocation a released frame // can be cached for re-use which would also benefit // non-tail calls but it is not clear that this caching // would gain in performance due to potentially // bad iteraction with GC. callParentFrame = frame.parentFrame; // Release the current frame. See Bug #344501 to see why // it is being done here. // TODO: If using the graphical debugger, tail call // optimization will create a "hole" in the context stack. // The correct thing to do may be to disable tail call // optimization if the code is being debugged. exitFrame(cx, frame, null); } initFrame(cx, calleeScope, funThisObj, stack, sDbl, stackTop + 2, indexReg, ifun, callParentFrame, calleeFrame); if (op != Icode_TAIL_CALL) { frame.savedStackTop = stackTop; frame.savedCallOp = op; } frame = calleeFrame; continue StateLoop; } } if (fun instanceof Continuation) { // Jump to the captured continuation ContinuationJump cjump; cjump = new ContinuationJump((Continuation)fun, frame); // continuation result is the first argument if any // of contination call if (indexReg == 0) { cjump.result = undefined; } else { cjump.result = stack[stackTop + 2]; cjump.resultDbl = sDbl[stackTop + 2]; } // Start the real unwind job throwable = cjump; break withoutExceptions; } if (fun instanceof IdFunctionObject) { IdFunctionObject ifun = (IdFunctionObject)fun; if (Continuation.isContinuationConstructor(ifun)) { captureContinuation(cx, frame, stackTop); continue Loop; } } Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 2, indexReg); stack[stackTop] = fun.call(cx, calleeScope, funThisObj, outArgs); continue Loop; } case Token.NEW : { if (instructionCounting) { cx.instructionCount += INVOCATION_COST; } // stack change: function arg0 .. argN -> newResult // indexReg: number of arguments stackTop -= indexReg; Object lhs = stack[stackTop]; if (lhs instanceof InterpretedFunction) { InterpretedFunction f = (InterpretedFunction)lhs; if (frame.fnOrScript.securityDomain == f.securityDomain) { Scriptable newInstance = f.createObject(cx, frame.scope); CallFrame calleeFrame = new CallFrame(); initFrame(cx, frame.scope, newInstance, stack, sDbl, stackTop + 1, indexReg, f, frame, calleeFrame); stack[stackTop] = newInstance; frame.savedStackTop = stackTop; frame.savedCallOp = op; frame = calleeFrame; continue StateLoop; } } if (!(lhs instanceof Function)) { if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); throw ScriptRuntime.notFunctionError(lhs); } Function fun = (Function)lhs; if (fun instanceof IdFunctionObject) { IdFunctionObject ifun = (IdFunctionObject)fun; if (Continuation.isContinuationConstructor(ifun)) { captureContinuation(cx, frame, stackTop); continue Loop; } } Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 1, indexReg); stack[stackTop] = fun.construct(cx, frame.scope, outArgs); continue Loop; } case Token.TYPEOF : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.typeof(lhs); continue Loop; } case Icode_TYPEOFNAME : stack[++stackTop] = ScriptRuntime.typeofName(frame.scope, stringReg); continue Loop; case Token.STRING : stack[++stackTop] = stringReg; continue Loop; case Icode_SHORTNUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = getShort(iCode, frame.pc); frame.pc += 2; continue Loop; case Icode_INTNUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = getInt(iCode, frame.pc); frame.pc += 4; continue Loop; case Token.NUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = frame.idata.itsDoubleTable[indexReg]; continue Loop; case Token.NAME : stack[++stackTop] = ScriptRuntime.name(cx, frame.scope, stringReg); continue Loop; case Icode_NAME_INC_DEC : stack[++stackTop] = ScriptRuntime.nameIncrDecr(frame.scope, stringReg, cx, iCode[frame.pc]); ++frame.pc; continue Loop; case Icode_SETCONSTVAR1: indexReg = iCode[frame.pc++]; // fallthrough case Token.SETCONSTVAR : if (!frame.useActivation) { if ((varAttributes[indexReg] & ScriptableObject.READONLY) == 0) { throw Context.reportRuntimeError1("msg.var.redecl", frame.idata.argNames[indexReg]); } if ((varAttributes[indexReg] & ScriptableObject.UNINITIALIZED_CONST) != 0) { vars[indexReg] = stack[stackTop]; varAttributes[indexReg] &= ~ScriptableObject.UNINITIALIZED_CONST; varDbls[indexReg] = sDbl[stackTop]; } } else { Object val = stack[stackTop]; if (val == DBL_MRK) val = ScriptRuntime.wrapNumber(sDbl[stackTop]); stringReg = frame.idata.argNames[indexReg]; if (frame.scope instanceof ConstProperties) { ConstProperties cp = (ConstProperties)frame.scope; cp.putConst(stringReg, frame.scope, val); } else throw Kit.codeBug(); } continue Loop; case Icode_SETVAR1: indexReg = iCode[frame.pc++]; // fallthrough case Token.SETVAR : if (!frame.useActivation) { if ((varAttributes[indexReg] & ScriptableObject.READONLY) == 0) { vars[indexReg] = stack[stackTop]; varDbls[indexReg] = sDbl[stackTop]; } } else { Object val = stack[stackTop]; if (val == DBL_MRK) val = ScriptRuntime.wrapNumber(sDbl[stackTop]); stringReg = frame.idata.argNames[indexReg]; frame.scope.put(stringReg, frame.scope, val); } continue Loop; case Icode_GETVAR1: indexReg = iCode[frame.pc++]; // fallthrough case Token.GETVAR : ++stackTop; if (!frame.useActivation) { stack[stackTop] = vars[indexReg]; sDbl[stackTop] = varDbls[indexReg]; } else { stringReg = frame.idata.argNames[indexReg]; stack[stackTop] = frame.scope.get(stringReg, frame.scope); } continue Loop; case Icode_VAR_INC_DEC : { // indexReg : varindex ++stackTop; int incrDecrMask = iCode[frame.pc]; if (!frame.useActivation) { stack[stackTop] = DBL_MRK; Object varValue = vars[indexReg]; double d; if (varValue == DBL_MRK) { d = varDbls[indexReg]; } else { d = ScriptRuntime.toNumber(varValue); vars[indexReg] = DBL_MRK; } double d2 = ((incrDecrMask & Node.DECR_FLAG) == 0) ? d + 1.0 : d - 1.0; varDbls[indexReg] = d2; sDbl[stackTop] = ((incrDecrMask & Node.POST_FLAG) == 0) ? d2 : d; } else { String varName = frame.idata.argNames[indexReg]; stack[stackTop] = ScriptRuntime.nameIncrDecr(frame.scope, varName, cx, incrDecrMask); } ++frame.pc; continue Loop; } case Icode_ZERO : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = 0; continue Loop; case Icode_ONE : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = 1; continue Loop; case Token.NULL : stack[++stackTop] = null; continue Loop; case Token.THIS : stack[++stackTop] = frame.thisObj; continue Loop; case Token.THISFN : stack[++stackTop] = frame.fnOrScript; continue Loop; case Token.FALSE : stack[++stackTop] = Boolean.FALSE; continue Loop; case Token.TRUE : stack[++stackTop] = Boolean.TRUE; continue Loop; case Icode_UNDEF : stack[++stackTop] = undefined; continue Loop; case Token.ENTERWITH : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; frame.scope = ScriptRuntime.enterWith(lhs, cx, frame.scope); continue Loop; } case Token.LEAVEWITH : frame.scope = ScriptRuntime.leaveWith(frame.scope); continue Loop; case Token.CATCH_SCOPE : { // stack top: exception object // stringReg: name of exception variable // indexReg: local for exception scope --stackTop; indexReg += frame.localShift; boolean afterFirstScope = (frame.idata.itsICode[frame.pc] != 0); Throwable caughtException = (Throwable)stack[stackTop + 1]; Scriptable lastCatchScope; if (!afterFirstScope) { lastCatchScope = null; } else { lastCatchScope = (Scriptable)stack[indexReg]; } stack[indexReg] = ScriptRuntime.newCatchScope(caughtException, lastCatchScope, stringReg, cx, frame.scope); ++frame.pc; continue Loop; } case Token.ENUM_INIT_KEYS : case Token.ENUM_INIT_VALUES : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; indexReg += frame.localShift; stack[indexReg] = ScriptRuntime.enumInit( lhs, cx, (op == Token.ENUM_INIT_VALUES)); continue Loop; } case Token.ENUM_NEXT : case Token.ENUM_ID : { indexReg += frame.localShift; Object val = stack[indexReg]; ++stackTop; stack[stackTop] = (op == Token.ENUM_NEXT) ? (Object)ScriptRuntime.enumNext(val) : (Object)ScriptRuntime.enumId(val, cx); continue Loop; } case Token.REF_SPECIAL : { //stringReg: name of special property Object obj = stack[stackTop]; if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.specialRef(obj, stringReg, cx); continue Loop; } case Token.REF_MEMBER: { //indexReg: flags Object elem = stack[stackTop]; if (elem == DBL_MRK) elem = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object obj = stack[stackTop]; if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.memberRef(obj, elem, cx, indexReg); continue Loop; } case Token.REF_NS_MEMBER: { //indexReg: flags Object elem = stack[stackTop]; if (elem == DBL_MRK) elem = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object ns = stack[stackTop]; if (ns == DBL_MRK) ns = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object obj = stack[stackTop]; if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.memberRef(obj, ns, elem, cx, indexReg); continue Loop; } case Token.REF_NAME: { //indexReg: flags Object name = stack[stackTop]; if (name == DBL_MRK) name = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.nameRef(name, cx, frame.scope, indexReg); continue Loop; } case Token.REF_NS_NAME: { //indexReg: flags Object name = stack[stackTop]; if (name == DBL_MRK) name = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object ns = stack[stackTop]; if (ns == DBL_MRK) ns = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.nameRef(ns, name, cx, frame.scope, indexReg); continue Loop; } case Icode_SCOPE_LOAD : indexReg += frame.localShift; frame.scope = (Scriptable)stack[indexReg]; continue Loop; case Icode_SCOPE_SAVE : indexReg += frame.localShift; stack[indexReg] = frame.scope; continue Loop; case Icode_CLOSURE_EXPR : stack[++stackTop] = InterpretedFunction.createFunction(cx, frame.scope, frame.fnOrScript, indexReg); continue Loop; case Icode_CLOSURE_STMT : initFunction(cx, frame.scope, frame.fnOrScript, indexReg); continue Loop; case Token.REGEXP : stack[++stackTop] = frame.scriptRegExps[indexReg]; continue Loop; case Icode_LITERAL_NEW : // indexReg: number of values in the literal ++stackTop; stack[stackTop] = new int[indexReg]; ++stackTop; stack[stackTop] = new Object[indexReg]; sDbl[stackTop] = 0; continue Loop; case Icode_LITERAL_SET : { Object value = stack[stackTop]; if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; int i = (int)sDbl[stackTop]; ((Object[])stack[stackTop])[i] = value; sDbl[stackTop] = i + 1; continue Loop; } case Icode_LITERAL_GETTER : { Object value = stack[stackTop]; --stackTop; int i = (int)sDbl[stackTop]; ((Object[])stack[stackTop])[i] = value; ((int[])stack[stackTop - 1])[i] = -1; sDbl[stackTop] = i + 1; continue Loop; } case Icode_LITERAL_SETTER : { Object value = stack[stackTop]; --stackTop; int i = (int)sDbl[stackTop]; ((Object[])stack[stackTop])[i] = value; ((int[])stack[stackTop - 1])[i] = +1; sDbl[stackTop] = i + 1; continue Loop; } case Token.ARRAYLIT : case Icode_SPARE_ARRAYLIT : case Token.OBJECTLIT : { Object[] data = (Object[])stack[stackTop]; --stackTop; int[] getterSetters = (int[])stack[stackTop]; Object val; if (op == Token.OBJECTLIT) { Object[] ids = (Object[])frame.idata.literalIds[indexReg]; val = ScriptRuntime.newObjectLiteral(ids, data, getterSetters, cx, frame.scope); } else { int[] skipIndexces = null; if (op == Icode_SPARE_ARRAYLIT) { skipIndexces = (int[])frame.idata.literalIds[indexReg]; } val = ScriptRuntime.newArrayLiteral(data, skipIndexces, cx, frame.scope); } stack[stackTop] = val; continue Loop; } case Icode_ENTERDQ : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; frame.scope = ScriptRuntime.enterDotQuery(lhs, frame.scope); continue Loop; } case Icode_LEAVEDQ : { boolean valBln = stack_boolean(frame, stackTop); Object x = ScriptRuntime.updateDotQuery(valBln, frame.scope); if (x != null) { stack[stackTop] = x; frame.scope = ScriptRuntime.leaveDotQuery(frame.scope); frame.pc += 2; continue Loop; } // reset stack and PC to code after ENTERDQ --stackTop; break jumplessRun; } case Token.DEFAULTNAMESPACE : { Object value = stack[stackTop]; if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.setDefaultNamespace(value, cx); continue Loop; } case Token.ESCXMLATTR : { Object value = stack[stackTop]; if (value != DBL_MRK) { stack[stackTop] = "\"" + ScriptRuntime.escapeAttributeValue(value, cx) + "\""; } continue Loop; } case Token.ESCXMLTEXT : { Object value = stack[stackTop]; if (value != DBL_MRK) { stack[stackTop] = ScriptRuntime.escapeTextValue(value, cx); } continue Loop; } case Icode_DEBUGGER: if (frame.debuggerFrame != null) { frame.debuggerFrame.onDebuggerStatement(cx); } break Loop; case Icode_LINE : frame.pcSourceLineStart = frame.pc; if (frame.debuggerFrame != null) { int line = getIndex(iCode, frame.pc); frame.debuggerFrame.onLineChange(cx, line); } frame.pc += 2; continue Loop; case Icode_REG_IND_C0: indexReg = 0; continue Loop; case Icode_REG_IND_C1: indexReg = 1; continue Loop; case Icode_REG_IND_C2: indexReg = 2; continue Loop; case Icode_REG_IND_C3: indexReg = 3; continue Loop; case Icode_REG_IND_C4: indexReg = 4; continue Loop; case Icode_REG_IND_C5: indexReg = 5; continue Loop; case Icode_REG_IND1: indexReg = 0xFF & iCode[frame.pc]; ++frame.pc; continue Loop; case Icode_REG_IND2: indexReg = getIndex(iCode, frame.pc); frame.pc += 2; continue Loop; case Icode_REG_IND4: indexReg = getInt(iCode, frame.pc); frame.pc += 4; continue Loop; case Icode_REG_STR_C0: stringReg = strings[0]; continue Loop; case Icode_REG_STR_C1: stringReg = strings[1]; continue Loop; case Icode_REG_STR_C2: stringReg = strings[2]; continue Loop; case Icode_REG_STR_C3: stringReg = strings[3]; continue Loop; case Icode_REG_STR1: stringReg = strings[0xFF & iCode[frame.pc]]; ++frame.pc; continue Loop; case Icode_REG_STR2: stringReg = strings[getIndex(iCode, frame.pc)]; frame.pc += 2; continue Loop; case Icode_REG_STR4: stringReg = strings[getInt(iCode, frame.pc)]; frame.pc += 4; continue Loop; default : dumpICode(frame.idata); throw new RuntimeException( "Unknown icode : "+op+" @ pc : "+(frame.pc-1)); } // end of interpreter switch } // end of jumplessRun label block // This should be reachable only for jump implementation // when pc points to encoded target offset if (instructionCounting) { addInstructionCount(cx, frame, 2); } int offset = getShort(iCode, frame.pc); if (offset != 0) { // -1 accounts for pc pointing to jump opcode + 1 frame.pc += offset - 1; } else { frame.pc = frame.idata.longJumps. getExistingInt(frame.pc); } if (instructionCounting) { frame.pcPrevBranch = frame.pc; } continue Loop; } // end of Loop: for exitFrame(cx, frame, null); interpreterResult = frame.result; interpreterResultDbl = frame.resultDbl; if (frame.parentFrame != null) { frame = frame.parentFrame; if (frame.frozen) { frame = frame.cloneFrozen(); } setCallResult( frame, interpreterResult, interpreterResultDbl); interpreterResult = null; // Help GC continue StateLoop; } break StateLoop; } // end of interpreter withoutExceptions: try catch (Throwable ex) { if (throwable != null) { // This is serious bug and it is better to track it ASAP ex.printStackTrace(System.err); throw new IllegalStateException(); } throwable = ex; } // This should be reachable only after above catch or from // finally when it needs to propagate exception or from // explicit throw if (throwable == null) Kit.codeBug(); // Exception type final int EX_CATCH_STATE = 2; // Can execute JS catch final int EX_FINALLY_STATE = 1; // Can execute JS finally final int EX_NO_JS_STATE = 0; // Terminate JS execution int exState; ContinuationJump cjump = null; if (generatorState != null && generatorState.operation == NativeGenerator.GENERATOR_CLOSE && throwable == generatorState.value) { exState = EX_FINALLY_STATE; } else if (throwable instanceof JavaScriptException) { exState = EX_CATCH_STATE; } else if (throwable instanceof EcmaError) { // an offical ECMA error object, exState = EX_CATCH_STATE; } else if (throwable instanceof EvaluatorException) { exState = EX_CATCH_STATE; } else if (throwable instanceof RuntimeException) { exState = EX_FINALLY_STATE; } else if (throwable instanceof Error) { exState = EX_NO_JS_STATE; } else { // It must be ContinuationJump exState = EX_FINALLY_STATE; cjump = (ContinuationJump)throwable; } if (instructionCounting) { try { addInstructionCount(cx, frame, EXCEPTION_COST); } catch (RuntimeException ex) { throwable = ex; exState = EX_FINALLY_STATE; } catch (Error ex) { // Error from instruction counting // => unconditionally terminate JS throwable = ex; cjump = null; exState = EX_NO_JS_STATE; } } if (frame.debuggerFrame != null && throwable instanceof RuntimeException) { // Call debugger only for RuntimeException RuntimeException rex = (RuntimeException)throwable; try { frame.debuggerFrame.onExceptionThrown(cx, rex); } catch (Throwable ex) { // Any exception from debugger // => unconditionally terminate JS throwable = ex; cjump = null; exState = EX_NO_JS_STATE; } } for (;;) { if (exState != EX_NO_JS_STATE) { boolean onlyFinally = (exState != EX_CATCH_STATE); indexReg = getExceptionHandler(frame, onlyFinally); if (indexReg >= 0) { // We caught an exception, restart the loop // with exception pending the processing at the loop // start continue StateLoop; } } // No allowed exception handlers in this frame, unwind // to parent and try to look there exitFrame(cx, frame, throwable); frame = frame.parentFrame; if (frame == null) { break; } if (cjump != null && cjump.branchFrame == frame) { // Continuation branch point was hit, // restart the state loop to reenter continuation indexReg = -1; continue StateLoop; } } // No more frames, rethrow the exception or deal with continuation if (cjump != null) { if (cjump.branchFrame != null) { // The above loop should locate the top frame Kit.codeBug(); } if (cjump.capturedFrame != null) { // Restarting detached continuation indexReg = -1; continue StateLoop; } // Return continuation result to the caller interpreterResult = cjump.result; interpreterResultDbl = cjump.resultDbl; throwable = null; } break StateLoop; } // end of StateLoop: for(;;) // Do cleanups/restorations before the final return or throw if (cx.previousInterpreterInvocations != null && cx.previousInterpreterInvocations.size() != 0) { cx.lastInterpreterFrame = cx.previousInterpreterInvocations.pop(); } else { // It was the last interpreter frame on the stack cx.lastInterpreterFrame = null; // Force GC of the value cx.previousInterpreterInvocations cx.previousInterpreterInvocations = null; } if (throwable != null) { if (throwable instanceof RuntimeException) { throw (RuntimeException)throwable; } else { // Must be instance of Error or code bug throw (Error)throwable; } } return (interpreterResult != DBL_MRK) ? interpreterResult : ScriptRuntime.wrapNumber(interpreterResultDbl); }
private static Object interpretLoop(Context cx, CallFrame frame, Object throwable) { // throwable holds exception object to rethrow or catch // It is also used for continuation restart in which case // it holds ContinuationJump final Object DBL_MRK = UniqueTag.DOUBLE_MARK; final Object undefined = Undefined.instance; final boolean instructionCounting = (cx.instructionThreshold != 0); // arbitrary number to add to instructionCount when calling // other functions final int INVOCATION_COST = 100; // arbitrary exception cost for instruction counting final int EXCEPTION_COST = 100; String stringReg = null; int indexReg = -1; if (cx.lastInterpreterFrame != null) { // save the top frame from the previous interpreterLoop // invocation on the stack if (cx.previousInterpreterInvocations == null) { cx.previousInterpreterInvocations = new ObjArray(); } cx.previousInterpreterInvocations.push(cx.lastInterpreterFrame); } // When restarting continuation throwable is not null and to jump // to the code that rewind continuation state indexReg should be set // to -1. // With the normal call throable == null and indexReg == -1 allows to // catch bugs with using indeReg to access array eleemnts before // initializing indexReg. GeneratorState generatorState = null; if (throwable != null) { if (throwable instanceof GeneratorState) { generatorState = (GeneratorState) throwable; // reestablish this call frame enterFrame(cx, frame, ScriptRuntime.emptyArgs, true); throwable = null; } else if (!(throwable instanceof ContinuationJump)) { // It should be continuation Kit.codeBug(); } } Object interpreterResult = null; double interpreterResultDbl = 0.0; StateLoop: for (;;) { withoutExceptions: try { if (throwable != null) { // Recovering from exception, indexReg contains // the index of handler if (indexReg >= 0) { // Normal exception handler, transfer // control appropriately if (frame.frozen) { // XXX Deal with exceptios!!! frame = frame.cloneFrozen(); } int[] table = frame.idata.itsExceptionTable; frame.pc = table[indexReg + EXCEPTION_HANDLER_SLOT]; if (instructionCounting) { frame.pcPrevBranch = frame.pc; } frame.savedStackTop = frame.emptyStackTop; int scopeLocal = frame.localShift + table[indexReg + EXCEPTION_SCOPE_SLOT]; int exLocal = frame.localShift + table[indexReg + EXCEPTION_LOCAL_SLOT]; frame.scope = (Scriptable)frame.stack[scopeLocal]; frame.stack[exLocal] = throwable; throwable = null; } else { // Continuation restoration ContinuationJump cjump = (ContinuationJump)throwable; // Clear throwable to indicate that exceptions are OK throwable = null; if (cjump.branchFrame != frame) Kit.codeBug(); // Check that we have at least one frozen frame // in the case of detached continuation restoration: // unwind code ensure that if (cjump.capturedFrame == null) Kit.codeBug(); // Need to rewind branchFrame, capturedFrame // and all frames in between int rewindCount = cjump.capturedFrame.frameIndex + 1; if (cjump.branchFrame != null) { rewindCount -= cjump.branchFrame.frameIndex; } int enterCount = 0; CallFrame[] enterFrames = null; CallFrame x = cjump.capturedFrame; for (int i = 0; i != rewindCount; ++i) { if (!x.frozen) Kit.codeBug(); if (isFrameEnterExitRequired(x)) { if (enterFrames == null) { // Allocate enough space to store the rest // of rewind frames in case all of them // would require to enter enterFrames = new CallFrame[rewindCount - i]; } enterFrames[enterCount] = x; ++enterCount; } x = x.parentFrame; } while (enterCount != 0) { // execute enter: walk enterFrames in the reverse // order since they were stored starting from // the capturedFrame, not branchFrame --enterCount; x = enterFrames[enterCount]; enterFrame(cx, x, ScriptRuntime.emptyArgs, true); } // Continuation jump is almost done: capturedFrame // points to the call to the function that captured // continuation, so clone capturedFrame and // emulate return that function with the suplied result frame = cjump.capturedFrame.cloneFrozen(); setCallResult(frame, cjump.result, cjump.resultDbl); // restart the execution } } else { if (generatorState == null && frame.frozen) Kit.codeBug(); } // Use local variables for constant values in frame // for faster access Object[] stack = frame.stack; double[] sDbl = frame.sDbl; Object[] vars = frame.varSource.stack; double[] varDbls = frame.varSource.sDbl; int[] varAttributes = frame.varSource.stackAttributes; byte[] iCode = frame.idata.itsICode; String[] strings = frame.idata.itsStringTable; // Use local for stackTop as well. Since execption handlers // can only exist at statement level where stack is empty, // it is necessary to save/restore stackTop only across // function calls and normal returns. int stackTop = frame.savedStackTop; // Store new frame in cx which is used for error reporting etc. cx.lastInterpreterFrame = frame; Loop: for (;;) { // Exception handler assumes that PC is already incremented // pass the instruction start when it searches the // exception handler int op = iCode[frame.pc++]; jumplessRun: { // Back indent to ease implementation reading switch (op) { case Icode_GENERATOR: { if (!frame.frozen) { // First time encountering this opcode: create new generator // object and return frame.pc--; // we want to come back here when we resume CallFrame generatorFrame = captureFrameForGenerator(frame); generatorFrame.frozen = true; NativeGenerator generator = new NativeGenerator(frame.scope, generatorFrame.fnOrScript, generatorFrame); frame.result = generator; break Loop; } else { // We are now resuming execution. Fall through to YIELD case. } } // fall through... case Token.YIELD: { if (!frame.frozen) { if (generatorState.operation == NativeGenerator.GENERATOR_CLOSE) { // Error: no yields when generator is closing throw ScriptRuntime.typeError0("msg.yield.closing"); } // return to our caller (which should be a method of NativeGenerator) frame.frozen = true; frame.result = stack[stackTop]; frame.resultDbl = sDbl[stackTop]; frame.savedStackTop = stackTop; frame.pc--; // we want to come back here when we resume ScriptRuntime.exitActivationFunction(cx); return (frame.result != DBL_MRK) ? frame.result : ScriptRuntime.wrapNumber(frame.resultDbl); } else { // we are resuming execution frame.frozen = false; int sourceLine = getIndex(iCode, frame.pc); frame.pc += 2; // skip line number data if (generatorState.operation == NativeGenerator.GENERATOR_THROW) { // processing a call to <generator>.throw(exception): must // act as if exception was thrown from resumption point throwable = new JavaScriptException(generatorState.value, frame.idata.itsSourceFile, sourceLine); break withoutExceptions; } if (generatorState.operation == NativeGenerator.GENERATOR_CLOSE) { throwable = generatorState.value; break withoutExceptions; } if (generatorState.operation != NativeGenerator.GENERATOR_SEND) throw Kit.codeBug(); if (op == Token.YIELD) stack[stackTop] = generatorState.value; continue Loop; } } case Icode_GENERATOR_END: { // throw StopIteration frame.frozen = true; Scriptable top = ScriptableObject.getTopLevelScope(frame.scope); Object e = top.get(NativeIterator.STOP_ITERATION, frame.scope); int sourceLine = getIndex(iCode, frame.pc); generatorState.returnedException = new JavaScriptException(e, frame.idata.itsSourceFile, sourceLine); break Loop; } case Token.THROW: { Object value = stack[stackTop]; if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; int sourceLine = getIndex(iCode, frame.pc); throwable = new JavaScriptException(value, frame.idata.itsSourceFile, sourceLine); break withoutExceptions; } case Token.RETHROW: { indexReg += frame.localShift; throwable = stack[indexReg]; break withoutExceptions; } case Token.GE : case Token.LE : case Token.GT : case Token.LT : { --stackTop; Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; boolean valBln; object_compare: { number_compare: { double rDbl, lDbl; if (rhs == DBL_MRK) { rDbl = sDbl[stackTop + 1]; lDbl = stack_double(frame, stackTop); } else if (lhs == DBL_MRK) { rDbl = ScriptRuntime.toNumber(rhs); lDbl = sDbl[stackTop]; } else { break number_compare; } switch (op) { case Token.GE: valBln = (lDbl >= rDbl); break object_compare; case Token.LE: valBln = (lDbl <= rDbl); break object_compare; case Token.GT: valBln = (lDbl > rDbl); break object_compare; case Token.LT: valBln = (lDbl < rDbl); break object_compare; default: throw Kit.codeBug(); } } switch (op) { case Token.GE: valBln = ScriptRuntime.cmp_LE(rhs, lhs); break; case Token.LE: valBln = ScriptRuntime.cmp_LE(lhs, rhs); break; case Token.GT: valBln = ScriptRuntime.cmp_LT(rhs, lhs); break; case Token.LT: valBln = ScriptRuntime.cmp_LT(lhs, rhs); break; default: throw Kit.codeBug(); } } stack[stackTop] = ScriptRuntime.wrapBoolean(valBln); continue Loop; } case Token.IN : case Token.INSTANCEOF : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); boolean valBln; if (op == Token.IN) { valBln = ScriptRuntime.in(lhs, rhs, cx); } else { valBln = ScriptRuntime.instanceOf(lhs, rhs, cx); } stack[stackTop] = ScriptRuntime.wrapBoolean(valBln); continue Loop; } case Token.EQ : case Token.NE : { --stackTop; boolean valBln; Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; if (rhs == DBL_MRK) { if (lhs == DBL_MRK) { valBln = (sDbl[stackTop] == sDbl[stackTop + 1]); } else { valBln = ScriptRuntime.eqNumber(sDbl[stackTop + 1], lhs); } } else { if (lhs == DBL_MRK) { valBln = ScriptRuntime.eqNumber(sDbl[stackTop], rhs); } else { valBln = ScriptRuntime.eq(lhs, rhs); } } valBln ^= (op == Token.NE); stack[stackTop] = ScriptRuntime.wrapBoolean(valBln); continue Loop; } case Token.SHEQ : case Token.SHNE : { --stackTop; Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; boolean valBln; shallow_compare: { double rdbl, ldbl; if (rhs == DBL_MRK) { rdbl = sDbl[stackTop + 1]; if (lhs == DBL_MRK) { ldbl = sDbl[stackTop]; } else if (lhs instanceof Number) { ldbl = ((Number)lhs).doubleValue(); } else { valBln = false; break shallow_compare; } } else if (lhs == DBL_MRK) { ldbl = sDbl[stackTop]; if (rhs == DBL_MRK) { rdbl = sDbl[stackTop + 1]; } else if (rhs instanceof Number) { rdbl = ((Number)rhs).doubleValue(); } else { valBln = false; break shallow_compare; } } else { valBln = ScriptRuntime.shallowEq(lhs, rhs); break shallow_compare; } valBln = (ldbl == rdbl); } valBln ^= (op == Token.SHNE); stack[stackTop] = ScriptRuntime.wrapBoolean(valBln); continue Loop; } case Token.IFNE : if (stack_boolean(frame, stackTop--)) { frame.pc += 2; continue Loop; } break jumplessRun; case Token.IFEQ : if (!stack_boolean(frame, stackTop--)) { frame.pc += 2; continue Loop; } break jumplessRun; case Icode_IFEQ_POP : if (!stack_boolean(frame, stackTop--)) { frame.pc += 2; continue Loop; } stack[stackTop--] = null; break jumplessRun; case Token.GOTO : break jumplessRun; case Icode_GOSUB : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = frame.pc + 2; break jumplessRun; case Icode_STARTSUB : if (stackTop == frame.emptyStackTop + 1) { // Call from Icode_GOSUB: store return PC address in the local indexReg += frame.localShift; stack[indexReg] = stack[stackTop]; sDbl[indexReg] = sDbl[stackTop]; --stackTop; } else { // Call from exception handler: exception object is already stored // in the local if (stackTop != frame.emptyStackTop) Kit.codeBug(); } continue Loop; case Icode_RETSUB : { // indexReg: local to store return address if (instructionCounting) { addInstructionCount(cx, frame, 0); } indexReg += frame.localShift; Object value = stack[indexReg]; if (value != DBL_MRK) { // Invocation from exception handler, restore object to rethrow throwable = value; break withoutExceptions; } // Normal return from GOSUB frame.pc = (int)sDbl[indexReg]; if (instructionCounting) { frame.pcPrevBranch = frame.pc; } continue Loop; } case Icode_POP : stack[stackTop] = null; stackTop--; continue Loop; case Icode_POP_RESULT : frame.result = stack[stackTop]; frame.resultDbl = sDbl[stackTop]; stack[stackTop] = null; --stackTop; continue Loop; case Icode_DUP : stack[stackTop + 1] = stack[stackTop]; sDbl[stackTop + 1] = sDbl[stackTop]; stackTop++; continue Loop; case Icode_DUP2 : stack[stackTop + 1] = stack[stackTop - 1]; sDbl[stackTop + 1] = sDbl[stackTop - 1]; stack[stackTop + 2] = stack[stackTop]; sDbl[stackTop + 2] = sDbl[stackTop]; stackTop += 2; continue Loop; case Icode_SWAP : { Object o = stack[stackTop]; stack[stackTop] = stack[stackTop - 1]; stack[stackTop - 1] = o; double d = sDbl[stackTop]; sDbl[stackTop] = sDbl[stackTop - 1]; sDbl[stackTop - 1] = d; continue Loop; } case Token.RETURN : frame.result = stack[stackTop]; frame.resultDbl = sDbl[stackTop]; --stackTop; break Loop; case Token.RETURN_RESULT : break Loop; case Icode_RETUNDEF : frame.result = undefined; break Loop; case Token.BITNOT : { int rIntValue = stack_int32(frame, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = ~rIntValue; continue Loop; } case Token.BITAND : case Token.BITOR : case Token.BITXOR : case Token.LSH : case Token.RSH : { int rIntValue = stack_int32(frame, stackTop); --stackTop; int lIntValue = stack_int32(frame, stackTop); stack[stackTop] = DBL_MRK; switch (op) { case Token.BITAND: lIntValue &= rIntValue; break; case Token.BITOR: lIntValue |= rIntValue; break; case Token.BITXOR: lIntValue ^= rIntValue; break; case Token.LSH: lIntValue <<= rIntValue; break; case Token.RSH: lIntValue >>= rIntValue; break; } sDbl[stackTop] = lIntValue; continue Loop; } case Token.URSH : { int rIntValue = stack_int32(frame, stackTop) & 0x1F; --stackTop; double lDbl = stack_double(frame, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = ScriptRuntime.toUint32(lDbl) >>> rIntValue; continue Loop; } case Token.NEG : case Token.POS : { double rDbl = stack_double(frame, stackTop); stack[stackTop] = DBL_MRK; if (op == Token.NEG) { rDbl = -rDbl; } sDbl[stackTop] = rDbl; continue Loop; } case Token.ADD : --stackTop; do_add(stack, sDbl, stackTop, cx); continue Loop; case Token.SUB : case Token.MUL : case Token.DIV : case Token.MOD : { double rDbl = stack_double(frame, stackTop); --stackTop; double lDbl = stack_double(frame, stackTop); stack[stackTop] = DBL_MRK; switch (op) { case Token.SUB: lDbl -= rDbl; break; case Token.MUL: lDbl *= rDbl; break; case Token.DIV: lDbl /= rDbl; break; case Token.MOD: lDbl %= rDbl; break; } sDbl[stackTop] = lDbl; continue Loop; } case Token.NOT : stack[stackTop] = ScriptRuntime.wrapBoolean( !stack_boolean(frame, stackTop)); continue Loop; case Token.BINDNAME : stack[++stackTop] = ScriptRuntime.bind(cx, frame.scope, stringReg); continue Loop; case Token.SETNAME : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Scriptable lhs = (Scriptable)stack[stackTop]; stack[stackTop] = ScriptRuntime.setName(lhs, rhs, cx, frame.scope, stringReg); continue Loop; } case Icode_SETCONST: { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Scriptable lhs = (Scriptable)stack[stackTop]; stack[stackTop] = ScriptRuntime.setConst(lhs, rhs, cx, stringReg); continue Loop; } case Token.DELPROP : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.delete(lhs, rhs, cx); continue Loop; } case Token.GETPROP : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getObjectProp(lhs, stringReg, cx); continue Loop; } case Token.SETPROP : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.setObjectProp(lhs, stringReg, rhs, cx); continue Loop; } case Icode_PROP_INC_DEC : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.propIncrDecr(lhs, stringReg, cx, iCode[frame.pc]); ++frame.pc; continue Loop; } case Token.GETELEM : { --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) { lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); } Object value; Object id = stack[stackTop + 1]; if (id != DBL_MRK) { value = ScriptRuntime.getObjectElem(lhs, id, cx); } else { double d = sDbl[stackTop + 1]; value = ScriptRuntime.getObjectIndex(lhs, d, cx); } stack[stackTop] = value; continue Loop; } case Token.SETELEM : { stackTop -= 2; Object rhs = stack[stackTop + 2]; if (rhs == DBL_MRK) { rhs = ScriptRuntime.wrapNumber(sDbl[stackTop + 2]); } Object lhs = stack[stackTop]; if (lhs == DBL_MRK) { lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); } Object value; Object id = stack[stackTop + 1]; if (id != DBL_MRK) { value = ScriptRuntime.setObjectElem(lhs, id, rhs, cx); } else { double d = sDbl[stackTop + 1]; value = ScriptRuntime.setObjectIndex(lhs, d, rhs, cx); } stack[stackTop] = value; continue Loop; } case Icode_ELEM_INC_DEC: { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.elemIncrDecr(lhs, rhs, cx, iCode[frame.pc]); ++frame.pc; continue Loop; } case Token.GET_REF : { Ref ref = (Ref)stack[stackTop]; stack[stackTop] = ScriptRuntime.refGet(ref, cx); continue Loop; } case Token.SET_REF : { Object value = stack[stackTop]; if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Ref ref = (Ref)stack[stackTop]; stack[stackTop] = ScriptRuntime.refSet(ref, value, cx); continue Loop; } case Token.DEL_REF : { Ref ref = (Ref)stack[stackTop]; stack[stackTop] = ScriptRuntime.refDel(ref, cx); continue Loop; } case Icode_REF_INC_DEC : { Ref ref = (Ref)stack[stackTop]; stack[stackTop] = ScriptRuntime.refIncrDecr(ref, cx, iCode[frame.pc]); ++frame.pc; continue Loop; } case Token.LOCAL_LOAD : ++stackTop; indexReg += frame.localShift; stack[stackTop] = stack[indexReg]; sDbl[stackTop] = sDbl[indexReg]; continue Loop; case Icode_LOCAL_CLEAR : indexReg += frame.localShift; stack[indexReg] = null; continue Loop; case Icode_NAME_AND_THIS : // stringReg: name ++stackTop; stack[stackTop] = ScriptRuntime.getNameFunctionAndThis(stringReg, cx, frame.scope); ++stackTop; stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx); continue Loop; case Icode_PROP_AND_THIS: { Object obj = stack[stackTop]; if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]); // stringReg: property stack[stackTop] = ScriptRuntime.getPropFunctionAndThis(obj, stringReg, cx); ++stackTop; stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx); continue Loop; } case Icode_ELEM_AND_THIS: { Object obj = stack[stackTop - 1]; if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop - 1]); Object id = stack[stackTop]; if (id == DBL_MRK) id = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop - 1] = ScriptRuntime.getElemFunctionAndThis(obj, id, cx); stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx); continue Loop; } case Icode_VALUE_AND_THIS : { Object value = stack[stackTop]; if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getValueFunctionAndThis(value, cx); ++stackTop; stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx); continue Loop; } case Icode_CALLSPECIAL : { if (instructionCounting) { cx.instructionCount += INVOCATION_COST; } int callType = iCode[frame.pc] & 0xFF; boolean isNew = (iCode[frame.pc + 1] != 0); int sourceLine = getIndex(iCode, frame.pc + 2); // indexReg: number of arguments if (isNew) { // stack change: function arg0 .. argN -> newResult stackTop -= indexReg; Object function = stack[stackTop]; if (function == DBL_MRK) function = ScriptRuntime.wrapNumber(sDbl[stackTop]); Object[] outArgs = getArgsArray( stack, sDbl, stackTop + 1, indexReg); stack[stackTop] = ScriptRuntime.newSpecial( cx, function, outArgs, frame.scope, callType); } else { // stack change: function thisObj arg0 .. argN -> result stackTop -= 1 + indexReg; // Call code generation ensure that stack here // is ... Callable Scriptable Scriptable functionThis = (Scriptable)stack[stackTop + 1]; Callable function = (Callable)stack[stackTop]; Object[] outArgs = getArgsArray( stack, sDbl, stackTop + 2, indexReg); stack[stackTop] = ScriptRuntime.callSpecial( cx, function, functionThis, outArgs, frame.scope, frame.thisObj, callType, frame.idata.itsSourceFile, sourceLine); } frame.pc += 4; continue Loop; } case Token.CALL : case Icode_TAIL_CALL : case Token.REF_CALL : { if (instructionCounting) { cx.instructionCount += INVOCATION_COST; } // stack change: function thisObj arg0 .. argN -> result // indexReg: number of arguments stackTop -= 1 + indexReg; // CALL generation ensures that fun and funThisObj // are already Scriptable and Callable objects respectively Callable fun = (Callable)stack[stackTop]; Scriptable funThisObj = (Scriptable)stack[stackTop + 1]; if (op == Token.REF_CALL) { Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 2, indexReg); stack[stackTop] = ScriptRuntime.callRef(fun, funThisObj, outArgs, cx); continue Loop; } Scriptable calleeScope = frame.scope; if (frame.useActivation) { calleeScope = ScriptableObject.getTopLevelScope(frame.scope); } if (fun instanceof InterpretedFunction) { InterpretedFunction ifun = (InterpretedFunction)fun; if (frame.fnOrScript.securityDomain == ifun.securityDomain) { CallFrame callParentFrame = frame; CallFrame calleeFrame = new CallFrame(); if (op == Icode_TAIL_CALL) { // In principle tail call can re-use the current // frame and its stack arrays but it is hard to // do properly. Any exceptions that can legally // happen during frame re-initialization including // StackOverflowException during innocent looking // System.arraycopy may leave the current frame // data corrupted leading to undefined behaviour // in the catch code bellow that unwinds JS stack // on exceptions. Then there is issue about frame release // end exceptions there. // To avoid frame allocation a released frame // can be cached for re-use which would also benefit // non-tail calls but it is not clear that this caching // would gain in performance due to potentially // bad iteraction with GC. callParentFrame = frame.parentFrame; // Release the current frame. See Bug #344501 to see why // it is being done here. // TODO: If using the graphical debugger, tail call // optimization will create a "hole" in the context stack. // The correct thing to do may be to disable tail call // optimization if the code is being debugged. exitFrame(cx, frame, null); } initFrame(cx, calleeScope, funThisObj, stack, sDbl, stackTop + 2, indexReg, ifun, callParentFrame, calleeFrame); if (op != Icode_TAIL_CALL) { frame.savedStackTop = stackTop; frame.savedCallOp = op; } frame = calleeFrame; continue StateLoop; } } if (fun instanceof Continuation) { // Jump to the captured continuation ContinuationJump cjump; cjump = new ContinuationJump((Continuation)fun, frame); // continuation result is the first argument if any // of contination call if (indexReg == 0) { cjump.result = undefined; } else { cjump.result = stack[stackTop + 2]; cjump.resultDbl = sDbl[stackTop + 2]; } // Start the real unwind job throwable = cjump; break withoutExceptions; } if (fun instanceof IdFunctionObject) { IdFunctionObject ifun = (IdFunctionObject)fun; if (Continuation.isContinuationConstructor(ifun)) { captureContinuation(cx, frame, stackTop); continue Loop; } } Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 2, indexReg); stack[stackTop] = fun.call(cx, calleeScope, funThisObj, outArgs); continue Loop; } case Token.NEW : { if (instructionCounting) { cx.instructionCount += INVOCATION_COST; } // stack change: function arg0 .. argN -> newResult // indexReg: number of arguments stackTop -= indexReg; Object lhs = stack[stackTop]; if (lhs instanceof InterpretedFunction) { InterpretedFunction f = (InterpretedFunction)lhs; if (frame.fnOrScript.securityDomain == f.securityDomain) { Scriptable newInstance = f.createObject(cx, frame.scope); CallFrame calleeFrame = new CallFrame(); initFrame(cx, frame.scope, newInstance, stack, sDbl, stackTop + 1, indexReg, f, frame, calleeFrame); stack[stackTop] = newInstance; frame.savedStackTop = stackTop; frame.savedCallOp = op; frame = calleeFrame; continue StateLoop; } } if (!(lhs instanceof Function)) { if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); throw ScriptRuntime.notFunctionError(lhs); } Function fun = (Function)lhs; if (fun instanceof IdFunctionObject) { IdFunctionObject ifun = (IdFunctionObject)fun; if (Continuation.isContinuationConstructor(ifun)) { captureContinuation(cx, frame, stackTop); continue Loop; } } Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 1, indexReg); stack[stackTop] = fun.construct(cx, frame.scope, outArgs); continue Loop; } case Token.TYPEOF : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.typeof(lhs); continue Loop; } case Icode_TYPEOFNAME : stack[++stackTop] = ScriptRuntime.typeofName(frame.scope, stringReg); continue Loop; case Token.STRING : stack[++stackTop] = stringReg; continue Loop; case Icode_SHORTNUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = getShort(iCode, frame.pc); frame.pc += 2; continue Loop; case Icode_INTNUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = getInt(iCode, frame.pc); frame.pc += 4; continue Loop; case Token.NUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = frame.idata.itsDoubleTable[indexReg]; continue Loop; case Token.NAME : stack[++stackTop] = ScriptRuntime.name(cx, frame.scope, stringReg); continue Loop; case Icode_NAME_INC_DEC : stack[++stackTop] = ScriptRuntime.nameIncrDecr(frame.scope, stringReg, cx, iCode[frame.pc]); ++frame.pc; continue Loop; case Icode_SETCONSTVAR1: indexReg = iCode[frame.pc++]; // fallthrough case Token.SETCONSTVAR : if (!frame.useActivation) { if ((varAttributes[indexReg] & ScriptableObject.READONLY) == 0) { throw Context.reportRuntimeError1("msg.var.redecl", frame.idata.argNames[indexReg]); } if ((varAttributes[indexReg] & ScriptableObject.UNINITIALIZED_CONST) != 0) { vars[indexReg] = stack[stackTop]; varAttributes[indexReg] &= ~ScriptableObject.UNINITIALIZED_CONST; varDbls[indexReg] = sDbl[stackTop]; } } else { Object val = stack[stackTop]; if (val == DBL_MRK) val = ScriptRuntime.wrapNumber(sDbl[stackTop]); stringReg = frame.idata.argNames[indexReg]; if (frame.scope instanceof ConstProperties) { ConstProperties cp = (ConstProperties)frame.scope; cp.putConst(stringReg, frame.scope, val); } else throw Kit.codeBug(); } continue Loop; case Icode_SETVAR1: indexReg = iCode[frame.pc++]; // fallthrough case Token.SETVAR : if (!frame.useActivation) { if ((varAttributes[indexReg] & ScriptableObject.READONLY) == 0) { vars[indexReg] = stack[stackTop]; varDbls[indexReg] = sDbl[stackTop]; } } else { Object val = stack[stackTop]; if (val == DBL_MRK) val = ScriptRuntime.wrapNumber(sDbl[stackTop]); stringReg = frame.idata.argNames[indexReg]; frame.scope.put(stringReg, frame.scope, val); } continue Loop; case Icode_GETVAR1: indexReg = iCode[frame.pc++]; // fallthrough case Token.GETVAR : ++stackTop; if (!frame.useActivation) { stack[stackTop] = vars[indexReg]; sDbl[stackTop] = varDbls[indexReg]; } else { stringReg = frame.idata.argNames[indexReg]; stack[stackTop] = frame.scope.get(stringReg, frame.scope); } continue Loop; case Icode_VAR_INC_DEC : { // indexReg : varindex ++stackTop; int incrDecrMask = iCode[frame.pc]; if (!frame.useActivation) { stack[stackTop] = DBL_MRK; Object varValue = vars[indexReg]; double d; if (varValue == DBL_MRK) { d = varDbls[indexReg]; } else { d = ScriptRuntime.toNumber(varValue); vars[indexReg] = DBL_MRK; } double d2 = ((incrDecrMask & Node.DECR_FLAG) == 0) ? d + 1.0 : d - 1.0; varDbls[indexReg] = d2; sDbl[stackTop] = ((incrDecrMask & Node.POST_FLAG) == 0) ? d2 : d; } else { String varName = frame.idata.argNames[indexReg]; stack[stackTop] = ScriptRuntime.nameIncrDecr(frame.scope, varName, cx, incrDecrMask); } ++frame.pc; continue Loop; } case Icode_ZERO : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = 0; continue Loop; case Icode_ONE : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = 1; continue Loop; case Token.NULL : stack[++stackTop] = null; continue Loop; case Token.THIS : stack[++stackTop] = frame.thisObj; continue Loop; case Token.THISFN : stack[++stackTop] = frame.fnOrScript; continue Loop; case Token.FALSE : stack[++stackTop] = Boolean.FALSE; continue Loop; case Token.TRUE : stack[++stackTop] = Boolean.TRUE; continue Loop; case Icode_UNDEF : stack[++stackTop] = undefined; continue Loop; case Token.ENTERWITH : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; frame.scope = ScriptRuntime.enterWith(lhs, cx, frame.scope); continue Loop; } case Token.LEAVEWITH : frame.scope = ScriptRuntime.leaveWith(frame.scope); continue Loop; case Token.CATCH_SCOPE : { // stack top: exception object // stringReg: name of exception variable // indexReg: local for exception scope --stackTop; indexReg += frame.localShift; boolean afterFirstScope = (frame.idata.itsICode[frame.pc] != 0); Throwable caughtException = (Throwable)stack[stackTop + 1]; Scriptable lastCatchScope; if (!afterFirstScope) { lastCatchScope = null; } else { lastCatchScope = (Scriptable)stack[indexReg]; } stack[indexReg] = ScriptRuntime.newCatchScope(caughtException, lastCatchScope, stringReg, cx, frame.scope); ++frame.pc; continue Loop; } case Token.ENUM_INIT_KEYS : case Token.ENUM_INIT_VALUES : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; indexReg += frame.localShift; stack[indexReg] = ScriptRuntime.enumInit( lhs, cx, (op == Token.ENUM_INIT_VALUES)); continue Loop; } case Token.ENUM_NEXT : case Token.ENUM_ID : { indexReg += frame.localShift; Object val = stack[indexReg]; ++stackTop; stack[stackTop] = (op == Token.ENUM_NEXT) ? (Object)ScriptRuntime.enumNext(val) : (Object)ScriptRuntime.enumId(val, cx); continue Loop; } case Token.REF_SPECIAL : { //stringReg: name of special property Object obj = stack[stackTop]; if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.specialRef(obj, stringReg, cx); continue Loop; } case Token.REF_MEMBER: { //indexReg: flags Object elem = stack[stackTop]; if (elem == DBL_MRK) elem = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object obj = stack[stackTop]; if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.memberRef(obj, elem, cx, indexReg); continue Loop; } case Token.REF_NS_MEMBER: { //indexReg: flags Object elem = stack[stackTop]; if (elem == DBL_MRK) elem = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object ns = stack[stackTop]; if (ns == DBL_MRK) ns = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object obj = stack[stackTop]; if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.memberRef(obj, ns, elem, cx, indexReg); continue Loop; } case Token.REF_NAME: { //indexReg: flags Object name = stack[stackTop]; if (name == DBL_MRK) name = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.nameRef(name, cx, frame.scope, indexReg); continue Loop; } case Token.REF_NS_NAME: { //indexReg: flags Object name = stack[stackTop]; if (name == DBL_MRK) name = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object ns = stack[stackTop]; if (ns == DBL_MRK) ns = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.nameRef(ns, name, cx, frame.scope, indexReg); continue Loop; } case Icode_SCOPE_LOAD : indexReg += frame.localShift; frame.scope = (Scriptable)stack[indexReg]; continue Loop; case Icode_SCOPE_SAVE : indexReg += frame.localShift; stack[indexReg] = frame.scope; continue Loop; case Icode_CLOSURE_EXPR : stack[++stackTop] = InterpretedFunction.createFunction(cx, frame.scope, frame.fnOrScript, indexReg); continue Loop; case Icode_CLOSURE_STMT : initFunction(cx, frame.scope, frame.fnOrScript, indexReg); continue Loop; case Token.REGEXP : stack[++stackTop] = frame.scriptRegExps[indexReg]; continue Loop; case Icode_LITERAL_NEW : // indexReg: number of values in the literal ++stackTop; stack[stackTop] = new int[indexReg]; ++stackTop; stack[stackTop] = new Object[indexReg]; sDbl[stackTop] = 0; continue Loop; case Icode_LITERAL_SET : { Object value = stack[stackTop]; if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; int i = (int)sDbl[stackTop]; ((Object[])stack[stackTop])[i] = value; sDbl[stackTop] = i + 1; continue Loop; } case Icode_LITERAL_GETTER : { Object value = stack[stackTop]; --stackTop; int i = (int)sDbl[stackTop]; ((Object[])stack[stackTop])[i] = value; ((int[])stack[stackTop - 1])[i] = -1; sDbl[stackTop] = i + 1; continue Loop; } case Icode_LITERAL_SETTER : { Object value = stack[stackTop]; --stackTop; int i = (int)sDbl[stackTop]; ((Object[])stack[stackTop])[i] = value; ((int[])stack[stackTop - 1])[i] = +1; sDbl[stackTop] = i + 1; continue Loop; } case Token.ARRAYLIT : case Icode_SPARE_ARRAYLIT : case Token.OBJECTLIT : { Object[] data = (Object[])stack[stackTop]; --stackTop; int[] getterSetters = (int[])stack[stackTop]; Object val; if (op == Token.OBJECTLIT) { Object[] ids = (Object[])frame.idata.literalIds[indexReg]; val = ScriptRuntime.newObjectLiteral(ids, data, getterSetters, cx, frame.scope); } else { int[] skipIndexces = null; if (op == Icode_SPARE_ARRAYLIT) { skipIndexces = (int[])frame.idata.literalIds[indexReg]; } val = ScriptRuntime.newArrayLiteral(data, skipIndexces, cx, frame.scope); } stack[stackTop] = val; continue Loop; } case Icode_ENTERDQ : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; frame.scope = ScriptRuntime.enterDotQuery(lhs, frame.scope); continue Loop; } case Icode_LEAVEDQ : { boolean valBln = stack_boolean(frame, stackTop); Object x = ScriptRuntime.updateDotQuery(valBln, frame.scope); if (x != null) { stack[stackTop] = x; frame.scope = ScriptRuntime.leaveDotQuery(frame.scope); frame.pc += 2; continue Loop; } // reset stack and PC to code after ENTERDQ --stackTop; break jumplessRun; } case Token.DEFAULTNAMESPACE : { Object value = stack[stackTop]; if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.setDefaultNamespace(value, cx); continue Loop; } case Token.ESCXMLATTR : { Object value = stack[stackTop]; if (value != DBL_MRK) { stack[stackTop] = ScriptRuntime.escapeAttributeValue(value, cx); } continue Loop; } case Token.ESCXMLTEXT : { Object value = stack[stackTop]; if (value != DBL_MRK) { stack[stackTop] = ScriptRuntime.escapeTextValue(value, cx); } continue Loop; } case Icode_DEBUGGER: if (frame.debuggerFrame != null) { frame.debuggerFrame.onDebuggerStatement(cx); } break Loop; case Icode_LINE : frame.pcSourceLineStart = frame.pc; if (frame.debuggerFrame != null) { int line = getIndex(iCode, frame.pc); frame.debuggerFrame.onLineChange(cx, line); } frame.pc += 2; continue Loop; case Icode_REG_IND_C0: indexReg = 0; continue Loop; case Icode_REG_IND_C1: indexReg = 1; continue Loop; case Icode_REG_IND_C2: indexReg = 2; continue Loop; case Icode_REG_IND_C3: indexReg = 3; continue Loop; case Icode_REG_IND_C4: indexReg = 4; continue Loop; case Icode_REG_IND_C5: indexReg = 5; continue Loop; case Icode_REG_IND1: indexReg = 0xFF & iCode[frame.pc]; ++frame.pc; continue Loop; case Icode_REG_IND2: indexReg = getIndex(iCode, frame.pc); frame.pc += 2; continue Loop; case Icode_REG_IND4: indexReg = getInt(iCode, frame.pc); frame.pc += 4; continue Loop; case Icode_REG_STR_C0: stringReg = strings[0]; continue Loop; case Icode_REG_STR_C1: stringReg = strings[1]; continue Loop; case Icode_REG_STR_C2: stringReg = strings[2]; continue Loop; case Icode_REG_STR_C3: stringReg = strings[3]; continue Loop; case Icode_REG_STR1: stringReg = strings[0xFF & iCode[frame.pc]]; ++frame.pc; continue Loop; case Icode_REG_STR2: stringReg = strings[getIndex(iCode, frame.pc)]; frame.pc += 2; continue Loop; case Icode_REG_STR4: stringReg = strings[getInt(iCode, frame.pc)]; frame.pc += 4; continue Loop; default : dumpICode(frame.idata); throw new RuntimeException( "Unknown icode : "+op+" @ pc : "+(frame.pc-1)); } // end of interpreter switch } // end of jumplessRun label block // This should be reachable only for jump implementation // when pc points to encoded target offset if (instructionCounting) { addInstructionCount(cx, frame, 2); } int offset = getShort(iCode, frame.pc); if (offset != 0) { // -1 accounts for pc pointing to jump opcode + 1 frame.pc += offset - 1; } else { frame.pc = frame.idata.longJumps. getExistingInt(frame.pc); } if (instructionCounting) { frame.pcPrevBranch = frame.pc; } continue Loop; } // end of Loop: for exitFrame(cx, frame, null); interpreterResult = frame.result; interpreterResultDbl = frame.resultDbl; if (frame.parentFrame != null) { frame = frame.parentFrame; if (frame.frozen) { frame = frame.cloneFrozen(); } setCallResult( frame, interpreterResult, interpreterResultDbl); interpreterResult = null; // Help GC continue StateLoop; } break StateLoop; } // end of interpreter withoutExceptions: try catch (Throwable ex) { if (throwable != null) { // This is serious bug and it is better to track it ASAP ex.printStackTrace(System.err); throw new IllegalStateException(); } throwable = ex; } // This should be reachable only after above catch or from // finally when it needs to propagate exception or from // explicit throw if (throwable == null) Kit.codeBug(); // Exception type final int EX_CATCH_STATE = 2; // Can execute JS catch final int EX_FINALLY_STATE = 1; // Can execute JS finally final int EX_NO_JS_STATE = 0; // Terminate JS execution int exState; ContinuationJump cjump = null; if (generatorState != null && generatorState.operation == NativeGenerator.GENERATOR_CLOSE && throwable == generatorState.value) { exState = EX_FINALLY_STATE; } else if (throwable instanceof JavaScriptException) { exState = EX_CATCH_STATE; } else if (throwable instanceof EcmaError) { // an offical ECMA error object, exState = EX_CATCH_STATE; } else if (throwable instanceof EvaluatorException) { exState = EX_CATCH_STATE; } else if (throwable instanceof RuntimeException) { exState = EX_FINALLY_STATE; } else if (throwable instanceof Error) { exState = EX_NO_JS_STATE; } else { // It must be ContinuationJump exState = EX_FINALLY_STATE; cjump = (ContinuationJump)throwable; } if (instructionCounting) { try { addInstructionCount(cx, frame, EXCEPTION_COST); } catch (RuntimeException ex) { throwable = ex; exState = EX_FINALLY_STATE; } catch (Error ex) { // Error from instruction counting // => unconditionally terminate JS throwable = ex; cjump = null; exState = EX_NO_JS_STATE; } } if (frame.debuggerFrame != null && throwable instanceof RuntimeException) { // Call debugger only for RuntimeException RuntimeException rex = (RuntimeException)throwable; try { frame.debuggerFrame.onExceptionThrown(cx, rex); } catch (Throwable ex) { // Any exception from debugger // => unconditionally terminate JS throwable = ex; cjump = null; exState = EX_NO_JS_STATE; } } for (;;) { if (exState != EX_NO_JS_STATE) { boolean onlyFinally = (exState != EX_CATCH_STATE); indexReg = getExceptionHandler(frame, onlyFinally); if (indexReg >= 0) { // We caught an exception, restart the loop // with exception pending the processing at the loop // start continue StateLoop; } } // No allowed exception handlers in this frame, unwind // to parent and try to look there exitFrame(cx, frame, throwable); frame = frame.parentFrame; if (frame == null) { break; } if (cjump != null && cjump.branchFrame == frame) { // Continuation branch point was hit, // restart the state loop to reenter continuation indexReg = -1; continue StateLoop; } } // No more frames, rethrow the exception or deal with continuation if (cjump != null) { if (cjump.branchFrame != null) { // The above loop should locate the top frame Kit.codeBug(); } if (cjump.capturedFrame != null) { // Restarting detached continuation indexReg = -1; continue StateLoop; } // Return continuation result to the caller interpreterResult = cjump.result; interpreterResultDbl = cjump.resultDbl; throwable = null; } break StateLoop; } // end of StateLoop: for(;;) // Do cleanups/restorations before the final return or throw if (cx.previousInterpreterInvocations != null && cx.previousInterpreterInvocations.size() != 0) { cx.lastInterpreterFrame = cx.previousInterpreterInvocations.pop(); } else { // It was the last interpreter frame on the stack cx.lastInterpreterFrame = null; // Force GC of the value cx.previousInterpreterInvocations cx.previousInterpreterInvocations = null; } if (throwable != null) { if (throwable instanceof RuntimeException) { throw (RuntimeException)throwable; } else { // Must be instance of Error or code bug throw (Error)throwable; } } return (interpreterResult != DBL_MRK) ? interpreterResult : ScriptRuntime.wrapNumber(interpreterResultDbl); }
diff --git a/src/test/java/com/github/rickyclarkson/monitorablefutures/MonitorableFuturesTest.java b/src/test/java/com/github/rickyclarkson/monitorablefutures/MonitorableFuturesTest.java index 9949fa1..2d7e647 100644 --- a/src/test/java/com/github/rickyclarkson/monitorablefutures/MonitorableFuturesTest.java +++ b/src/test/java/com/github/rickyclarkson/monitorablefutures/MonitorableFuturesTest.java @@ -1,48 +1,49 @@ package com.github.rickyclarkson.monitorablefutures; import org.junit.Test; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static com.github.rickyclarkson.monitorablefutures.MonitorableExecutorService.monitorable; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class MonitorableFuturesTest { @Test public void withMonitorable() throws InterruptedException { MonitorableExecutorService service = monitorable(Executors.newSingleThreadExecutor()); class Count extends MonitorableRunnable<Integer> { @Override public void run() { for (int a = 0; a < 3; a++) { try { if (!updates().offer(a, 1, TimeUnit.SECONDS)) new IllegalStateException("Couldn't offer " + a + " to the BlockingQueue after waiting for 1 second.").printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Added " + a); } } } MonitorableFuture<?, Integer> future = service.submit(new Count()); for (;;) { final Integer integer = future.updates().poll(10, TimeUnit.MILLISECONDS); if (integer != null) System.out.println("Progress: " + integer); if (integer == null) continue; if (integer == 2) { + Thread.sleep(500); assertTrue(future.isDone()); return; } if (integer > 2) { fail("The test case is faulty if the value is >2"); } } } }
true
true
public void withMonitorable() throws InterruptedException { MonitorableExecutorService service = monitorable(Executors.newSingleThreadExecutor()); class Count extends MonitorableRunnable<Integer> { @Override public void run() { for (int a = 0; a < 3; a++) { try { if (!updates().offer(a, 1, TimeUnit.SECONDS)) new IllegalStateException("Couldn't offer " + a + " to the BlockingQueue after waiting for 1 second.").printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Added " + a); } } } MonitorableFuture<?, Integer> future = service.submit(new Count()); for (;;) { final Integer integer = future.updates().poll(10, TimeUnit.MILLISECONDS); if (integer != null) System.out.println("Progress: " + integer); if (integer == null) continue; if (integer == 2) { assertTrue(future.isDone()); return; } if (integer > 2) { fail("The test case is faulty if the value is >2"); } } }
public void withMonitorable() throws InterruptedException { MonitorableExecutorService service = monitorable(Executors.newSingleThreadExecutor()); class Count extends MonitorableRunnable<Integer> { @Override public void run() { for (int a = 0; a < 3; a++) { try { if (!updates().offer(a, 1, TimeUnit.SECONDS)) new IllegalStateException("Couldn't offer " + a + " to the BlockingQueue after waiting for 1 second.").printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Added " + a); } } } MonitorableFuture<?, Integer> future = service.submit(new Count()); for (;;) { final Integer integer = future.updates().poll(10, TimeUnit.MILLISECONDS); if (integer != null) System.out.println("Progress: " + integer); if (integer == null) continue; if (integer == 2) { Thread.sleep(500); assertTrue(future.isDone()); return; } if (integer > 2) { fail("The test case is faulty if the value is >2"); } } }
diff --git a/spiffyui/build/maven/maven-spiffyui-plugin/src/main/java/org/spiffyui/maven/plugins/CssCompressMojo.java b/spiffyui/build/maven/maven-spiffyui-plugin/src/main/java/org/spiffyui/maven/plugins/CssCompressMojo.java index 78f9f0a7..066601a9 100644 --- a/spiffyui/build/maven/maven-spiffyui-plugin/src/main/java/org/spiffyui/maven/plugins/CssCompressMojo.java +++ b/spiffyui/build/maven/maven-spiffyui-plugin/src/main/java/org/spiffyui/maven/plugins/CssCompressMojo.java @@ -1,220 +1,220 @@ /******************************************************************************* * * Copyright 2011 Spiffy UI Team * * 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.spiffyui.maven.plugins; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Collection; import org.apache.commons.io.FileUtils; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.codehaus.plexus.util.IOUtil; import com.yahoo.platform.yui.compressor.CssCompressor; /** * Invokes the YUI Compressor for the project .css source * * @goal css-compress * @phase process-resources */ public class CssCompressMojo extends AbstractMojo { /** * The character encoding scheme to be applied exporting the JSON document * * @parameter expression="${encoding}" default-value="UTF-8" */ private String encoding; /** * The output filename suffix. * * @parameter expression="${spiffyui.yuicompressor.suffix}" * default-value=".min" */ private String suffix; /** * Insert line breaks in output after the specified column number. * * @parameter expression="${spiffyui.yuicompressor.linebreakpos}" * default-value="0" */ private int linebreakpos; /** * The CSS directory name under source. This directory is added * in addition to the source directory * * @parameter expression="${spiffyui.css.directory}" * default-value="css" */ private String css; /** * Path to the project .css sources to compress * * @parameter default-value="src/main/webapp" */ private File sourceDirectory; /** * The output directory to emit compressed artifacts * * @parameter default-value="${spiffyui.www}" * @required */ private File outputDirectory; /** * The name of the generated compressed CSS file * * @parameter default-value="SpiffyUi.min.css" */ private String outputFileName; @Override public void execute() throws MojoExecutionException, MojoFailureException { if (!sourceDirectory.exists()) { getLog().debug("No sources, skipping"); return; } String[] exts = new String[] { "css" }; Collection<File> files = FileUtils.listFiles(sourceDirectory, exts, false); File cssDir = new File(sourceDirectory, css); if (cssDir.exists()) { files.addAll(FileUtils.listFiles(cssDir, exts, false)); - }; + } try { String name = outputFileName; if (files.size() == 1) { /* If there is only one file then we can use the name of that file as the name of our CSS file. We want this for backward compatability so existing projects don't have to change their HTML. */ name = files.iterator().next().getName().replace(".css", ".min.css"); } compress(concat(files), name); } catch (Exception e) { e.printStackTrace(); throw new MojoExecutionException(e.getMessage()); } } /** * This method concatenates the set of CSS source files since YUI requires a * single input file. * * @param files the files to concatenate * * @return a temporary file containing the concatenated source files * @exception IOException */ private File concat(Collection<File> files) throws IOException { File outFile = File.createTempFile("spiffy_", ".css"); OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(outFile), encoding); try { for (File file : files) { InputStreamReader in = new InputStreamReader(new FileInputStream(file), encoding); int read; char[] buf = new char[1024]; try { while ((read = in.read(buf)) > 0) { out.write(buf, 0, read); } out.write('\n'); } finally { if (in != null) { in.close(); } } } } finally { if (out != null) { out.close(); } } //outFile.deleteOnExit(); return outFile; } /** * Call the YUI compressor to compress our concatenated CSS file. * * @param inFile the concatenated CSS file * * @exception IOException * @exception MojoExecutionException */ private void compress(File inFile, String outFileName) throws IOException, MojoExecutionException { File outFile = new File(outputDirectory, outFileName); InputStreamReader in = null; OutputStreamWriter out = null; try { in = new InputStreamReader(new FileInputStream(inFile), encoding); out = new OutputStreamWriter(new FileOutputStream(outFile), encoding); if (!outFile.getParentFile().exists() && !outFile.getParentFile().mkdirs()) { throw new MojoExecutionException("Cannot create resource output directory: " + outFile.getParentFile()); } getLog().debug("YUICOMPRESS: " + inFile.getAbsolutePath() + " -> " + outFile.getAbsolutePath()); try { CssCompressor compressor = new CssCompressor(in); compressor.compress(out, linebreakpos); } catch (IllegalArgumentException e) { throw new IllegalArgumentException( "Unexpected characters found in CSS file. Ensure that the CSS file does not contain '$', and try again", e); } } finally { IOUtil.close(in); IOUtil.close(out); } } }
true
true
public void execute() throws MojoExecutionException, MojoFailureException { if (!sourceDirectory.exists()) { getLog().debug("No sources, skipping"); return; } String[] exts = new String[] { "css" }; Collection<File> files = FileUtils.listFiles(sourceDirectory, exts, false); File cssDir = new File(sourceDirectory, css); if (cssDir.exists()) { files.addAll(FileUtils.listFiles(cssDir, exts, false)); }; try { String name = outputFileName; if (files.size() == 1) { /* If there is only one file then we can use the name of that file as the name of our CSS file. We want this for backward compatability so existing projects don't have to change their HTML. */ name = files.iterator().next().getName().replace(".css", ".min.css"); } compress(concat(files), name); } catch (Exception e) { e.printStackTrace(); throw new MojoExecutionException(e.getMessage()); } }
public void execute() throws MojoExecutionException, MojoFailureException { if (!sourceDirectory.exists()) { getLog().debug("No sources, skipping"); return; } String[] exts = new String[] { "css" }; Collection<File> files = FileUtils.listFiles(sourceDirectory, exts, false); File cssDir = new File(sourceDirectory, css); if (cssDir.exists()) { files.addAll(FileUtils.listFiles(cssDir, exts, false)); } try { String name = outputFileName; if (files.size() == 1) { /* If there is only one file then we can use the name of that file as the name of our CSS file. We want this for backward compatability so existing projects don't have to change their HTML. */ name = files.iterator().next().getName().replace(".css", ".min.css"); } compress(concat(files), name); } catch (Exception e) { e.printStackTrace(); throw new MojoExecutionException(e.getMessage()); } }
diff --git a/org.eclipse.mylyn.context.tasks.tests/src/org/eclipse/mylyn/context/tasks/tests/RefactorRepositoryUrlOperationTest.java b/org.eclipse.mylyn.context.tasks.tests/src/org/eclipse/mylyn/context/tasks/tests/RefactorRepositoryUrlOperationTest.java index 1b85a663e..4ff973f0b 100644 --- a/org.eclipse.mylyn.context.tasks.tests/src/org/eclipse/mylyn/context/tasks/tests/RefactorRepositoryUrlOperationTest.java +++ b/org.eclipse.mylyn.context.tasks.tests/src/org/eclipse/mylyn/context/tasks/tests/RefactorRepositoryUrlOperationTest.java @@ -1,109 +1,114 @@ /******************************************************************************* * Copyright (c) 2011 Tasktop Technologies. * 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.context.tasks.tests; import java.util.Calendar; import junit.framework.TestCase; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.mylyn.internal.context.core.ContextCorePlugin; import org.eclipse.mylyn.internal.context.core.InteractionContext; import org.eclipse.mylyn.internal.context.core.InteractionContextManager; import org.eclipse.mylyn.internal.tasks.core.AbstractTask; import org.eclipse.mylyn.internal.tasks.core.RepositoryQuery; import org.eclipse.mylyn.internal.tasks.core.TaskList; import org.eclipse.mylyn.internal.tasks.ui.RefactorRepositoryUrlOperation; import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin; import org.eclipse.mylyn.monitor.core.InteractionEvent; import org.eclipse.mylyn.tasks.core.IRepositoryQuery; import org.eclipse.mylyn.tasks.tests.TaskTestUtil; import org.eclipse.mylyn.tasks.tests.connector.MockRepositoryQuery; import org.eclipse.mylyn.tasks.tests.connector.MockTask; import org.junit.Before; import org.junit.Test; /** * @author Robert Elves * @author Steffen Pingel */ public class RefactorRepositoryUrlOperationTest extends TestCase { private TaskList taskList; @Override @Before public void setUp() throws Exception { taskList = TasksUiPlugin.getTaskList(); TaskTestUtil.resetTaskList(); } @Test public void testMigrateQueryUrlHandles() throws Exception { RepositoryQuery query = new MockRepositoryQuery("mquery"); query.setRepositoryUrl("http://foo.bar"); query.setUrl("http://foo.bar/b"); taskList.addQuery(query); assertTrue(taskList.getRepositoryQueries("http://foo.bar").size() > 0); new RefactorRepositoryUrlOperation("http://foo.bar", "http://bar.baz").run(new NullProgressMonitor()); assertTrue(taskList.getRepositoryQueries("http://foo.bar").size() == 0); assertTrue(taskList.getRepositoryQueries("http://bar.baz").size() > 0); IRepositoryQuery changedQuery = taskList.getRepositoryQueries("http://bar.baz").iterator().next(); assertEquals("http://bar.baz/b", changedQuery.getUrl()); } @Test public void testRefactorMetaContextHandles() throws Exception { + Calendar now = Calendar.getInstance(); String firstUrl = "http://repository1.com/bugs"; String secondUrl = "http://repository2.com/bugs"; AbstractTask task1 = new MockTask(firstUrl, "1"); AbstractTask task2 = new MockTask(firstUrl, "2"); taskList.addTask(task1); taskList.addTask(task2); Calendar startDate = Calendar.getInstance(); + startDate.setTimeInMillis(now.getTimeInMillis()); Calendar endDate = Calendar.getInstance(); + endDate.setTimeInMillis(now.getTimeInMillis()); endDate.add(Calendar.MINUTE, 5); Calendar startDate2 = Calendar.getInstance(); + startDate2.setTimeInMillis(now.getTimeInMillis()); startDate2.add(Calendar.MINUTE, 15); Calendar endDate2 = Calendar.getInstance(); + endDate2.setTimeInMillis(now.getTimeInMillis()); endDate2.add(Calendar.MINUTE, 25); ContextCorePlugin.getContextManager().resetActivityMetaContext(); InteractionContext metaContext = ContextCorePlugin.getContextManager().getActivityMetaContext(); assertEquals(0, metaContext.getInteractionHistory().size()); ContextCorePlugin.getContextManager().processActivityMetaContextEvent( new InteractionEvent(InteractionEvent.Kind.ATTENTION, InteractionContextManager.ACTIVITY_STRUCTUREKIND_TIMING, task1.getHandleIdentifier(), "origin", null, InteractionContextManager.ACTIVITY_DELTA_ADDED, 1f, startDate.getTime(), endDate.getTime())); ContextCorePlugin.getContextManager().processActivityMetaContextEvent( new InteractionEvent(InteractionEvent.Kind.ATTENTION, InteractionContextManager.ACTIVITY_STRUCTUREKIND_TIMING, task2.getHandleIdentifier(), "origin", null, InteractionContextManager.ACTIVITY_DELTA_ADDED, 1f, startDate2.getTime(), endDate2.getTime())); assertEquals(2, metaContext.getInteractionHistory().size()); - assertEquals(60 * 1000 * 5, TasksUiPlugin.getTaskActivityManager().getElapsedTime(task1)); - assertEquals(2 * 60 * 1000 * 5, TasksUiPlugin.getTaskActivityManager().getElapsedTime(task2)); + assertEquals(5 * 60 * 1000, TasksUiPlugin.getTaskActivityManager().getElapsedTime(task1)); + assertEquals(10 * 60 * 1000, TasksUiPlugin.getTaskActivityManager().getElapsedTime(task2)); new RefactorRepositoryUrlOperation(firstUrl, secondUrl).run(new NullProgressMonitor()); metaContext = ContextCorePlugin.getContextManager().getActivityMetaContext(); assertEquals(2, metaContext.getInteractionHistory().size()); - assertEquals(60 * 1000 * 5, TasksUiPlugin.getTaskActivityManager().getElapsedTime(new MockTask(secondUrl, "1"))); - assertEquals(2 * 60 * 1000 * 5, - TasksUiPlugin.getTaskActivityManager().getElapsedTime(new MockTask(secondUrl, "2"))); + assertEquals(5 * 60 * 1000, TasksUiPlugin.getTaskActivityManager().getElapsedTime(new MockTask(secondUrl, "1"))); + assertEquals(10 * 60 * 1000, TasksUiPlugin.getTaskActivityManager() + .getElapsedTime(new MockTask(secondUrl, "2"))); assertEquals(secondUrl + "-1", metaContext.getInteractionHistory().get(0).getStructureHandle()); } }
false
true
public void testRefactorMetaContextHandles() throws Exception { String firstUrl = "http://repository1.com/bugs"; String secondUrl = "http://repository2.com/bugs"; AbstractTask task1 = new MockTask(firstUrl, "1"); AbstractTask task2 = new MockTask(firstUrl, "2"); taskList.addTask(task1); taskList.addTask(task2); Calendar startDate = Calendar.getInstance(); Calendar endDate = Calendar.getInstance(); endDate.add(Calendar.MINUTE, 5); Calendar startDate2 = Calendar.getInstance(); startDate2.add(Calendar.MINUTE, 15); Calendar endDate2 = Calendar.getInstance(); endDate2.add(Calendar.MINUTE, 25); ContextCorePlugin.getContextManager().resetActivityMetaContext(); InteractionContext metaContext = ContextCorePlugin.getContextManager().getActivityMetaContext(); assertEquals(0, metaContext.getInteractionHistory().size()); ContextCorePlugin.getContextManager().processActivityMetaContextEvent( new InteractionEvent(InteractionEvent.Kind.ATTENTION, InteractionContextManager.ACTIVITY_STRUCTUREKIND_TIMING, task1.getHandleIdentifier(), "origin", null, InteractionContextManager.ACTIVITY_DELTA_ADDED, 1f, startDate.getTime(), endDate.getTime())); ContextCorePlugin.getContextManager().processActivityMetaContextEvent( new InteractionEvent(InteractionEvent.Kind.ATTENTION, InteractionContextManager.ACTIVITY_STRUCTUREKIND_TIMING, task2.getHandleIdentifier(), "origin", null, InteractionContextManager.ACTIVITY_DELTA_ADDED, 1f, startDate2.getTime(), endDate2.getTime())); assertEquals(2, metaContext.getInteractionHistory().size()); assertEquals(60 * 1000 * 5, TasksUiPlugin.getTaskActivityManager().getElapsedTime(task1)); assertEquals(2 * 60 * 1000 * 5, TasksUiPlugin.getTaskActivityManager().getElapsedTime(task2)); new RefactorRepositoryUrlOperation(firstUrl, secondUrl).run(new NullProgressMonitor()); metaContext = ContextCorePlugin.getContextManager().getActivityMetaContext(); assertEquals(2, metaContext.getInteractionHistory().size()); assertEquals(60 * 1000 * 5, TasksUiPlugin.getTaskActivityManager().getElapsedTime(new MockTask(secondUrl, "1"))); assertEquals(2 * 60 * 1000 * 5, TasksUiPlugin.getTaskActivityManager().getElapsedTime(new MockTask(secondUrl, "2"))); assertEquals(secondUrl + "-1", metaContext.getInteractionHistory().get(0).getStructureHandle()); }
public void testRefactorMetaContextHandles() throws Exception { Calendar now = Calendar.getInstance(); String firstUrl = "http://repository1.com/bugs"; String secondUrl = "http://repository2.com/bugs"; AbstractTask task1 = new MockTask(firstUrl, "1"); AbstractTask task2 = new MockTask(firstUrl, "2"); taskList.addTask(task1); taskList.addTask(task2); Calendar startDate = Calendar.getInstance(); startDate.setTimeInMillis(now.getTimeInMillis()); Calendar endDate = Calendar.getInstance(); endDate.setTimeInMillis(now.getTimeInMillis()); endDate.add(Calendar.MINUTE, 5); Calendar startDate2 = Calendar.getInstance(); startDate2.setTimeInMillis(now.getTimeInMillis()); startDate2.add(Calendar.MINUTE, 15); Calendar endDate2 = Calendar.getInstance(); endDate2.setTimeInMillis(now.getTimeInMillis()); endDate2.add(Calendar.MINUTE, 25); ContextCorePlugin.getContextManager().resetActivityMetaContext(); InteractionContext metaContext = ContextCorePlugin.getContextManager().getActivityMetaContext(); assertEquals(0, metaContext.getInteractionHistory().size()); ContextCorePlugin.getContextManager().processActivityMetaContextEvent( new InteractionEvent(InteractionEvent.Kind.ATTENTION, InteractionContextManager.ACTIVITY_STRUCTUREKIND_TIMING, task1.getHandleIdentifier(), "origin", null, InteractionContextManager.ACTIVITY_DELTA_ADDED, 1f, startDate.getTime(), endDate.getTime())); ContextCorePlugin.getContextManager().processActivityMetaContextEvent( new InteractionEvent(InteractionEvent.Kind.ATTENTION, InteractionContextManager.ACTIVITY_STRUCTUREKIND_TIMING, task2.getHandleIdentifier(), "origin", null, InteractionContextManager.ACTIVITY_DELTA_ADDED, 1f, startDate2.getTime(), endDate2.getTime())); assertEquals(2, metaContext.getInteractionHistory().size()); assertEquals(5 * 60 * 1000, TasksUiPlugin.getTaskActivityManager().getElapsedTime(task1)); assertEquals(10 * 60 * 1000, TasksUiPlugin.getTaskActivityManager().getElapsedTime(task2)); new RefactorRepositoryUrlOperation(firstUrl, secondUrl).run(new NullProgressMonitor()); metaContext = ContextCorePlugin.getContextManager().getActivityMetaContext(); assertEquals(2, metaContext.getInteractionHistory().size()); assertEquals(5 * 60 * 1000, TasksUiPlugin.getTaskActivityManager().getElapsedTime(new MockTask(secondUrl, "1"))); assertEquals(10 * 60 * 1000, TasksUiPlugin.getTaskActivityManager() .getElapsedTime(new MockTask(secondUrl, "2"))); assertEquals(secondUrl + "-1", metaContext.getInteractionHistory().get(0).getStructureHandle()); }
diff --git a/src/main/java/com/bergerkiller/bukkit/nolagg/itemstacker/StackingTask.java b/src/main/java/com/bergerkiller/bukkit/nolagg/itemstacker/StackingTask.java index 6a1b334..c6fa9f2 100644 --- a/src/main/java/com/bergerkiller/bukkit/nolagg/itemstacker/StackingTask.java +++ b/src/main/java/com/bergerkiller/bukkit/nolagg/itemstacker/StackingTask.java @@ -1,155 +1,155 @@ package com.bergerkiller.bukkit.nolagg.itemstacker; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.Item; import org.bukkit.inventory.ItemStack; import com.bergerkiller.bukkit.common.utils.ItemUtil; public class StackingTask <T extends Entity> { private static Location locationBuffer = new Location(null, 0.0, 0.0, 0.0); private static Location selfLocationBuffer = new Location(null, 0.0, 0.0, 0.0); private T entity; private List<T> nearby = new ArrayList<T>(0); /** * Resets this Stacking Task * * @param entity to set */ public void reset(T entity) { this.entity = entity; this.nearby.clear(); } /** * Clears this Stacking Task to ensure minimal memory usage */ public void clear() { this.entity = null; this.nearby = new ArrayList<T>(0); } /** * Gets the nearby entities * * @return nearby entities */ public List<T> getNearby() { return this.nearby; } /** * Gets the center Entity * * @return center entity */ public T getEntity() { return this.entity; } /** * Checks if this Stacking Task contains a valid Entity * * @return True if this task is Valid, False if not */ public boolean isValid() { return this.entity != null; } /** * Checks if this Stacking Task can be processed upon * * @return True if processing is possible, False if not */ public boolean canProcess() { return !this.entity.isDead() && this.nearby.size() >= NoLaggItemStacker.stackThreshold - 1; } /** * Checks whether a given item reached it's maximum stacking size * * @return True if the item is maxed, False if not */ public static boolean isMaxed(Item item) { return item.getItemStack().getAmount() >= ItemUtil.getMaxSize(item.getItemStack()); } /** * Checks whether a given item reached it's maximum stacking size * * @return True if the item is maxed, False if not */ public static boolean isMaxed(ItemStack item) { return item.getAmount() >= ItemUtil.getMaxSize(item); } /** * Fills the nearby entities of this task * * @param Entitytasks to use as source for entities * @param radiusSquared for stacking */ public void fillNearby(List<StackingTask<T>> Entitytasks, final double radiusSquared) { if (this.entity.isDead()) { return; } this.entity.getLocation(selfLocationBuffer); T entity; ItemStack entityItemStack = this.entity instanceof Item ? ((Item) this.entity).getItemStack() : null; for (StackingTask<T> task : Entitytasks) { if (!task.isValid()) { break; // Reached end of data } entity = task.entity; // Same entity, dead entity or out of range? - if (entity.isDead() || entity == this.entity || + if (entity.isDead() || entity == this.entity || entity.getWorld() != this.entity.getWorld() || entity.getLocation(locationBuffer).distanceSquared(selfLocationBuffer) > radiusSquared) { continue; } // Same item type and data? (If item) if (entityItemStack != null) { Item to = (Item) entity; if (isMaxed(entityItemStack) || !ItemUtil.equalsIgnoreAmount(entityItemStack, to.getItemStack())) { continue; } } // This item can stack: add the nearby entity this.nearby.add(entity); } } /** * Transfers all entities into Stacking Tasks * * @param entities to transfer * @param tasks to transfer the entities to */ public static <T extends Entity> void transfer(Collection<T> entities, Collection<StackingTask<T>> tasks) { // Ensure required tasks capacity if (entities.size() > tasks.size()) { for (int i = tasks.size(); i < entities.size(); i++) { tasks.add(new StackingTask<T>()); } } // Transfer Iterator<T> entitiesIter = entities.iterator(); Iterator<StackingTask<T>> tasksIter = tasks.iterator(); while (entitiesIter.hasNext()) { tasksIter.next().reset(entitiesIter.next()); } // Clear unused elements while (tasksIter.hasNext()) { tasksIter.next().clear(); } } }
true
true
public void fillNearby(List<StackingTask<T>> Entitytasks, final double radiusSquared) { if (this.entity.isDead()) { return; } this.entity.getLocation(selfLocationBuffer); T entity; ItemStack entityItemStack = this.entity instanceof Item ? ((Item) this.entity).getItemStack() : null; for (StackingTask<T> task : Entitytasks) { if (!task.isValid()) { break; // Reached end of data } entity = task.entity; // Same entity, dead entity or out of range? if (entity.isDead() || entity == this.entity || entity.getLocation(locationBuffer).distanceSquared(selfLocationBuffer) > radiusSquared) { continue; } // Same item type and data? (If item) if (entityItemStack != null) { Item to = (Item) entity; if (isMaxed(entityItemStack) || !ItemUtil.equalsIgnoreAmount(entityItemStack, to.getItemStack())) { continue; } } // This item can stack: add the nearby entity this.nearby.add(entity); } }
public void fillNearby(List<StackingTask<T>> Entitytasks, final double radiusSquared) { if (this.entity.isDead()) { return; } this.entity.getLocation(selfLocationBuffer); T entity; ItemStack entityItemStack = this.entity instanceof Item ? ((Item) this.entity).getItemStack() : null; for (StackingTask<T> task : Entitytasks) { if (!task.isValid()) { break; // Reached end of data } entity = task.entity; // Same entity, dead entity or out of range? if (entity.isDead() || entity == this.entity || entity.getWorld() != this.entity.getWorld() || entity.getLocation(locationBuffer).distanceSquared(selfLocationBuffer) > radiusSquared) { continue; } // Same item type and data? (If item) if (entityItemStack != null) { Item to = (Item) entity; if (isMaxed(entityItemStack) || !ItemUtil.equalsIgnoreAmount(entityItemStack, to.getItemStack())) { continue; } } // This item can stack: add the nearby entity this.nearby.add(entity); } }
diff --git a/robocode.ui.editor/src/main/java/net/sf/robocode/ui/editor/RobocodeCompilerFactory.java b/robocode.ui.editor/src/main/java/net/sf/robocode/ui/editor/RobocodeCompilerFactory.java index c6c5bd9f6..102c845a0 100644 --- a/robocode.ui.editor/src/main/java/net/sf/robocode/ui/editor/RobocodeCompilerFactory.java +++ b/robocode.ui.editor/src/main/java/net/sf/robocode/ui/editor/RobocodeCompilerFactory.java @@ -1,227 +1,227 @@ /******************************************************************************* * Copyright (c) 2001-2011 Mathew A. Nelson and Robocode contributors * 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://robocode.sourceforge.net/license/epl-v10.html * * Contributors: * Mathew A. Nelson * - Initial API and implementation * Flemming N. Larsen * - Changed to use the Eclipse Compiler for Java (ECJ) *******************************************************************************/ package net.sf.robocode.ui.editor; import net.sf.robocode.core.ContainerBase; import net.sf.robocode.io.FileUtil; import net.sf.robocode.io.Logger; import net.sf.robocode.manager.IVersionManagerBase; import static net.sf.robocode.io.Logger.logError; import static net.sf.robocode.io.Logger.logMessage; import net.sf.robocode.ui.dialog.ConsoleDialog; import net.sf.robocode.ui.dialog.WindowUtil; import javax.swing.*; import java.io.*; /** * @author Mathew A. Nelson (original) * @author Flemming N. Larsen (contributor) */ public class RobocodeCompilerFactory { private static final String COMPILER_CLASSPATH = "-classpath " + getJavaLib() + File.pathSeparator + "libs" + File.separator + "robocode.jar" + File.pathSeparator + FileUtil.quoteFileName(FileUtil.getRobotsDir().toString()); private CompilerProperties compilerProperties; public RobocodeCompiler createCompiler(RobocodeEditor editor) { compilerProperties = null; if (getCompilerProperties().getCompilerBinary() == null || getCompilerProperties().getCompilerBinary().length() == 0) { if (configureCompiler(editor)) { return new RobocodeCompiler(editor, getCompilerProperties().getCompilerBinary(), getCompilerProperties().getCompilerOptions(), getCompilerProperties().getCompilerClasspath()); } logError("Unable to create compiler."); return null; } return new RobocodeCompiler(editor, getCompilerProperties().getCompilerBinary(), getCompilerProperties().getCompilerOptions(), getCompilerProperties().getCompilerClasspath()); } public CompilerProperties getCompilerProperties() { if (compilerProperties == null) { compilerProperties = new CompilerProperties(); FileInputStream in = null; File file = null; try { file = FileUtil.getCompilerConfigFile(); in = new FileInputStream(file); compilerProperties.load(in); if (compilerProperties.getRobocodeVersion() == null) { logMessage("Setting up new compiler."); compilerProperties.setCompilerBinary(""); } } catch (FileNotFoundException e) { logMessage("Compiler configuration file was not found. A new one will be created."); } catch (IOException e) { logError("Error while reading " + file, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignored) {} } } } return compilerProperties; } private static String getJavaLib() { String javahome = System.getProperty("java.home"); String javalib; if (System.getProperty("os.name").indexOf("Mac") == 0) { javalib = new File(javahome).getParentFile().getPath() + "/Classes/classes.jar"; } else { javalib = javahome + "/lib/rt.jar"; } return FileUtil.quoteFileName(javalib); } public boolean configureCompiler(RobocodeEditor editor) { ConsoleDialog console = new ConsoleDialog(editor, "Setting up compiler", false); console.setSize(500, 400); console.getOkButton().setEnabled(false); console.setText("Please wait while Robocode sets up a compiler for you...\n\n"); WindowUtil.centerShow(editor, console); console.append("Setting up compiler\n"); console.append("Java home is " + System.getProperty("java.home") + "\n\n"); String compilerName = "Java Compiler (javac)"; String compilerBinary = "javac"; String compilerOptions = "-deprecation -g -source 1.5 -encoding UTF-8"; boolean javacOK = testCompiler(compilerName, compilerBinary, console); boolean ecjOK = false; if (javacOK) { int rc = JOptionPane.showConfirmDialog(editor, "Robocode has found a working javac (Java Compiler) on this system.\nWould you like to use it?\n" + "(If you click No, Robocode will use the build-in Eclipse Compiler for Java (ECJ))", "Confirm javac", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (rc == JOptionPane.NO_OPTION) { javacOK = false; } } if (!javacOK) { compilerName = "Eclipse Compiler for Java (ECJ)"; - compilerBinary = "java -jar compilers/ecj.jar"; + compilerBinary = "java -cp compilers/ecj.jar org.eclipse.jdt.internal.compiler.batch.Main"; ecjOK = testCompiler("Eclipse Compiler for Java (ECJ)", compilerBinary, console); } boolean compilerOK = javacOK || ecjOK; if (compilerOK) { console.append("\nCompiler has been set up successfully.\nClick OK to continue.\n"); } else { final String errorText = "Could not set up a working compiler for Robocode.\n" + "Please consult the console window for errors.\n\n" + "For help with this, please post to Help forum here:\n" + "http://sourceforge.net/projects/robocode/forums/forum/116459"; console.append("\nUnable to set up a working compiler for Robocode.\n"); JOptionPane.showMessageDialog(editor, errorText, "Error", JOptionPane.ERROR_MESSAGE); compilerBinary = ""; compilerOptions = ""; } getCompilerProperties().setRobocodeVersion(ContainerBase.getComponent(IVersionManagerBase.class).getVersion()); getCompilerProperties().setCompilerBinary(compilerBinary); getCompilerProperties().setCompilerOptions(compilerOptions); getCompilerProperties().setCompilerClasspath(COMPILER_CLASSPATH); saveCompilerProperties(); console.scrollToBottom(); console.getOkButton().setEnabled(true); return compilerOK; } public void saveCompilerProperties() { FileOutputStream out = null; try { out = new FileOutputStream(FileUtil.getCompilerConfigFile()); getCompilerProperties().store(out, "Robocode Compiler Properties"); } catch (IOException e) { Logger.logError(e); } finally { FileUtil.cleanupStream(out); } } /** * Tests a compiler by trying to let it compile the CompilerTest.java file. * * @param friendlyName friendly name of the compiler to test. * @param filepath the file path of the compiler. * @param console the console which outputs the result. * @return true if the compiler was found and did compile the test file; false otherwise. */ private static boolean testCompiler(String friendlyName, String filepath, ConsoleDialog console) { console.append("Testing compile with " + friendlyName + "\n"); boolean result = false; try { String cmdAndArgs = filepath + " compilers/CompilerTest.java"; // Must be split command and arguments individually ProcessBuilder pb = new ProcessBuilder(cmdAndArgs.split(" ")); pb.directory(FileUtil.getCwd()); pb.redirectErrorStream(true); // we can use p.getInputStream() Process p = pb.start(); // The waitFor() must done after reading the input and error stream of the process console.processStream(p.getInputStream()); p.waitFor(); result = (p.exitValue() == 0); } catch (IOException e) { logError(e); } catch (InterruptedException e) { // Immediately reasserts the exception by interrupting the caller thread itself Thread.currentThread().interrupt(); } if (result) { console.append(friendlyName + " was found and is working.\n"); } else { console.append(friendlyName + " does not exists or cannot compile.\n"); } return result; } }
true
true
public boolean configureCompiler(RobocodeEditor editor) { ConsoleDialog console = new ConsoleDialog(editor, "Setting up compiler", false); console.setSize(500, 400); console.getOkButton().setEnabled(false); console.setText("Please wait while Robocode sets up a compiler for you...\n\n"); WindowUtil.centerShow(editor, console); console.append("Setting up compiler\n"); console.append("Java home is " + System.getProperty("java.home") + "\n\n"); String compilerName = "Java Compiler (javac)"; String compilerBinary = "javac"; String compilerOptions = "-deprecation -g -source 1.5 -encoding UTF-8"; boolean javacOK = testCompiler(compilerName, compilerBinary, console); boolean ecjOK = false; if (javacOK) { int rc = JOptionPane.showConfirmDialog(editor, "Robocode has found a working javac (Java Compiler) on this system.\nWould you like to use it?\n" + "(If you click No, Robocode will use the build-in Eclipse Compiler for Java (ECJ))", "Confirm javac", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (rc == JOptionPane.NO_OPTION) { javacOK = false; } } if (!javacOK) { compilerName = "Eclipse Compiler for Java (ECJ)"; compilerBinary = "java -jar compilers/ecj.jar"; ecjOK = testCompiler("Eclipse Compiler for Java (ECJ)", compilerBinary, console); } boolean compilerOK = javacOK || ecjOK; if (compilerOK) { console.append("\nCompiler has been set up successfully.\nClick OK to continue.\n"); } else { final String errorText = "Could not set up a working compiler for Robocode.\n" + "Please consult the console window for errors.\n\n" + "For help with this, please post to Help forum here:\n" + "http://sourceforge.net/projects/robocode/forums/forum/116459"; console.append("\nUnable to set up a working compiler for Robocode.\n"); JOptionPane.showMessageDialog(editor, errorText, "Error", JOptionPane.ERROR_MESSAGE); compilerBinary = ""; compilerOptions = ""; } getCompilerProperties().setRobocodeVersion(ContainerBase.getComponent(IVersionManagerBase.class).getVersion()); getCompilerProperties().setCompilerBinary(compilerBinary); getCompilerProperties().setCompilerOptions(compilerOptions); getCompilerProperties().setCompilerClasspath(COMPILER_CLASSPATH); saveCompilerProperties(); console.scrollToBottom(); console.getOkButton().setEnabled(true); return compilerOK; }
public boolean configureCompiler(RobocodeEditor editor) { ConsoleDialog console = new ConsoleDialog(editor, "Setting up compiler", false); console.setSize(500, 400); console.getOkButton().setEnabled(false); console.setText("Please wait while Robocode sets up a compiler for you...\n\n"); WindowUtil.centerShow(editor, console); console.append("Setting up compiler\n"); console.append("Java home is " + System.getProperty("java.home") + "\n\n"); String compilerName = "Java Compiler (javac)"; String compilerBinary = "javac"; String compilerOptions = "-deprecation -g -source 1.5 -encoding UTF-8"; boolean javacOK = testCompiler(compilerName, compilerBinary, console); boolean ecjOK = false; if (javacOK) { int rc = JOptionPane.showConfirmDialog(editor, "Robocode has found a working javac (Java Compiler) on this system.\nWould you like to use it?\n" + "(If you click No, Robocode will use the build-in Eclipse Compiler for Java (ECJ))", "Confirm javac", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (rc == JOptionPane.NO_OPTION) { javacOK = false; } } if (!javacOK) { compilerName = "Eclipse Compiler for Java (ECJ)"; compilerBinary = "java -cp compilers/ecj.jar org.eclipse.jdt.internal.compiler.batch.Main"; ecjOK = testCompiler("Eclipse Compiler for Java (ECJ)", compilerBinary, console); } boolean compilerOK = javacOK || ecjOK; if (compilerOK) { console.append("\nCompiler has been set up successfully.\nClick OK to continue.\n"); } else { final String errorText = "Could not set up a working compiler for Robocode.\n" + "Please consult the console window for errors.\n\n" + "For help with this, please post to Help forum here:\n" + "http://sourceforge.net/projects/robocode/forums/forum/116459"; console.append("\nUnable to set up a working compiler for Robocode.\n"); JOptionPane.showMessageDialog(editor, errorText, "Error", JOptionPane.ERROR_MESSAGE); compilerBinary = ""; compilerOptions = ""; } getCompilerProperties().setRobocodeVersion(ContainerBase.getComponent(IVersionManagerBase.class).getVersion()); getCompilerProperties().setCompilerBinary(compilerBinary); getCompilerProperties().setCompilerOptions(compilerOptions); getCompilerProperties().setCompilerClasspath(COMPILER_CLASSPATH); saveCompilerProperties(); console.scrollToBottom(); console.getOkButton().setEnabled(true); return compilerOK; }
diff --git a/javafx.source/src/org/netbeans/api/javafx/source/TreeUtilities.java b/javafx.source/src/org/netbeans/api/javafx/source/TreeUtilities.java index 2b56bfae..ebbe14ce 100644 --- a/javafx.source/src/org/netbeans/api/javafx/source/TreeUtilities.java +++ b/javafx.source/src/org/netbeans/api/javafx/source/TreeUtilities.java @@ -1,506 +1,506 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2008 Sun Microsystems, Inc. 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 * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. 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 * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2008 Sun * Microsystems, Inc. All Rights Reserved. * * 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 do not 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.netbeans.api.javafx.source; import com.sun.javafx.api.tree.ExpressionTree; import com.sun.javafx.api.tree.JavaFXTreePath; import com.sun.javafx.api.tree.SyntheticTree.SynthType; import com.sun.javafx.api.tree.Tree; import com.sun.javafx.api.tree.JavaFXTreePathScanner; import com.sun.javafx.api.tree.Scope; import com.sun.javafx.api.tree.SourcePositions; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javafx.api.JavafxcScope; import com.sun.tools.javafx.comp.JavafxAttrContext; import com.sun.tools.javafx.comp.JavafxEnv; import com.sun.tools.javafx.comp.JavafxResolve; import com.sun.tools.javafx.tree.JFXBreak; import com.sun.tools.javafx.tree.JFXContinue; import com.sun.tools.javafx.tree.JFXTree; import com.sun.tools.javafx.tree.JavafxPretty; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.Writer; import java.util.Collections; import java.util.Random; import org.netbeans.api.javafx.lexer.JFXTokenId; import java.util.logging.Level; import java.util.logging.Logger; import javax.lang.model.element.Element; import javax.lang.model.type.TypeMirror; import javax.swing.text.Document; import org.netbeans.api.javafx.source.JavaFXSource.Phase; import org.netbeans.api.lexer.TokenHierarchy; import org.netbeans.api.lexer.TokenSequence; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileSystem; import org.openide.filesystems.FileUtil; /** * * @author Jan Lahoda, Dusan Balek, Tomas Zezula */ public final class TreeUtilities { private static final Logger logger = Logger.getLogger(TreeUtilities.class.getName()); private static final boolean LOGGABLE = logger.isLoggable(Level.FINE); private final CompilationInfo info; // private final CommentHandlerService handler; /** Creates a new instance of CommentUtilities */ public TreeUtilities(final CompilationInfo info) { assert info != null; this.info = info; // this.handler = CommentHandlerService.instance(info.impl.getJavacTask().getContext()); } /** * Returns whether or not the given tree is synthetic - generated by the parser. * Please note that this method does not check trees transitively - a child of a syntetic tree * may be considered non-syntetic. * @return true if the given tree is synthetic, false otherwise */ public boolean isSynthetic(JavaFXTreePath path) { if (path == null) { if (LOGGABLE) log("isSynthetic invoked with null argument"); return false; } final Tree leaf = path.getLeaf(); if (leaf instanceof JFXTree) { JFXTree fxLeaf = (JFXTree)leaf; SynthType type = fxLeaf.getGenType(); return SynthType.SYNTHETIC.equals(type); } if (LOGGABLE) log("isSynthetic returning false because the leaf is not JFXTree."); return false; } /**Returns list of comments attached to a given tree. Can return either * preceding or trailing comments. * * @param tree for which comments should be returned * @param preceding true if preceding comments should be returned, false if trailing comments should be returned. * @return list of preceding/trailing comments attached to the given tree */ // public List<Comment> getComments(Tree tree, boolean preceding) { // CommentSetImpl set = handler.getComments(tree); // // if (!set.areCommentsMapped()) { // boolean assertsEnabled = false; // boolean automap = true; // // assert assertsEnabled = true; // // if (assertsEnabled) { // TreePath tp = TreePath.getPath(info.getCompilationUnit(), tree); // // if (tp == null) { // Logger.getLogger(TreeUtilities.class.getName()).log(Level.WARNING, "Comment automap requested for Tree not from the root compilation info. Please, make sure to call GeneratorUtilities.importComments before Treeutilities.getComments. Tree: {0}", tree); // Logger.getLogger(TreeUtilities.class.getName()).log(Level.WARNING, "Caller", new Exception()); // automap = false; // } // } // // if (automap) { // try { // TokenSequence<JFXTokenId> seq = ((SourceFileObject) info.getCompilationUnit().getSourceFile()).getTokenHierarchy().tokenSequence(JFXTokenId.language()); // new TranslateIdentifier(info, true, false, seq).translate(tree); // } catch (IOException ex) { // Exceptions.printStackTrace(ex); // } // } // } // // List<Comment> comments = preceding ? set.getPrecedingComments() : set.getTrailingComments(); // // return Collections.unmodifiableList(comments); // } public JavaFXTreePath pathFor(int pos) { return pathFor(new JavaFXTreePath(info.getCompilationUnit()), pos); } /*XXX: dbalek */ public JavaFXTreePath pathFor(JavaFXTreePath path, int pos) { return pathFor(path, pos, info.getTrees().getSourcePositions()); } /*XXX: dbalek */ public JavaFXTreePath pathFor(JavaFXTreePath path, int pos, SourcePositions sourcePositions) { if (info == null || path == null || sourcePositions == null) throw new IllegalArgumentException(); class Result extends Error { JavaFXTreePath path; Result(JavaFXTreePath path) { this.path = path; } } class PathFinder extends JavaFXTreePathScanner<Void,Void> { private int pos; private SourcePositions sourcePositions; private PathFinder(int pos, SourcePositions sourcePositions) { this.pos = pos; this.sourcePositions = sourcePositions; } @Override public Void scan(Tree tree, Void p) { if (tree != null) { super.scan(tree, p); long start = sourcePositions.getStartPosition(getCurrentPath().getCompilationUnit(), tree); long end = sourcePositions.getEndPosition(getCurrentPath().getCompilationUnit(), tree); - if (start != -1 && start < pos && end >= pos) { + if (start != -1 && start <= pos && end > pos) { JavaFXTreePath tp = new JavaFXTreePath(getCurrentPath(), tree); boolean isSynteticMainBlock = isSynthetic(tp); // we don't want to return the syntetic main block as the result if (tree.getJavaFXKind() == Tree.JavaFXKind.BLOCK_EXPRESSION) { JavaFXTreePath parentPath = tp.getParentPath(); if (parentPath != null) { JavaFXTreePath grandParentPath = parentPath.getParentPath(); if (grandParentPath != null) { Tree grandParent = grandParentPath.getLeaf(); if (grandParent.getJavaFXKind() == Tree.JavaFXKind.FUNCTION_DEFINITION && isSynthetic(grandParentPath)) { isSynteticMainBlock = true; } } } } if (tree.getJavaFXKind() == Tree.JavaFXKind.FUNCTION_VALUE) { JavaFXTreePath parentPath = tp.getParentPath(); if (parentPath != null) { Tree parent = parentPath.getLeaf(); if (parent.getJavaFXKind() == Tree.JavaFXKind.FUNCTION_DEFINITION && isSynthetic(parentPath)) { isSynteticMainBlock = true; } } } if (!isSynteticMainBlock) { throw new Result(new JavaFXTreePath(getCurrentPath(), tree)); } } else { if ((start == -1) || (end == -1)) { if (!isSynthetic(getCurrentPath())) { // here we might have a problem if (LOGGABLE) { logger.finest("SCAN: Cannot determine start and end for: " + treeToString(info, tree)); } } } } } return null; } } try { new PathFinder(pos, sourcePositions).scan(path, null); } catch (Result result) { path = result.path; } if (path.getLeaf() == path.getCompilationUnit()) { log("pathFor returning compilation unit for position: " + pos); return path; } int start = (int)sourcePositions.getStartPosition(info.getCompilationUnit(), path.getLeaf()); int end = (int)sourcePositions.getEndPosition(info.getCompilationUnit(), path.getLeaf()); while (start == -1 || pos < start || pos > end) { if (LOGGABLE) { logger.finer("pathFor moving to parent: " + treeToString(info, path.getLeaf())); } path = path.getParentPath(); if (LOGGABLE) { logger.finer("pathFor moved to parent: " + treeToString(info, path.getLeaf())); } if (path.getLeaf() == path.getCompilationUnit()) { break; } start = (int)sourcePositions.getStartPosition(info.getCompilationUnit(), path.getLeaf()); end = (int)sourcePositions.getEndPosition(info.getCompilationUnit(), path.getLeaf()); } if (LOGGABLE) { log("pathFor(pos: " + pos + ") returning: " + treeToString(info, path.getLeaf())); } return path; } /**Computes {@link Scope} for the given position. */ public JavafxcScope scopeFor(int pos) { JavaFXTreePath path = pathFor(pos); JavafxcScope scope = getScope(path); return scope; } public JavafxcScope getScope(JavaFXTreePath p) { JavafxcScope scope = null; while ((p != null) && (scope == null)) { try { scope = info.getTrees().getScope(p); } catch (Exception ex) { if (logger.isLoggable(Level.FINEST)) { logger.log(Level.FINEST, " getScope failed on " + p, ex); } p = p.getParentPath(); } } return scope; } /**Returns tokens for a given tree. */ public TokenSequence<JFXTokenId> tokensFor(Tree tree) { return tokensFor(tree, info.getTrees().getSourcePositions()); } /**Returns tokens for a given tree. Uses specified {@link SourcePositions}. */ public TokenSequence<JFXTokenId> tokensFor(Tree tree, SourcePositions sourcePositions) { int start = (int)sourcePositions.getStartPosition(info.getCompilationUnit(), tree); int end = (int)sourcePositions.getEndPosition(info.getCompilationUnit(), tree); if ((start == -1) || (end == -1)) { throw new RuntimeException("RE Cannot determine start and end for: " + treeToString(info, tree)); } TokenSequence<JFXTokenId> t = ((TokenHierarchy<?>)info.getTokenHierarchy()).tokenSequence(JFXTokenId.language()); if (t == null) { throw new RuntimeException("RE SDid not get a token sequence."); } return t.subSequence(start, end); } private static String treeToString(CompilationInfo info, Tree t) { Tree.JavaFXKind k = null; StringWriter s = new StringWriter(); try { new JavafxPretty(s, false).printExpr((JFXTree)t); } catch (Exception e) { if (LOGGABLE) logger.log(Level.FINE, "Unable to pretty print " + t.getJavaFXKind(), e); } k = t.getJavaFXKind(); String res = k.toString(); SourcePositions pos = info.getTrees().getSourcePositions(); res = res + '[' + pos.getStartPosition(info.getCompilationUnit(), t) + ',' + pos.getEndPosition(info.getCompilationUnit(), t) + "]:" + s.toString(); return res; } public ExpressionTree getBreakContinueTarget(JavaFXTreePath breakOrContinue) throws IllegalArgumentException { if (info.getPhase().lessThan(Phase.ANALYZED)) throw new IllegalArgumentException("Not in correct Phase. Required: Phase.RESOLVED, got: Phase." + info.getPhase().toString()); Tree leaf = breakOrContinue.getLeaf(); switch (leaf.getJavaFXKind()) { case BREAK: return (ExpressionTree) ((JFXBreak) leaf).target; case CONTINUE: ExpressionTree target = (ExpressionTree) ((JFXContinue) leaf).target; if (target == null) return null; // always true with current grammar //if (((JFXContinue) leaf).label == null) return target; default: throw new IllegalArgumentException("Unsupported kind: " + leaf.getJavaFXKind()); } } /** * Parses and analyzes given expression. * @param expr String expression to be parsed and analyzed * @param pos position in the source where the expression would occur * @return parsed expression tree or <code>null</code> if it was not * successfull */ public ExpressionTree parseExpression(String expr, int pos) { if (LOGGABLE) log("parseExpression pos= " + pos + " : " + expr); try { Document d = info.getJavaFXSource().getDocument(); String start = d.getText(0, pos); if (LOGGABLE) log(" start = " + start); String end = d.getText(pos, d.getLength()-pos); if (LOGGABLE) log(" end = " + end); FileSystem fs = FileUtil.createMemoryFileSystem(); final FileObject fo = fs.getRoot().createData("tmp" + (new Random().nextLong()) + ".fx"); Writer w = new OutputStreamWriter(fo.getOutputStream()); w.write(start); w.write("\n" + expr+"\n"); w.write(end); w.close(); if (LOGGABLE) log(" source written to " + fo); ClasspathInfo cp = ClasspathInfo.create(info.getFileObject()); JavaFXSource s = JavaFXSource.create(cp, Collections.singleton(fo)); if (LOGGABLE) log(" jfxsource obtained " + s); CompilationInfoImpl ci = new CompilationInfoImpl(s); s.moveToPhase(Phase.ANALYZED, ci, false); CompilationController cc = new CompilationController(ci); JavaFXTreePath p = cc.getTreeUtilities().pathFor(pos+2); if (p == null) { if (LOGGABLE) log(" path for returned null"); return null; } SourcePositions sp = cc.getTrees().getSourcePositions(); if (LOGGABLE) log(p.getLeaf().getClass().getName() + " p = " + p.getLeaf()); // first loop will try to find our expression while ((p != null) && (! (p.getLeaf() instanceof ExpressionTree))) { if (LOGGABLE) log(p.getLeaf().getClass().getName() + " p (2) = " + p.getLeaf()); p = p.getParentPath(); } if (p == null) { if (LOGGABLE) log(" ExpressionTree not found! Returning null"); return null; } // the second while loop will try to find as big expression as possible JavaFXTreePath pp = p.getParentPath(); if (LOGGABLE && pp != null) { log(pp.getLeaf().getClass().getName() + " pp = " + pp.getLeaf()); log(" start == " + sp.getStartPosition(cc.getCompilationUnit(),pp.getLeaf())); log(" end == " + sp.getEndPosition(cc.getCompilationUnit(),pp.getLeaf())); log(" pos == " + pos); log(" pos+length == " + (pos+expr.length())); log(" (pp.getLeaf() instanceof ExpressionTree)" + (pp.getLeaf() instanceof ExpressionTree)); } while ((pp != null) && ((pp.getLeaf() instanceof ExpressionTree)) && (sp.getStartPosition(cc.getCompilationUnit(),pp.getLeaf())>=pos) && (sp.getEndPosition(cc.getCompilationUnit(),pp.getLeaf())<=(pos+expr.length()))) { if (LOGGABLE) log(pp.getLeaf().getClass().getName() + " p (3) = " + pp.getLeaf()); p = pp; pp = pp.getParentPath(); if (LOGGABLE) { log(pp.getLeaf().getClass().getName() + " pp = " + pp.getLeaf()); log(" start == " + sp.getStartPosition(cc.getCompilationUnit(),pp.getLeaf())); log(" end == " + sp.getEndPosition(cc.getCompilationUnit(),pp.getLeaf())); log(" (pp.getLeaf() instanceof ExpressionTree)" + (pp.getLeaf() instanceof ExpressionTree)); } } if (LOGGABLE) log(p.getLeaf().getClass().getName() + " p (4) = " + p.getLeaf()); return (ExpressionTree)p.getLeaf(); } catch (Exception x) { logger.log(Level.FINE, "Exception during parseExpression", x); } return null; } /** * @param scope * @param member * @param type * @return true if the given member of the given type is accessible in the * given scope */ public boolean isAccessible(Scope scope, Element member, TypeMirror type) { if (LOGGABLE) { log("isAccessible scope == " + scope); log(" member == " + member); log(" type == " + type); } if (scope instanceof JavafxcScope && member instanceof Symbol && type instanceof Type) { JavafxResolve resolve = JavafxResolve.instance(info.impl.getContext()); if (LOGGABLE) log(" resolve == " + resolve); Object env = ((JavafxcScope) scope).getEnv(); JavafxEnv<JavafxAttrContext> fxEnv = (JavafxEnv<JavafxAttrContext>) env; if (LOGGABLE) log(" fxEnv == " + fxEnv); boolean res = resolve.isAccessible(fxEnv, (Type) type, (Symbol) member); if (LOGGABLE) log(" returning " + res); return res; } else { if (LOGGABLE) log(" returning FALSE from the else branch"); return false; } } /** * * @param scope * @param type * @return true if the class denoted by the type element is accessible * in the given scope */ public boolean isAccessible(Scope scope, Element type) { if (LOGGABLE) { log("isAccessible scope == " + scope); log(" type == " + type); } if (scope instanceof JavafxcScope && type instanceof Symbol.TypeSymbol) { JavafxResolve resolve = JavafxResolve.instance(info.impl.getContext()); if (LOGGABLE) log(" resolve == " + resolve); Object env = ((JavafxcScope) scope).getEnv(); JavafxEnv<JavafxAttrContext> fxEnv = (JavafxEnv<JavafxAttrContext>) env; if (LOGGABLE) log(" fxEnv == " + fxEnv); boolean res = resolve.isAccessible(fxEnv, (Symbol.TypeSymbol) type); if (LOGGABLE) log(" returning " + res); return res; } else { if (LOGGABLE) log(" returning FALSE from the else branch"); return false; } } /** * * @param scope * @return */ public boolean isStaticContext(Scope scope) { Object env = ((JavafxcScope) scope).getEnv(); JavafxEnv<JavafxAttrContext> fxEnv = (JavafxEnv<JavafxAttrContext>) env; return JavafxResolve.isStatic(fxEnv); // return Resolve.isStatic(((JavafxcScope) scope).getEnv()); } private static void log(String s) { if (LOGGABLE) { logger.fine(s); } } }
true
true
public JavaFXTreePath pathFor(JavaFXTreePath path, int pos, SourcePositions sourcePositions) { if (info == null || path == null || sourcePositions == null) throw new IllegalArgumentException(); class Result extends Error { JavaFXTreePath path; Result(JavaFXTreePath path) { this.path = path; } } class PathFinder extends JavaFXTreePathScanner<Void,Void> { private int pos; private SourcePositions sourcePositions; private PathFinder(int pos, SourcePositions sourcePositions) { this.pos = pos; this.sourcePositions = sourcePositions; } @Override public Void scan(Tree tree, Void p) { if (tree != null) { super.scan(tree, p); long start = sourcePositions.getStartPosition(getCurrentPath().getCompilationUnit(), tree); long end = sourcePositions.getEndPosition(getCurrentPath().getCompilationUnit(), tree); if (start != -1 && start < pos && end >= pos) { JavaFXTreePath tp = new JavaFXTreePath(getCurrentPath(), tree); boolean isSynteticMainBlock = isSynthetic(tp); // we don't want to return the syntetic main block as the result if (tree.getJavaFXKind() == Tree.JavaFXKind.BLOCK_EXPRESSION) { JavaFXTreePath parentPath = tp.getParentPath(); if (parentPath != null) { JavaFXTreePath grandParentPath = parentPath.getParentPath(); if (grandParentPath != null) { Tree grandParent = grandParentPath.getLeaf(); if (grandParent.getJavaFXKind() == Tree.JavaFXKind.FUNCTION_DEFINITION && isSynthetic(grandParentPath)) { isSynteticMainBlock = true; } } } } if (tree.getJavaFXKind() == Tree.JavaFXKind.FUNCTION_VALUE) { JavaFXTreePath parentPath = tp.getParentPath(); if (parentPath != null) { Tree parent = parentPath.getLeaf(); if (parent.getJavaFXKind() == Tree.JavaFXKind.FUNCTION_DEFINITION && isSynthetic(parentPath)) { isSynteticMainBlock = true; } } } if (!isSynteticMainBlock) { throw new Result(new JavaFXTreePath(getCurrentPath(), tree)); } } else { if ((start == -1) || (end == -1)) { if (!isSynthetic(getCurrentPath())) { // here we might have a problem if (LOGGABLE) { logger.finest("SCAN: Cannot determine start and end for: " + treeToString(info, tree)); } } } } } return null; } } try { new PathFinder(pos, sourcePositions).scan(path, null); } catch (Result result) { path = result.path; } if (path.getLeaf() == path.getCompilationUnit()) { log("pathFor returning compilation unit for position: " + pos); return path; } int start = (int)sourcePositions.getStartPosition(info.getCompilationUnit(), path.getLeaf()); int end = (int)sourcePositions.getEndPosition(info.getCompilationUnit(), path.getLeaf()); while (start == -1 || pos < start || pos > end) { if (LOGGABLE) { logger.finer("pathFor moving to parent: " + treeToString(info, path.getLeaf())); } path = path.getParentPath(); if (LOGGABLE) { logger.finer("pathFor moved to parent: " + treeToString(info, path.getLeaf())); } if (path.getLeaf() == path.getCompilationUnit()) { break; } start = (int)sourcePositions.getStartPosition(info.getCompilationUnit(), path.getLeaf()); end = (int)sourcePositions.getEndPosition(info.getCompilationUnit(), path.getLeaf()); } if (LOGGABLE) { log("pathFor(pos: " + pos + ") returning: " + treeToString(info, path.getLeaf())); } return path; }
public JavaFXTreePath pathFor(JavaFXTreePath path, int pos, SourcePositions sourcePositions) { if (info == null || path == null || sourcePositions == null) throw new IllegalArgumentException(); class Result extends Error { JavaFXTreePath path; Result(JavaFXTreePath path) { this.path = path; } } class PathFinder extends JavaFXTreePathScanner<Void,Void> { private int pos; private SourcePositions sourcePositions; private PathFinder(int pos, SourcePositions sourcePositions) { this.pos = pos; this.sourcePositions = sourcePositions; } @Override public Void scan(Tree tree, Void p) { if (tree != null) { super.scan(tree, p); long start = sourcePositions.getStartPosition(getCurrentPath().getCompilationUnit(), tree); long end = sourcePositions.getEndPosition(getCurrentPath().getCompilationUnit(), tree); if (start != -1 && start <= pos && end > pos) { JavaFXTreePath tp = new JavaFXTreePath(getCurrentPath(), tree); boolean isSynteticMainBlock = isSynthetic(tp); // we don't want to return the syntetic main block as the result if (tree.getJavaFXKind() == Tree.JavaFXKind.BLOCK_EXPRESSION) { JavaFXTreePath parentPath = tp.getParentPath(); if (parentPath != null) { JavaFXTreePath grandParentPath = parentPath.getParentPath(); if (grandParentPath != null) { Tree grandParent = grandParentPath.getLeaf(); if (grandParent.getJavaFXKind() == Tree.JavaFXKind.FUNCTION_DEFINITION && isSynthetic(grandParentPath)) { isSynteticMainBlock = true; } } } } if (tree.getJavaFXKind() == Tree.JavaFXKind.FUNCTION_VALUE) { JavaFXTreePath parentPath = tp.getParentPath(); if (parentPath != null) { Tree parent = parentPath.getLeaf(); if (parent.getJavaFXKind() == Tree.JavaFXKind.FUNCTION_DEFINITION && isSynthetic(parentPath)) { isSynteticMainBlock = true; } } } if (!isSynteticMainBlock) { throw new Result(new JavaFXTreePath(getCurrentPath(), tree)); } } else { if ((start == -1) || (end == -1)) { if (!isSynthetic(getCurrentPath())) { // here we might have a problem if (LOGGABLE) { logger.finest("SCAN: Cannot determine start and end for: " + treeToString(info, tree)); } } } } } return null; } } try { new PathFinder(pos, sourcePositions).scan(path, null); } catch (Result result) { path = result.path; } if (path.getLeaf() == path.getCompilationUnit()) { log("pathFor returning compilation unit for position: " + pos); return path; } int start = (int)sourcePositions.getStartPosition(info.getCompilationUnit(), path.getLeaf()); int end = (int)sourcePositions.getEndPosition(info.getCompilationUnit(), path.getLeaf()); while (start == -1 || pos < start || pos > end) { if (LOGGABLE) { logger.finer("pathFor moving to parent: " + treeToString(info, path.getLeaf())); } path = path.getParentPath(); if (LOGGABLE) { logger.finer("pathFor moved to parent: " + treeToString(info, path.getLeaf())); } if (path.getLeaf() == path.getCompilationUnit()) { break; } start = (int)sourcePositions.getStartPosition(info.getCompilationUnit(), path.getLeaf()); end = (int)sourcePositions.getEndPosition(info.getCompilationUnit(), path.getLeaf()); } if (LOGGABLE) { log("pathFor(pos: " + pos + ") returning: " + treeToString(info, path.getLeaf())); } return path; }
diff --git a/CapstoneProject/src/java/capstone/server/GameRecorder.java b/CapstoneProject/src/java/capstone/server/GameRecorder.java index 8a99b4f..bddfab1 100644 --- a/CapstoneProject/src/java/capstone/server/GameRecorder.java +++ b/CapstoneProject/src/java/capstone/server/GameRecorder.java @@ -1,36 +1,39 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package capstone.server; import capstone.game.GameSession; import capstone.player.GameRecord; import java.util.List; import java.util.Map; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.ConcurrentHashMap; public class GameRecorder { private static Map<String, List<String>> gameIDs = new ConcurrentHashMap<String, List<String>>(); //PlayerName -> GameID private static Map<String, GameRecord> players = new ConcurrentHashMap<String, GameRecord>(); //GameID -> GameRecord public static void record(String gameID, String player, String coords) { if (!gameIDs.containsKey(player)) { gameIDs.put(player, new ArrayList<String>()); } if (gameIDs.get(player).indexOf(gameID) == -1) { GameRecord game = new GameRecord(); game.putCoords(coords); - players.put(gameID, game); + if (!players.get(gameID).equals(game)) + { + players.put(gameID, game); + } gameIDs.get(player).add(gameID); } else { players.get(gameID).putCoords(coords); } } }
true
true
public static void record(String gameID, String player, String coords) { if (!gameIDs.containsKey(player)) { gameIDs.put(player, new ArrayList<String>()); } if (gameIDs.get(player).indexOf(gameID) == -1) { GameRecord game = new GameRecord(); game.putCoords(coords); players.put(gameID, game); gameIDs.get(player).add(gameID); } else { players.get(gameID).putCoords(coords); } }
public static void record(String gameID, String player, String coords) { if (!gameIDs.containsKey(player)) { gameIDs.put(player, new ArrayList<String>()); } if (gameIDs.get(player).indexOf(gameID) == -1) { GameRecord game = new GameRecord(); game.putCoords(coords); if (!players.get(gameID).equals(game)) { players.put(gameID, game); } gameIDs.get(player).add(gameID); } else { players.get(gameID).putCoords(coords); } }
diff --git a/applet/src/DynVizGraph.java b/applet/src/DynVizGraph.java index 6a2e417..572780c 100644 --- a/applet/src/DynVizGraph.java +++ b/applet/src/DynVizGraph.java @@ -1,348 +1,349 @@ import javax.swing.JApplet; import javax.swing.JPanel; import javax.swing.border.LineBorder; import javax.swing.SwingUtilities; import java.awt.Color; import java.awt.Dimension; import java.awt.Container; import java.awt.GridLayout; import java.awt.GraphicsEnvironment; import java.awt.GraphicsDevice; import java.awt.GraphicsConfiguration; import java.awt.Transparency; /** * * @author gmcwhirt */ public class DynVizGraph extends JApplet { private int chartWidth = 210; // The width of the canvas panel private int chartHeight = 210; // The height of the canvas panel private int chartPadding = 5; private CanvasPanel BRChart; // JPanel canvas for graphics drawing private CanvasPanel DtRChart; private CanvasPanel CtRChart; private int payoffA; private int payoffB; private int payoffC; private int payoffD; private Thread BRThread; private Thread DtRThread; private Thread CtRThread; @Override public void init(){ try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { goBabyGo(); } }); } catch (Exception e) { System.err.println("goBabyGo failed."); e.printStackTrace(); } } public void goBabyGo(){ Container c = getContentPane(); setPreferredSize(new Dimension(chartWidth * 3 + 2, chartHeight)); c.setPreferredSize(new Dimension(chartWidth * 3 + 2, chartHeight)); JPanel panel = new JPanel(new GridLayout(1,3)); BRChart = new CanvasPanel(chartWidth, chartHeight, chartPadding); DtRChart = new CanvasPanel(chartWidth, chartHeight, chartPadding); CtRChart = new CanvasPanel(chartWidth, chartHeight, chartPadding); panel.setBorder(new LineBorder(Color.LIGHT_GRAY)); panel.setPreferredSize(new Dimension(chartWidth * 3 + 2, chartHeight)); BRChart.setPreferredSize(new Dimension(chartWidth, chartHeight)); DtRChart.setPreferredSize(new Dimension(chartWidth, chartHeight)); CtRChart.setPreferredSize(new Dimension(chartWidth, chartHeight)); panel.add(BRChart); panel.add(DtRChart); panel.add(CtRChart); c.add(panel); try { String pAS = getParameter("A"); payoffA = Integer.parseInt(pAS); } catch (NumberFormatException e) { payoffA = 0; } catch (NullPointerException e) { payoffA = 0; } try { String pBS = getParameter("B"); payoffB = Integer.parseInt(pBS); } catch (NumberFormatException e) { payoffB = 0; } catch (NullPointerException e) { payoffB = 0; } try { String pCS = getParameter("C"); payoffC = Integer.parseInt(pCS); } catch (NumberFormatException e) { payoffC = 0; } catch (NullPointerException e) { payoffC = 0; } try { String pDS = getParameter("D"); payoffD = Integer.parseInt(pDS); } catch (NumberFormatException e) { payoffD = 0; } catch (NullPointerException e) { payoffD = 0; } BRThread = new Thread(new BRGraphGenerator(payoffA, payoffB, payoffC, payoffD, BRChart.getRealWidth(), BRChart.getRealHeight())); DtRThread = new Thread(new DtRGraphGenerator(payoffA, payoffB, payoffC, payoffD, DtRChart.getRealWidth(), DtRChart.getRealHeight())); CtRThread = new Thread(new CtRGraphGenerator(payoffA, payoffB, payoffC, payoffD, CtRChart.getRealWidth(), CtRChart.getRealHeight())); } @Override public void start(){ BRThread.start(); DtRThread.start(); CtRThread.start(); } @Override public void stop(){ BRThread.interrupt(); DtRThread.interrupt(); CtRThread.interrupt(); } private void BRGraphInfo(CanvasImage ci){ BRChart.setCImage(ci); BRChart.flush(); } private void DtRGraphInfo(CanvasImage ci){ DtRChart.setCImage(ci); DtRChart.flush(); } private void CtRGraphInfo(CanvasImage ci){ CtRChart.setCImage(ci); CtRChart.flush(); } class BRGraphGenerator implements Runnable { private CanvasImage ci; private int A, B, C, D; public BRGraphGenerator(int Ap, int Bp, int Cp, int Dp, int width, int height){ A = Ap; B = Bp; C = Cp; D = Dp; GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice gs = ge.getDefaultScreenDevice(); GraphicsConfiguration gc = gs.getDefaultConfiguration(); ci = new CanvasImage(gc.createCompatibleImage(width, height, Transparency.BITMASK)); BRGraphInfo(ci); } private float _lrespy(){ if (A + C > 0){ return 1f; } else if (A + C < 0){ return 0f; } else if (0 <= A) { return 1f; } else { return 0f; } } private float _lrespx(){ if (B + D > 0){ return 0f; } else if (B + D < 0){ return 1f; } else if (0 >= D){ return 0f; } else { return 1f; } } @Override public void run(){ //draw stuff float lrespx = _lrespx(); float lrespy = _lrespy(); float qlim = (float)A / (float)(A + C); float plim = (float)D / (float)(B + D); int dots = 11; //effectively 10 for (int x = 0; x <= dots; x++){ for (int y = 0; y <= dots; y++){ float xf = (float)x / (float)dots; float yf = (float)y / (float)dots; float xxf; float yyf; if (xf < qlim || Float.isNaN(qlim)){ yyf = lrespy; } else if (xf > qlim){ yyf = 1f - lrespy; } else { yyf = yf; } if (yf < plim || Float.isNaN(plim)){ xxf = lrespx; } else if (yf > qlim){ xxf = 1f - lrespx; } else { xxf = xf; } ci.drawArrow(xf, yf, xxf, yyf, Color.green, Color.black); ci.drawLine(xf, yf, xf, yf, Color.black); } } if (A + C > 0){ if (qlim <= 1f && qlim >= 0f){ ci.drawLine(0f, 1f, qlim, 1f, Color.red); ci.drawLine(qlim, 0f, 1f, 0f, Color.red); ci.drawLine(qlim, 0f, qlim, 1f, Color.red); } else if (qlim > 1f) { //play this ci.drawLine(0f, 1f, 1f, 1f, Color.red); } else { //play other ci.drawLine(0f, 0f, 1f, 0f, Color.red); } } else if (A + C < 0){ if (qlim <= 1f && qlim >= 0f){ ci.drawLine(0f, 0f, qlim, 0f, Color.red); ci.drawLine(qlim, 1f, 1f, 1f, Color.red); ci.drawLine(qlim, 0f, qlim, 1f, Color.red); } else if (qlim > 1f) { //play other ci.drawLine(0f, 0f, 1f, 0f, Color.red); } else { //play this ci.drawLine(0f, 1f, 1f, 1f, Color.red); } } else if (0 <= A) { //play this ci.drawLine(0f, 1f, 1f, 1f, Color.red); } else { //play other ci.drawLine(0f, 0f, 1f, 0f, Color.red); } if (B + D > 0){ if (plim >= 0f && plim <= 1f){ ci.drawLine(0f, 1f, 0f, plim, Color.blue); ci.drawLine(1f, plim, 1f, 0f, Color.blue); ci.drawLine(0f, plim, 1f, plim); } else if (plim > 1f){ //play other ci.drawLine(1f, 1f, 1f, 0f, Color.blue); } else { //play this ci.drawLine(0f, 1f, 0f, 0f, Color.blue); } } else if (B + D < 0){ if (plim >= 0f && plim <= 1f){ ci.drawLine(0f, 0f, 0f, plim, Color.blue); ci.drawLine(1f, plim, 1f, 1f, Color.blue); ci.drawLine(0f, plim, 1f, plim, Color.blue); } else if (plim > 1f) { //play this ci.drawLine(0f, 1f, 0f, 0f, Color.blue); } else { //play other ci.drawLine(1f, 1f, 1f, 0f, Color.blue); } } else if (0 >= D) { //play this ci.drawLine(0f, 1f, 0f, 0f, Color.blue); } else { //play other ci.drawLine(1f, 1f, 1f, 0f, Color.blue); } ci.flush(); + BRGraphInfo(ci); } } class DtRGraphGenerator implements Runnable { private CanvasImage ci; private int A, B, C, D; public DtRGraphGenerator(int Ap, int Bp, int Cp, int Dp, int width, int height){ A = Ap; B = Bp; C = Cp; D = Dp; GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice gs = ge.getDefaultScreenDevice(); GraphicsConfiguration gc = gs.getDefaultConfiguration(); ci = new CanvasImage(gc.createCompatibleImage(width, height, Transparency.BITMASK)); DtRGraphInfo(ci); } @Override public void run(){ //todo } } class CtRGraphGenerator implements Runnable { private CanvasImage ci; private int A, B, C, D; public CtRGraphGenerator(int Ap, int Bp, int Cp, int Dp, int width, int height){ A = Ap; B = Bp; C = Cp; D = Dp; GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice gs = ge.getDefaultScreenDevice(); GraphicsConfiguration gc = gs.getDefaultConfiguration(); ci = new CanvasImage(gc.createCompatibleImage(width, height, Transparency.BITMASK)); CtRGraphInfo(ci); } @Override public void run(){ //todo } } }
true
true
public void run(){ //draw stuff float lrespx = _lrespx(); float lrespy = _lrespy(); float qlim = (float)A / (float)(A + C); float plim = (float)D / (float)(B + D); int dots = 11; //effectively 10 for (int x = 0; x <= dots; x++){ for (int y = 0; y <= dots; y++){ float xf = (float)x / (float)dots; float yf = (float)y / (float)dots; float xxf; float yyf; if (xf < qlim || Float.isNaN(qlim)){ yyf = lrespy; } else if (xf > qlim){ yyf = 1f - lrespy; } else { yyf = yf; } if (yf < plim || Float.isNaN(plim)){ xxf = lrespx; } else if (yf > qlim){ xxf = 1f - lrespx; } else { xxf = xf; } ci.drawArrow(xf, yf, xxf, yyf, Color.green, Color.black); ci.drawLine(xf, yf, xf, yf, Color.black); } } if (A + C > 0){ if (qlim <= 1f && qlim >= 0f){ ci.drawLine(0f, 1f, qlim, 1f, Color.red); ci.drawLine(qlim, 0f, 1f, 0f, Color.red); ci.drawLine(qlim, 0f, qlim, 1f, Color.red); } else if (qlim > 1f) { //play this ci.drawLine(0f, 1f, 1f, 1f, Color.red); } else { //play other ci.drawLine(0f, 0f, 1f, 0f, Color.red); } } else if (A + C < 0){ if (qlim <= 1f && qlim >= 0f){ ci.drawLine(0f, 0f, qlim, 0f, Color.red); ci.drawLine(qlim, 1f, 1f, 1f, Color.red); ci.drawLine(qlim, 0f, qlim, 1f, Color.red); } else if (qlim > 1f) { //play other ci.drawLine(0f, 0f, 1f, 0f, Color.red); } else { //play this ci.drawLine(0f, 1f, 1f, 1f, Color.red); } } else if (0 <= A) { //play this ci.drawLine(0f, 1f, 1f, 1f, Color.red); } else { //play other ci.drawLine(0f, 0f, 1f, 0f, Color.red); } if (B + D > 0){ if (plim >= 0f && plim <= 1f){ ci.drawLine(0f, 1f, 0f, plim, Color.blue); ci.drawLine(1f, plim, 1f, 0f, Color.blue); ci.drawLine(0f, plim, 1f, plim); } else if (plim > 1f){ //play other ci.drawLine(1f, 1f, 1f, 0f, Color.blue); } else { //play this ci.drawLine(0f, 1f, 0f, 0f, Color.blue); } } else if (B + D < 0){ if (plim >= 0f && plim <= 1f){ ci.drawLine(0f, 0f, 0f, plim, Color.blue); ci.drawLine(1f, plim, 1f, 1f, Color.blue); ci.drawLine(0f, plim, 1f, plim, Color.blue); } else if (plim > 1f) { //play this ci.drawLine(0f, 1f, 0f, 0f, Color.blue); } else { //play other ci.drawLine(1f, 1f, 1f, 0f, Color.blue); } } else if (0 >= D) { //play this ci.drawLine(0f, 1f, 0f, 0f, Color.blue); } else { //play other ci.drawLine(1f, 1f, 1f, 0f, Color.blue); } ci.flush(); }
public void run(){ //draw stuff float lrespx = _lrespx(); float lrespy = _lrespy(); float qlim = (float)A / (float)(A + C); float plim = (float)D / (float)(B + D); int dots = 11; //effectively 10 for (int x = 0; x <= dots; x++){ for (int y = 0; y <= dots; y++){ float xf = (float)x / (float)dots; float yf = (float)y / (float)dots; float xxf; float yyf; if (xf < qlim || Float.isNaN(qlim)){ yyf = lrespy; } else if (xf > qlim){ yyf = 1f - lrespy; } else { yyf = yf; } if (yf < plim || Float.isNaN(plim)){ xxf = lrespx; } else if (yf > qlim){ xxf = 1f - lrespx; } else { xxf = xf; } ci.drawArrow(xf, yf, xxf, yyf, Color.green, Color.black); ci.drawLine(xf, yf, xf, yf, Color.black); } } if (A + C > 0){ if (qlim <= 1f && qlim >= 0f){ ci.drawLine(0f, 1f, qlim, 1f, Color.red); ci.drawLine(qlim, 0f, 1f, 0f, Color.red); ci.drawLine(qlim, 0f, qlim, 1f, Color.red); } else if (qlim > 1f) { //play this ci.drawLine(0f, 1f, 1f, 1f, Color.red); } else { //play other ci.drawLine(0f, 0f, 1f, 0f, Color.red); } } else if (A + C < 0){ if (qlim <= 1f && qlim >= 0f){ ci.drawLine(0f, 0f, qlim, 0f, Color.red); ci.drawLine(qlim, 1f, 1f, 1f, Color.red); ci.drawLine(qlim, 0f, qlim, 1f, Color.red); } else if (qlim > 1f) { //play other ci.drawLine(0f, 0f, 1f, 0f, Color.red); } else { //play this ci.drawLine(0f, 1f, 1f, 1f, Color.red); } } else if (0 <= A) { //play this ci.drawLine(0f, 1f, 1f, 1f, Color.red); } else { //play other ci.drawLine(0f, 0f, 1f, 0f, Color.red); } if (B + D > 0){ if (plim >= 0f && plim <= 1f){ ci.drawLine(0f, 1f, 0f, plim, Color.blue); ci.drawLine(1f, plim, 1f, 0f, Color.blue); ci.drawLine(0f, plim, 1f, plim); } else if (plim > 1f){ //play other ci.drawLine(1f, 1f, 1f, 0f, Color.blue); } else { //play this ci.drawLine(0f, 1f, 0f, 0f, Color.blue); } } else if (B + D < 0){ if (plim >= 0f && plim <= 1f){ ci.drawLine(0f, 0f, 0f, plim, Color.blue); ci.drawLine(1f, plim, 1f, 1f, Color.blue); ci.drawLine(0f, plim, 1f, plim, Color.blue); } else if (plim > 1f) { //play this ci.drawLine(0f, 1f, 0f, 0f, Color.blue); } else { //play other ci.drawLine(1f, 1f, 1f, 0f, Color.blue); } } else if (0 >= D) { //play this ci.drawLine(0f, 1f, 0f, 0f, Color.blue); } else { //play other ci.drawLine(1f, 1f, 1f, 0f, Color.blue); } ci.flush(); BRGraphInfo(ci); }
diff --git a/org.emftext.sdk.antlr3_4_0/src-sdk/org/stringtemplate/v4/NumberRenderer.java b/org.emftext.sdk.antlr3_4_0/src-sdk/org/stringtemplate/v4/NumberRenderer.java index 05b59de34..27e60e8ca 100644 --- a/org.emftext.sdk.antlr3_4_0/src-sdk/org/stringtemplate/v4/NumberRenderer.java +++ b/org.emftext.sdk.antlr3_4_0/src-sdk/org/stringtemplate/v4/NumberRenderer.java @@ -1,50 +1,52 @@ /* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * 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 name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 org.stringtemplate.v4; import java.util.Formatter; import java.util.Locale; /** Works with Byte, Short, Integer, Long, and BigInteger as well as * Float, Double, and BigDecimal. You pass in a format string suitable * for Formatter object: * * http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html * * For example, "%10d" emits a number as a decimal int padding to 10 char. * This can even do long to date conversions using the format string. */ public class NumberRenderer implements AttributeRenderer { public String toString(Object o, String formatString, Locale locale) { // o will be instanceof Number if ( formatString==null ) return o.toString(); Formatter f = new Formatter(locale); f.format(formatString, o); - return f.toString(); + String result = f.toString(); + f.close(); + return result; } }
true
true
public String toString(Object o, String formatString, Locale locale) { // o will be instanceof Number if ( formatString==null ) return o.toString(); Formatter f = new Formatter(locale); f.format(formatString, o); return f.toString(); }
public String toString(Object o, String formatString, Locale locale) { // o will be instanceof Number if ( formatString==null ) return o.toString(); Formatter f = new Formatter(locale); f.format(formatString, o); String result = f.toString(); f.close(); return result; }
diff --git a/org.emftext.sdk.concretesyntax.resource.cs/src/org/emftext/sdk/concretesyntax/resource/cs/postprocessing/AbstractPostProcessor.java b/org.emftext.sdk.concretesyntax.resource.cs/src/org/emftext/sdk/concretesyntax/resource/cs/postprocessing/AbstractPostProcessor.java index d4ffcfd21..c0d8e754a 100644 --- a/org.emftext.sdk.concretesyntax.resource.cs/src/org/emftext/sdk/concretesyntax/resource/cs/postprocessing/AbstractPostProcessor.java +++ b/org.emftext.sdk.concretesyntax.resource.cs/src/org/emftext/sdk/concretesyntax/resource/cs/postprocessing/AbstractPostProcessor.java @@ -1,149 +1,149 @@ /******************************************************************************* * Copyright (c) 2006-2011 * Software Technology Group, Dresden University of Technology * * 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: * Software Technology Group - TU Dresden, Germany * - initial API and implementation ******************************************************************************/ package org.emftext.sdk.concretesyntax.resource.cs.postprocessing; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.resource.Resource; import org.emftext.sdk.concretesyntax.CompleteTokenDefinition; import org.emftext.sdk.concretesyntax.ConcreteSyntax; import org.emftext.sdk.concretesyntax.QuotedTokenDefinition; import org.emftext.sdk.concretesyntax.resource.cs.ICsQuickFix; import org.emftext.sdk.concretesyntax.resource.cs.mopp.CsAnalysisProblem; import org.emftext.sdk.concretesyntax.resource.cs.mopp.CsAnalysisProblemType; import org.emftext.sdk.concretesyntax.resource.cs.util.CsResourceUtil; import org.emftext.sdk.regex.TokenSorter; /** * An abstract super class for all post processors. It tries to resolve all * proxy objects and if this succeeds analyse(CsResource, ConcreteSyntax) * is called. */ public abstract class AbstractPostProcessor { // We share the token sorter using a static field, which is bad design, but the // only way to globally make use of the shared automaton cache. This cache is // needed to substantially improve loading of concrete syntax files. The cache // has an upper limit for its size, which makes sure that this static field // does not end up as a memory leak. protected static final TokenSorter tokenSorter = new TokenSorter(); private PostProcessingContext context; private boolean terminate; public final void process(PostProcessingContext context) { this.context = context; boolean hasErrors = getContext().hasErrors(); if (hasErrors && !doAnalysisAfterPreviousErrors()) { return; } Resource resource = getContext().getResource(); if (doResolveProxiesBeforeAnalysis()) { // it is actually sufficient to do this once (for the first post processor) // but, since all post processors work in isolation, we cannot pass on the // information that proxy objects have already been resolved. if this turns // out to be a performance problem one can attach an adapter to the resource - // which carried the information. this adapter must also react to all changes + // which carries this information. this adapter must also react to all changes // made to the resource in order to trigger proxy resolution again after the - // resource has changed + // resource has changed. if (!CsResourceUtil.resolveAll(resource)) { return; } } List<EObject> objects = resource.getContents(); for (EObject next : objects) { if (next instanceof ConcreteSyntax) { analyse((ConcreteSyntax) next); } } } protected PostProcessingContext getContext() { return context; } protected boolean doAnalysisAfterPreviousErrors() { return false; } protected boolean doResolveProxiesBeforeAnalysis() { return true; } protected void addProblem(CsAnalysisProblemType problemType, final String message, EObject cause) { context.addProblem(new CsAnalysisProblem(message, problemType), cause); } protected void addProblem(CsAnalysisProblemType problemType, final String message, EObject cause, ICsQuickFix quickFix) { context.addProblem(new CsAnalysisProblem(message, problemType, quickFix), cause); } protected void addProblem(CsAnalysisProblemType problemType, final String message, EObject cause, Collection<ICsQuickFix> quickFixes) { context.addProblem(new CsAnalysisProblem(message, problemType, quickFixes), cause); } protected void addProblem(CsAnalysisProblemType problemType, final String message, int column, int line, int charStart, int charEnd) { context.addProblem(new CsAnalysisProblem(message, problemType), column, line, charStart, charEnd); } protected void addProblem(CsAnalysisProblemType problemType, final String message, int column, int line, int charStart, int charEnd, ICsQuickFix quickFix) { context.addProblem(new CsAnalysisProblem(message, problemType, quickFix), column, line, charStart, charEnd); } protected void addProblem(CsAnalysisProblemType problemType, final String message, int column, int line, int charStart, int charEnd, List<ICsQuickFix> quickFixes) { context.addProblem(new CsAnalysisProblem(message, problemType, quickFixes), column, line, charStart, charEnd); } protected void addTokenProblem( CsAnalysisProblemType type, String message, ConcreteSyntax syntax, CompleteTokenDefinition definition) { Set<EObject> causes = new LinkedHashSet<EObject>(); // problems that refer to quoted definition must be added to the placeholders, // because the tokens were created automatically and do thus not exist in the // syntax physically if (definition instanceof QuotedTokenDefinition) { QuotedTokenDefinition quotedDefinition = (QuotedTokenDefinition) definition; causes.addAll(quotedDefinition.getAttributeReferences()); } else { causes.add(definition); } for (EObject cause : causes) { addProblem(type, message, cause); } } public abstract void analyse(ConcreteSyntax syntax); public void terminate() { this.terminate = true; } protected boolean doTerminate() { return terminate; } }
false
true
public final void process(PostProcessingContext context) { this.context = context; boolean hasErrors = getContext().hasErrors(); if (hasErrors && !doAnalysisAfterPreviousErrors()) { return; } Resource resource = getContext().getResource(); if (doResolveProxiesBeforeAnalysis()) { // it is actually sufficient to do this once (for the first post processor) // but, since all post processors work in isolation, we cannot pass on the // information that proxy objects have already been resolved. if this turns // out to be a performance problem one can attach an adapter to the resource // which carried the information. this adapter must also react to all changes // made to the resource in order to trigger proxy resolution again after the // resource has changed if (!CsResourceUtil.resolveAll(resource)) { return; } } List<EObject> objects = resource.getContents(); for (EObject next : objects) { if (next instanceof ConcreteSyntax) { analyse((ConcreteSyntax) next); } } }
public final void process(PostProcessingContext context) { this.context = context; boolean hasErrors = getContext().hasErrors(); if (hasErrors && !doAnalysisAfterPreviousErrors()) { return; } Resource resource = getContext().getResource(); if (doResolveProxiesBeforeAnalysis()) { // it is actually sufficient to do this once (for the first post processor) // but, since all post processors work in isolation, we cannot pass on the // information that proxy objects have already been resolved. if this turns // out to be a performance problem one can attach an adapter to the resource // which carries this information. this adapter must also react to all changes // made to the resource in order to trigger proxy resolution again after the // resource has changed. if (!CsResourceUtil.resolveAll(resource)) { return; } } List<EObject> objects = resource.getContents(); for (EObject next : objects) { if (next instanceof ConcreteSyntax) { analyse((ConcreteSyntax) next); } } }
diff --git a/org.eclipse.b3.build/src/org/eclipse/b3/build/core/SimpleResolver.java b/org.eclipse.b3.build/src/org/eclipse/b3/build/core/SimpleResolver.java index b30c93d4..e1f3cc6e 100644 --- a/org.eclipse.b3.build/src/org/eclipse/b3/build/core/SimpleResolver.java +++ b/org.eclipse.b3.build/src/org/eclipse/b3/build/core/SimpleResolver.java @@ -1,258 +1,258 @@ /** * Copyright (c) 2010, Cloudsmith Inc. * The code, documentation and other materials contained herein have been * licensed under the Eclipse Public License - v 1.0 by the copyright holder * listed above, as the Initial Contributor under such license. The text of * such license is available at www.eclipse.org. */ package org.eclipse.b3.build.core; import org.eclipse.b3.backend.core.B3InternalError; import org.eclipse.b3.backend.core.B3NoSuchVariableException; import org.eclipse.b3.backend.evaluator.IB3Evaluator; import org.eclipse.b3.backend.evaluator.b3backend.BExecutionContext; import org.eclipse.b3.build.B3BuildFactory; import org.eclipse.b3.build.BeeModel; import org.eclipse.b3.build.BuildUnit; import org.eclipse.b3.build.DelegatingUnitProvider; import org.eclipse.b3.build.EffectiveRequirementFacade; import org.eclipse.b3.build.EffectiveUnitFacade; import org.eclipse.b3.build.FirstFoundUnitProvider; import org.eclipse.b3.build.RepositoryUnitProvider; import org.eclipse.b3.build.RequiredCapability; import org.eclipse.b3.build.ResolutionInfo; import org.eclipse.b3.build.UnitProvider; import org.eclipse.b3.build.UnitResolutionInfo; import org.eclipse.b3.build.internal.B3BuildActivator; import org.eclipse.b3.build.repository.IBuildUnitResolver; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.MultiStatus; import org.eclipse.core.runtime.Status; import org.eclipse.emf.common.util.EList; import com.google.inject.Inject; /** * A simplistic (brute force) resolver that resolves all units defined in the specified context. * An attempt is made to satisfy all effective requirements by resolving each against the * effective requirement's context's view of repository configuration. * */ public class SimpleResolver implements IBuildUnitResolver { @Inject IB3Evaluator evaluator; /* * (non-Javadoc) * * @see org.eclipse.b3.build.core.IBuildUnitResolver#resolveAll(org.eclipse.b3.build.BuildContext) */ public IStatus resolveAll(BExecutionContext ctx) { // System.err.print("RESOLVE ALL\n"); EffectiveUnitIterator uItor = new EffectiveUnitIterator(ctx); // ctx.printStackTrace(); MultiStatus ms = new MultiStatus(B3BuildActivator.instance.getBundle().getSymbolicName(), 0, "", null); while(uItor.hasNext()) ms.add(resolveUnit(uItor.next(), ctx)); return ms; } /* * (non-Javadoc) * * @see org.eclipse.b3.build.core.IBuildUnitResolver#resolveUnit(org.eclipse.b3.build.BuildUnit, org.eclipse.b3.build.BuildContext) */ public IStatus resolveUnit(BuildUnit unit, BExecutionContext ctx) { // System.err.printf("RESOLVING UNIT: %s", unit.getName()); // ALREADY RESOLVED // check if the unit is already resolved final ResolutionInfoAdapter unitAdapter = ResolutionInfoAdapterFactory.eINSTANCE.adapt(unit); final UnitResolutionInfo knownUnitResolutionInfo = (UnitResolutionInfo) unitAdapter.getAssociatedInfo(this); if(knownUnitResolutionInfo != null && knownUnitResolutionInfo.getStatus().isOK()) { // System.err.printf(" ALREADY RESOLVED - %s\n", ri.getStatus().getCode() == IStatus.OK // ? "OK" // : "FAIL"); return knownUnitResolutionInfo.getStatus(); } // GIVE THE UNIT A NEW RESOLUTION INFO final UnitResolutionInfo resultingUnitResolutionInfo = B3BuildFactory.eINSTANCE.createUnitResolutionInfo(); unitAdapter.setAssociatedInfo(this, resultingUnitResolutionInfo); resultingUnitResolutionInfo.setUnit(unit); // System.err.printf(" processing\n"); // DEFINE UNIT IF NOT DEFINED // check if the unit is defined, and define it (and its parent BeeModel) if not BuildUnit u = ctx.getSomeThing(BuildUnit.class, BuildUnitProxyAdapterFactory.eINSTANCE.adapt(unit).getIface()); // BuildUnit u = ctx.getEffectiveBuildUnit(unit); if(u == null) { // System.err.printf("Unit: %s, not defined - defining\n", unit.getName()); ctx = ctx.createOuterContext(); try { if(unit.eContainer() instanceof BeeModel) evaluator.doEvaluate(unit.eContainer(), ctx); else evaluator.doDefine(unit, ctx); // ctx.defineBuildUnit(unit, false); u = ctx.getSomeThing(BuildUnit.class, BuildUnitProxyAdapterFactory.eINSTANCE.adapt(unit).getIface()); // if(u == null) { // System.err.printf("Definition of unit: %s failed\n", unit.getName()); // } } catch(Throwable e) { resultingUnitResolutionInfo.setContext(ctx); // may be bad... resultingUnitResolutionInfo.setStatus(new Status( IStatus.ERROR, B3BuildActivator.instance.getBundle().getSymbolicName(), "Resolution failed with exception when defining a candidate unit", e)); return resultingUnitResolutionInfo.getStatus(); // give up on unit } } // EFFECTIVE UNIT EffectiveUnitFacade uFacade; try { uFacade = unit.getEffectiveFacade(ctx); ctx = uFacade.getContext(); } catch(Throwable e1) { resultingUnitResolutionInfo.setContext(ctx); // may be bad... resultingUnitResolutionInfo.setStatus(new Status( IStatus.ERROR, B3BuildActivator.instance.getBundle().getSymbolicName(), "Resolution failed with exception when getting effective unit", e1)); return resultingUnitResolutionInfo.getStatus(); // give up on unit } // the unit being resolved should always have this context // it's status may be set resultingUnitResolutionInfo.setContext(ctx); // PROCESS ALL REQUIREMENTS // If there are no requirements, return OK status after having updated the Unit's resolution Info. EList<EffectiveRequirementFacade> requiredCapabilities = uFacade.getRequiredCapabilities(); // trivial case - no requirements if(requiredCapabilities.size() < 1) { resultingUnitResolutionInfo.setStatus(Status.OK_STATUS); // System.err.print(" OK - NO REQUIREMENTS\n"); return resultingUnitResolutionInfo.getStatus(); } // Satisfy all requirements // final MultiStatus ms = new MultiStatus(B3BuildActivator.instance.getBundle().getSymbolicName(), 0, "", null); resultingUnitResolutionInfo.setStatus(ms); // create a stack provider (to be used in front of any defined providers) final RepositoryUnitProvider stackProvider = B3BuildFactory.eINSTANCE.createRepositoryUnitProvider(); stackProvider.setBuildUnitRepository(B3BuildFactory.eINSTANCE.createExecutionStackRepository()); for(EffectiveRequirementFacade ereq : requiredCapabilities) { RequiredCapability r = ereq.getRequirement(); // POSSIBLE BAD MODEL STATE if(r == null) { // bad model state (should have been caught by validation). // override the ms already set, it is not needed, better to set the error status directly // as there are no other statuses to collect (requirements are null). resultingUnitResolutionInfo.setStatus(new Status( IStatus.ERROR, B3BuildActivator.instance.getBundle().getSymbolicName(), "Unit contains null requirement")); // System.err.print(" FAIL - NULL EFFECTIVE REQUIREMENTS\n"); return resultingUnitResolutionInfo.getStatus(); } // GET regAdapter, to associate result with requirement (i.e. what it resolved to). final ResolutionInfoAdapter reqAdapter = ResolutionInfoAdapterFactory.eINSTANCE.adapt(r); // System.err.printf(" REQUIREMENT %s, %s - has status: %s\n", r.getName(), r.getVersionRange(), ri == null // ? "UNRESOLVED" // : ri.getStatus().getCode() == IStatus.OK // ? "OK" // : "FAIL"); // A single requirement can be used multiple times (declared in unit, used in several builders), // so it may already have been processed if(reqAdapter.getAssociatedInfo(this) != null) continue; // already processed and it has a status (ok, error, cancel) // get the effective unit providers to use for resolution try { UnitProvider repos = null; UnitProvider providerToUse = stackProvider; try { repos = UnitProvider.class.cast(ereq.getContext().getValue( B3BuildConstants.B3ENGINE_VAR_UNITPROVIDERS)); } catch(B3NoSuchVariableException e) { // ignore - repos remain null } // if providers were configured, combine them with a first found using the stack // if combination of multiple provider definitions should be performed, this is up // to whoever assigns B3ENGINE_CAR_UNITPROVIDERS (i.e. delegate first, or last). // if(repos != null) { FirstFoundUnitProvider ff = B3BuildFactory.eINSTANCE.createFirstFoundUnitProvider(); EList<UnitProvider> plist = ff.getProviders(); plist.add(stackProvider); DelegatingUnitProvider delegate = B3BuildFactory.eINSTANCE.createDelegatingUnitProvider(); delegate.setDelegate(repos); plist.add(delegate); providerToUse = ff; } // GET THE UNIT FROM THE REPOSITORY CONFIGURATION // note effective requirement has reference to the context to use BuildUnit result = providerToUse.resolve(ereq); if(result == null) { // System.err.printf(" UNRESOLVED - provider did not find it.\n"); ms.add(new Status( IStatus.WARNING, B3BuildActivator.instance.getBundle().getSymbolicName(), "Unresolved.")); reqAdapter.setAssociatedInfo(this, resultingUnitResolutionInfo); } else { // System.err.printf(" RESOLVED - provider found match.\n"); // SET THE REQUIREMENT's RESOLUTION INFO -> Resolved Unit final UnitResolutionInfo unitRi = B3BuildFactory.eINSTANCE.createUnitResolutionInfo(); unitRi.setUnit(result); unitRi.setStatus(Status.OK_STATUS); // prevent recursion if(ereq.getContext() == null) { throw new B3InternalError("Effective Requirement found with null context"); } unitRi.setContext(ereq.getContext()); // the context in which the requirement was resolved. // update status with resulting status graph (i.e. both on requirement, and result for unit being // resolved. unitRi.setStatus(resolveUnit(result, ctx)); ms.add(unitRi.getStatus()); reqAdapter.setAssociatedInfo(this, unitRi); - // destroy to see error output - resultingUnitResolutionInfo.setContext(null); // CRASH !! + // // destroy to see error output + // resultingUnitResolutionInfo.setContext(null); // CRASH !! } } catch(Throwable e) { // System.err.printf(" ERROR - %s, %s.\n", e.getClass().getName(), e.getMessage()); e.printStackTrace(); // associate the error information with the requirement final ResolutionInfo ri = B3BuildFactory.eINSTANCE.createResolutionInfo(); ri.setStatus(new Status( IStatus.ERROR, B3BuildActivator.instance.getBundle().getSymbolicName(), "Resolution failed with exception", e)); reqAdapter.setAssociatedInfo(this, ri); ms.add(ri.getStatus()); } } resultingUnitResolutionInfo.setStatus(ms); // // update the unit with the status information from resolving all of its requirements // ri = B3BuildFactory.eINSTANCE.createResolutionInfo(); // ri.setStatus(ms); // unitAdapter.setAssociatedInfo(this, ri); return ms; } }
true
true
public IStatus resolveUnit(BuildUnit unit, BExecutionContext ctx) { // System.err.printf("RESOLVING UNIT: %s", unit.getName()); // ALREADY RESOLVED // check if the unit is already resolved final ResolutionInfoAdapter unitAdapter = ResolutionInfoAdapterFactory.eINSTANCE.adapt(unit); final UnitResolutionInfo knownUnitResolutionInfo = (UnitResolutionInfo) unitAdapter.getAssociatedInfo(this); if(knownUnitResolutionInfo != null && knownUnitResolutionInfo.getStatus().isOK()) { // System.err.printf(" ALREADY RESOLVED - %s\n", ri.getStatus().getCode() == IStatus.OK // ? "OK" // : "FAIL"); return knownUnitResolutionInfo.getStatus(); } // GIVE THE UNIT A NEW RESOLUTION INFO final UnitResolutionInfo resultingUnitResolutionInfo = B3BuildFactory.eINSTANCE.createUnitResolutionInfo(); unitAdapter.setAssociatedInfo(this, resultingUnitResolutionInfo); resultingUnitResolutionInfo.setUnit(unit); // System.err.printf(" processing\n"); // DEFINE UNIT IF NOT DEFINED // check if the unit is defined, and define it (and its parent BeeModel) if not BuildUnit u = ctx.getSomeThing(BuildUnit.class, BuildUnitProxyAdapterFactory.eINSTANCE.adapt(unit).getIface()); // BuildUnit u = ctx.getEffectiveBuildUnit(unit); if(u == null) { // System.err.printf("Unit: %s, not defined - defining\n", unit.getName()); ctx = ctx.createOuterContext(); try { if(unit.eContainer() instanceof BeeModel) evaluator.doEvaluate(unit.eContainer(), ctx); else evaluator.doDefine(unit, ctx); // ctx.defineBuildUnit(unit, false); u = ctx.getSomeThing(BuildUnit.class, BuildUnitProxyAdapterFactory.eINSTANCE.adapt(unit).getIface()); // if(u == null) { // System.err.printf("Definition of unit: %s failed\n", unit.getName()); // } } catch(Throwable e) { resultingUnitResolutionInfo.setContext(ctx); // may be bad... resultingUnitResolutionInfo.setStatus(new Status( IStatus.ERROR, B3BuildActivator.instance.getBundle().getSymbolicName(), "Resolution failed with exception when defining a candidate unit", e)); return resultingUnitResolutionInfo.getStatus(); // give up on unit } } // EFFECTIVE UNIT EffectiveUnitFacade uFacade; try { uFacade = unit.getEffectiveFacade(ctx); ctx = uFacade.getContext(); } catch(Throwable e1) { resultingUnitResolutionInfo.setContext(ctx); // may be bad... resultingUnitResolutionInfo.setStatus(new Status( IStatus.ERROR, B3BuildActivator.instance.getBundle().getSymbolicName(), "Resolution failed with exception when getting effective unit", e1)); return resultingUnitResolutionInfo.getStatus(); // give up on unit } // the unit being resolved should always have this context // it's status may be set resultingUnitResolutionInfo.setContext(ctx); // PROCESS ALL REQUIREMENTS // If there are no requirements, return OK status after having updated the Unit's resolution Info. EList<EffectiveRequirementFacade> requiredCapabilities = uFacade.getRequiredCapabilities(); // trivial case - no requirements if(requiredCapabilities.size() < 1) { resultingUnitResolutionInfo.setStatus(Status.OK_STATUS); // System.err.print(" OK - NO REQUIREMENTS\n"); return resultingUnitResolutionInfo.getStatus(); } // Satisfy all requirements // final MultiStatus ms = new MultiStatus(B3BuildActivator.instance.getBundle().getSymbolicName(), 0, "", null); resultingUnitResolutionInfo.setStatus(ms); // create a stack provider (to be used in front of any defined providers) final RepositoryUnitProvider stackProvider = B3BuildFactory.eINSTANCE.createRepositoryUnitProvider(); stackProvider.setBuildUnitRepository(B3BuildFactory.eINSTANCE.createExecutionStackRepository()); for(EffectiveRequirementFacade ereq : requiredCapabilities) { RequiredCapability r = ereq.getRequirement(); // POSSIBLE BAD MODEL STATE if(r == null) { // bad model state (should have been caught by validation). // override the ms already set, it is not needed, better to set the error status directly // as there are no other statuses to collect (requirements are null). resultingUnitResolutionInfo.setStatus(new Status( IStatus.ERROR, B3BuildActivator.instance.getBundle().getSymbolicName(), "Unit contains null requirement")); // System.err.print(" FAIL - NULL EFFECTIVE REQUIREMENTS\n"); return resultingUnitResolutionInfo.getStatus(); } // GET regAdapter, to associate result with requirement (i.e. what it resolved to). final ResolutionInfoAdapter reqAdapter = ResolutionInfoAdapterFactory.eINSTANCE.adapt(r); // System.err.printf(" REQUIREMENT %s, %s - has status: %s\n", r.getName(), r.getVersionRange(), ri == null // ? "UNRESOLVED" // : ri.getStatus().getCode() == IStatus.OK // ? "OK" // : "FAIL"); // A single requirement can be used multiple times (declared in unit, used in several builders), // so it may already have been processed if(reqAdapter.getAssociatedInfo(this) != null) continue; // already processed and it has a status (ok, error, cancel) // get the effective unit providers to use for resolution try { UnitProvider repos = null; UnitProvider providerToUse = stackProvider; try { repos = UnitProvider.class.cast(ereq.getContext().getValue( B3BuildConstants.B3ENGINE_VAR_UNITPROVIDERS)); } catch(B3NoSuchVariableException e) { // ignore - repos remain null } // if providers were configured, combine them with a first found using the stack // if combination of multiple provider definitions should be performed, this is up // to whoever assigns B3ENGINE_CAR_UNITPROVIDERS (i.e. delegate first, or last). // if(repos != null) { FirstFoundUnitProvider ff = B3BuildFactory.eINSTANCE.createFirstFoundUnitProvider(); EList<UnitProvider> plist = ff.getProviders(); plist.add(stackProvider); DelegatingUnitProvider delegate = B3BuildFactory.eINSTANCE.createDelegatingUnitProvider(); delegate.setDelegate(repos); plist.add(delegate); providerToUse = ff; } // GET THE UNIT FROM THE REPOSITORY CONFIGURATION // note effective requirement has reference to the context to use BuildUnit result = providerToUse.resolve(ereq); if(result == null) { // System.err.printf(" UNRESOLVED - provider did not find it.\n"); ms.add(new Status( IStatus.WARNING, B3BuildActivator.instance.getBundle().getSymbolicName(), "Unresolved.")); reqAdapter.setAssociatedInfo(this, resultingUnitResolutionInfo); } else { // System.err.printf(" RESOLVED - provider found match.\n"); // SET THE REQUIREMENT's RESOLUTION INFO -> Resolved Unit final UnitResolutionInfo unitRi = B3BuildFactory.eINSTANCE.createUnitResolutionInfo(); unitRi.setUnit(result); unitRi.setStatus(Status.OK_STATUS); // prevent recursion if(ereq.getContext() == null) { throw new B3InternalError("Effective Requirement found with null context"); } unitRi.setContext(ereq.getContext()); // the context in which the requirement was resolved. // update status with resulting status graph (i.e. both on requirement, and result for unit being // resolved. unitRi.setStatus(resolveUnit(result, ctx)); ms.add(unitRi.getStatus()); reqAdapter.setAssociatedInfo(this, unitRi); // destroy to see error output resultingUnitResolutionInfo.setContext(null); // CRASH !! } } catch(Throwable e) { // System.err.printf(" ERROR - %s, %s.\n", e.getClass().getName(), e.getMessage()); e.printStackTrace(); // associate the error information with the requirement final ResolutionInfo ri = B3BuildFactory.eINSTANCE.createResolutionInfo(); ri.setStatus(new Status( IStatus.ERROR, B3BuildActivator.instance.getBundle().getSymbolicName(), "Resolution failed with exception", e)); reqAdapter.setAssociatedInfo(this, ri); ms.add(ri.getStatus()); } } resultingUnitResolutionInfo.setStatus(ms); // // update the unit with the status information from resolving all of its requirements // ri = B3BuildFactory.eINSTANCE.createResolutionInfo(); // ri.setStatus(ms); // unitAdapter.setAssociatedInfo(this, ri); return ms; }
public IStatus resolveUnit(BuildUnit unit, BExecutionContext ctx) { // System.err.printf("RESOLVING UNIT: %s", unit.getName()); // ALREADY RESOLVED // check if the unit is already resolved final ResolutionInfoAdapter unitAdapter = ResolutionInfoAdapterFactory.eINSTANCE.adapt(unit); final UnitResolutionInfo knownUnitResolutionInfo = (UnitResolutionInfo) unitAdapter.getAssociatedInfo(this); if(knownUnitResolutionInfo != null && knownUnitResolutionInfo.getStatus().isOK()) { // System.err.printf(" ALREADY RESOLVED - %s\n", ri.getStatus().getCode() == IStatus.OK // ? "OK" // : "FAIL"); return knownUnitResolutionInfo.getStatus(); } // GIVE THE UNIT A NEW RESOLUTION INFO final UnitResolutionInfo resultingUnitResolutionInfo = B3BuildFactory.eINSTANCE.createUnitResolutionInfo(); unitAdapter.setAssociatedInfo(this, resultingUnitResolutionInfo); resultingUnitResolutionInfo.setUnit(unit); // System.err.printf(" processing\n"); // DEFINE UNIT IF NOT DEFINED // check if the unit is defined, and define it (and its parent BeeModel) if not BuildUnit u = ctx.getSomeThing(BuildUnit.class, BuildUnitProxyAdapterFactory.eINSTANCE.adapt(unit).getIface()); // BuildUnit u = ctx.getEffectiveBuildUnit(unit); if(u == null) { // System.err.printf("Unit: %s, not defined - defining\n", unit.getName()); ctx = ctx.createOuterContext(); try { if(unit.eContainer() instanceof BeeModel) evaluator.doEvaluate(unit.eContainer(), ctx); else evaluator.doDefine(unit, ctx); // ctx.defineBuildUnit(unit, false); u = ctx.getSomeThing(BuildUnit.class, BuildUnitProxyAdapterFactory.eINSTANCE.adapt(unit).getIface()); // if(u == null) { // System.err.printf("Definition of unit: %s failed\n", unit.getName()); // } } catch(Throwable e) { resultingUnitResolutionInfo.setContext(ctx); // may be bad... resultingUnitResolutionInfo.setStatus(new Status( IStatus.ERROR, B3BuildActivator.instance.getBundle().getSymbolicName(), "Resolution failed with exception when defining a candidate unit", e)); return resultingUnitResolutionInfo.getStatus(); // give up on unit } } // EFFECTIVE UNIT EffectiveUnitFacade uFacade; try { uFacade = unit.getEffectiveFacade(ctx); ctx = uFacade.getContext(); } catch(Throwable e1) { resultingUnitResolutionInfo.setContext(ctx); // may be bad... resultingUnitResolutionInfo.setStatus(new Status( IStatus.ERROR, B3BuildActivator.instance.getBundle().getSymbolicName(), "Resolution failed with exception when getting effective unit", e1)); return resultingUnitResolutionInfo.getStatus(); // give up on unit } // the unit being resolved should always have this context // it's status may be set resultingUnitResolutionInfo.setContext(ctx); // PROCESS ALL REQUIREMENTS // If there are no requirements, return OK status after having updated the Unit's resolution Info. EList<EffectiveRequirementFacade> requiredCapabilities = uFacade.getRequiredCapabilities(); // trivial case - no requirements if(requiredCapabilities.size() < 1) { resultingUnitResolutionInfo.setStatus(Status.OK_STATUS); // System.err.print(" OK - NO REQUIREMENTS\n"); return resultingUnitResolutionInfo.getStatus(); } // Satisfy all requirements // final MultiStatus ms = new MultiStatus(B3BuildActivator.instance.getBundle().getSymbolicName(), 0, "", null); resultingUnitResolutionInfo.setStatus(ms); // create a stack provider (to be used in front of any defined providers) final RepositoryUnitProvider stackProvider = B3BuildFactory.eINSTANCE.createRepositoryUnitProvider(); stackProvider.setBuildUnitRepository(B3BuildFactory.eINSTANCE.createExecutionStackRepository()); for(EffectiveRequirementFacade ereq : requiredCapabilities) { RequiredCapability r = ereq.getRequirement(); // POSSIBLE BAD MODEL STATE if(r == null) { // bad model state (should have been caught by validation). // override the ms already set, it is not needed, better to set the error status directly // as there are no other statuses to collect (requirements are null). resultingUnitResolutionInfo.setStatus(new Status( IStatus.ERROR, B3BuildActivator.instance.getBundle().getSymbolicName(), "Unit contains null requirement")); // System.err.print(" FAIL - NULL EFFECTIVE REQUIREMENTS\n"); return resultingUnitResolutionInfo.getStatus(); } // GET regAdapter, to associate result with requirement (i.e. what it resolved to). final ResolutionInfoAdapter reqAdapter = ResolutionInfoAdapterFactory.eINSTANCE.adapt(r); // System.err.printf(" REQUIREMENT %s, %s - has status: %s\n", r.getName(), r.getVersionRange(), ri == null // ? "UNRESOLVED" // : ri.getStatus().getCode() == IStatus.OK // ? "OK" // : "FAIL"); // A single requirement can be used multiple times (declared in unit, used in several builders), // so it may already have been processed if(reqAdapter.getAssociatedInfo(this) != null) continue; // already processed and it has a status (ok, error, cancel) // get the effective unit providers to use for resolution try { UnitProvider repos = null; UnitProvider providerToUse = stackProvider; try { repos = UnitProvider.class.cast(ereq.getContext().getValue( B3BuildConstants.B3ENGINE_VAR_UNITPROVIDERS)); } catch(B3NoSuchVariableException e) { // ignore - repos remain null } // if providers were configured, combine them with a first found using the stack // if combination of multiple provider definitions should be performed, this is up // to whoever assigns B3ENGINE_CAR_UNITPROVIDERS (i.e. delegate first, or last). // if(repos != null) { FirstFoundUnitProvider ff = B3BuildFactory.eINSTANCE.createFirstFoundUnitProvider(); EList<UnitProvider> plist = ff.getProviders(); plist.add(stackProvider); DelegatingUnitProvider delegate = B3BuildFactory.eINSTANCE.createDelegatingUnitProvider(); delegate.setDelegate(repos); plist.add(delegate); providerToUse = ff; } // GET THE UNIT FROM THE REPOSITORY CONFIGURATION // note effective requirement has reference to the context to use BuildUnit result = providerToUse.resolve(ereq); if(result == null) { // System.err.printf(" UNRESOLVED - provider did not find it.\n"); ms.add(new Status( IStatus.WARNING, B3BuildActivator.instance.getBundle().getSymbolicName(), "Unresolved.")); reqAdapter.setAssociatedInfo(this, resultingUnitResolutionInfo); } else { // System.err.printf(" RESOLVED - provider found match.\n"); // SET THE REQUIREMENT's RESOLUTION INFO -> Resolved Unit final UnitResolutionInfo unitRi = B3BuildFactory.eINSTANCE.createUnitResolutionInfo(); unitRi.setUnit(result); unitRi.setStatus(Status.OK_STATUS); // prevent recursion if(ereq.getContext() == null) { throw new B3InternalError("Effective Requirement found with null context"); } unitRi.setContext(ereq.getContext()); // the context in which the requirement was resolved. // update status with resulting status graph (i.e. both on requirement, and result for unit being // resolved. unitRi.setStatus(resolveUnit(result, ctx)); ms.add(unitRi.getStatus()); reqAdapter.setAssociatedInfo(this, unitRi); // // destroy to see error output // resultingUnitResolutionInfo.setContext(null); // CRASH !! } } catch(Throwable e) { // System.err.printf(" ERROR - %s, %s.\n", e.getClass().getName(), e.getMessage()); e.printStackTrace(); // associate the error information with the requirement final ResolutionInfo ri = B3BuildFactory.eINSTANCE.createResolutionInfo(); ri.setStatus(new Status( IStatus.ERROR, B3BuildActivator.instance.getBundle().getSymbolicName(), "Resolution failed with exception", e)); reqAdapter.setAssociatedInfo(this, ri); ms.add(ri.getStatus()); } } resultingUnitResolutionInfo.setStatus(ms); // // update the unit with the status information from resolving all of its requirements // ri = B3BuildFactory.eINSTANCE.createResolutionInfo(); // ri.setStatus(ms); // unitAdapter.setAssociatedInfo(this, ri); return ms; }
diff --git a/src/main/java/enlight/model/primitive/SkySphere.java b/src/main/java/enlight/model/primitive/SkySphere.java index aee257d..560bf55 100644 --- a/src/main/java/enlight/model/primitive/SkySphere.java +++ b/src/main/java/enlight/model/primitive/SkySphere.java @@ -1,26 +1,27 @@ package enlight.model.primitive; import mikera.vectorz.geom.Ray; import enlight.model.AInfinitePrimitive; import enlight.model.IntersectionInfo; public class SkySphere extends AInfinitePrimitive { @Override public boolean getIntersection(Ray ray, IntersectionInfo result) { if (ray.end<Double.POSITIVE_INFINITY) return false; + ray.end=Double.POSITIVE_INFINITY; result.intersectionDistance=Double.POSITIVE_INFINITY; result.intersectionObject=this; // surface normal is opposite of direction result.surfaceNormal.set(ray.direction); result.surfaceNormal.negate(); return true; } }
true
true
public boolean getIntersection(Ray ray, IntersectionInfo result) { if (ray.end<Double.POSITIVE_INFINITY) return false; result.intersectionDistance=Double.POSITIVE_INFINITY; result.intersectionObject=this; // surface normal is opposite of direction result.surfaceNormal.set(ray.direction); result.surfaceNormal.negate(); return true; }
public boolean getIntersection(Ray ray, IntersectionInfo result) { if (ray.end<Double.POSITIVE_INFINITY) return false; ray.end=Double.POSITIVE_INFINITY; result.intersectionDistance=Double.POSITIVE_INFINITY; result.intersectionObject=this; // surface normal is opposite of direction result.surfaceNormal.set(ray.direction); result.surfaceNormal.negate(); return true; }
diff --git a/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/PerfTestService.java b/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/PerfTestService.java index e60fb95b..fdc35eae 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/PerfTestService.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/PerfTestService.java @@ -1,621 +1,621 @@ /* * Copyright (C) 2012 - 2012 NHN Corporation * All rights reserved. * * This file is part of The nGrinder software distribution. Refer to * the file LICENSE which is part of The nGrinder distribution for * licensing details. The nGrinder distribution is available on the * Internet at http://nhnopensource.org/ngrinder * * 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 HOLDERS 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 org.ngrinder.perftest.service; import static org.ngrinder.common.util.Preconditions.checkNotEmpty; import static org.ngrinder.common.util.Preconditions.checkNotNull; import static org.ngrinder.common.util.Preconditions.checkNotZero; import static org.ngrinder.perftest.repository.PerfTestSpecification.createdBy; import static org.ngrinder.perftest.repository.PerfTestSpecification.emptyPredicate; import static org.ngrinder.perftest.repository.PerfTestSpecification.idSetEqual; import static org.ngrinder.perftest.repository.PerfTestSpecification.likeTestNameOrDescription; import static org.ngrinder.perftest.repository.PerfTestSpecification.statusSetEqual; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import net.grinder.SingleConsole; import net.grinder.common.GrinderProperties; import net.grinder.console.model.ConsoleProperties; import net.grinder.util.ConsolePropertiesFactory; import net.grinder.util.Directory; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.Predicate; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.math.NumberUtils; import org.ngrinder.common.constant.NGrinderConstants; import org.ngrinder.common.exception.NGrinderRuntimeException; import org.ngrinder.infra.config.Config; import org.ngrinder.model.Role; import org.ngrinder.model.User; import org.ngrinder.perftest.model.PerfTest; import org.ngrinder.perftest.model.ProcessAndThread; import org.ngrinder.perftest.model.Status; import org.ngrinder.perftest.repository.PerfTestRepository; import org.ngrinder.script.model.FileEntry; import org.ngrinder.script.model.FileType; import org.ngrinder.script.service.FileEntryService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specifications; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * {@link PerfTest} Service Class. * * This class contains various method which mainly get the {@link PerfTest} matching specific conditions. * * @author Mavlarn * @author JunHo Yoon * @since 3.0 */ @Service public class PerfTestService implements NGrinderConstants { private static final Logger LOGGER = LoggerFactory.getLogger(PerfTestService.class); private static final String DATA_FILE_EXTENSION = ".data"; @Autowired private PerfTestRepository perfTestRepository; @Autowired private ConsoleManager consoleManager; @Autowired private Config config; @Autowired private FileEntryService fileEntryService; private NumberFormat formatter = new DecimalFormat("###.###"); /** * Get {@link PerfTest} list on the user. * * @param user * user * @param query * @param isFinished * only find finished test * @param pageable * paging info * @return found {@link PerfTest} list */ public Page<PerfTest> getPerfTestList(User user, String query, boolean isFinished, Pageable pageable) { Specifications<PerfTest> spec = Specifications.where(emptyPredicate()); // User can see only his own test if (user.getRole().equals(Role.USER)) { spec = spec.and(createdBy(user)); } if (isFinished) { spec = spec.and(statusSetEqual(Status.FINISHED)); } if (StringUtils.isNotBlank(query)) { spec = spec.and(likeTestNameOrDescription(query)); } return perfTestRepository.findAll(spec, pageable); } public List<PerfTest> getPerfTest(User user, Integer[] ids) { Specifications<PerfTest> spec = Specifications.where(emptyPredicate()); // User can see only his own test if (user.getRole().equals(Role.USER)) { spec = spec.and(createdBy(user)); } spec = spec.and(idSetEqual(ids)); return perfTestRepository.findAll(spec); } /** * Get PerfTest count which have given status. * * @param user * user who created test. null to retrieve all * @param statuses * status set * @return the count */ public long getPerfTestCount(User user, Status... statuses) { Specifications<PerfTest> spec = Specifications.where(emptyPredicate()); // User can see only his own test if (user != null) { spec = spec.and(createdBy(user)); } if (statuses.length != 0) { spec = spec.and(statusSetEqual(statuses)); } return perfTestRepository.count(spec); } /** * Get {@link PerfTest} list which have give state. * * @param user * user who created {@link PerfTest}. if null, retrieve all test * @param statuses * set of {@link Status} * @return found {@link PerfTest} list. */ public List<PerfTest> getPerfTest(User user, Status... statuses) { Specifications<PerfTest> spec = Specifications.where(emptyPredicate()); // User can see only his own test if (user != null) { spec = spec.and(createdBy(user)); } if (statuses.length != 0) { spec = spec.and(statusSetEqual(statuses)); } return perfTestRepository.findAll(spec); } /** * Save {@link PerfTest}. * * @param perfTest * {@link PerfTest} instance to be saved. * @return Saved {@link PerfTest} */ @CacheEvict(value = { "perftest", "perftestlist" }, allEntries = true) public PerfTest savePerfTest(PerfTest perfTest) { checkNotNull(perfTest); // Merge if necessary if (perfTest.exist()) { PerfTest existingPerfTest = perfTestRepository.findOne(perfTest.getId()); perfTest = existingPerfTest.merge(perfTest); } return perfTestRepository.save(perfTest); } /** * Save performance test with given status. * * This method is only used for changing {@link Status} * * @param perfTest * {@link PerfTest} instance which will be saved. * @param status * Status to be assigned * @return saved {@link PerfTest} */ @CacheEvict(value = { "perftest", "perftestlist" }, allEntries = true) public PerfTest savePerfTest(PerfTest perfTest, Status status) { checkNotNull(perfTest); checkNotNull(perfTest.getId(), "perfTest with status should save Id"); perfTest.setStatus(checkNotNull(status, "status should not be null")); return perfTestRepository.save(perfTest); } /** * Get PerfTest by testId. * * @param testId * PerfTest id * @return found {@link PerfTest}, null otherwise */ @Cacheable(value = "perftest") public PerfTest getPerfTest(long testId) { return perfTestRepository.findOne(testId); } /** * Get next runnable PerfTest list. * * @return found {@link PerfTest}, null otherwise */ @Cacheable(value = "perftest") @Transactional public PerfTest getPerfTestCandiate() { List<PerfTest> readyPerfTests = perfTestRepository.findAllByStatusOrderByScheduledTimeAsc(Status.READY); List<PerfTest> usersFirstPerfTests = filterCurrentlyRunningTestUsersTest(readyPerfTests); return usersFirstPerfTests.isEmpty() ? null : readyPerfTests.get(0); } /** * Get currently running {@link PerfTest} list. * * @return */ public List<PerfTest> getCurrentlyRunningTest() { return getPerfTest(null, Status.getProcessingOrTestingTestStatus()); } /** * Filter out {@link PerfTest} whose owner is running another test now.. * * @param perfTestLists * perf test * @return filtered perf test */ private List<PerfTest> filterCurrentlyRunningTestUsersTest(List<PerfTest> perfTestLists) { List<PerfTest> currentlyRunningTests = getCurrentlyRunningTest(); final Set<User> currentlyRunningTestOwners = new HashSet<User>(); for (PerfTest each : currentlyRunningTests) { currentlyRunningTestOwners.add((User) ObjectUtils.defaultIfNull(each.getLastModifiedUser(), each.getCreatedUser())); } CollectionUtils.filter(perfTestLists, new Predicate() { @Override public boolean evaluate(Object object) { PerfTest perfTest = (PerfTest) object; return !currentlyRunningTestOwners.contains(ObjectUtils.defaultIfNull(perfTest.getLastModifiedUser(), perfTest.getCreatedUser())); } }); return perfTestLists; } /** * Get currently testing PerfTest. * * @return found {@link PerfTest} list */ @Cacheable(value = "perftestlist") public List<PerfTest> getTestingPerfTest() { return getPerfTest(null, Status.getTestingTestStates()); } /** * Get abnormally testing PerfTest. * * @return found {@link PerfTest} list */ public List<PerfTest> getAbnoramlTestingPerfTest() { return getPerfTest(null, Status.ABNORMAL_TESTING); } /** * Delete PerfTest by id. * * Never use this method in runtime. This method is used only for testing. * * @param id * {@link PerfTest} it */ @CacheEvict(value = { "perftest", "perftestlist" }, allEntries = true) public void deletePerfTest(long id) { perfTestRepository.delete(id); } /** * Get PerfTest Directory in which the distributed file is stored. * * @param perfTest * pefTest from which distribution dire.ctory calculated * @return path on in files are saved. */ public File getPerfTestFilePath(PerfTest perfTest) { return config.getHome().getPerfTestDirectory( checkNotZero(perfTest.getId(), "perftest id should not be 0 or zero").toString()); } /** * Create {@link GrinderProperties} based on the passed {@link PerfTest} * * @param perfTest * base data * @return created {@link GrinderProperties} instance */ public GrinderProperties getGrinderProperties(PerfTest perfTest) { try { // Copy grinder properties File userGrinderPropertiesPath = new File(getPerfTestDirectory(perfTest), DEFAULT_GRINDER_PROPERTIES_PATH); FileUtils.copyFile(config.getHome().getDefaultGrinderProperties(), userGrinderPropertiesPath); GrinderProperties grinderProperties = new GrinderProperties(userGrinderPropertiesPath); grinderProperties.setAssociatedFile(new File(userGrinderPropertiesPath.getName())); grinderProperties.setProperty(GrinderProperties.SCRIPT, FilenameUtils.getName(checkNotEmpty(perfTest.getScriptName()))); ProcessAndThread calcProcessAndThread = calcProcessAndThread(checkNotZero(perfTest.getVuserPerAgent(), "vuser count should be provided")); grinderProperties.setInt(GRINDER_PROP_THREAD, calcProcessAndThread.getThreadCount()); grinderProperties.setInt(GRINDER_PROP_PROCESSES, calcProcessAndThread.getProcessCount()); if ("D".equals(perfTest.getThreshold())) { grinderProperties.setLong(GRINDER_PROP_DURATION, perfTest.getDuration()); } else { grinderProperties.setInt(GRINDER_PROP_RUNS, perfTest.getRunCount()); } grinderProperties.setBoolean(GRINDER_PROP_USE_CONSOLE, true); grinderProperties.setInt(GRINDER_PROP_INITIAL_SLEEP_TIME, perfTest.getInitSleepTime()); grinderProperties.setInt(GRINDER_PROP_PROCESS_INCREMENT, perfTest.getProcessIncrement()); grinderProperties.setInt(GRINDER_PROP_PROCESS_INCREMENT_INTERVAL, perfTest.getProcessIncrementInterval()); return grinderProperties; } catch (Exception e) { throw new NGrinderRuntimeException("error while prepare grinder property for " + perfTest.getTestName(), e); } } /** * Prepare files for distribution. * * @param perfTest * perfTest * @return File location in which the perftest should have. */ public File prepareDistribution(PerfTest perfTest) { checkNotNull(perfTest.getId(), "perfTest should have id"); String scriptName = checkNotEmpty(perfTest.getScriptName(), "perfTest should have script name"); User user = perfTest.getCreatedUser(); // Get all files in the script path List<FileEntry> fileEntries = fileEntryService.getFileEntries(user, FilenameUtils.getPath(checkNotEmpty(scriptName))); File perfTestDirectory = getPerfTestDirectory(perfTest); perfTestDirectory.mkdirs(); // Distribute each files in that folder. for (FileEntry each : fileEntries) { // Directory is not subject to be distributed. if (each.getFileType() == FileType.DIR) { continue; } LOGGER.info(each.getPath() + " is being written in " + perfTestDirectory); fileEntryService.writeContentTo(user, each.getPath(), perfTestDirectory); } LOGGER.info("File write is completed in " + perfTestDirectory); return perfTestDirectory; } /** * Get perf test base directory * * @param perfTest * perfTest * @return prefTest base path */ public File getPerfTestBaseDirectory(PerfTest perfTest) { return config.getHome().getPerfTestDirectory(perfTest.getId().toString()); } /** * Get user perf test directory fot * * @param perfTest * @param subDir * @return */ public File getPerfTestDirectory(PerfTest perfTest) { return new File(getPerfTestBaseDirectory(perfTest), NGrinderConstants.PATH_DIST); } /** * Get the optimal process and thread count. * * FIXME : This method should be optimized more. * * @param newVuser * the count of virtual users per agent * @return optimal process thread count */ public ProcessAndThread calcProcessAndThread(int newVuser) { int threadCount = 2; int processCount = newVuser / threadCount + newVuser % threadCount; return new ProcessAndThread(processCount, threadCount); } /** * get report data by test id, data type, and image width * * @param testId * test id * @param dataType * data type * @param imgWidth * image width * @return report data * @throws IOException */ public List<Object> getReportData(long testId, String dataType, int imgWidth) throws IOException { // TODO: later, we can make the file content as the string of list, then // we can // just return the file content directly, it will be much faster. List<Object> reportData = new ArrayList<Object>(); File reportFolder = config.getHome().getPerfTestDirectory( testId + File.separator + NGrinderConstants.PATH_REPORT); if (imgWidth < 100) { imgWidth = 100; } int pointCount = imgWidth / 10; int lineNumber; File targetFile = null; targetFile = new File(reportFolder, dataType.toLowerCase() + DATA_FILE_EXTENSION); if (!targetFile.exists()) { return reportData; } LineNumberReader lnr = null; try { lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(targetFile))); lnr.skip(targetFile.length()); lineNumber = lnr.getLineNumber() + 1; } finally { IOUtils.closeQuietly(lnr); } FileReader reader = null; BufferedReader br = null; try { reader = new FileReader(targetFile); br = new BufferedReader(reader); String data = null; int current = 0; int interval = lineNumber / pointCount; // TODO should get average data // FIXME : NEVER NEVER DO IT. Be aware of memory size.!! while (StringUtils.isNotBlank(data = br.readLine())) { if (0 == current) { - long number = NumberUtils.createLong(data); + double number = NumberUtils.createDouble(data); reportData.add(number); } if (++current >= interval) { current = 0; } } } finally { IOUtils.closeQuietly(reader); IOUtils.closeQuietly(br); } return reportData; } /** * Get report file name for give test id. * * @param testId * @return report file path */ public File getReportFile(long testId) { return new File(getReportFileDirectory(testId), NGrinderConstants.REPORT_CSV); } /** * Get report file directory for give test id. * * @param testId * @return report file path */ public File getReportFileDirectory(long testId) { return new File(config.getHome().getPerfTestDirectory(String.valueOf(testId)), NGrinderConstants.PATH_REPORT); } /** * To get statistics data when test is running If the console is not available.. it returns empty map. */ public Map<String, Object> getStatistics(int port) { SingleConsole consoleUsingPort = consoleManager.getConsoleUsingPort(port); LOGGER.warn("console using {} port is not available", port); return consoleUsingPort == null ? new HashMap<String, Object>() : consoleUsingPort.getStatictisData(); } /** * Get all perf test list. * * Note : This is only for test * * @return all {@link PerfTest} list * */ public List<PerfTest> getAllPerfTest() { return perfTestRepository.findAll(); } /** * Create {@link ConsoleProperties} based on given {@link PerfTest} instance. * * @param perfTest * perfTest * @return {@link ConsoleProperties} */ public ConsoleProperties createConsoleProperties(PerfTest perfTest) { ConsoleProperties consoleProperties = ConsolePropertiesFactory.createEmptyConsoleProperties(); try { consoleProperties.setAndSaveDistributionDirectory(new Directory(getPerfTestDirectory(perfTest))); } catch (Exception e) { throw new NGrinderRuntimeException("Error while setting console properties", e); } return consoleProperties; } /** * Update the given {@link PerfTest} properties after test finished. * * @param perfTest * perfTest * @return updated {@link PerfTest} */ public PerfTest updatePerfTestAfterTestFinish(PerfTest perfTest) { checkNotNull(perfTest); int port = perfTest.getPort(); Map<String, Object> result = getStatistics(port); if (result == null) { return perfTest; } checkNotNull(result); @SuppressWarnings("unchecked") Map<String, Object> totalStatistics = (Map<String, Object>) result.get("totalStatistics"); perfTest.setErrors((int) ((Double) totalStatistics.get("Errors")).doubleValue()); perfTest.setTps(Double.parseDouble(formatter.format(totalStatistics.get("TPS")))); perfTest.setMeanTestTime(Double.parseDouble(formatter.format(ObjectUtils.defaultIfNull( totalStatistics.get("Mean_Test_Time_(ms)"), 0D)))); perfTest.setPeakTps(Double.parseDouble(formatter.format(ObjectUtils.defaultIfNull( totalStatistics.get("Peak_TPS"), 0D)))); perfTest.setTests((int) ((Double) totalStatistics.get("Tests")).doubleValue()); return perfTest; } /** * Get maximum concurrent test count. * * @return maximum concurrent test */ public int getMaximumConcurrentTestCount() { return config.getSystemProperties().getPropertyInt(NGrinderConstants.NGRINDER_PROP_MAX_CONCURRENT_TEST, NGrinderConstants.NGRINDER_PROP_MAX_CONCURRENT_TEST_VALUE); } /** * Check the test can be executed more. * * @return true if possible */ public boolean canExecuteTestMore() { return getPerfTestCount(null, Status.getProcessingOrTestingTestStatus()) < getMaximumConcurrentTestCount(); } }
true
true
public List<Object> getReportData(long testId, String dataType, int imgWidth) throws IOException { // TODO: later, we can make the file content as the string of list, then // we can // just return the file content directly, it will be much faster. List<Object> reportData = new ArrayList<Object>(); File reportFolder = config.getHome().getPerfTestDirectory( testId + File.separator + NGrinderConstants.PATH_REPORT); if (imgWidth < 100) { imgWidth = 100; } int pointCount = imgWidth / 10; int lineNumber; File targetFile = null; targetFile = new File(reportFolder, dataType.toLowerCase() + DATA_FILE_EXTENSION); if (!targetFile.exists()) { return reportData; } LineNumberReader lnr = null; try { lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(targetFile))); lnr.skip(targetFile.length()); lineNumber = lnr.getLineNumber() + 1; } finally { IOUtils.closeQuietly(lnr); } FileReader reader = null; BufferedReader br = null; try { reader = new FileReader(targetFile); br = new BufferedReader(reader); String data = null; int current = 0; int interval = lineNumber / pointCount; // TODO should get average data // FIXME : NEVER NEVER DO IT. Be aware of memory size.!! while (StringUtils.isNotBlank(data = br.readLine())) { if (0 == current) { long number = NumberUtils.createLong(data); reportData.add(number); } if (++current >= interval) { current = 0; } } } finally { IOUtils.closeQuietly(reader); IOUtils.closeQuietly(br); } return reportData; }
public List<Object> getReportData(long testId, String dataType, int imgWidth) throws IOException { // TODO: later, we can make the file content as the string of list, then // we can // just return the file content directly, it will be much faster. List<Object> reportData = new ArrayList<Object>(); File reportFolder = config.getHome().getPerfTestDirectory( testId + File.separator + NGrinderConstants.PATH_REPORT); if (imgWidth < 100) { imgWidth = 100; } int pointCount = imgWidth / 10; int lineNumber; File targetFile = null; targetFile = new File(reportFolder, dataType.toLowerCase() + DATA_FILE_EXTENSION); if (!targetFile.exists()) { return reportData; } LineNumberReader lnr = null; try { lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(targetFile))); lnr.skip(targetFile.length()); lineNumber = lnr.getLineNumber() + 1; } finally { IOUtils.closeQuietly(lnr); } FileReader reader = null; BufferedReader br = null; try { reader = new FileReader(targetFile); br = new BufferedReader(reader); String data = null; int current = 0; int interval = lineNumber / pointCount; // TODO should get average data // FIXME : NEVER NEVER DO IT. Be aware of memory size.!! while (StringUtils.isNotBlank(data = br.readLine())) { if (0 == current) { double number = NumberUtils.createDouble(data); reportData.add(number); } if (++current >= interval) { current = 0; } } } finally { IOUtils.closeQuietly(reader); IOUtils.closeQuietly(br); } return reportData; }
diff --git a/FiltersPlugin/src/org/gephi/filters/plugin/graph/OutDegreeRangeBuilder.java b/FiltersPlugin/src/org/gephi/filters/plugin/graph/OutDegreeRangeBuilder.java index f928fc474..0b9d660e2 100644 --- a/FiltersPlugin/src/org/gephi/filters/plugin/graph/OutDegreeRangeBuilder.java +++ b/FiltersPlugin/src/org/gephi/filters/plugin/graph/OutDegreeRangeBuilder.java @@ -1,143 +1,143 @@ /* Copyright 2008-2010 Gephi Authors : Mathieu Bastian <[email protected]> Website : http://www.gephi.org This file is part of Gephi. DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. Copyright 2011 Gephi Consortium. All rights reserved. The contents of this file are subject to the terms of either the GNU General Public License Version 3 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 http://gephi.org/about/legal/license-notice/ or /cddl-1.0.txt and /gpl-3.0.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 files at /cddl-1.0.txt and /gpl-3.0.txt. If applicable, add the following below the License Header, with the fields enclosed by brackets [] replaced by your own identifying information: "Portions Copyrighted [year] [name of copyright owner]" If you wish your version of this file to be governed by only the CDDL or only the GPL Version 3, indicate your decision by adding "[Contributor] elects to include this software in this distribution under the [CDDL or GPL Version 3] license." If you do not 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 3 or to extend the choice of license to its licensees as provided above. However, if you add GPL Version 3 code and therefore, elected the GPL Version 3 license, then the option applies only if the new code is made subject to such option by the copyright holder. Contributor(s): Portions Copyrighted 2011 Gephi Consortium. */ package org.gephi.filters.plugin.graph; import java.util.ArrayList; import java.util.List; import javax.swing.Icon; import javax.swing.JPanel; import org.gephi.filters.api.FilterLibrary; import org.gephi.filters.api.Range; import org.gephi.filters.plugin.AbstractFilter; import org.gephi.filters.spi.*; import org.gephi.graph.api.*; import org.openide.util.Lookup; import org.openide.util.NbBundle; import org.openide.util.lookup.ServiceProvider; /** * * @author Mathieu Bastian */ @ServiceProvider(service = FilterBuilder.class) public class OutDegreeRangeBuilder implements FilterBuilder { public Category getCategory() { return FilterLibrary.TOPOLOGY; } public String getName() { return NbBundle.getMessage(OutDegreeRangeBuilder.class, "OutDegreeRangeBuilder.name"); } public Icon getIcon() { return null; } public String getDescription() { return NbBundle.getMessage(OutDegreeRangeBuilder.class, "OutDegreeRangeBuilder.description"); } public Filter getFilter() { return new OutDegreeRangeFilter(); } public JPanel getPanel(Filter filter) { RangeUI ui = Lookup.getDefault().lookup(RangeUI.class); if (ui != null) { return ui.getPanel((OutDegreeRangeFilter) filter); } return null; } public void destroy(Filter filter) { } public static class OutDegreeRangeFilter extends AbstractFilter implements RangeFilter, NodeFilter { private Range range; public OutDegreeRangeFilter() { super(NbBundle.getMessage(OutDegreeRangeBuilder.class, "OutDegreeRangeBuilder.name")); //Add property addProperty(Range.class, "range"); } public boolean init(Graph graph) { if (graph.getNodeCount() == 0 || !(graph instanceof DirectedGraph)) { return false; } return true; } public boolean evaluate(Graph graph, Node node) { int degree = ((HierarchicalDirectedGraph) graph).getTotalOutDegree(node); return range.isInRange(degree); } public void finish() { } public Number[] getValues(Graph graph) { HierarchicalDirectedGraph hgraph = (HierarchicalDirectedGraph) graph; List<Integer> values = new ArrayList<Integer>(((HierarchicalGraph) graph).getNodeCount()); for (Node n : hgraph.getNodes()) { - int degree = hgraph.getMutualDegree(n); + int degree = hgraph.getTotalOutDegree(n); values.add(degree); } return values.toArray(new Number[0]); } public FilterProperty getRangeProperty() { return getProperties()[0]; } public Range getRange() { return range; } public void setRange(Range range) { this.range = range; } } }
true
true
public Number[] getValues(Graph graph) { HierarchicalDirectedGraph hgraph = (HierarchicalDirectedGraph) graph; List<Integer> values = new ArrayList<Integer>(((HierarchicalGraph) graph).getNodeCount()); for (Node n : hgraph.getNodes()) { int degree = hgraph.getMutualDegree(n); values.add(degree); } return values.toArray(new Number[0]); }
public Number[] getValues(Graph graph) { HierarchicalDirectedGraph hgraph = (HierarchicalDirectedGraph) graph; List<Integer> values = new ArrayList<Integer>(((HierarchicalGraph) graph).getNodeCount()); for (Node n : hgraph.getNodes()) { int degree = hgraph.getTotalOutDegree(n); values.add(degree); } return values.toArray(new Number[0]); }
diff --git a/bato/src/com/samportnow/bato/addthought/AddThoughtCopingStrategyFragment.java b/bato/src/com/samportnow/bato/addthought/AddThoughtCopingStrategyFragment.java index 472d693..b7d5cdb 100644 --- a/bato/src/com/samportnow/bato/addthought/AddThoughtCopingStrategyFragment.java +++ b/bato/src/com/samportnow/bato/addthought/AddThoughtCopingStrategyFragment.java @@ -1,132 +1,131 @@ package com.samportnow.bato.addthought; import java.util.List; import android.app.AlertDialog; import android.app.Fragment; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import com.samportnow.bato.R; import com.samportnow.bato.database.BatoDataSource; public class AddThoughtCopingStrategyFragment extends Fragment { private ArrayAdapter<String> mHistoryAdapter = null; private ListView mHistoryListView = null; private EditText mCopingStrategyEditText = null; private Button mNextButton = null; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); View view = inflater.inflate(R.layout.fragment_add_thought_coping_strategy, null); BatoDataSource dataSource = new BatoDataSource(getActivity()).open(); mHistoryAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1); List<String> strats = dataSource.getAllThoughtCopingStrategy(); mHistoryAdapter.addAll(strats); dataSource.close(); mHistoryListView = (ListView) view.findViewById(R.id.thought_coping_strategy_history); -// SwingRightInAnimationAdapter animationAdapter = new SwingRightInAnimationAdapter(mHistoryAdapter); -// animationAdapter.setAbsListView(mHistoryListView); + SwingRightInAnimationAdapter animationAdapter = new SwingRightInAnimationAdapter(mHistoryAdapter); + animationAdapter.setAbsListView(mHistoryListView); mHistoryListView.setAdapter(mHistoryAdapter); mHistoryListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String item = (String) mHistoryListView.getItemAtPosition(position); mCopingStrategyEditText.setText(item); mCopingStrategyEditText.setSelection(item.length()); } }); mCopingStrategyEditText = (EditText) view.findViewById(R.id.thought_coping_strategy); mCopingStrategyEditText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { mHistoryAdapter.getFilter().filter(s); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { mNextButton.setEnabled(s.length() > 0); } }); mNextButton = (Button) view.findViewById(R.id.next_fragment); mNextButton.setEnabled(false); mNextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(v.getWindowToken(), 0); Bundle bundle = getArguments(); bundle.putString("copingStrategy", mCopingStrategyEditText.getText().toString()); - Log.e("edit it", "" + mCopingStrategyEditText.getText().toString()); ((AddEventActivity) getActivity()).createNewEvent(); } }); view.findViewById(R.id.show_default_coping_strategies).setOnClickListener(new View.OnClickListener() { public void onClick(View v) { final String[] strategies = getResources().getStringArray(R.array.common_coping_strategies); final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, strategies); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setNegativeButton(android.R.string.cancel, null); builder.setAdapter(adapter, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mCopingStrategyEditText.setText(adapter.getItem(which)); dialog.dismiss(); } }); builder.create().show(); } }); return view; } }
false
true
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); View view = inflater.inflate(R.layout.fragment_add_thought_coping_strategy, null); BatoDataSource dataSource = new BatoDataSource(getActivity()).open(); mHistoryAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1); List<String> strats = dataSource.getAllThoughtCopingStrategy(); mHistoryAdapter.addAll(strats); dataSource.close(); mHistoryListView = (ListView) view.findViewById(R.id.thought_coping_strategy_history); // SwingRightInAnimationAdapter animationAdapter = new SwingRightInAnimationAdapter(mHistoryAdapter); // animationAdapter.setAbsListView(mHistoryListView); mHistoryListView.setAdapter(mHistoryAdapter); mHistoryListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String item = (String) mHistoryListView.getItemAtPosition(position); mCopingStrategyEditText.setText(item); mCopingStrategyEditText.setSelection(item.length()); } }); mCopingStrategyEditText = (EditText) view.findViewById(R.id.thought_coping_strategy); mCopingStrategyEditText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { mHistoryAdapter.getFilter().filter(s); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { mNextButton.setEnabled(s.length() > 0); } }); mNextButton = (Button) view.findViewById(R.id.next_fragment); mNextButton.setEnabled(false); mNextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(v.getWindowToken(), 0); Bundle bundle = getArguments(); bundle.putString("copingStrategy", mCopingStrategyEditText.getText().toString()); Log.e("edit it", "" + mCopingStrategyEditText.getText().toString()); ((AddEventActivity) getActivity()).createNewEvent(); } }); view.findViewById(R.id.show_default_coping_strategies).setOnClickListener(new View.OnClickListener() { public void onClick(View v) { final String[] strategies = getResources().getStringArray(R.array.common_coping_strategies); final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, strategies); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setNegativeButton(android.R.string.cancel, null); builder.setAdapter(adapter, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mCopingStrategyEditText.setText(adapter.getItem(which)); dialog.dismiss(); } }); builder.create().show(); } }); return view; }
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); View view = inflater.inflate(R.layout.fragment_add_thought_coping_strategy, null); BatoDataSource dataSource = new BatoDataSource(getActivity()).open(); mHistoryAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1); List<String> strats = dataSource.getAllThoughtCopingStrategy(); mHistoryAdapter.addAll(strats); dataSource.close(); mHistoryListView = (ListView) view.findViewById(R.id.thought_coping_strategy_history); SwingRightInAnimationAdapter animationAdapter = new SwingRightInAnimationAdapter(mHistoryAdapter); animationAdapter.setAbsListView(mHistoryListView); mHistoryListView.setAdapter(mHistoryAdapter); mHistoryListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String item = (String) mHistoryListView.getItemAtPosition(position); mCopingStrategyEditText.setText(item); mCopingStrategyEditText.setSelection(item.length()); } }); mCopingStrategyEditText = (EditText) view.findViewById(R.id.thought_coping_strategy); mCopingStrategyEditText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { mHistoryAdapter.getFilter().filter(s); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { mNextButton.setEnabled(s.length() > 0); } }); mNextButton = (Button) view.findViewById(R.id.next_fragment); mNextButton.setEnabled(false); mNextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(v.getWindowToken(), 0); Bundle bundle = getArguments(); bundle.putString("copingStrategy", mCopingStrategyEditText.getText().toString()); ((AddEventActivity) getActivity()).createNewEvent(); } }); view.findViewById(R.id.show_default_coping_strategies).setOnClickListener(new View.OnClickListener() { public void onClick(View v) { final String[] strategies = getResources().getStringArray(R.array.common_coping_strategies); final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, strategies); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setNegativeButton(android.R.string.cancel, null); builder.setAdapter(adapter, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mCopingStrategyEditText.setText(adapter.getItem(which)); dialog.dismiss(); } }); builder.create().show(); } }); return view; }
diff --git a/src/com/activeandroid/query/From.java b/src/com/activeandroid/query/From.java index bc8213a..fcfeed6 100644 --- a/src/com/activeandroid/query/From.java +++ b/src/com/activeandroid/query/From.java @@ -1,233 +1,234 @@ package com.activeandroid.query; /* * Copyright (C) 2010 Michael Pardo * * 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. */ import android.text.TextUtils; import com.activeandroid.Cache; import com.activeandroid.Model; import com.activeandroid.query.Join.JoinType; import com.activeandroid.util.Log; import com.activeandroid.util.SQLiteUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public final class From implements Sqlable { private Sqlable mQueryBase; private Class<? extends Model> mType; private String mAlias; private List<Join> mJoins; private String mWhere; private String mGroupBy; private String mHaving; private String mOrderBy; private String mLimit; private String mOffset; private List<Object> mArguments; public From(Class<? extends Model> table, Sqlable queryBase) { mType = table; mJoins = new ArrayList<Join>(); mQueryBase = queryBase; mJoins = new ArrayList<Join>(); mArguments = new ArrayList<Object>(); } public From as(String alias) { mAlias = alias; return this; } public Join join(Class<? extends Model> table) { Join join = new Join(this, table, null); mJoins.add(join); return join; } public Join leftJoin(Class<? extends Model> table) { Join join = new Join(this, table, JoinType.LEFT); mJoins.add(join); return join; } public Join outerJoin(Class<? extends Model> table) { Join join = new Join(this, table, JoinType.OUTER); mJoins.add(join); return join; } public Join innerJoin(Class<? extends Model> table) { Join join = new Join(this, table, JoinType.INNER); mJoins.add(join); return join; } public Join crossJoin(Class<? extends Model> table) { Join join = new Join(this, table, JoinType.CROSS); mJoins.add(join); return join; } public From where(String where) { mWhere = where; mArguments.clear(); return this; } public From where(String where, Object... args) { mWhere = where; mArguments.clear(); mArguments.addAll(Arrays.asList(args)); return this; } public From groupBy(String groupBy) { mGroupBy = groupBy; return this; } public From having(String having) { mHaving = having; return this; } public From orderBy(String orderBy) { mOrderBy = orderBy; return this; } public From limit(int limit) { return limit(String.valueOf(limit)); } public From limit(String limit) { mLimit = limit; return this; } public From offset(int offset) { return offset(String.valueOf(offset)); } public From offset(String offset) { mOffset = offset; return this; } void addArguments(Object[] args) { mArguments.addAll(Arrays.asList(args)); } @Override public String toSql() { StringBuilder sql = new StringBuilder(); sql.append(mQueryBase.toSql()); sql.append("FROM "); sql.append(Cache.getTableName(mType)).append(" "); if (mAlias != null) { sql.append("AS "); sql.append(mAlias); sql.append(" "); } for (Join join : mJoins) { sql.append(join.toSql()); } if (mWhere != null) { sql.append("WHERE "); sql.append(mWhere); sql.append(" "); } if (mGroupBy != null) { sql.append("GROUP BY "); sql.append(mGroupBy); sql.append(" "); } if (mHaving != null) { sql.append("HAVING "); sql.append(mHaving); sql.append(" "); } if (mOrderBy != null) { sql.append("ORDER BY "); sql.append(mOrderBy); sql.append(" "); } if (mLimit != null) { sql.append("LIMIT "); + sql.append(mLimit); sql.append(" "); } if (mOffset != null) { sql.append("OFFSET "); sql.append(mOffset); sql.append(" "); } // Don't wast time building the string // unless we're going to log it. if (Log.isEnabled()) { Log.v(sql.toString() + " " + TextUtils.join(",", getArguments())); } return sql.toString().trim(); } public <T extends Model> List<T> execute() { if (mQueryBase instanceof Select) { return SQLiteUtils.rawQuery(mType, toSql(), getArguments()); } else { SQLiteUtils.execSql(toSql(), getArguments()); return null; } } public <T extends Model> T executeSingle() { if (mQueryBase instanceof Select) { limit(1); return SQLiteUtils.rawQuerySingle(mType, toSql(), getArguments()); } else { SQLiteUtils.execSql(toSql(), getArguments()); return null; } } public String[] getArguments() { final int size = mArguments.size(); final String[] args = new String[size]; for (int i = 0; i < size; i++) { args[i] = mArguments.get(i).toString(); } return args; } }
true
true
public String toSql() { StringBuilder sql = new StringBuilder(); sql.append(mQueryBase.toSql()); sql.append("FROM "); sql.append(Cache.getTableName(mType)).append(" "); if (mAlias != null) { sql.append("AS "); sql.append(mAlias); sql.append(" "); } for (Join join : mJoins) { sql.append(join.toSql()); } if (mWhere != null) { sql.append("WHERE "); sql.append(mWhere); sql.append(" "); } if (mGroupBy != null) { sql.append("GROUP BY "); sql.append(mGroupBy); sql.append(" "); } if (mHaving != null) { sql.append("HAVING "); sql.append(mHaving); sql.append(" "); } if (mOrderBy != null) { sql.append("ORDER BY "); sql.append(mOrderBy); sql.append(" "); } if (mLimit != null) { sql.append("LIMIT "); sql.append(" "); } if (mOffset != null) { sql.append("OFFSET "); sql.append(mOffset); sql.append(" "); } // Don't wast time building the string // unless we're going to log it. if (Log.isEnabled()) { Log.v(sql.toString() + " " + TextUtils.join(",", getArguments())); } return sql.toString().trim(); }
public String toSql() { StringBuilder sql = new StringBuilder(); sql.append(mQueryBase.toSql()); sql.append("FROM "); sql.append(Cache.getTableName(mType)).append(" "); if (mAlias != null) { sql.append("AS "); sql.append(mAlias); sql.append(" "); } for (Join join : mJoins) { sql.append(join.toSql()); } if (mWhere != null) { sql.append("WHERE "); sql.append(mWhere); sql.append(" "); } if (mGroupBy != null) { sql.append("GROUP BY "); sql.append(mGroupBy); sql.append(" "); } if (mHaving != null) { sql.append("HAVING "); sql.append(mHaving); sql.append(" "); } if (mOrderBy != null) { sql.append("ORDER BY "); sql.append(mOrderBy); sql.append(" "); } if (mLimit != null) { sql.append("LIMIT "); sql.append(mLimit); sql.append(" "); } if (mOffset != null) { sql.append("OFFSET "); sql.append(mOffset); sql.append(" "); } // Don't wast time building the string // unless we're going to log it. if (Log.isEnabled()) { Log.v(sql.toString() + " " + TextUtils.join(",", getArguments())); } return sql.toString().trim(); }
diff --git a/GAE/src/com/gallatinsystems/framework/gwt/wizard/client/AbstractWizardPortlet.java b/GAE/src/com/gallatinsystems/framework/gwt/wizard/client/AbstractWizardPortlet.java index ef5ad34c5..7443620b6 100644 --- a/GAE/src/com/gallatinsystems/framework/gwt/wizard/client/AbstractWizardPortlet.java +++ b/GAE/src/com/gallatinsystems/framework/gwt/wizard/client/AbstractWizardPortlet.java @@ -1,487 +1,489 @@ package com.gallatinsystems.framework.gwt.wizard.client; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.gallatinsystems.framework.gwt.component.Breadcrumb; import com.gallatinsystems.framework.gwt.component.PageController; import com.gallatinsystems.framework.gwt.portlet.client.Portlet; import com.gallatinsystems.framework.gwt.portlet.client.WizardBundleConstants; import com.gallatinsystems.framework.gwt.util.client.MessageDialog; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; /** * Widget that can act as a flow controller for a wizard-like interface. It * handles rendering a main portlet, breadcrumbs and navigational buttons. * * * The wizard is configured by subclassing this class and creating a * WizardWorkflow object in the getWizardWorkflow method. The wizardWorkflow is * a DSL that defines the series of steps available from each node in the * wizard. * * As the user clicks buttons in the wizard, this class will call a method to * flush the state of the loaded wizard node (if it implements ContextualAware) * and then will load the next node. State context will also be associated with * breadcrumbs so the correct page can be loaded on click. * * * * This component uses the following CSS styles: wizard-back-navbutton - for * "backwards" flow control buttons wizard-fwd-navbutton - for "forward" flow * control buttons wizard-navbutton - default button look and feel * * @author Christopher Fagiani */ @SuppressWarnings("unchecked") public abstract class AbstractWizardPortlet extends Portlet implements ClickHandler, PageController, CompletionListener { private static final String NAV_BUTTON_STYLE = "wizard-navbutton"; private static final String BACK_NAV_BUTTON_STYLE = "wizard-back-navbutton"; private static final String FWD_NAV_BUTTON_STYLE = "wizard-fwd-navbutton"; private static final String BREADCRUMB_PANEL_STYLE = "wizard-breadcrumb-panel"; private VerticalPanel contentPane; private HorizontalPanel breadcrumbPanel; private HorizontalPanel buttonPanel; private VerticalPanel widgetPanel; private List<Button> forwardNavButtons; private List<Button> backwardNavButtons; private ArrayList<String> breadcrumbList; private Map<String, Widget> breadcrumbWidgets; private WizardWorkflow workflow; private Widget currentPage; private ContextAware pendingPage; private WizardNode pageToLoad; private MessageDialog waitDialog; private Map<String, String> buttonMapping; private boolean working; protected AbstractWizardPortlet(String name, int width, int height) { super(name, true, false, false, width, height); working = false; contentPane = new VerticalPanel(); breadcrumbPanel = new HorizontalPanel(); breadcrumbPanel.setStylePrimaryName(BREADCRUMB_PANEL_STYLE); buttonPanel = new HorizontalPanel(); widgetPanel = new VerticalPanel(); buttonMapping = new HashMap<String, String>(); contentPane.add(breadcrumbPanel); contentPane.add(widgetPanel); contentPane.add(buttonPanel); forwardNavButtons = new ArrayList<Button>(); backwardNavButtons = new ArrayList<Button>(); breadcrumbList = new ArrayList<String>(); breadcrumbWidgets = new HashMap<String, Widget>(); workflow = getWizardWorkflow(); } protected void init() { pageToLoad = workflow.getStartNode(); renderWizardPage(pageToLoad, true, null); setContent(contentPane); waitDialog = new MessageDialog("Saving...", "Please wait", true); } /** * Clears current buttons and replaces them with the buttons dictated by the * WizardNode passed in * */ protected void resetNav(WizardNode node) { buttonPanel.clear(); forwardNavButtons.clear(); backwardNavButtons.clear(); buttonMapping.clear(); installButtons(backwardNavButtons, node.getPrevNodes(), BACK_NAV_BUTTON_STYLE); installButtons(forwardNavButtons, node.getNextNodes(), FWD_NAV_BUTTON_STYLE); } /** * Adds the buttons passed in to the button panel and attaches their * listeners * */ private void installButtons(List<Button> buttonList, WizardButton[] buttonDefinitions, String style) { if (buttonDefinitions != null) { for (int i = 0; i < buttonDefinitions.length; i++) { Button button = new Button(); if (style == null) { button.setStylePrimaryName(NAV_BUTTON_STYLE); } else { button.setStylePrimaryName(style); } button.setText(buttonDefinitions[i].getLabel()); button.addClickHandler(this); buttonList.add(button); buttonPanel.add(button); buttonMapping.put(buttonDefinitions[i].getLabel(), buttonDefinitions[i].getNodeName()); } } } /* * This method handles the majority of the page loading logic. It will do * the following: Calls the prePageUnload method Clear the current widget If * the page is "forward" (i.e. not a click of a breadcrumb or a back button) * and the old page is ContextAware: calls persistContext on the old page. * Since the save is async, the remainder of initialization is performed in * the operationComplete callback Initializes the widget for the new page If * the page is "forward" (i.e. not a click of a breadcrumb or a back button) * install the new breadcrumb for the new page (if its WizardNode object * contains a breadcrumb name) Add the new page to the display Call the * onLoadComplete hook */ protected void renderWizardPage(WizardNode page, boolean isForward, Map<String, Object> bundle) { boolean calledSave = false; prePageUnload(page); widgetPanel.clear(); pageToLoad = page; if (isForward && currentPage instanceof ContextAware) { pendingPage = (ContextAware) currentPage; // need to update current page first since we don't know when the // callback to operationComplete will occur and currentPage needs to // point to the new page at that point - currentPage = initializeNode(page); - waitDialog.showRelativeTo(widgetPanel); - pendingPage.persistContext(this); - calledSave = true; + currentPage = initializeNode(page); + if(! (pendingPage instanceof AutoAdvancing)){ + waitDialog.showRelativeTo(widgetPanel); + pendingPage.persistContext(this); + calledSave = true; + } } if(!isForward && currentPage instanceof ContextAware){ bundle = ((ContextAware) currentPage).getContextBundle(isForward); } if (isForward && page.getBreadcrumb() != null) { if (currentPage instanceof ContextAware) { addBreadcrumb(page, ((ContextAware) currentPage) .getContextBundle(isForward)); } else { addBreadcrumb(page, null); } } else if (!isForward && page != null && page.getBreadcrumb() != null) { removeBreadcrumb(page); } if (!calledSave) { currentPage = initializeNode(page); // since there is nothing being saved, we can populate the bundle // immediately (in the case of save being called, this happens in // the callback) populateBundle(bundle); widgetPanel.add(currentPage); resetNav(page); onLoadComplete(page); if (currentPage instanceof AutoAdvancing) { ((AutoAdvancing) currentPage).advance(this); } } } /** *Populates the bundle in the current page * */ private void populateBundle(Map<String, Object> bundle) { if (currentPage instanceof ContextAware) { if (bundle == null) { bundle = new HashMap<String, Object>(); } ((ContextAware) currentPage).setContextBundle(bundle); } } /** * Callback received when persistContext is completed * */ public void operationComplete(boolean isSuccessful, Map<String, Object> bundle) { waitDialog.hide(); if (isSuccessful) { widgetPanel.add(currentPage); populateBundle(bundle); if (bundle.get(WizardBundleConstants.AUTO_ADVANCE_FLAG) != null) { bundle.remove(WizardBundleConstants.AUTO_ADVANCE_FLAG); renderWizardPage(workflow.getWorkflowNode(pageToLoad .getNextNodes()[0].getNodeName()), true, bundle); } else { if (currentPage instanceof AutoAdvancing) { ((AutoAdvancing) currentPage).advance(this); } else { resetNav(pageToLoad); } } onLoadComplete(pageToLoad); } else { widgetPanel.clear(); currentPage = (Widget) pendingPage; widgetPanel.add(currentPage); } } /** * Adds a breadcrumb to the UI and installs click listeners * */ protected Breadcrumb addBreadcrumb(WizardNode node, Map<String, Object> bundle) { Breadcrumb bc = new Breadcrumb(node.getBreadcrumb(), node.getName(), bundle); if (!breadcrumbList.contains(node.getBreadcrumb())) { bc.addClickHandler(this); breadcrumbList.add(node.getBreadcrumb()); breadcrumbWidgets.put(node.getBreadcrumb(), bc); breadcrumbPanel.add(bc); return bc; } return null; } /** * removes breadcrumb from the UI * */ protected void removeBreadcrumb(WizardNode node) { int index = breadcrumbList.indexOf(node.getBreadcrumb()); if (index >= 0) { List<String> crumbsToNix = new ArrayList<String>(); for (int i = index + 1; i < breadcrumbList.size(); i++) { crumbsToNix.add(breadcrumbList.get(i)); Widget w = breadcrumbWidgets.remove(breadcrumbList.get(i)); if (w != null) { breadcrumbPanel.remove(w); } } breadcrumbList.removeAll(crumbsToNix); } } /** * Handles clicks of navigational buttons and breadcrumbs * */ public void onClick(ClickEvent event) { if (!working) { if (forwardNavButtons.contains(event.getSource())) { renderWizardPage(workflow.getWorkflowNode(buttonMapping .get(((Button) event.getSource()).getText())), true, null); } else if (backwardNavButtons.contains(event.getSource())) { renderWizardPage(workflow.getWorkflowNode(buttonMapping .get(((Button) event.getSource()).getText())), false, null); } else if (event.getSource() instanceof Breadcrumb) { // if it is a breadcrumb renderWizardPage(workflow.getWorkflowNode(((Breadcrumb) event .getSource()).getTargetNode()), false, ((Breadcrumb) event.getSource()).getBundle()); } } } /** * Opens a page. This can be called from wizard nodes to open a new page * that doesn't directly correspond to a back/forward/breadcrumb click * */ public void openPage(Class clazz, Map<String, Object> bundle) { if(!working){ if (clazz != null) { WizardNode node = workflow.findNode(clazz); if (node != null) { renderWizardPage(node, true, bundle); } } } } public void setWorking(boolean isWorking){ working = isWorking; } public boolean isWorking(){ return working; } /** * This method will return a populated WizardWorkflow object defining the * workflow for a wizard */ protected abstract WizardWorkflow getWizardWorkflow(); /** * * called to instantiate a widget that corresponds to the wizardNode that is * passed in */ protected abstract Widget initializeNode(WizardNode node); /** * called when all loading is complete and the widget has been added to the * display */ protected abstract void onLoadComplete(WizardNode node); /** * called before a page is removed from the UI */ protected abstract void prePageUnload(WizardNode nextNode); /** * Defines a workflow for a wizard. It must contain a start node */ public class WizardWorkflow { private WizardNode startNode; private Map<String, WizardNode> allNodes; public WizardWorkflow() { allNodes = new HashMap<String, WizardNode>(); } public void setStartNode(WizardNode n) { startNode = n; addInternalNode(n); } public WizardNode getStartNode() { return startNode; } public void addInternalNode(WizardNode n) { allNodes.put(n.getName(), n); } public WizardNode getWorkflowNode(String name) { return allNodes.get(name); } public WizardNode findNode(Class className) { if (allNodes != null) { for (WizardNode n : allNodes.values()) { if (n.getWidgetClass().equals(className)) { return n; } } } return null; } } /** * Defines a node (page) within a wizard. Each object defines the node name, * the class to be used for the widget, the breadcrumb name (null if no * breadcrumb) and 2 arrays of node names corresponding to the "forard" and * "backward" buttons. * * */ public class WizardNode { private Class widgetClass; private String name; private String breadcrumb; private WizardButton[] nextNodes; private WizardButton[] prevNodes; public WizardNode(String name, String breadcrumb, Class clazz, WizardButton next, WizardButton prev) { this.name = name; widgetClass = clazz; if (next != null) { nextNodes = new WizardButton[1]; nextNodes[0] = next; } else { nextNodes = new WizardButton[0]; } if (prev != null) { prevNodes = new WizardButton[1]; prevNodes[0] = prev; } else { prevNodes = new WizardButton[0]; } this.breadcrumb = breadcrumb; } public WizardNode(String name, String breadcrumb, Class clazz, WizardButton[] next, WizardButton[] prev) { this.name = name; this.breadcrumb = breadcrumb; widgetClass = clazz; nextNodes = next; prevNodes = prev; } public String getName() { return name; } public Class getWidgetClass() { return widgetClass; } public WizardButton[] getNextNodes() { return nextNodes; } public WizardButton[] getPrevNodes() { return prevNodes; } public String getBreadcrumb() { return breadcrumb; } } public class WizardButton { private String nodeName; private String label; public WizardButton(String node) { nodeName = node; label = node; } public WizardButton(String node, String label) { nodeName = node; this.label = label; } public String getNodeName() { return nodeName; } public void setNodeName(String nodeName) { this.nodeName = nodeName; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } } }
true
true
protected void renderWizardPage(WizardNode page, boolean isForward, Map<String, Object> bundle) { boolean calledSave = false; prePageUnload(page); widgetPanel.clear(); pageToLoad = page; if (isForward && currentPage instanceof ContextAware) { pendingPage = (ContextAware) currentPage; // need to update current page first since we don't know when the // callback to operationComplete will occur and currentPage needs to // point to the new page at that point currentPage = initializeNode(page); waitDialog.showRelativeTo(widgetPanel); pendingPage.persistContext(this); calledSave = true; } if(!isForward && currentPage instanceof ContextAware){ bundle = ((ContextAware) currentPage).getContextBundle(isForward); } if (isForward && page.getBreadcrumb() != null) { if (currentPage instanceof ContextAware) { addBreadcrumb(page, ((ContextAware) currentPage) .getContextBundle(isForward)); } else { addBreadcrumb(page, null); } } else if (!isForward && page != null && page.getBreadcrumb() != null) { removeBreadcrumb(page); } if (!calledSave) { currentPage = initializeNode(page); // since there is nothing being saved, we can populate the bundle // immediately (in the case of save being called, this happens in // the callback) populateBundle(bundle); widgetPanel.add(currentPage); resetNav(page); onLoadComplete(page); if (currentPage instanceof AutoAdvancing) { ((AutoAdvancing) currentPage).advance(this); } } }
protected void renderWizardPage(WizardNode page, boolean isForward, Map<String, Object> bundle) { boolean calledSave = false; prePageUnload(page); widgetPanel.clear(); pageToLoad = page; if (isForward && currentPage instanceof ContextAware) { pendingPage = (ContextAware) currentPage; // need to update current page first since we don't know when the // callback to operationComplete will occur and currentPage needs to // point to the new page at that point currentPage = initializeNode(page); if(! (pendingPage instanceof AutoAdvancing)){ waitDialog.showRelativeTo(widgetPanel); pendingPage.persistContext(this); calledSave = true; } } if(!isForward && currentPage instanceof ContextAware){ bundle = ((ContextAware) currentPage).getContextBundle(isForward); } if (isForward && page.getBreadcrumb() != null) { if (currentPage instanceof ContextAware) { addBreadcrumb(page, ((ContextAware) currentPage) .getContextBundle(isForward)); } else { addBreadcrumb(page, null); } } else if (!isForward && page != null && page.getBreadcrumb() != null) { removeBreadcrumb(page); } if (!calledSave) { currentPage = initializeNode(page); // since there is nothing being saved, we can populate the bundle // immediately (in the case of save being called, this happens in // the callback) populateBundle(bundle); widgetPanel.add(currentPage); resetNav(page); onLoadComplete(page); if (currentPage instanceof AutoAdvancing) { ((AutoAdvancing) currentPage).advance(this); } } }
diff --git a/resources/sip11/ra/src/main/java/org/mobicents/slee/resource/sip11/wrappers/ClientDialogWrapper.java b/resources/sip11/ra/src/main/java/org/mobicents/slee/resource/sip11/wrappers/ClientDialogWrapper.java index b9974d702..bb9091aa5 100644 --- a/resources/sip11/ra/src/main/java/org/mobicents/slee/resource/sip11/wrappers/ClientDialogWrapper.java +++ b/resources/sip11/ra/src/main/java/org/mobicents/slee/resource/sip11/wrappers/ClientDialogWrapper.java @@ -1,925 +1,925 @@ package org.mobicents.slee.resource.sip11.wrappers; import gov.nist.javax.sip.DialogExt; import gov.nist.javax.sip.ListeningPointImpl; import gov.nist.javax.sip.address.SipUri; import gov.nist.javax.sip.header.CSeq; import gov.nist.javax.sip.header.RouteList; import gov.nist.javax.sip.message.SIPResponse; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicLong; import javax.sip.ClientTransaction; import javax.sip.DialogDoesNotExistException; import javax.sip.DialogState; import javax.sip.InvalidArgumentException; import javax.sip.ResponseEvent; import javax.sip.ServerTransaction; import javax.sip.SipException; import javax.sip.Transaction; import javax.sip.TransactionDoesNotExistException; import javax.sip.TransactionUnavailableException; import javax.sip.address.Address; import javax.sip.address.SipURI; import javax.sip.address.URI; import javax.sip.header.CSeqHeader; import javax.sip.header.CallIdHeader; import javax.sip.header.ContactHeader; import javax.sip.header.FromHeader; import javax.sip.header.HeaderFactory; import javax.sip.header.MaxForwardsHeader; import javax.sip.header.RouteHeader; import javax.sip.header.ToHeader; import javax.sip.header.ViaHeader; import javax.sip.message.Request; import javax.sip.message.Response; import javax.slee.facilities.Tracer; import javax.slee.resource.FireableEventType; import net.java.slee.resource.sip.DialogForkedEvent; import org.mobicents.slee.resource.sip11.ClusteredSipActivityManagement; import org.mobicents.slee.resource.sip11.DialogWithoutIdActivityHandle; import org.mobicents.slee.resource.sip11.SipActivityHandle; import org.mobicents.slee.resource.sip11.SipResourceAdaptor; import org.mobicents.slee.resource.sip11.SleeSipProviderImpl; import org.mobicents.slee.resource.sip11.Utils; public class ClientDialogWrapper extends DialogWrapper { /** * */ private static final long serialVersionUID = 1L; private static Tracer tracer; protected ClientDialogWrapperData data; private ClientDialogWrapper(SipActivityHandle activityHandle, String localTag, SipResourceAdaptor ra, ClientDialogForkHandler forkData) { super(activityHandle, localTag, ra); data = new ClientDialogWrapperData(forkData); setResourceAdaptor(ra); } @Override public void setResourceAdaptor(SipResourceAdaptor ra) { super.setResourceAdaptor(ra); if (tracer == null) { tracer = ra.getTracer(ClientDialogWrapper.class.getSimpleName()); } } /** * Constructs an instance of a UAC dialog. * * @param from * @param localTag * @param to * @param callIdHeader * @param provider * @param ra */ public ClientDialogWrapper(Address from, String localTag, Address to, CallIdHeader callIdHeader, SipResourceAdaptor ra, ClientDialogForkHandler forkData) { this(new DialogWithoutIdActivityHandle(callIdHeader.getCallId(), localTag, null), localTag, ra, forkData); data.setToAddress(to); data.setFromAddress(from); data.setCustomCallId(callIdHeader); } /** * for forks * * @param wrappedDialog * @param forkInitialActivityHandle * @param provider * @param ra */ private ClientDialogWrapper(DialogWithoutIdActivityHandle forkHandle, ClientDialogWrapper master) { this(forkHandle,master.getLocalTag(), master.ra, new ClientDialogForkHandler((DialogWithoutIdActivityHandle) master.activityHandle)); this.wrappedDialog = master.wrappedDialog; } @Override public javax.slee.Address getEventFiringAddress() { if (eventFiringAddress == null) { if (wrappedDialog != null) { eventFiringAddress = super.getEventFiringAddress(); } else { // outgoing dialog where the wrapped dialog does not exists yet eventFiringAddress = ClientTransactionWrapper.getEventFiringAddress(data.getFromAddress()); } } return eventFiringAddress; } @Override public Request createAck(long arg0) throws InvalidArgumentException, SipException { verifyDialogExistency(); return super.createAck(arg0); } @Override public Request createPrack(Response arg0) throws DialogDoesNotExistException, SipException { verifyDialogExistency(); return super.createPrack(arg0); } @Override public Response createReliableProvisionalResponse(int arg0) throws InvalidArgumentException, SipException { verifyDialogExistency(); return super.createReliableProvisionalResponse(arg0); } @Override public void delete() { if (wrappedDialog == null) { if (tracer.isFineEnabled()) { tracer.fine("Deleting "+getActivityHandle()+" dialog activity, there is no wrapped dialog."); } // no real dialog ra.processDialogTerminated(this); } else { final ClientDialogForkHandler forkHandler = data.getForkHandler(); if (forkHandler.getMaster() == null) { // we are master, if it is forking lets terminate all forks forkHandler.terminate(ra); if (forkHandler.getForkWinner() == null) { // this is the confirmed dialog, it's safe to delete the wrapped dialog in super if (tracer.isFineEnabled()) { tracer.fine("Fully deleting "+getActivityHandle()+" dialog, there is no confirmed fork."); } super.delete(); } else { // a fork confirmed, just terminate the activity for this one if (tracer.isFineEnabled()) { tracer.fine("Deleting "+getActivityHandle()+" dialog activity, the wrapped dialog is still used by a confirmed fork."); } ra.processDialogTerminated(this); } } else { // a fork dialog DialogWithoutIdActivityHandle forkWinner = forkHandler.getForkWinner(); if (forkHandler.isForking() || forkWinner == null || !forkWinner.equals(getActivityHandle())) { if (tracer.isFineEnabled()) { tracer.fine("Deleting "+getActivityHandle()+" dialog activity, a fork which was not confirmed."); } ra.processDialogTerminated(this); } else { if (tracer.isFineEnabled()) { tracer.fine("Fully deleting "+getActivityHandle()+" dialog, a fork which was confirmed."); } super.delete(); } } } } @Override public CallIdHeader getCallId() { if (this.wrappedDialog == null) { return data.getCustomCallId(); } return super.getCallId(); } @Override public String getDialogId() { if (this.wrappedDialog == null) { return null; } return super.getDialogId(); } @SuppressWarnings("deprecation") @Override public Transaction getFirstTransaction() { verifyDialogExistency(); return super.getFirstTransaction(); } @Override public Address getLocalParty() { if (wrappedDialog != null && !data.getForkHandler().isForking()) { return super.getLocalParty(); } else { return data.getFromAddress(); } } @Override public Address getRemoteParty() { if (wrappedDialog != null && !data.getForkHandler().isForking()) { return super.getRemoteParty(); } else { return data.getToAddress(); } } @Override public Address getRemoteTarget() { if (wrappedDialog != null && !data.getForkHandler().isForking()) { return super.getRemoteTarget(); } else { return data.getToAddress(); } } @Override public long getLocalSeqNumber() { if (data.getForkHandler().isForking() || wrappedDialog == null) { return data.getLocalSequenceNumber().get(); } else { return super.getLocalSeqNumber(); } } @Override public int getLocalSequenceNumber() { return (int) getLocalSeqNumber(); } @Override public long getRemoteSeqNumber() { if (wrappedDialog != null) return super.getRemoteSeqNumber(); else return 1L; } @Override public int getRemoteSequenceNumber() { return (int) getRemoteSeqNumber(); } @Override public String getRemoteTag() { if (wrappedDialog != null && !data.getForkHandler().isForking()) { return super.getRemoteTag(); } else { return data.getLocalRemoteTag(); } } @Override public DialogState getState() { if (wrappedDialog == null) { return null; } return super.getState(); } @Override public void incrementLocalSequenceNumber() { if (data.getForkHandler().isForking() || wrappedDialog == null) { data.getLocalSequenceNumber().incrementAndGet(); // not needed till we have some sort of early dialog replication // updateReplicatedState(); } else { super.incrementLocalSequenceNumber(); } } @Override public boolean isSecure() { if (wrappedDialog == null) return false; return super.isSecure(); } @Override public boolean isServer() { return false; } @Override public void sendAck(Request arg0) throws SipException { verifyDialogExistency(); super.sendAck(arg0); } @Override public void sendReliableProvisionalResponse(Response arg0) throws SipException { verifyDialogExistency(); super.sendReliableProvisionalResponse(arg0); } @Override public void terminateOnBye(boolean arg0) throws SipException { verifyDialogExistency(); super.terminateOnBye(arg0); } @Override public boolean addOngoingTransaction(ServerTransactionWrapper stw) { if (data.getForkHandler().isForking()) { // Yup, could be reinveite? we have to update local DW cseq :) final long cSeqNewValue = ((CSeqHeader) stw.getRequest().getHeader( CSeqHeader.NAME)).getSeqNumber(); final AtomicLong cSeq = data.getLocalSequenceNumber(); if (cSeqNewValue > cSeq.get()) cSeq.set(cSeqNewValue); } // super updates replicated state return super.addOngoingTransaction(stw); } // =========================== XXX: Helper methods ===================== @Override public String toString() { return new StringBuilder("ClientDialogWrapper Id[").append( this.getDialogId()).append("] Handle[").append( this.getActivityHandle()).append("] State[").append( this.getState()).append("] OngoingCTX[").append( this.ongoingClientTransactions.keySet()).append("] OngoingSTX[") .append(this.ongoingServerTransactions.keySet()).append("]") .toString(); } // ########################################### // # Strictly DialogActivity defined methods # // ########################################### @Override public ClientTransaction sendCancel() throws SipException { verifyDialogExistency(); return super.sendCancel(); } @Override public void associateServerTransaction(ClientTransaction ct, ServerTransaction st) { // ct MUST be in ongoing transaction, its local, st - comes from another // dialog verifyDialogExistency(); super.associateServerTransaction(ct, st); } /* (non-Javadoc) * @see org.mobicents.slee.resource.sip11.wrappers.DialogWrapper#createRequest(javax.sip.message.Request) */ @Override public Request createRequest(Request origRequest) throws SipException { Request request = super.createRequest(origRequest); if (wrappedDialog != null && data.getForkHandler().isForking()) { updateRequestWithForkData(request); } return request; } @Override public Request createRequest(String methodName) throws SipException { if (methodName.equals(Request.ACK) || methodName.equals(Request.PRACK)) { throw new SipException("Invalid method specified for createRequest:" + methodName); } final SleeSipProviderImpl provider = ra.getProviderWrapper(); final HeaderFactory headerFactory = provider.getHeaderFactory(); Request request = null; if (this.wrappedDialog == null) { // the real dialog doesn't exist yet so we act like we will build // such a dialog when sending this request try { // create headers URI requestURI = null; if (this.getRemoteTarget() != null) requestURI = (URI) getRemoteTarget().getURI().clone(); else { requestURI = (URI) data.getToAddress().getURI().clone(); //FIXME: check for SipUri instanceof ? if(requestURI.isSipURI()) { ((SipUri)requestURI).clearUriParms(); } } final FromHeader fromHeader = headerFactory.createFromHeader( data.getFromAddress(), getLocalTag()); final ToHeader toHeader = headerFactory.createToHeader( data.getToAddress(), null); final List<Object> viaHeadersList = new ArrayList<Object>(1); viaHeadersList.add(provider.getLocalVia()); final MaxForwardsHeader maxForwardsHeader = headerFactory .createMaxForwardsHeader(70); final CSeqHeader cSeqHeader = headerFactory.createCSeqHeader( data.getLocalSequenceNumber().get() + 1, methodName); request = provider.getMessageFactory() .createRequest(requestURI, methodName, data.getCustomCallId(), cSeqHeader, fromHeader, toHeader, viaHeadersList, maxForwardsHeader); final RouteList routeList = data.getLocalRouteList(); if (routeList != null) { request.setHeader(routeList); } } catch (Exception e) { throw new SipException(e.getMessage(), e); } } else if (data.getForkHandler().isForking()) { // create request using dialog request = this.wrappedDialog.createRequest(methodName); updateRequestWithForkData(request); } else { request = super.createRequest(methodName); } if (getState() == null) { // adds load balancer to route if exists ra.getProviderWrapper().addLoadBalancerToRoute(request); } return request; } private void updateRequestWithForkData(Request request) throws SipException { final URI requestURI = (URI) data.getRequestURI().clone(); request.setRequestURI(requestURI); final RouteList routeList = data.getLocalRouteList(); if (routeList != null) { request.setHeader(routeList); } final CSeqHeader cseq = (CSeqHeader) request .getHeader(CSeq.NAME); try { if (!request.getMethod().equals(Request.CANCEL) && !request.getMethod().equals(Request.ACK)) { cseq.setSeqNumber(data.getLocalSequenceNumber().get() + 1); } request.setMethod(cseq.getMethod()); if (data.getLocalRemoteTag() != null) { ((ToHeader) request.getHeader(ToHeader.NAME)) .setTag(data.getLocalRemoteTag()); } } catch (ParseException e) { throw new SipException(e.getMessage(), e); } catch (InvalidArgumentException e) { throw new SipException(e.getMessage(), e); } } @Override public ClientTransaction sendRequest(Request request) throws SipException, TransactionUnavailableException { if (wrappedDialog == null && !Utils.getDialogCreatingMethods().contains( request.getMethod())) { throw new IllegalStateException( "Dialog activity present, but no dialog creating reqeust has been sent yet! This method: " + request.getMethod() + " is not dialog creating one"); } ensureCorrectDialogLocalTag(request); final SleeSipProviderImpl provider = ra.getProviderWrapper(); final ClientTransactionWrapper ctw = provider .getNewDialogActivityClientTransaction(this, request); final String method = request.getMethod(); if (method.equals(Request.INVITE)) lastCancelableTransactionId = ctw.activityHandle; final boolean createDialog = wrappedDialog == null; if (createDialog) { this.wrappedDialog = provider.getRealProvider().getNewDialog( ctw.getWrappedTransaction()); if(ra.isValidateDialogCSeq()) { ((DialogExt)this.wrappedDialog).disableSequenceNumberValidation(); } this.wrappedDialog.setApplicationData(this); } else { // only when wrapped dialog exist we need to care about right remote // tag ensureCorrectDialogRemoteTag(request); } if (tracer.isInfoEnabled()) { tracer.info(String.valueOf(ctw) + " sending request:\n" + request); } if (data.getForkHandler().isForking()) { // cause dialog spoils - changes cseq, we dont want that if (!method.equals(Request.ACK) && !method.equals(Request.CANCEL)) data.getLocalSequenceNumber().incrementAndGet(); ctw.getWrappedClientTransaction().sendRequest(); } else { if (createDialog) { // dialog in null state does not allows to send request ctw.getWrappedClientTransaction().sendRequest(); } else { this.wrappedDialog.sendRequest(ctw .getWrappedClientTransaction()); } } return ctw; } private void ensureCorrectDialogRemoteTag(Request request) throws SipException { final String remoteTag = (data.getForkHandler().isForking() && data.getLocalRemoteTag() != null ? data.getLocalRemoteTag() : wrappedDialog.getRemoteTag()); if (remoteTag != null) { // ensure we are using the right remote tag try { ((ToHeader) request.getHeader(ToHeader.NAME)).setTag(remoteTag); } catch (ParseException e) { throw new SipException(e.getMessage(), e); } } } @Override public void sendRequest(ClientTransaction ct) throws TransactionDoesNotExistException, SipException { final SleeSipProviderImpl provider = ra.getProviderWrapper(); final Request request = ct.getRequest(); final ClientTransactionWrapper ctw = (ClientTransactionWrapper) ct; ensureCorrectDialogLocalTag(request); final boolean createDialog = wrappedDialog == null; if (createDialog) { if (!Utils.getDialogCreatingMethods().contains(request.getMethod())) { throw new IllegalStateException( "Dialog activity present, but no dialog creating reqeust has been sent yet! This method: " + request.getMethod() + " is not dialog creating one"); } if (request.getMethod().equals(Request.INVITE)) lastCancelableTransactionId = ctw.getActivityHandle(); this.wrappedDialog = provider.getRealProvider().getNewDialog( ctw.getWrappedTransaction()); this.wrappedDialog.setApplicationData(this); this.addOngoingTransaction(ctw); if (tracer.isInfoEnabled()) { tracer.info(String.valueOf(ctw) + " sending request:\n" + request); } // dialog in null state does not allows to send request ctw.getWrappedClientTransaction().sendRequest(); } else { ensureCorrectDialogRemoteTag(request); if (tracer.isInfoEnabled()) { tracer.info(String.valueOf(ctw) + " sending request:\n" + request); } if (data.getForkHandler().isForking()) { if (!request.getMethod().equals(Request.ACK) && !request.getMethod().equals(Request.CANCEL)) data.getLocalSequenceNumber().incrementAndGet(); ctw.getWrappedClientTransaction().sendRequest(); } else { wrappedDialog.sendRequest(ctw.getWrappedClientTransaction()); } } } // ############################################################## // # Strictly dialog forge - used when no dialog is present yet # // ############################################################## /** * */ private void verifyDialogExistency() { if (wrappedDialog == null) { throw new IllegalStateException( "Dialog activity present, but no dialog creating request has been sent yet!"); } } @Override public boolean processIncomingResponse(ResponseEvent respEvent) { final ClientDialogForkHandler forkHandler = data.getForkHandler(); - if (!forkHandler.isForking()) { + if (!forkHandler.isForking() || respEvent.getClientTransaction().getRequest().getMethod().equals(Request.CANCEL)) { // nothing to do, let the ra fire the event return false; } final Response response = respEvent.getResponse(); boolean eventFired = false; final int statusCode = response.getStatusCode(); final String toTag = ((ToHeader) response.getHeader(ToHeader.NAME)) .getTag(); boolean fineTrace = tracer.isFineEnabled(); if (statusCode < 200) { if (toTag != null) { if (data.getLocalRemoteTag() == null) { if (fineTrace) { tracer.fine("Client dialog "+getActivityHandle()+" received "+statusCode+" response with first remote tag "+toTag); } data.setLocalRemoteTag(toTag); this.fetchData(response); } else if (data.getLocalRemoteTag().equals(toTag)) { if (fineTrace) { tracer.fine("Client dialog "+getActivityHandle()+" received "+statusCode+" response with first remote tag "+toTag+" again"); } this.fetchData(response); } else { // fork DialogWithoutIdActivityHandle forkHandle = forkHandler.getFork(toTag); if (forkHandle == null) { if (fineTrace) { tracer.fine("Client dialog "+getActivityHandle()+" received "+statusCode+" response with new fork remote tag "+toTag); } ClientDialogWrapper forkDialog = getNewDialogFork(toTag,fineTrace); forkDialog.fetchData(response); forkHandler.addFork(ra, (DialogWithoutIdActivityHandle) forkDialog.getActivityHandle()); // fire dialog forked event on original activity fireDialogForkEvent(respEvent, forkDialog, fineTrace); eventFired = true; } else { if (fineTrace) { tracer.fine("Client dialog "+getActivityHandle()+" received "+statusCode+" response with existent fork remote tag "+toTag); } ClientDialogWrapper forkDialog = (ClientDialogWrapper) this.ra.getActivity(forkHandle); if (forkDialog == null) { // dude, where is my dialog? if (tracer.isSevereEnabled()) { tracer.severe("Can't find dialog "+activityHandle+" fork with remote tag "+toTag+" in RA's activity management"); } return true; } forkDialog.fetchData(response); // fire event on fork activity fireReceivedEvent(respEvent,forkDialog,fineTrace); eventFired = true; } } } } else if (statusCode < 300) { if (toTag != null) { if (data.getLocalRemoteTag() == null) { if (fineTrace) { tracer.fine("Client dialog "+getActivityHandle()+" confirmed with remote tag "+toTag); } data.setLocalRemoteTag(toTag); if (!ra.inLocalMode()) { ((ClusteredSipActivityManagement)ra.getActivityManagement()).replicateRemoteTag((DialogWithoutIdActivityHandle) getActivityHandle(),toTag); } this.fetchData(response); forkHandler.terminate(ra); } else if (data.getLocalRemoteTag().equals(toTag)) { if (fineTrace) { tracer.fine("Client dialog "+getActivityHandle()+" confirmed with remote tag "+toTag); } if (!ra.inLocalMode()) { ((ClusteredSipActivityManagement)ra.getActivityManagement()).replicateRemoteTag((DialogWithoutIdActivityHandle) getActivityHandle(),toTag); } this.fetchData(response); forkHandler.terminate(ra); } else { // fork DialogWithoutIdActivityHandle forkHandle = forkHandler.getFork(toTag); if (forkHandle == null) { if (fineTrace) { tracer.fine("Client dialog "+getActivityHandle()+" confirmed with new fork remote tag "+toTag); } final ClientDialogWrapper forkDialog = getNewDialogFork(toTag,fineTrace); forkDialog.fetchData(response); // end forking forkHandler.forkConfirmed(ra, this, forkDialog); // fire dialog forked event on original activity fireDialogForkEvent(respEvent, forkDialog, fineTrace); eventFired = true; } else { if (fineTrace) { tracer.fine("Client dialog "+getActivityHandle()+" confirmed with existent fork remote tag "+toTag); } final ClientDialogWrapper forkDialog = (ClientDialogWrapper) ra .getActivityManagement().get(forkHandle); if (forkDialog == null) { // dude, where is my dialog? if (tracer.isSevereEnabled()) { tracer.severe("Can't find dialog "+activityHandle+" fork with remote tag "+toTag+" in RA's activity management"); } return true; } forkHandler.forkConfirmed(ra, this, forkDialog); forkDialog.fetchData(response); // fire event on fork activity fireReceivedEvent(respEvent,forkDialog,fineTrace); eventFired = true; } } // if in cluster mode we now need to redo replication since the wrapper state chnaged wrappedDialog.setApplicationData(this); } } else { if (fineTrace) { tracer.fine("Client dialog "+getActivityHandle()+" received "+statusCode+" error response, terminating fork"); } // error while forking, fire event and terminate forking fireReceivedEvent(respEvent, this, fineTrace); eventFired = true; this.data.getForkHandler().terminate(ra); } // not needed till we have some sort of early dialog replication // updateReplicatedState(); return eventFired; } /** * @param respEvent * @param dw * @param fineTrace */ private void fireReceivedEvent(ResponseEvent respEvent, ClientDialogWrapper dw, boolean fineTrace) { final FireableEventType eventType = ra.getEventIdCache() .getEventId(ra.getEventLookupFacility(), respEvent.getResponse()); final ResponseEventWrapper eventObject = new ResponseEventWrapper( ra.getProviderWrapper(), (ClientTransaction) respEvent .getClientTransaction() .getApplicationData(), this, respEvent.getResponse()); fireEvent(fineTrace, eventObject, dw.activityHandle,dw.getEventFiringAddress(), eventType); } /** * * @param respEvent * @param fork * @param fineTrace */ private void fireDialogForkEvent(ResponseEvent respEvent, ClientDialogWrapper fork, boolean fineTrace) { // fire dialog forked event on original activity final FireableEventType eventID = ra.getEventIdCache() .getDialogForkEventId(ra .getEventLookupFacility()); final DialogForkedEvent eventObject = new DialogForkedEvent( ra.getProviderWrapper(), respEvent .getClientTransaction(), this, fork, respEvent.getResponse()); fireEvent(fineTrace, eventObject, this.activityHandle,this.getEventFiringAddress(), eventID); } /** * @param fineTrace * @param event * @param activityHandle * @param eventFiringAddress * @param eventID */ private void fireEvent(boolean fineTrace, Object event, SipActivityHandle activityHandle, javax.slee.Address eventFiringAddress, FireableEventType eventType) { if (ra.getEventIDFilter().filterEvent(eventType)) { if(fineTrace) { tracer.fine("Event "+(eventType==null?"null":eventType.getEventType())+" filtered."); } return; } try { ra.getSleeEndpoint().fireEvent(activityHandle, eventType, event, eventFiringAddress, null,SipResourceAdaptor.DEFAULT_EVENT_FLAGS); } catch (Throwable e) { tracer.severe("Failed to fire event",e); } } /** * * @param dialog * @return */ private ClientDialogWrapper getNewDialogFork(String forkRemoteTag, boolean fineTrace) { final DialogWithoutIdActivityHandle originalHandle = (DialogWithoutIdActivityHandle) this.activityHandle; final DialogWithoutIdActivityHandle forkHandle = new DialogWithoutIdActivityHandle(originalHandle.getCallId(), originalHandle.getLocalTag(), forkRemoteTag); final ClientDialogWrapper dw = new ClientDialogWrapper(forkHandle, this); dw.data.setLocalRemoteTag(forkRemoteTag); data.getForkHandler().addFork(ra, forkHandle); ra.addActivity(dw, false, fineTrace); return dw; } private void fetchData(Response response) { // fetch routeSet, requestURI and ToTag, callId // this is done only once? data.setLocalRemoteTag(((ToHeader) response.getHeader(ToHeader.NAME)) .getTag()); ContactHeader contact = ((ContactHeader) response .getHeader(ContactHeader.NAME)); // issue 623 if (contact != null && data.getRequestURI() == null) { data.setRequestURI(contact.getAddress().getURI()); } // save the route, but ensure we don't save the top route pointing to us final SIPResponse sipResponse = (SIPResponse) response; RouteList routeList = sipResponse.getRouteHeaders(); if (routeList != null) { final RouteHeader topRoute = routeList.get(0); final URI topRouteURI = topRoute.getAddress().getURI(); if (topRouteURI.isSipURI()) { final SipURI topRouteSipURI = (SipURI) topRouteURI; final String transport = ((ViaHeader)sipResponse.getHeader(ViaHeader.NAME)).getTransport(); final ListeningPointImpl lp = (ListeningPointImpl) ra.getProviderWrapper().getListeningPoint(transport); if (topRouteSipURI.getHost().equals( lp.getIPAddress()) && topRouteSipURI.getPort() == lp.getPort()) { if (routeList.size() > 1) { routeList = (RouteList) routeList.clone(); routeList.remove(0); data.setLocalRouteList(routeList); } } else { data.setLocalRouteList((RouteList) routeList.clone()); } } } data.setCustomCallId((CallIdHeader) response.getHeader(CallIdHeader.NAME)); } /* (non-Javadoc) * @see org.mobicents.slee.resource.sip11.wrappers.Wrapper#clear() */ @Override public void clear() { final ClientDialogForkHandler forkHandler = data.getForkHandler(); if (forkHandler.getMaster() != null) { if (wrappedDialog != null) { // a confirmed fork, remove the master now if (tracer.isFineEnabled()) { tracer.fine("Confirmed fork dialog "+getActivityHandle()+" ended, removing its master dialog"); } ra.getActivityManagement().remove(forkHandler.getMaster()); } } else { if (forkHandler.getForkWinner() != null) { // a fork confirmed the dialog, lets add it again to the activities map, to be able to handle late fork confirmations if (tracer.isFineEnabled()) { tracer.fine("Restoring dialog "+getActivityHandle()+" to the RA's activity management o handle possible late 2xx responses, a fork was confirmed."); } ra.getActivityManagement().put(getActivityHandle(), this); } } super.clear(); data = null; } // serialization private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); } private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); activityHandle.setActivity(this); } }
true
true
public boolean processIncomingResponse(ResponseEvent respEvent) { final ClientDialogForkHandler forkHandler = data.getForkHandler(); if (!forkHandler.isForking()) { // nothing to do, let the ra fire the event return false; } final Response response = respEvent.getResponse(); boolean eventFired = false; final int statusCode = response.getStatusCode(); final String toTag = ((ToHeader) response.getHeader(ToHeader.NAME)) .getTag(); boolean fineTrace = tracer.isFineEnabled(); if (statusCode < 200) { if (toTag != null) { if (data.getLocalRemoteTag() == null) { if (fineTrace) { tracer.fine("Client dialog "+getActivityHandle()+" received "+statusCode+" response with first remote tag "+toTag); } data.setLocalRemoteTag(toTag); this.fetchData(response); } else if (data.getLocalRemoteTag().equals(toTag)) { if (fineTrace) { tracer.fine("Client dialog "+getActivityHandle()+" received "+statusCode+" response with first remote tag "+toTag+" again"); } this.fetchData(response); } else { // fork DialogWithoutIdActivityHandle forkHandle = forkHandler.getFork(toTag); if (forkHandle == null) { if (fineTrace) { tracer.fine("Client dialog "+getActivityHandle()+" received "+statusCode+" response with new fork remote tag "+toTag); } ClientDialogWrapper forkDialog = getNewDialogFork(toTag,fineTrace); forkDialog.fetchData(response); forkHandler.addFork(ra, (DialogWithoutIdActivityHandle) forkDialog.getActivityHandle()); // fire dialog forked event on original activity fireDialogForkEvent(respEvent, forkDialog, fineTrace); eventFired = true; } else { if (fineTrace) { tracer.fine("Client dialog "+getActivityHandle()+" received "+statusCode+" response with existent fork remote tag "+toTag); } ClientDialogWrapper forkDialog = (ClientDialogWrapper) this.ra.getActivity(forkHandle); if (forkDialog == null) { // dude, where is my dialog? if (tracer.isSevereEnabled()) { tracer.severe("Can't find dialog "+activityHandle+" fork with remote tag "+toTag+" in RA's activity management"); } return true; } forkDialog.fetchData(response); // fire event on fork activity fireReceivedEvent(respEvent,forkDialog,fineTrace); eventFired = true; } } } } else if (statusCode < 300) { if (toTag != null) { if (data.getLocalRemoteTag() == null) { if (fineTrace) { tracer.fine("Client dialog "+getActivityHandle()+" confirmed with remote tag "+toTag); } data.setLocalRemoteTag(toTag); if (!ra.inLocalMode()) { ((ClusteredSipActivityManagement)ra.getActivityManagement()).replicateRemoteTag((DialogWithoutIdActivityHandle) getActivityHandle(),toTag); } this.fetchData(response); forkHandler.terminate(ra); } else if (data.getLocalRemoteTag().equals(toTag)) { if (fineTrace) { tracer.fine("Client dialog "+getActivityHandle()+" confirmed with remote tag "+toTag); } if (!ra.inLocalMode()) { ((ClusteredSipActivityManagement)ra.getActivityManagement()).replicateRemoteTag((DialogWithoutIdActivityHandle) getActivityHandle(),toTag); } this.fetchData(response); forkHandler.terminate(ra); } else { // fork DialogWithoutIdActivityHandle forkHandle = forkHandler.getFork(toTag); if (forkHandle == null) { if (fineTrace) { tracer.fine("Client dialog "+getActivityHandle()+" confirmed with new fork remote tag "+toTag); } final ClientDialogWrapper forkDialog = getNewDialogFork(toTag,fineTrace); forkDialog.fetchData(response); // end forking forkHandler.forkConfirmed(ra, this, forkDialog); // fire dialog forked event on original activity fireDialogForkEvent(respEvent, forkDialog, fineTrace); eventFired = true; } else { if (fineTrace) { tracer.fine("Client dialog "+getActivityHandle()+" confirmed with existent fork remote tag "+toTag); } final ClientDialogWrapper forkDialog = (ClientDialogWrapper) ra .getActivityManagement().get(forkHandle); if (forkDialog == null) { // dude, where is my dialog? if (tracer.isSevereEnabled()) { tracer.severe("Can't find dialog "+activityHandle+" fork with remote tag "+toTag+" in RA's activity management"); } return true; } forkHandler.forkConfirmed(ra, this, forkDialog); forkDialog.fetchData(response); // fire event on fork activity fireReceivedEvent(respEvent,forkDialog,fineTrace); eventFired = true; } } // if in cluster mode we now need to redo replication since the wrapper state chnaged wrappedDialog.setApplicationData(this); } } else { if (fineTrace) { tracer.fine("Client dialog "+getActivityHandle()+" received "+statusCode+" error response, terminating fork"); } // error while forking, fire event and terminate forking fireReceivedEvent(respEvent, this, fineTrace); eventFired = true; this.data.getForkHandler().terminate(ra); } // not needed till we have some sort of early dialog replication // updateReplicatedState(); return eventFired; }
public boolean processIncomingResponse(ResponseEvent respEvent) { final ClientDialogForkHandler forkHandler = data.getForkHandler(); if (!forkHandler.isForking() || respEvent.getClientTransaction().getRequest().getMethod().equals(Request.CANCEL)) { // nothing to do, let the ra fire the event return false; } final Response response = respEvent.getResponse(); boolean eventFired = false; final int statusCode = response.getStatusCode(); final String toTag = ((ToHeader) response.getHeader(ToHeader.NAME)) .getTag(); boolean fineTrace = tracer.isFineEnabled(); if (statusCode < 200) { if (toTag != null) { if (data.getLocalRemoteTag() == null) { if (fineTrace) { tracer.fine("Client dialog "+getActivityHandle()+" received "+statusCode+" response with first remote tag "+toTag); } data.setLocalRemoteTag(toTag); this.fetchData(response); } else if (data.getLocalRemoteTag().equals(toTag)) { if (fineTrace) { tracer.fine("Client dialog "+getActivityHandle()+" received "+statusCode+" response with first remote tag "+toTag+" again"); } this.fetchData(response); } else { // fork DialogWithoutIdActivityHandle forkHandle = forkHandler.getFork(toTag); if (forkHandle == null) { if (fineTrace) { tracer.fine("Client dialog "+getActivityHandle()+" received "+statusCode+" response with new fork remote tag "+toTag); } ClientDialogWrapper forkDialog = getNewDialogFork(toTag,fineTrace); forkDialog.fetchData(response); forkHandler.addFork(ra, (DialogWithoutIdActivityHandle) forkDialog.getActivityHandle()); // fire dialog forked event on original activity fireDialogForkEvent(respEvent, forkDialog, fineTrace); eventFired = true; } else { if (fineTrace) { tracer.fine("Client dialog "+getActivityHandle()+" received "+statusCode+" response with existent fork remote tag "+toTag); } ClientDialogWrapper forkDialog = (ClientDialogWrapper) this.ra.getActivity(forkHandle); if (forkDialog == null) { // dude, where is my dialog? if (tracer.isSevereEnabled()) { tracer.severe("Can't find dialog "+activityHandle+" fork with remote tag "+toTag+" in RA's activity management"); } return true; } forkDialog.fetchData(response); // fire event on fork activity fireReceivedEvent(respEvent,forkDialog,fineTrace); eventFired = true; } } } } else if (statusCode < 300) { if (toTag != null) { if (data.getLocalRemoteTag() == null) { if (fineTrace) { tracer.fine("Client dialog "+getActivityHandle()+" confirmed with remote tag "+toTag); } data.setLocalRemoteTag(toTag); if (!ra.inLocalMode()) { ((ClusteredSipActivityManagement)ra.getActivityManagement()).replicateRemoteTag((DialogWithoutIdActivityHandle) getActivityHandle(),toTag); } this.fetchData(response); forkHandler.terminate(ra); } else if (data.getLocalRemoteTag().equals(toTag)) { if (fineTrace) { tracer.fine("Client dialog "+getActivityHandle()+" confirmed with remote tag "+toTag); } if (!ra.inLocalMode()) { ((ClusteredSipActivityManagement)ra.getActivityManagement()).replicateRemoteTag((DialogWithoutIdActivityHandle) getActivityHandle(),toTag); } this.fetchData(response); forkHandler.terminate(ra); } else { // fork DialogWithoutIdActivityHandle forkHandle = forkHandler.getFork(toTag); if (forkHandle == null) { if (fineTrace) { tracer.fine("Client dialog "+getActivityHandle()+" confirmed with new fork remote tag "+toTag); } final ClientDialogWrapper forkDialog = getNewDialogFork(toTag,fineTrace); forkDialog.fetchData(response); // end forking forkHandler.forkConfirmed(ra, this, forkDialog); // fire dialog forked event on original activity fireDialogForkEvent(respEvent, forkDialog, fineTrace); eventFired = true; } else { if (fineTrace) { tracer.fine("Client dialog "+getActivityHandle()+" confirmed with existent fork remote tag "+toTag); } final ClientDialogWrapper forkDialog = (ClientDialogWrapper) ra .getActivityManagement().get(forkHandle); if (forkDialog == null) { // dude, where is my dialog? if (tracer.isSevereEnabled()) { tracer.severe("Can't find dialog "+activityHandle+" fork with remote tag "+toTag+" in RA's activity management"); } return true; } forkHandler.forkConfirmed(ra, this, forkDialog); forkDialog.fetchData(response); // fire event on fork activity fireReceivedEvent(respEvent,forkDialog,fineTrace); eventFired = true; } } // if in cluster mode we now need to redo replication since the wrapper state chnaged wrappedDialog.setApplicationData(this); } } else { if (fineTrace) { tracer.fine("Client dialog "+getActivityHandle()+" received "+statusCode+" error response, terminating fork"); } // error while forking, fire event and terminate forking fireReceivedEvent(respEvent, this, fineTrace); eventFired = true; this.data.getForkHandler().terminate(ra); } // not needed till we have some sort of early dialog replication // updateReplicatedState(); return eventFired; }
diff --git a/src/net/sf/freecol/server/generator/MapGenerator.java b/src/net/sf/freecol/server/generator/MapGenerator.java index 1ff718d40..2b54efad4 100644 --- a/src/net/sf/freecol/server/generator/MapGenerator.java +++ b/src/net/sf/freecol/server/generator/MapGenerator.java @@ -1,520 +1,521 @@ package net.sf.freecol.server.generator; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.Random; import java.util.Vector; import java.util.logging.Logger; import net.sf.freecol.common.model.Building; import net.sf.freecol.common.model.Colony; import net.sf.freecol.common.model.ColonyTile; import net.sf.freecol.common.model.Game; import net.sf.freecol.common.model.Goods; import net.sf.freecol.common.model.IndianSettlement; import net.sf.freecol.common.model.Map; import net.sf.freecol.common.model.Player; import net.sf.freecol.common.model.Tile; import net.sf.freecol.common.model.Unit; import net.sf.freecol.common.model.Map.Position; import net.sf.freecol.server.model.ServerPlayer; /** * Creates random maps and sets the starting locations for the players. */ public class MapGenerator { private static final Logger logger = Logger.getLogger(MapGenerator.class.getName()); public static final String COPYRIGHT = "Copyright (C) 2003-2005 The FreeCol Team"; public static final String LICENSE = "http://www.gnu.org/licenses/gpl.html"; public static final String REVISION = "$Revision$"; private final static int NUM_STARTING_LOCATIONS = 4; private final Random random; private final MapGeneratorOptions mapGeneratorOptions; private final LandGenerator landGenerator; private final TerrainGenerator terrainGenerator; /** * Creates a <code>MapGenerator</code> * @see #createMap */ public MapGenerator() { this.mapGeneratorOptions = new MapGeneratorOptions(); this.random = new Random(); landGenerator = new LandGenerator(mapGeneratorOptions); terrainGenerator = new TerrainGenerator(mapGeneratorOptions); } /** * Creates a new <code>Map</code> for the given * <code>Game</code>. The <code>Map</code> is * {@link Game#setMap(Map) added to the game} in this process. * * <br><br> * * The <code>Map</code> will be created using the assigned * options (see {@link #getMapGeneratorOptions()}). * * @param game The <code>Game</code> that will be getting a map. * @see LandGenerator * @see TerrainGenerator */ public void createMap(Game game) { final int width = getMapGeneratorOptions().getWidth(); final int height = getMapGeneratorOptions().getHeight(); boolean[][] landMap = landGenerator.createLandMap(); terrainGenerator.createMap(game, landMap); Map map = game.getMap(); createIndianSettlements(map, game.getPlayers()); createEuropeanUnits(map, width, height, game.getPlayers()); createLostCityRumours(map); } public LandGenerator getLandGenerator() { return landGenerator; } public TerrainGenerator getTerrainGenerator() { return terrainGenerator; } /** * Gets the options used when generating the map. * @return The <code>MapGeneratorOptions</code>. */ public MapGeneratorOptions getMapGeneratorOptions() { return mapGeneratorOptions; } /** * Creates lost city rumours on the given map. * The number of rumours depends on the map size. * * @param map The map to use. */ public void createLostCityRumours(Map map) { int number = getMapGeneratorOptions().getNumberOfRumours(); int counter = 0; for (int i = 0; i < number; i++) { for (int tries=0; tries<100; tries++) { Position p = new Position(random.nextInt(getMapGeneratorOptions().getWidth()), random.nextInt(getMapGeneratorOptions().getHeight())); Tile t = map.getTile(p); if (map.getTile(p).isLand() && !t.hasLostCityRumour() && t.getSettlement() == null && t.getUnitCount() == 0) { counter++; t.setLostCityRumour(true); break; } } } logger.info("Created " + counter + " lost city rumours of maximum " + number + "."); } /** * Create the Indian settlements, at least a capital for every nation and * random numbers of other settlements. * * @param map The <code>Map</code> to place the indian settlments on. * @param players The players to create <code>Settlement</code>s * and starting locations for. That is; both indian and * european players. If players does not contain any indian players, * no settlements are added. */ protected void createIndianSettlements(Map map, Vector<Player> players) { Collections.sort(players, new Comparator<Player>() { public int compare(Player o, Player p) { return o.getNation() - p.getNation(); } }); Vector<Player> indians = new Vector<Player>(); for (Player player : players) { if (player.isIndian()) indians.add(player); } if (indians.size() == 0) return; Position[] territoryCenter = new Position[indians.size()]; for (int tribe = 0; tribe < territoryCenter.length; tribe++) { int x = random.nextInt(map.getWidth()); int y = random.nextInt(map.getHeight()); territoryCenter[tribe] = new Position(x, y); } IndianSettlement[] capitalCandidate = new IndianSettlement[indians.size()]; final int minSettlementDistance = 4; final int width = map.getWidth() / minSettlementDistance; final int height = map.getHeight() / (minSettlementDistance * 2); for (int i = 1; i < width; i++) { for (int j = 1; j < height; j++) { int x = i * minSettlementDistance + random.nextInt(3) - 1; if (j % 2 != 0) { x += minSettlementDistance / 2; } int y = j * (2 * minSettlementDistance) + random.nextInt(3) - 1; if (!map.isValid(x, y)) { continue; } Tile candidate = map.getTile(x, y); if (candidate.isSettleable()) { int bestTribe = 0; int minDistance = Integer.MAX_VALUE; for (int t = 0; t < territoryCenter.length; t++) { if (map.getDistance(territoryCenter[t], candidate.getPosition()) < minDistance) { minDistance = map.getDistance(territoryCenter[t], candidate .getPosition()); bestTribe = t; } } IndianSettlement is = placeIndianSettlement(players.get(bestTribe + 4), bestTribe, false, candidate.getPosition(), map, players); // CO: Fix for missing capital if (capitalCandidate[bestTribe] == null) { capitalCandidate[bestTribe] = is; } else { // If new settlement is closer to center of territory // for this tribe, mark it as a better candidate if (map.getDistance(territoryCenter[bestTribe], capitalCandidate[bestTribe] .getTile().getPosition()) > map.getDistance(territoryCenter[bestTribe], candidate.getPosition())) capitalCandidate[bestTribe] = is; } } } } for (int i = 0; i < capitalCandidate.length; i++) { if (capitalCandidate[i] != null) { capitalCandidate[i].setCapital(true); } } } /** * Builds a <code>IndianSettlement</code> at the given position. * * @param tribe The tribe owning the new settlement. * @param capital <code>true</code> if the settlement should be a * {@link IndianSettlement#isCapital() capital}. * @param position The position to place the settlement. * @param map The map that should get a new settlement. * @param players The list of the {@link Player players}. * @return The <code>IndianSettlement</code> just being placed * on the map. */ private IndianSettlement placeIndianSettlement(Player player, int tribe, boolean capital, Position position, Map map, Vector<Player> players) { final int kind = IndianSettlement.getKind(tribe); final Tile tile = map.getTile(position); IndianSettlement settlement = new IndianSettlement(map.getGame(), player, tile, tribe, kind, capital, generateSkillForLocation(map, map.getTile(position)), false, null); logger.fine("Generated skill: " + Unit.getName(settlement.getLearnableSkill())); tile.setSettlement(settlement); tile.setClaim(Tile.CLAIM_CLAIMED); tile.setOwner(settlement); Iterator<Position> circleIterator = map.getCircleIterator(position, true, IndianSettlement.getRadius(kind)); while (circleIterator.hasNext()) { Position adjPos = circleIterator.next(); map.getTile(adjPos).setClaim(Tile.CLAIM_CLAIMED); map.getTile(adjPos).setNationOwner(player.getNation()); } for (int i = 0; i < (kind * 2) + 4; i++) { Unit unit = new Unit(map.getGame(), player, Unit.BRAVE); unit.setIndianSettlement(settlement); if (i == 0) { unit.setLocation(tile); } else { unit.setLocation(settlement); } } return settlement; } /** * Generates a skill that could be taught from a settlement on the given Tile. * TODO: This method should be properly implemented. The surrounding terrain * should be taken into account and it should be partially randomized. * * @param map The <code>Map</code>. * @param tile The tile where the settlement will be located. * @return A skill that can be taught to Europeans. */ private int generateSkillForLocation(Map map, Tile tile) { int rand = random.nextInt(2); int[] potentials = new int[Goods.HORSES]; Iterator<Position> iter = map.getAdjacentIterator(tile.getPosition()); while (iter.hasNext()) { Map.Position p = iter.next(); Tile t = map.getTile(p); if (t.hasBonus()) { if (t.getAddition() == Tile.ADD_HILLS) { return IndianSettlement.EXPERT_ORE_MINER; } else if (t.getAddition() == Tile.ADD_MOUNTAINS) { return IndianSettlement.EXPERT_SILVER_MINER; } else if (t.isForested()) { switch (t.getType()) { case Tile.PLAINS: case Tile.PRAIRIE: case Tile.TUNDRA: return IndianSettlement.EXPERT_FUR_TRAPPER; case Tile.GRASSLANDS: case Tile.SAVANNAH: return IndianSettlement.EXPERT_LUMBER_JACK; case Tile.MARSH: return (rand==0 ? IndianSettlement.EXPERT_SILVER_MINER : IndianSettlement.EXPERT_ORE_MINER); case Tile.SWAMP: return (rand==0 ? IndianSettlement.EXPERT_SILVER_MINER : IndianSettlement.EXPERT_ORE_MINER); case Tile.DESERT: return (rand==0 ? IndianSettlement.EXPERT_LUMBER_JACK : IndianSettlement.EXPERT_FARMER); default: throw new IllegalArgumentException("Invalid tile provided: Tile type is invalid"); } } else { switch (t.getType()) { case Tile.PLAINS: return IndianSettlement.MASTER_COTTON_PLANTER; case Tile.GRASSLANDS: return IndianSettlement.MASTER_TOBACCO_PLANTER; case Tile.PRAIRIE: return IndianSettlement.MASTER_COTTON_PLANTER; case Tile.SAVANNAH: return IndianSettlement.MASTER_SUGAR_PLANTER; case Tile.MARSH: return IndianSettlement.EXPERT_ORE_MINER; case Tile.SWAMP: if (rand == 0) { return IndianSettlement.MASTER_TOBACCO_PLANTER; } else { return IndianSettlement.MASTER_SUGAR_PLANTER; } case Tile.DESERT: return IndianSettlement.SEASONED_SCOUT; case Tile.TUNDRA: if (rand == 0) { return IndianSettlement.EXPERT_SILVER_MINER; } else { return IndianSettlement.EXPERT_ORE_MINER; } case Tile.ARCTIC: continue; case Tile.OCEAN: return IndianSettlement.EXPERT_FISHERMAN; default: throw new IllegalArgumentException("Invalid tile provided: Tile type is invalid"); } } } else { for (int goodsType = Goods.FOOD; goodsType < Goods.HORSES; goodsType++) { potentials[goodsType] += t.potential(goodsType); } } } int counter = 0; for (int goodsType = Goods.FOOD; goodsType < Goods.HORSES; goodsType++) { counter += potentials[goodsType]; potentials[goodsType] = counter; } int newRand = random.nextInt(counter); for (int goodsType = Goods.FOOD; goodsType < Goods.HORSES; goodsType++) { if (newRand < potentials[goodsType]) { switch (goodsType) { case Goods.FOOD: return IndianSettlement.EXPERT_FARMER; case Goods.SUGAR: return IndianSettlement.MASTER_SUGAR_PLANTER; case Goods.TOBACCO: return IndianSettlement.MASTER_TOBACCO_PLANTER; case Goods.COTTON: return IndianSettlement.MASTER_COTTON_PLANTER; case Goods.FURS: return IndianSettlement.EXPERT_FUR_TRAPPER; case Goods.LUMBER: return IndianSettlement.EXPERT_LUMBER_JACK; case Goods.ORE: return IndianSettlement.EXPERT_ORE_MINER; case Goods.SILVER: return IndianSettlement.EXPERT_SILVER_MINER; default: return IndianSettlement.SEASONED_SCOUT; } } } return IndianSettlement.SEASONED_SCOUT; } /** * Create two ships, one with a colonist, for each player, and * select suitable starting positions. * * @param map The <code>Map</code> to place the european units on. * @param width The width of the map to create. * @param height The height of the map to create. * @param players The players to create <code>Settlement</code>s * and starting locations for. That is; both indian and * european players. */ protected void createEuropeanUnits(Map map, int width, int height, Vector<Player> players) { int[] shipYPos = new int[NUM_STARTING_LOCATIONS]; for (int i = 0; i < NUM_STARTING_LOCATIONS; i++) { shipYPos[i] = 0; } for (int i = 0; i < players.size(); i++) { Player player = players.elementAt(i); if (player.isREF()) { player.setEntryLocation(map.getTile(width - 2, random.nextInt(height - 20) + 10)); continue; } if (!player.isEuropean()) { continue; } int y = random.nextInt(height - 20) + 10; int x = width - 1; while (isAShipTooClose(y, shipYPos)) { y = random.nextInt(height - 20) + 10; } shipYPos[i] = y; while (map.getTile(x - 1, y).getType() == Tile.HIGH_SEAS) { x--; } Tile startTile = map.getTile(x,y); + startTile.setExploredBy(player, true); player.setEntryLocation(startTile); int navalUnitType = (player.getNation() == ServerPlayer.DUTCH) ? Unit.MERCHANTMAN : Unit.CARAVEL; int pioneerUnitType = (player.getNation() == ServerPlayer.FRENCH) ? Unit.HARDY_PIONEER : Unit.FREE_COLONIST; int soldierUnitType = (player.getNation() == ServerPlayer.SPANISH) ? Unit.VETERAN_SOLDIER : Unit.FREE_COLONIST; Unit unit1 = new Unit(map.getGame(), startTile, player, navalUnitType, Unit.ACTIVE); //unit1.setName(Messages.message("shipName." + player.getNation() + ".0")); @SuppressWarnings("unused") Unit unit2 = new Unit(map.getGame(), unit1, player, pioneerUnitType, Unit.SENTRY, false, false, 100, false); @SuppressWarnings("unused") Unit unit3 = new Unit(map.getGame(), unit1, player, soldierUnitType, Unit.SENTRY, true, false, 0, false); // START DEBUG: if (net.sf.freecol.FreeCol.isInDebugMode()) { Unit unit4 = new Unit(map.getGame(), startTile, player, Unit.GALLEON, Unit.ACTIVE); @SuppressWarnings("unused") Unit unit5 = new Unit(map.getGame(), unit4, player, Unit.FREE_COLONIST, Unit.SENTRY); @SuppressWarnings("unused") Unit unit6 = new Unit(map.getGame(), unit4, player, Unit.VETERAN_SOLDIER, Unit.SENTRY); @SuppressWarnings("unused") Unit unit7 = new Unit(map.getGame(), unit4, player, Unit.JESUIT_MISSIONARY, Unit.SENTRY); Tile colonyTile = null; Iterator<Position> cti = map.getFloodFillIterator(new Position(x, y)); while(cti.hasNext()) { Tile tempTile = map.getTile(cti.next()); if (tempTile.isColonizeable()) { colonyTile = tempTile; break; } } if (colonyTile != null) { colonyTile.setType(Tile.PRAIRIE); colonyTile.setForested(false); colonyTile.setPlowed(true); colonyTile.setAddition(Tile.ADD_NONE); Unit buildColonyUnit = new Unit(map.getGame(), colonyTile, player, Unit.EXPERT_FARMER, Unit.ACTIVE); Colony colony = new Colony(map.getGame(), player, "Colony for Testing", colonyTile); buildColonyUnit.buildColony(colony); if (buildColonyUnit.getLocation() instanceof ColonyTile) { Tile ct = ((ColonyTile) buildColonyUnit.getLocation()).getWorkTile(); ct.setType(Tile.PLAINS); ct.setForested(false); ct.setPlowed(true); ct.setAddition(Tile.ADD_NONE); } colony.getBuilding(Building.SCHOOLHOUSE).setLevel(Building.SHOP); Unit carpenter = new Unit(map.getGame(), colonyTile, player, Unit.MASTER_CARPENTER, Unit.ACTIVE); carpenter.setLocation(colony.getBuilding(Building.CARPENTER)); Unit statesman = new Unit(map.getGame(), colonyTile, player, Unit.ELDER_STATESMAN, Unit.ACTIVE); statesman.setLocation(colony.getBuilding(Building.TOWN_HALL)); Unit lumberjack = new Unit(map.getGame(), colony, player, Unit.EXPERT_LUMBER_JACK, Unit.ACTIVE); if (lumberjack.getLocation() instanceof ColonyTile) { Tile lt = ((ColonyTile) lumberjack.getLocation()).getWorkTile(); lt.setType(Tile.PLAINS); lt.setForested(true); lt.setRoad(true); lt.setAddition(Tile.ADD_NONE); lumberjack.setWorkType(Goods.LUMBER); } @SuppressWarnings("unused") Unit scout = new Unit(map.getGame(), colonyTile, player, Unit.SEASONED_SCOUT, Unit.ACTIVE); @SuppressWarnings("unused") Unit unit8 = new Unit(map.getGame(), colonyTile, player, Unit.VETERAN_SOLDIER, Unit.ACTIVE); @SuppressWarnings("unused") Unit unit9 = new Unit(map.getGame(), colonyTile, player, Unit.VETERAN_SOLDIER, Unit.ACTIVE); @SuppressWarnings("unused") Unit unit10 = new Unit(map.getGame(), colonyTile, player, Unit.ARTILLERY, Unit.ACTIVE); @SuppressWarnings("unused") Unit unit11 = new Unit(map.getGame(), colonyTile, player, Unit.ARTILLERY, Unit.ACTIVE); @SuppressWarnings("unused") Unit unit12 = new Unit(map.getGame(), colonyTile, player, Unit.ARTILLERY, Unit.ACTIVE); Unit unit13 = new Unit(map.getGame(), colonyTile, player, Unit.TREASURE_TRAIN, Unit.ACTIVE); unit13.setTreasureAmount(10000); /* DEBUGGING LINES FOR AI (0.4.1): for (int j=0; j<10; j++) { Unit u = new Unit(game, null, player, Unit.FREE_COLONIST, Unit.ACTIVE); colony.add(u); } for (int j=0; j<3; j++) { Unit u = new Unit(game, null, player, Unit.PETTY_CRIMINAL, Unit.ACTIVE); colony.add(u); } */ } } // END DEBUG } } /** * Determine whether a proposed ship starting Y position is "too close" * to those already used. * @param proposedY Proposed ship starting Y position * @param usedYPositions List of already assigned positions * @return True if the proposed position is too close */ protected boolean isAShipTooClose(int proposedY, int[] usedYPositions) { for (int i = 0; i < NUM_STARTING_LOCATIONS && usedYPositions[i] != 0; i++) { if (Math.abs(usedYPositions[i] - proposedY) < (getMapGeneratorOptions().getHeight() / 2) / NUM_STARTING_LOCATIONS) { return true; } } return false; } }
true
true
protected void createEuropeanUnits(Map map, int width, int height, Vector<Player> players) { int[] shipYPos = new int[NUM_STARTING_LOCATIONS]; for (int i = 0; i < NUM_STARTING_LOCATIONS; i++) { shipYPos[i] = 0; } for (int i = 0; i < players.size(); i++) { Player player = players.elementAt(i); if (player.isREF()) { player.setEntryLocation(map.getTile(width - 2, random.nextInt(height - 20) + 10)); continue; } if (!player.isEuropean()) { continue; } int y = random.nextInt(height - 20) + 10; int x = width - 1; while (isAShipTooClose(y, shipYPos)) { y = random.nextInt(height - 20) + 10; } shipYPos[i] = y; while (map.getTile(x - 1, y).getType() == Tile.HIGH_SEAS) { x--; } Tile startTile = map.getTile(x,y); player.setEntryLocation(startTile); int navalUnitType = (player.getNation() == ServerPlayer.DUTCH) ? Unit.MERCHANTMAN : Unit.CARAVEL; int pioneerUnitType = (player.getNation() == ServerPlayer.FRENCH) ? Unit.HARDY_PIONEER : Unit.FREE_COLONIST; int soldierUnitType = (player.getNation() == ServerPlayer.SPANISH) ? Unit.VETERAN_SOLDIER : Unit.FREE_COLONIST; Unit unit1 = new Unit(map.getGame(), startTile, player, navalUnitType, Unit.ACTIVE); //unit1.setName(Messages.message("shipName." + player.getNation() + ".0")); @SuppressWarnings("unused") Unit unit2 = new Unit(map.getGame(), unit1, player, pioneerUnitType, Unit.SENTRY, false, false, 100, false); @SuppressWarnings("unused") Unit unit3 = new Unit(map.getGame(), unit1, player, soldierUnitType, Unit.SENTRY, true, false, 0, false); // START DEBUG: if (net.sf.freecol.FreeCol.isInDebugMode()) { Unit unit4 = new Unit(map.getGame(), startTile, player, Unit.GALLEON, Unit.ACTIVE); @SuppressWarnings("unused") Unit unit5 = new Unit(map.getGame(), unit4, player, Unit.FREE_COLONIST, Unit.SENTRY); @SuppressWarnings("unused") Unit unit6 = new Unit(map.getGame(), unit4, player, Unit.VETERAN_SOLDIER, Unit.SENTRY); @SuppressWarnings("unused") Unit unit7 = new Unit(map.getGame(), unit4, player, Unit.JESUIT_MISSIONARY, Unit.SENTRY); Tile colonyTile = null; Iterator<Position> cti = map.getFloodFillIterator(new Position(x, y)); while(cti.hasNext()) { Tile tempTile = map.getTile(cti.next()); if (tempTile.isColonizeable()) { colonyTile = tempTile; break; } } if (colonyTile != null) { colonyTile.setType(Tile.PRAIRIE); colonyTile.setForested(false); colonyTile.setPlowed(true); colonyTile.setAddition(Tile.ADD_NONE); Unit buildColonyUnit = new Unit(map.getGame(), colonyTile, player, Unit.EXPERT_FARMER, Unit.ACTIVE); Colony colony = new Colony(map.getGame(), player, "Colony for Testing", colonyTile); buildColonyUnit.buildColony(colony); if (buildColonyUnit.getLocation() instanceof ColonyTile) { Tile ct = ((ColonyTile) buildColonyUnit.getLocation()).getWorkTile(); ct.setType(Tile.PLAINS); ct.setForested(false); ct.setPlowed(true); ct.setAddition(Tile.ADD_NONE); } colony.getBuilding(Building.SCHOOLHOUSE).setLevel(Building.SHOP); Unit carpenter = new Unit(map.getGame(), colonyTile, player, Unit.MASTER_CARPENTER, Unit.ACTIVE); carpenter.setLocation(colony.getBuilding(Building.CARPENTER)); Unit statesman = new Unit(map.getGame(), colonyTile, player, Unit.ELDER_STATESMAN, Unit.ACTIVE); statesman.setLocation(colony.getBuilding(Building.TOWN_HALL)); Unit lumberjack = new Unit(map.getGame(), colony, player, Unit.EXPERT_LUMBER_JACK, Unit.ACTIVE); if (lumberjack.getLocation() instanceof ColonyTile) { Tile lt = ((ColonyTile) lumberjack.getLocation()).getWorkTile(); lt.setType(Tile.PLAINS); lt.setForested(true); lt.setRoad(true); lt.setAddition(Tile.ADD_NONE); lumberjack.setWorkType(Goods.LUMBER); } @SuppressWarnings("unused") Unit scout = new Unit(map.getGame(), colonyTile, player, Unit.SEASONED_SCOUT, Unit.ACTIVE); @SuppressWarnings("unused") Unit unit8 = new Unit(map.getGame(), colonyTile, player, Unit.VETERAN_SOLDIER, Unit.ACTIVE); @SuppressWarnings("unused") Unit unit9 = new Unit(map.getGame(), colonyTile, player, Unit.VETERAN_SOLDIER, Unit.ACTIVE); @SuppressWarnings("unused") Unit unit10 = new Unit(map.getGame(), colonyTile, player, Unit.ARTILLERY, Unit.ACTIVE); @SuppressWarnings("unused") Unit unit11 = new Unit(map.getGame(), colonyTile, player, Unit.ARTILLERY, Unit.ACTIVE); @SuppressWarnings("unused") Unit unit12 = new Unit(map.getGame(), colonyTile, player, Unit.ARTILLERY, Unit.ACTIVE); Unit unit13 = new Unit(map.getGame(), colonyTile, player, Unit.TREASURE_TRAIN, Unit.ACTIVE); unit13.setTreasureAmount(10000); /* DEBUGGING LINES FOR AI (0.4.1): for (int j=0; j<10; j++) { Unit u = new Unit(game, null, player, Unit.FREE_COLONIST, Unit.ACTIVE); colony.add(u); } for (int j=0; j<3; j++) { Unit u = new Unit(game, null, player, Unit.PETTY_CRIMINAL, Unit.ACTIVE); colony.add(u); } */ } } // END DEBUG } }
protected void createEuropeanUnits(Map map, int width, int height, Vector<Player> players) { int[] shipYPos = new int[NUM_STARTING_LOCATIONS]; for (int i = 0; i < NUM_STARTING_LOCATIONS; i++) { shipYPos[i] = 0; } for (int i = 0; i < players.size(); i++) { Player player = players.elementAt(i); if (player.isREF()) { player.setEntryLocation(map.getTile(width - 2, random.nextInt(height - 20) + 10)); continue; } if (!player.isEuropean()) { continue; } int y = random.nextInt(height - 20) + 10; int x = width - 1; while (isAShipTooClose(y, shipYPos)) { y = random.nextInt(height - 20) + 10; } shipYPos[i] = y; while (map.getTile(x - 1, y).getType() == Tile.HIGH_SEAS) { x--; } Tile startTile = map.getTile(x,y); startTile.setExploredBy(player, true); player.setEntryLocation(startTile); int navalUnitType = (player.getNation() == ServerPlayer.DUTCH) ? Unit.MERCHANTMAN : Unit.CARAVEL; int pioneerUnitType = (player.getNation() == ServerPlayer.FRENCH) ? Unit.HARDY_PIONEER : Unit.FREE_COLONIST; int soldierUnitType = (player.getNation() == ServerPlayer.SPANISH) ? Unit.VETERAN_SOLDIER : Unit.FREE_COLONIST; Unit unit1 = new Unit(map.getGame(), startTile, player, navalUnitType, Unit.ACTIVE); //unit1.setName(Messages.message("shipName." + player.getNation() + ".0")); @SuppressWarnings("unused") Unit unit2 = new Unit(map.getGame(), unit1, player, pioneerUnitType, Unit.SENTRY, false, false, 100, false); @SuppressWarnings("unused") Unit unit3 = new Unit(map.getGame(), unit1, player, soldierUnitType, Unit.SENTRY, true, false, 0, false); // START DEBUG: if (net.sf.freecol.FreeCol.isInDebugMode()) { Unit unit4 = new Unit(map.getGame(), startTile, player, Unit.GALLEON, Unit.ACTIVE); @SuppressWarnings("unused") Unit unit5 = new Unit(map.getGame(), unit4, player, Unit.FREE_COLONIST, Unit.SENTRY); @SuppressWarnings("unused") Unit unit6 = new Unit(map.getGame(), unit4, player, Unit.VETERAN_SOLDIER, Unit.SENTRY); @SuppressWarnings("unused") Unit unit7 = new Unit(map.getGame(), unit4, player, Unit.JESUIT_MISSIONARY, Unit.SENTRY); Tile colonyTile = null; Iterator<Position> cti = map.getFloodFillIterator(new Position(x, y)); while(cti.hasNext()) { Tile tempTile = map.getTile(cti.next()); if (tempTile.isColonizeable()) { colonyTile = tempTile; break; } } if (colonyTile != null) { colonyTile.setType(Tile.PRAIRIE); colonyTile.setForested(false); colonyTile.setPlowed(true); colonyTile.setAddition(Tile.ADD_NONE); Unit buildColonyUnit = new Unit(map.getGame(), colonyTile, player, Unit.EXPERT_FARMER, Unit.ACTIVE); Colony colony = new Colony(map.getGame(), player, "Colony for Testing", colonyTile); buildColonyUnit.buildColony(colony); if (buildColonyUnit.getLocation() instanceof ColonyTile) { Tile ct = ((ColonyTile) buildColonyUnit.getLocation()).getWorkTile(); ct.setType(Tile.PLAINS); ct.setForested(false); ct.setPlowed(true); ct.setAddition(Tile.ADD_NONE); } colony.getBuilding(Building.SCHOOLHOUSE).setLevel(Building.SHOP); Unit carpenter = new Unit(map.getGame(), colonyTile, player, Unit.MASTER_CARPENTER, Unit.ACTIVE); carpenter.setLocation(colony.getBuilding(Building.CARPENTER)); Unit statesman = new Unit(map.getGame(), colonyTile, player, Unit.ELDER_STATESMAN, Unit.ACTIVE); statesman.setLocation(colony.getBuilding(Building.TOWN_HALL)); Unit lumberjack = new Unit(map.getGame(), colony, player, Unit.EXPERT_LUMBER_JACK, Unit.ACTIVE); if (lumberjack.getLocation() instanceof ColonyTile) { Tile lt = ((ColonyTile) lumberjack.getLocation()).getWorkTile(); lt.setType(Tile.PLAINS); lt.setForested(true); lt.setRoad(true); lt.setAddition(Tile.ADD_NONE); lumberjack.setWorkType(Goods.LUMBER); } @SuppressWarnings("unused") Unit scout = new Unit(map.getGame(), colonyTile, player, Unit.SEASONED_SCOUT, Unit.ACTIVE); @SuppressWarnings("unused") Unit unit8 = new Unit(map.getGame(), colonyTile, player, Unit.VETERAN_SOLDIER, Unit.ACTIVE); @SuppressWarnings("unused") Unit unit9 = new Unit(map.getGame(), colonyTile, player, Unit.VETERAN_SOLDIER, Unit.ACTIVE); @SuppressWarnings("unused") Unit unit10 = new Unit(map.getGame(), colonyTile, player, Unit.ARTILLERY, Unit.ACTIVE); @SuppressWarnings("unused") Unit unit11 = new Unit(map.getGame(), colonyTile, player, Unit.ARTILLERY, Unit.ACTIVE); @SuppressWarnings("unused") Unit unit12 = new Unit(map.getGame(), colonyTile, player, Unit.ARTILLERY, Unit.ACTIVE); Unit unit13 = new Unit(map.getGame(), colonyTile, player, Unit.TREASURE_TRAIN, Unit.ACTIVE); unit13.setTreasureAmount(10000); /* DEBUGGING LINES FOR AI (0.4.1): for (int j=0; j<10; j++) { Unit u = new Unit(game, null, player, Unit.FREE_COLONIST, Unit.ACTIVE); colony.add(u); } for (int j=0; j<3; j++) { Unit u = new Unit(game, null, player, Unit.PETTY_CRIMINAL, Unit.ACTIVE); colony.add(u); } */ } } // END DEBUG } }
diff --git a/AIGameFramework/src/main/java/com/squirrelapps/aigameframework/BoardFragment.java b/AIGameFramework/src/main/java/com/squirrelapps/aigameframework/BoardFragment.java index d5ba0b3..0d3df64 100644 --- a/AIGameFramework/src/main/java/com/squirrelapps/aigameframework/BoardFragment.java +++ b/AIGameFramework/src/main/java/com/squirrelapps/aigameframework/BoardFragment.java @@ -1,349 +1,349 @@ package com.squirrelapps.aigameframework; import android.app.Activity; import android.graphics.Color; import android.graphics.drawable.AnimationDrawable; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.GridLayout; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.Button; import android.widget.Toast; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * Copyright (C) 2014 Francesco Vadicamo. */ public class BoardFragment extends Fragment implements Button.OnClickListener { // Container Activity must implement this interface public interface BoardListener { public boolean onBoardLayout(ViewGroup rootLayout, ViewGroup boardLayout); public boolean onBoardCreate(Cell cell, Button button); public boolean onBoardUpdate(Cell cell, Button button); } private static final String TAG = BoardFragment.class.getSimpleName(); protected BoardListener boardListener; //TODO da passare nel Bundle alla creazione del fragment final int xDim = 8, yDim = 8; final Board board = new SquareBoard(xDim, yDim); final Button[][] boardButtons = new Button[xDim][yDim]; final Set<Button> animatedButtons = new HashSet<Button>(); int lastDistance = 1; Button lastButton; @Override public void onAttach(Activity activity) { super.onAttach(activity); try{ this.boardListener = (BoardListener) activity; }catch(ClassCastException e){ throw new ClassCastException(activity.toString() + " must implement BoardListener"); } } @Override public void onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate()"); super.onCreate(savedInstanceState); //setHasOptionsMenu(false); //MainActivity mainActivity = (MainActivity)getActivity(); //this.mainActivityWeakRef = new WeakReference<MainActivity>(mainActivity); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d(TAG, "onCreateView()"); final View rootView = inflater.inflate(R.layout.f_board, container, false); assert rootView != null; Activity activity = getActivity(); GridLayout gridLayout = (GridLayout)rootView.findViewById(R.id.boardLayout); gridLayout.setUseDefaultMargins(false); //REMIND required for 0px gap between cells gridLayout.setAlignmentMode(GridLayout.ALIGN_BOUNDS); gridLayout.setColumnCount(xDim); gridLayout.setRowCount(yDim); //gridLayout.setBackgroundColor(Color.RED); //FIXME rimuovere a fine debug // Configuration configuration = activity.getResources().getConfiguration(); // if ((configuration.orientation == Configuration.ORIENTATION_PORTRAIT)) { // gridLayout.setColumnOrderPreserved(false); // } else { // gridLayout.setRowOrderPreserved(false); // } for (int y = 0; y < yDim; ++y){ //row.setBackgroundColor(Color.YELLOW); //FIXME rimuovere a fine debug for (int x = 0; x < xDim; ++x){ //TODO si potrebbe richiamare un metodo del listener per ricevere la view per la cella Button btn = new Button(activity); //width and height will be set later (see fillBoardLayout method) Cell cell = board.cells[x][y]; //REMIND setTag e setOnClickListener vanno messi prima di richiamare il metodo del listener in modo che questo possa sovrascrivere eventualmente if(!boardListener.onBoardCreate(cell, btn)){ onDefaultBoardCreate(cell, btn); } //TODO sono entrambi necessari, create e update!? o_O' if(!boardListener.onBoardUpdate(cell, btn)){ onDefaultBoardUpdate(cell, btn); } GridLayout.Spec rowSpec = GridLayout.spec(x, GridLayout.CENTER); GridLayout.Spec colSpec = GridLayout.spec(y, GridLayout.CENTER); GridLayout.LayoutParams cellParams = new GridLayout.LayoutParams(rowSpec, colSpec); // cellParams.setGravity(Gravity.CENTER); gridLayout.addView(btn, cellParams); boardButtons[x][y] = btn; } } - final ViewTreeObserver obs = gridLayout.getViewTreeObserver(); + ViewTreeObserver obs = gridLayout.getViewTreeObserver(); if(obs != null){ obs.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener(){ @Override public void onGlobalLayout() { ViewGroup rl = (ViewGroup)rootView.findViewById(R.id.rootLayout); Log.v(TAG, "root layout: "+rl.getWidth()+", "+rl.getHeight()); GridLayout gl = (GridLayout)rootView.findViewById(R.id.boardLayout); Log.v(TAG, "grid layout: "+gl.getWidth()+", "+gl.getHeight()); if(!boardListener.onBoardLayout(rl, gl)){ onDefaultBoardLayout(rl, gl); } - //ViewTreeObserver obs = gl.getViewTreeObserver(); - //assert obs != null; + ViewTreeObserver obs = gl.getViewTreeObserver(); + assert obs != null; obs.removeOnGlobalLayoutListener(this); } }); } //consider also the following // gridLayout.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener(){ // @Override // public boolean onPreDraw() // { // return false; // } // }); return rootView; } protected boolean onDefaultBoardCreate(Cell cell, Button btn) { btn.setTag(cell); btn.setOnClickListener(this); return true; } protected boolean onDefaultBoardUpdate(Cell cell, Button btn) { //Cell cell = (Cell)btn.getTag(); int x = cell.x; int y = cell.y; if(/*FIXME alternate*/false){ btn.setBackgroundColor((x + y) % 2 == 0 ? Color.BLACK : Color.WHITE); btn.setTextColor((x + y) % 2 == 0 ? Color.WHITE : Color.BLACK); }else{ btn.setBackgroundResource(R.drawable.cell_green_dark); btn.setTextColor(Color.WHITE); } btn.setText(/*board.cells[x][y].toString()*/"" + (y * xDim + x)); return true; } protected boolean onDefaultBoardLayout(ViewGroup rootLayout, ViewGroup boardLayout) { int cell_size = (int)(Math.min(/*gridLayout*/rootLayout.getWidth()/xDim, /*gridLayout*/rootLayout.getHeight()/yDim)); Log.v(TAG, "cell_size: "+cell_size); //TODO si potrebbero gestire Button, TextField e ImageView e utilizzare un Binder per gli altri (vd Adapter) Button btn; for(int i = 0; i < boardLayout.getChildCount(); i++){ btn = (Button) boardLayout.getChildAt(i); assert btn != null; btn.setWidth(cell_size); btn.setMinimumWidth(cell_size); btn.setMaxWidth(cell_size); btn.setHeight(cell_size); btn.setMinimumHeight(cell_size); btn.setMaxHeight(cell_size); } return true; } /* (non-Javadoc) * @see android.support.v4.app.Fragment#onActivityCreated(android.os.Bundle) */ @Override public void onActivityCreated(Bundle savedInstanceState) { Log.d(TAG, "onActivityCreated()"); super.onActivityCreated(savedInstanceState); } /* (non-Javadoc) * @see android.support.v4.app.Fragment#onResume() */ @Override public void onResume() { Log.d(TAG, "onResume()"); super.onResume(); } /* (non-Javadoc) * @see android.support.v4.app.Fragment#onPause() */ @Override public void onPause() { Log.d(TAG, "onPause()"); super.onPause(); } /* (non-Javadoc) * @see android.support.v4.app.Fragment#onDestroy() */ @Override public void onDestroy() { Log.d(TAG, "onDestroy()"); super.onDestroy(); } // /* (non-Javadoc) // * @see android.support.v4.app.Fragment#onCreateOptionsMenu(android.view.Menu, android.view.MenuInflater) // */ // @Override // public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) // { // //super.onCreateOptionsMenu(menu, inflater); // inflater.inflate(R.menu.f_board, menu); // } // // /* (non-Javadoc) // * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem) // */ // @Override // public boolean onOptionsItemSelected(MenuItem item) // { // return true; // /* // // respond to menu item selection // switch(item.getItemId()){ // case R.id.action_xxx: // Intent xxx = new Intent(getActivity(), XXX.class); // startActivity(xxx); // return true; // // break; // // default: // return super.onOptionsItemSelected(item); // } // */ // } @Override public void onClick(View view) { if(view instanceof Button){ Cell cell = (Cell)view.getTag(); synchronized(BoardFragment.this){ Button button = (Button)view; if(button == lastButton){ lastDistance = (lastDistance+1) % Math.max(Math.max(cell.x + 1, xDim - (cell.x /*+ 1*/)), Math.max(cell.y + 1, yDim - (cell.y /*+ 1*/))); }else{ lastButton = button; lastDistance = 1; } Toast.makeText(getActivity(), "" + cell + " (distance " + lastDistance + ")", Toast.LENGTH_SHORT).show(); stopAnimation(); Set<Cell> neighbors = board.borderNeighbors(cell, lastDistance); Log.v(TAG, neighbors.size() + " neighbors of " + cell + " at distance "+lastDistance+" found: "+ Arrays.toString(neighbors.toArray())); // for(Cell c : neighbors){ // Button btn = boardButtons[c.x][c.y]; // btn.setBackgroundResource(R.drawable.cell_neighbors_anim); // // Get the background, which has been compiled to an AnimationDrawable object. // AnimationDrawable frameAnimation = (AnimationDrawable)btn.getBackground(); // // Start the animation (looped playback by default). // frameAnimation.start(); // // animatedButtons.add(btn); // } animate(neighbors); } } } public synchronized void animate(Set<Cell> cells) { for(Cell c : cells){ Button btn = boardButtons[c.x][c.y]; btn.setBackgroundResource(R.drawable.cell_neighbors_anim); // Get the background, which has been compiled to an AnimationDrawable object. AnimationDrawable frameAnimation = (AnimationDrawable)btn.getBackground(); assert frameAnimation != null; // Start the animation (looped playback by default). frameAnimation.start(); animatedButtons.add(btn); } } public synchronized void stopAnimation() { for(Button btn : animatedButtons){ AnimationDrawable frameAnimation = (AnimationDrawable)btn.getBackground(); assert frameAnimation != null; // Stop the animation (looped playback by default). frameAnimation.stop(); Cell cell = (Cell)btn.getTag(); if(!boardListener.onBoardUpdate(cell, btn)){ onDefaultBoardUpdate(cell, btn); } } animatedButtons.clear(); } }
false
true
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d(TAG, "onCreateView()"); final View rootView = inflater.inflate(R.layout.f_board, container, false); assert rootView != null; Activity activity = getActivity(); GridLayout gridLayout = (GridLayout)rootView.findViewById(R.id.boardLayout); gridLayout.setUseDefaultMargins(false); //REMIND required for 0px gap between cells gridLayout.setAlignmentMode(GridLayout.ALIGN_BOUNDS); gridLayout.setColumnCount(xDim); gridLayout.setRowCount(yDim); //gridLayout.setBackgroundColor(Color.RED); //FIXME rimuovere a fine debug // Configuration configuration = activity.getResources().getConfiguration(); // if ((configuration.orientation == Configuration.ORIENTATION_PORTRAIT)) { // gridLayout.setColumnOrderPreserved(false); // } else { // gridLayout.setRowOrderPreserved(false); // } for (int y = 0; y < yDim; ++y){ //row.setBackgroundColor(Color.YELLOW); //FIXME rimuovere a fine debug for (int x = 0; x < xDim; ++x){ //TODO si potrebbe richiamare un metodo del listener per ricevere la view per la cella Button btn = new Button(activity); //width and height will be set later (see fillBoardLayout method) Cell cell = board.cells[x][y]; //REMIND setTag e setOnClickListener vanno messi prima di richiamare il metodo del listener in modo che questo possa sovrascrivere eventualmente if(!boardListener.onBoardCreate(cell, btn)){ onDefaultBoardCreate(cell, btn); } //TODO sono entrambi necessari, create e update!? o_O' if(!boardListener.onBoardUpdate(cell, btn)){ onDefaultBoardUpdate(cell, btn); } GridLayout.Spec rowSpec = GridLayout.spec(x, GridLayout.CENTER); GridLayout.Spec colSpec = GridLayout.spec(y, GridLayout.CENTER); GridLayout.LayoutParams cellParams = new GridLayout.LayoutParams(rowSpec, colSpec); // cellParams.setGravity(Gravity.CENTER); gridLayout.addView(btn, cellParams); boardButtons[x][y] = btn; } } final ViewTreeObserver obs = gridLayout.getViewTreeObserver(); if(obs != null){ obs.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener(){ @Override public void onGlobalLayout() { ViewGroup rl = (ViewGroup)rootView.findViewById(R.id.rootLayout); Log.v(TAG, "root layout: "+rl.getWidth()+", "+rl.getHeight()); GridLayout gl = (GridLayout)rootView.findViewById(R.id.boardLayout); Log.v(TAG, "grid layout: "+gl.getWidth()+", "+gl.getHeight()); if(!boardListener.onBoardLayout(rl, gl)){ onDefaultBoardLayout(rl, gl); } //ViewTreeObserver obs = gl.getViewTreeObserver(); //assert obs != null; obs.removeOnGlobalLayoutListener(this); } }); } //consider also the following // gridLayout.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener(){ // @Override // public boolean onPreDraw() // { // return false; // } // }); return rootView; }
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d(TAG, "onCreateView()"); final View rootView = inflater.inflate(R.layout.f_board, container, false); assert rootView != null; Activity activity = getActivity(); GridLayout gridLayout = (GridLayout)rootView.findViewById(R.id.boardLayout); gridLayout.setUseDefaultMargins(false); //REMIND required for 0px gap between cells gridLayout.setAlignmentMode(GridLayout.ALIGN_BOUNDS); gridLayout.setColumnCount(xDim); gridLayout.setRowCount(yDim); //gridLayout.setBackgroundColor(Color.RED); //FIXME rimuovere a fine debug // Configuration configuration = activity.getResources().getConfiguration(); // if ((configuration.orientation == Configuration.ORIENTATION_PORTRAIT)) { // gridLayout.setColumnOrderPreserved(false); // } else { // gridLayout.setRowOrderPreserved(false); // } for (int y = 0; y < yDim; ++y){ //row.setBackgroundColor(Color.YELLOW); //FIXME rimuovere a fine debug for (int x = 0; x < xDim; ++x){ //TODO si potrebbe richiamare un metodo del listener per ricevere la view per la cella Button btn = new Button(activity); //width and height will be set later (see fillBoardLayout method) Cell cell = board.cells[x][y]; //REMIND setTag e setOnClickListener vanno messi prima di richiamare il metodo del listener in modo che questo possa sovrascrivere eventualmente if(!boardListener.onBoardCreate(cell, btn)){ onDefaultBoardCreate(cell, btn); } //TODO sono entrambi necessari, create e update!? o_O' if(!boardListener.onBoardUpdate(cell, btn)){ onDefaultBoardUpdate(cell, btn); } GridLayout.Spec rowSpec = GridLayout.spec(x, GridLayout.CENTER); GridLayout.Spec colSpec = GridLayout.spec(y, GridLayout.CENTER); GridLayout.LayoutParams cellParams = new GridLayout.LayoutParams(rowSpec, colSpec); // cellParams.setGravity(Gravity.CENTER); gridLayout.addView(btn, cellParams); boardButtons[x][y] = btn; } } ViewTreeObserver obs = gridLayout.getViewTreeObserver(); if(obs != null){ obs.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener(){ @Override public void onGlobalLayout() { ViewGroup rl = (ViewGroup)rootView.findViewById(R.id.rootLayout); Log.v(TAG, "root layout: "+rl.getWidth()+", "+rl.getHeight()); GridLayout gl = (GridLayout)rootView.findViewById(R.id.boardLayout); Log.v(TAG, "grid layout: "+gl.getWidth()+", "+gl.getHeight()); if(!boardListener.onBoardLayout(rl, gl)){ onDefaultBoardLayout(rl, gl); } ViewTreeObserver obs = gl.getViewTreeObserver(); assert obs != null; obs.removeOnGlobalLayoutListener(this); } }); } //consider also the following // gridLayout.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener(){ // @Override // public boolean onPreDraw() // { // return false; // } // }); return rootView; }
diff --git a/src/main/java/hudson/plugins/ec2/SlaveTemplate.java b/src/main/java/hudson/plugins/ec2/SlaveTemplate.java index 93f98bc..2400c73 100644 --- a/src/main/java/hudson/plugins/ec2/SlaveTemplate.java +++ b/src/main/java/hudson/plugins/ec2/SlaveTemplate.java @@ -1,471 +1,472 @@ /* * The MIT License * * Copyright (c) 2004-, Kohsuke Kawaguchi, Sun Microsystems, Inc., and a number of other of contributors * * 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 hudson.plugins.ec2; import hudson.Extension; import hudson.Util; import hudson.model.Describable; import hudson.model.TaskListener; import hudson.model.Descriptor; import hudson.model.Descriptor.FormException; import hudson.model.Hudson; import hudson.model.Label; import hudson.model.Node; import hudson.model.labels.LabelAtom; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import java.io.IOException; import java.io.PrintStream; import java.util.*; import javax.servlet.ServletException; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang.StringUtils; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import com.amazonaws.AmazonClientException; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.model.*; /** * Template of {@link EC2Slave} to launch. * * @author Kohsuke Kawaguchi */ public class SlaveTemplate implements Describable<SlaveTemplate> { public final String ami; public final String description; public final String zone; public final String securityGroups; public final String remoteFS; public final String sshPort; public final InstanceType type; public final String labels; public final Node.Mode mode; public final String initScript; public final String userData; public final String numExecutors; public final String remoteAdmin; public final String rootCommandPrefix; public final String jvmopts; public final String subnetId; public final String idleTerminationMinutes; public final int instanceCap; public final boolean stopOnTerminate; private final List<EC2Tag> tags; public final boolean usePrivateDnsName; protected transient EC2Cloud parent; private transient /*almost final*/ Set<LabelAtom> labelSet; private transient /*almost final*/ Set<String> securityGroupSet; @DataBoundConstructor public SlaveTemplate(String ami, String zone, String securityGroups, String remoteFS, String sshPort, InstanceType type, String labelString, Node.Mode mode, String description, String initScript, String userData, String numExecutors, String remoteAdmin, String rootCommandPrefix, String jvmopts, boolean stopOnTerminate, String subnetId, List<EC2Tag> tags, String idleTerminationMinutes, boolean usePrivateDnsName, String instanceCapStr) { this.ami = ami; this.zone = zone; this.securityGroups = securityGroups; this.remoteFS = remoteFS; this.sshPort = sshPort; this.type = type; this.labels = Util.fixNull(labelString); this.mode = mode; this.description = description; this.initScript = initScript; this.userData = userData; this.numExecutors = Util.fixNull(numExecutors).trim(); this.remoteAdmin = remoteAdmin; this.rootCommandPrefix = rootCommandPrefix; this.jvmopts = jvmopts; this.stopOnTerminate = stopOnTerminate; this.subnetId = subnetId; this.tags = tags; this.idleTerminationMinutes = idleTerminationMinutes; this.usePrivateDnsName = usePrivateDnsName; if (null == instanceCapStr || instanceCapStr.equals("")) { this.instanceCap = Integer.MAX_VALUE; } else { this.instanceCap = Integer.parseInt(instanceCapStr); } readResolve(); // initialize } public EC2Cloud getParent() { return parent; } public String getLabelString() { return labels; } public Node.Mode getMode() { return mode; } public String getDisplayName() { return description+" ("+ami+")"; } String getZone() { return zone; } public String getSecurityGroupString() { return securityGroups; } public Set<String> getSecurityGroupSet() { return securityGroupSet; } public Set<String> parseSecurityGroups() { if (securityGroups == null || "".equals(securityGroups.trim())) { return Collections.emptySet(); } else { return new HashSet<String>(Arrays.asList(securityGroups.split("\\s*,\\s*"))); } } public int getNumExecutors() { try { return Integer.parseInt(numExecutors); } catch (NumberFormatException e) { return EC2Slave.toNumExecutors(type); } } public int getSshPort() { try { return Integer.parseInt(sshPort); } catch (NumberFormatException e) { return 22; } } public String getRemoteAdmin() { return remoteAdmin; } public String getRootCommandPrefix() { return rootCommandPrefix; } public String getSubnetId() { return subnetId; } public List<EC2Tag> getTags() { if (null == tags) return null; return Collections.unmodifiableList(tags); } public String getidleTerminationMinutes() { return idleTerminationMinutes; } public Set<LabelAtom> getLabelSet(){ return labelSet; } public int getInstanceCap() { return instanceCap; } public String getInstanceCapStr() { if (instanceCap==Integer.MAX_VALUE) { return ""; } else { return String.valueOf(instanceCap); } } /** * Does this contain the given label? * * @param l * can be null to indicate "don't care". */ public boolean containsLabel(Label l) { return l==null || labelSet.contains(l); } /** * Provisions a new EC2 slave. * * @return always non-null. This needs to be then added to {@link Hudson#addNode(Node)}. */ public EC2Slave provision(TaskListener listener) throws AmazonClientException, IOException { PrintStream logger = listener.getLogger(); AmazonEC2 ec2 = getParent().connect(); try { logger.println("Launching " + ami + " for template " + description); KeyPair keyPair = parent.getPrivateKey().find(ec2); if(keyPair==null) { throw new AmazonClientException("No matching keypair found on EC2. Is the EC2 private key a valid one?"); } RunInstancesRequest riRequest = new RunInstancesRequest(ami, 1, 1); List<Filter> diFilters = new ArrayList<Filter>(); diFilters.add(new Filter("image-id").withValues(ami)); if (StringUtils.isNotBlank(getZone())) { Placement placement = new Placement(getZone()); riRequest.setPlacement(placement); diFilters.add(new Filter("availability-zone").withValues(getZone())); } if (StringUtils.isNotBlank(getSubnetId())) { riRequest.setSubnetId(getSubnetId()); diFilters.add(new Filter("subnet-id").withValues(getSubnetId())); /* If we have a subnet ID then we can only use VPC security groups */ if (!securityGroupSet.isEmpty()) { List<String> group_ids = new ArrayList<String>(); DescribeSecurityGroupsRequest group_req = new DescribeSecurityGroupsRequest(); group_req.withFilters(new Filter("group-name").withValues(securityGroupSet)); DescribeSecurityGroupsResult group_result = ec2.describeSecurityGroups(group_req); for (SecurityGroup group : group_result.getSecurityGroups()) { if (group.getVpcId() != null && !group.getVpcId().isEmpty()) { List<Filter> filters = new ArrayList<Filter>(); filters.add(new Filter("vpc-id").withValues(group.getVpcId())); filters.add(new Filter("state").withValues("available")); filters.add(new Filter("subnet-id").withValues(getSubnetId())); DescribeSubnetsRequest subnet_req = new DescribeSubnetsRequest(); subnet_req.withFilters(filters); DescribeSubnetsResult subnet_result = ec2.describeSubnets(subnet_req); List subnets = subnet_result.getSubnets(); if(subnets != null && !subnets.isEmpty()) { group_ids.add(group.getGroupId()); } } } if (securityGroupSet.size() != group_ids.size()) { throw new AmazonClientException( "Security groups must all be VPC security groups to work in a VPC context" ); } if (!group_ids.isEmpty()) { riRequest.setSecurityGroupIds(group_ids); diFilters.add(new Filter("instance.group-id").withValues(group_ids)); } } } else { /* No subnet: we can use standard security groups by name */ riRequest.setSecurityGroups(securityGroupSet); if (securityGroupSet.size() > 0) diFilters.add(new Filter("group-name").withValues(securityGroupSet)); } String userDataString = Base64.encodeBase64String(userData.getBytes()); riRequest.setUserData(userDataString); riRequest.setKeyName(keyPair.getKeyName()); diFilters.add(new Filter("key-name").withValues(keyPair.getKeyName())); riRequest.setInstanceType(type.toString()); diFilters.add(new Filter("instance-type").withValues(type.toString())); HashSet<Tag> inst_tags = null; if (tags != null && !tags.isEmpty()) { inst_tags = new HashSet<Tag>(); for(EC2Tag t : tags) { + inst_tags.add(new Tag(t.getName(), t.getValue())); diFilters.add(new Filter("tag:"+t.getName()).withValues(t.getValue())); } } DescribeInstancesRequest diRequest = new DescribeInstancesRequest(); diFilters.add(new Filter("instance-state-name").withValues(InstanceStateName.Stopped.toString(), InstanceStateName.Stopping.toString())); diRequest.setFilters(diFilters); logger.println("Looking for existing instances: "+diRequest); DescribeInstancesResult diResult = ec2.describeInstances(diRequest); if (diResult.getReservations().size() == 0) { // Have to create a new instance Instance inst = ec2.runInstances(riRequest).getReservation().getInstances().get(0); /* Now that we have our instance, we can set tags on it */ if (inst_tags != null) { CreateTagsRequest tag_request = new CreateTagsRequest(); tag_request.withResources(inst.getInstanceId()).setTags(inst_tags); ec2.createTags(tag_request); // That was a remote request - we should also update our local instance data. inst.setTags(inst_tags); } logger.println("No existing instance found - created: "+inst); return newSlave(inst); } Instance inst = diResult.getReservations().get(0).getInstances().get(0); logger.println("Found existing stopped instance: "+inst); List<String> instances = new ArrayList<String>(); instances.add(inst.getInstanceId()); StartInstancesRequest siRequest = new StartInstancesRequest(instances); StartInstancesResult siResult = ec2.startInstances(siRequest); logger.println("Starting existing instance: "+inst+ " result:"+siResult); List<Node> nodes = Hudson.getInstance().getNodes(); for (int i = 0, len = nodes.size(); i < len; i++) { if (!(nodes.get(i) instanceof EC2Slave)) continue; EC2Slave ec2Node = (EC2Slave) nodes.get(i); if (ec2Node.getInstanceId().equals(inst.getInstanceId())) { logger.println("Found existing corresponding: "+ec2Node); return ec2Node; } } // Existing slave not found logger.println("Creating new slave for existing instance: "+inst); return newSlave(inst); } catch (FormException e) { throw new AssertionError(); // we should have discovered all configuration issues upfront } } private EC2Slave newSlave(Instance inst) throws FormException, IOException { return new EC2Slave(inst.getInstanceId(), description, remoteFS, getSshPort(), getNumExecutors(), labels, mode, initScript, remoteAdmin, rootCommandPrefix, jvmopts, stopOnTerminate, idleTerminationMinutes, inst.getPublicDnsName(), inst.getPrivateDnsName(), EC2Tag.fromAmazonTags(inst.getTags()), usePrivateDnsName); } /** * Provisions a new EC2 slave based on the currently running instance on EC2, * instead of starting a new one. */ public EC2Slave attach(String instanceId, TaskListener listener) throws AmazonClientException, IOException { PrintStream logger = listener.getLogger(); AmazonEC2 ec2 = getParent().connect(); try { logger.println("Attaching to "+instanceId); DescribeInstancesRequest request = new DescribeInstancesRequest(); request.setInstanceIds(Collections.singletonList(instanceId)); Instance inst = ec2.describeInstances(request).getReservations().get(0).getInstances().get(0); return newSlave(inst); } catch (FormException e) { throw new AssertionError(); // we should have discovered all configuration issues upfront } } /** * Initializes data structure that we don't persist. */ protected Object readResolve() { labelSet = Label.parse(labels); securityGroupSet = parseSecurityGroups(); return this; } public Descriptor<SlaveTemplate> getDescriptor() { return Hudson.getInstance().getDescriptor(getClass()); } @Extension public static final class DescriptorImpl extends Descriptor<SlaveTemplate> { @Override public String getDisplayName() { return null; } /** * Since this shares much of the configuration with {@link EC2Computer}, check its help page, too. */ @Override public String getHelpFile(String fieldName) { String p = super.getHelpFile(fieldName); if (p==null) p = Hudson.getInstance().getDescriptor(EC2Slave.class).getHelpFile(fieldName); return p; } /*** * Check that the AMI requested is available in the cloud and can be used. */ public FormValidation doValidateAmi( @QueryParameter String accessId, @QueryParameter String secretKey, @QueryParameter String region, final @QueryParameter String ami) throws IOException, ServletException { AmazonEC2 ec2 = EC2Cloud.connect(accessId, secretKey, AmazonEC2Cloud.getEc2EndpointUrl(region)); if(ec2!=null) { try { List<String> images = new LinkedList<String>(); images.add(ami); List<String> owners = new LinkedList<String>(); List<String> users = new LinkedList<String>(); DescribeImagesRequest request = new DescribeImagesRequest(); request.setImageIds(images); request.setOwners(owners); request.setExecutableUsers(users); List<Image> img = ec2.describeImages(request).getImages(); if(img==null || img.isEmpty()) // de-registered AMI causes an empty list to be returned. so be defensive // against other possibilities return FormValidation.error("No such AMI, or not usable with this accessId: "+ami); return FormValidation.ok(img.get(0).getImageLocation()+" by "+img.get(0).getImageOwnerAlias()); } catch (AmazonClientException e) { return FormValidation.error(e.getMessage()); } } else return FormValidation.ok(); // can't test } public FormValidation doCheckIdleTerminationMinutes(@QueryParameter String value) { if (value == null || value.trim() == "") return FormValidation.ok(); try { int val = Integer.parseInt(value); if (val >= 0) return FormValidation.ok(); } catch ( NumberFormatException nfe ) {} return FormValidation.error("Idle Termination time must be a non-negative integer (or null)"); } public FormValidation doCheckInstanceCapStr(@QueryParameter String value) { if (value == null || value.trim() == "") return FormValidation.ok(); try { int val = Integer.parseInt(value); if (val >= 0) return FormValidation.ok(); } catch ( NumberFormatException nfe ) {} return FormValidation.error("InstanceCap must be a non-negative integer (or null)"); } public ListBoxModel doFillZoneItems( @QueryParameter String accessId, @QueryParameter String secretKey, @QueryParameter String region) throws IOException, ServletException { return EC2Slave.fillZoneItems(accessId, secretKey, region); } } }
true
true
public EC2Slave provision(TaskListener listener) throws AmazonClientException, IOException { PrintStream logger = listener.getLogger(); AmazonEC2 ec2 = getParent().connect(); try { logger.println("Launching " + ami + " for template " + description); KeyPair keyPair = parent.getPrivateKey().find(ec2); if(keyPair==null) { throw new AmazonClientException("No matching keypair found on EC2. Is the EC2 private key a valid one?"); } RunInstancesRequest riRequest = new RunInstancesRequest(ami, 1, 1); List<Filter> diFilters = new ArrayList<Filter>(); diFilters.add(new Filter("image-id").withValues(ami)); if (StringUtils.isNotBlank(getZone())) { Placement placement = new Placement(getZone()); riRequest.setPlacement(placement); diFilters.add(new Filter("availability-zone").withValues(getZone())); } if (StringUtils.isNotBlank(getSubnetId())) { riRequest.setSubnetId(getSubnetId()); diFilters.add(new Filter("subnet-id").withValues(getSubnetId())); /* If we have a subnet ID then we can only use VPC security groups */ if (!securityGroupSet.isEmpty()) { List<String> group_ids = new ArrayList<String>(); DescribeSecurityGroupsRequest group_req = new DescribeSecurityGroupsRequest(); group_req.withFilters(new Filter("group-name").withValues(securityGroupSet)); DescribeSecurityGroupsResult group_result = ec2.describeSecurityGroups(group_req); for (SecurityGroup group : group_result.getSecurityGroups()) { if (group.getVpcId() != null && !group.getVpcId().isEmpty()) { List<Filter> filters = new ArrayList<Filter>(); filters.add(new Filter("vpc-id").withValues(group.getVpcId())); filters.add(new Filter("state").withValues("available")); filters.add(new Filter("subnet-id").withValues(getSubnetId())); DescribeSubnetsRequest subnet_req = new DescribeSubnetsRequest(); subnet_req.withFilters(filters); DescribeSubnetsResult subnet_result = ec2.describeSubnets(subnet_req); List subnets = subnet_result.getSubnets(); if(subnets != null && !subnets.isEmpty()) { group_ids.add(group.getGroupId()); } } } if (securityGroupSet.size() != group_ids.size()) { throw new AmazonClientException( "Security groups must all be VPC security groups to work in a VPC context" ); } if (!group_ids.isEmpty()) { riRequest.setSecurityGroupIds(group_ids); diFilters.add(new Filter("instance.group-id").withValues(group_ids)); } } } else { /* No subnet: we can use standard security groups by name */ riRequest.setSecurityGroups(securityGroupSet); if (securityGroupSet.size() > 0) diFilters.add(new Filter("group-name").withValues(securityGroupSet)); } String userDataString = Base64.encodeBase64String(userData.getBytes()); riRequest.setUserData(userDataString); riRequest.setKeyName(keyPair.getKeyName()); diFilters.add(new Filter("key-name").withValues(keyPair.getKeyName())); riRequest.setInstanceType(type.toString()); diFilters.add(new Filter("instance-type").withValues(type.toString())); HashSet<Tag> inst_tags = null; if (tags != null && !tags.isEmpty()) { inst_tags = new HashSet<Tag>(); for(EC2Tag t : tags) { diFilters.add(new Filter("tag:"+t.getName()).withValues(t.getValue())); } } DescribeInstancesRequest diRequest = new DescribeInstancesRequest(); diFilters.add(new Filter("instance-state-name").withValues(InstanceStateName.Stopped.toString(), InstanceStateName.Stopping.toString())); diRequest.setFilters(diFilters); logger.println("Looking for existing instances: "+diRequest); DescribeInstancesResult diResult = ec2.describeInstances(diRequest); if (diResult.getReservations().size() == 0) { // Have to create a new instance Instance inst = ec2.runInstances(riRequest).getReservation().getInstances().get(0); /* Now that we have our instance, we can set tags on it */ if (inst_tags != null) { CreateTagsRequest tag_request = new CreateTagsRequest(); tag_request.withResources(inst.getInstanceId()).setTags(inst_tags); ec2.createTags(tag_request); // That was a remote request - we should also update our local instance data. inst.setTags(inst_tags); } logger.println("No existing instance found - created: "+inst); return newSlave(inst); } Instance inst = diResult.getReservations().get(0).getInstances().get(0); logger.println("Found existing stopped instance: "+inst); List<String> instances = new ArrayList<String>(); instances.add(inst.getInstanceId()); StartInstancesRequest siRequest = new StartInstancesRequest(instances); StartInstancesResult siResult = ec2.startInstances(siRequest); logger.println("Starting existing instance: "+inst+ " result:"+siResult); List<Node> nodes = Hudson.getInstance().getNodes(); for (int i = 0, len = nodes.size(); i < len; i++) { if (!(nodes.get(i) instanceof EC2Slave)) continue; EC2Slave ec2Node = (EC2Slave) nodes.get(i); if (ec2Node.getInstanceId().equals(inst.getInstanceId())) { logger.println("Found existing corresponding: "+ec2Node); return ec2Node; } } // Existing slave not found logger.println("Creating new slave for existing instance: "+inst); return newSlave(inst); } catch (FormException e) { throw new AssertionError(); // we should have discovered all configuration issues upfront } }
public EC2Slave provision(TaskListener listener) throws AmazonClientException, IOException { PrintStream logger = listener.getLogger(); AmazonEC2 ec2 = getParent().connect(); try { logger.println("Launching " + ami + " for template " + description); KeyPair keyPair = parent.getPrivateKey().find(ec2); if(keyPair==null) { throw new AmazonClientException("No matching keypair found on EC2. Is the EC2 private key a valid one?"); } RunInstancesRequest riRequest = new RunInstancesRequest(ami, 1, 1); List<Filter> diFilters = new ArrayList<Filter>(); diFilters.add(new Filter("image-id").withValues(ami)); if (StringUtils.isNotBlank(getZone())) { Placement placement = new Placement(getZone()); riRequest.setPlacement(placement); diFilters.add(new Filter("availability-zone").withValues(getZone())); } if (StringUtils.isNotBlank(getSubnetId())) { riRequest.setSubnetId(getSubnetId()); diFilters.add(new Filter("subnet-id").withValues(getSubnetId())); /* If we have a subnet ID then we can only use VPC security groups */ if (!securityGroupSet.isEmpty()) { List<String> group_ids = new ArrayList<String>(); DescribeSecurityGroupsRequest group_req = new DescribeSecurityGroupsRequest(); group_req.withFilters(new Filter("group-name").withValues(securityGroupSet)); DescribeSecurityGroupsResult group_result = ec2.describeSecurityGroups(group_req); for (SecurityGroup group : group_result.getSecurityGroups()) { if (group.getVpcId() != null && !group.getVpcId().isEmpty()) { List<Filter> filters = new ArrayList<Filter>(); filters.add(new Filter("vpc-id").withValues(group.getVpcId())); filters.add(new Filter("state").withValues("available")); filters.add(new Filter("subnet-id").withValues(getSubnetId())); DescribeSubnetsRequest subnet_req = new DescribeSubnetsRequest(); subnet_req.withFilters(filters); DescribeSubnetsResult subnet_result = ec2.describeSubnets(subnet_req); List subnets = subnet_result.getSubnets(); if(subnets != null && !subnets.isEmpty()) { group_ids.add(group.getGroupId()); } } } if (securityGroupSet.size() != group_ids.size()) { throw new AmazonClientException( "Security groups must all be VPC security groups to work in a VPC context" ); } if (!group_ids.isEmpty()) { riRequest.setSecurityGroupIds(group_ids); diFilters.add(new Filter("instance.group-id").withValues(group_ids)); } } } else { /* No subnet: we can use standard security groups by name */ riRequest.setSecurityGroups(securityGroupSet); if (securityGroupSet.size() > 0) diFilters.add(new Filter("group-name").withValues(securityGroupSet)); } String userDataString = Base64.encodeBase64String(userData.getBytes()); riRequest.setUserData(userDataString); riRequest.setKeyName(keyPair.getKeyName()); diFilters.add(new Filter("key-name").withValues(keyPair.getKeyName())); riRequest.setInstanceType(type.toString()); diFilters.add(new Filter("instance-type").withValues(type.toString())); HashSet<Tag> inst_tags = null; if (tags != null && !tags.isEmpty()) { inst_tags = new HashSet<Tag>(); for(EC2Tag t : tags) { inst_tags.add(new Tag(t.getName(), t.getValue())); diFilters.add(new Filter("tag:"+t.getName()).withValues(t.getValue())); } } DescribeInstancesRequest diRequest = new DescribeInstancesRequest(); diFilters.add(new Filter("instance-state-name").withValues(InstanceStateName.Stopped.toString(), InstanceStateName.Stopping.toString())); diRequest.setFilters(diFilters); logger.println("Looking for existing instances: "+diRequest); DescribeInstancesResult diResult = ec2.describeInstances(diRequest); if (diResult.getReservations().size() == 0) { // Have to create a new instance Instance inst = ec2.runInstances(riRequest).getReservation().getInstances().get(0); /* Now that we have our instance, we can set tags on it */ if (inst_tags != null) { CreateTagsRequest tag_request = new CreateTagsRequest(); tag_request.withResources(inst.getInstanceId()).setTags(inst_tags); ec2.createTags(tag_request); // That was a remote request - we should also update our local instance data. inst.setTags(inst_tags); } logger.println("No existing instance found - created: "+inst); return newSlave(inst); } Instance inst = diResult.getReservations().get(0).getInstances().get(0); logger.println("Found existing stopped instance: "+inst); List<String> instances = new ArrayList<String>(); instances.add(inst.getInstanceId()); StartInstancesRequest siRequest = new StartInstancesRequest(instances); StartInstancesResult siResult = ec2.startInstances(siRequest); logger.println("Starting existing instance: "+inst+ " result:"+siResult); List<Node> nodes = Hudson.getInstance().getNodes(); for (int i = 0, len = nodes.size(); i < len; i++) { if (!(nodes.get(i) instanceof EC2Slave)) continue; EC2Slave ec2Node = (EC2Slave) nodes.get(i); if (ec2Node.getInstanceId().equals(inst.getInstanceId())) { logger.println("Found existing corresponding: "+ec2Node); return ec2Node; } } // Existing slave not found logger.println("Creating new slave for existing instance: "+inst); return newSlave(inst); } catch (FormException e) { throw new AssertionError(); // we should have discovered all configuration issues upfront } }
diff --git a/src/main/java/me/tehbeard/BeardStat/commands/playedCommand.java b/src/main/java/me/tehbeard/BeardStat/commands/playedCommand.java index 26951bd..b2f7a87 100644 --- a/src/main/java/me/tehbeard/BeardStat/commands/playedCommand.java +++ b/src/main/java/me/tehbeard/BeardStat/commands/playedCommand.java @@ -1,123 +1,123 @@ package me.tehbeard.BeardStat.commands; import java.util.List; import me.tehbeard.BeardStat.BeardStat; import me.tehbeard.BeardStat.LanguagePack; import me.tehbeard.BeardStat.containers.PlayerStatBlob; import me.tehbeard.BeardStat.containers.PlayerStatManager; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class playedCommand implements CommandExecutor { private PlayerStatManager playerStatManager; public playedCommand(PlayerStatManager playerStatManager) { this.playerStatManager = playerStatManager; } public boolean onCommand(CommandSender sender, Command command, String cmdLabel, String[] args) { long seconds = 0; Player pp = null; if (args.length == 0){ //check if we are a player, and use them instead if(sender instanceof Player){ pp = (Player)sender; } else { sender.sendMessage(ChatColor.RED + LanguagePack.getMsg("command.error.noconsole.noargs")); return true; } } //if they don't have permission, BAD PERSON GO AWAY - if(!BeardStat.hasPermission((Player)sender, "command.played")){ + if(!BeardStat.hasPermission(sender, "command.played")){ BeardStat.sendNoPermissionError(sender); return true; } // they put a player name, try and find out who it is. if(args.length == 1){ if(!BeardStat.hasPermission(sender, "command.played.other")){ BeardStat.sendNoPermissionError(sender); return true; } pp = Bukkit.getPlayer(args[0]); if(pp==null){ List<Player> ply = Bukkit.getServer().matchPlayer(args[0]); if(ply.size()>1){ for(Player p:ply){ if(p.getName().equals(args[0])){ pp = p; break; } } } else if(ply.size()==1){ pp = ply.get(0); } } } else//Funky number of arguments, return false { return false; } PlayerStatBlob blob; //no player match found, attempt to poll DB directly if(pp==null){ blob = playerStatManager.findPlayerBlob(args[0]);//Try to find by exact name } else //poll using found player { blob = playerStatManager.findPlayerBlob(pp.getName()); seconds += BeardStat.self().getStatManager().getSessionTime(pp.getName()); } if(blob != null && blob.getStat("stats", "playedfor").getValue() != 0){ sender.sendMessage(ChatColor.GOLD + blob.getName()); seconds += blob.getStat("stats","playedfor").getValue() + BeardStat.self().getStatManager().getSessionTime(pp.getName()); sender.sendMessage(GetPlayedString(seconds)); return true; } else { sender.sendMessage(ChatColor.RED + LanguagePack.getMsg("command.error.noplayer",args[0])); return true; } } public static String GetPlayedString(long seconds){ String output = LanguagePack.getMsg("command.played.zero"); if(seconds > 0){ int weeks = (int) seconds / 604800; int days = (int)Math.ceil((seconds -604800*weeks) / 86400); int hours = (int)Math.ceil((seconds - (86400 * days + 604800*weeks)) / 3600); int minutes = (int)Math.ceil((seconds - (604800*weeks + 86400 * days + 3600 * hours)) / 60); output = LanguagePack.getMsg("command.played.output", weeks , days , hours , minutes); } return output; } }
true
true
public boolean onCommand(CommandSender sender, Command command, String cmdLabel, String[] args) { long seconds = 0; Player pp = null; if (args.length == 0){ //check if we are a player, and use them instead if(sender instanceof Player){ pp = (Player)sender; } else { sender.sendMessage(ChatColor.RED + LanguagePack.getMsg("command.error.noconsole.noargs")); return true; } } //if they don't have permission, BAD PERSON GO AWAY if(!BeardStat.hasPermission((Player)sender, "command.played")){ BeardStat.sendNoPermissionError(sender); return true; } // they put a player name, try and find out who it is. if(args.length == 1){ if(!BeardStat.hasPermission(sender, "command.played.other")){ BeardStat.sendNoPermissionError(sender); return true; } pp = Bukkit.getPlayer(args[0]); if(pp==null){ List<Player> ply = Bukkit.getServer().matchPlayer(args[0]); if(ply.size()>1){ for(Player p:ply){ if(p.getName().equals(args[0])){ pp = p; break; } } } else if(ply.size()==1){ pp = ply.get(0); } } } else//Funky number of arguments, return false { return false; } PlayerStatBlob blob; //no player match found, attempt to poll DB directly if(pp==null){ blob = playerStatManager.findPlayerBlob(args[0]);//Try to find by exact name } else //poll using found player { blob = playerStatManager.findPlayerBlob(pp.getName()); seconds += BeardStat.self().getStatManager().getSessionTime(pp.getName()); } if(blob != null && blob.getStat("stats", "playedfor").getValue() != 0){ sender.sendMessage(ChatColor.GOLD + blob.getName()); seconds += blob.getStat("stats","playedfor").getValue() + BeardStat.self().getStatManager().getSessionTime(pp.getName()); sender.sendMessage(GetPlayedString(seconds)); return true; } else { sender.sendMessage(ChatColor.RED + LanguagePack.getMsg("command.error.noplayer",args[0])); return true; } }
public boolean onCommand(CommandSender sender, Command command, String cmdLabel, String[] args) { long seconds = 0; Player pp = null; if (args.length == 0){ //check if we are a player, and use them instead if(sender instanceof Player){ pp = (Player)sender; } else { sender.sendMessage(ChatColor.RED + LanguagePack.getMsg("command.error.noconsole.noargs")); return true; } } //if they don't have permission, BAD PERSON GO AWAY if(!BeardStat.hasPermission(sender, "command.played")){ BeardStat.sendNoPermissionError(sender); return true; } // they put a player name, try and find out who it is. if(args.length == 1){ if(!BeardStat.hasPermission(sender, "command.played.other")){ BeardStat.sendNoPermissionError(sender); return true; } pp = Bukkit.getPlayer(args[0]); if(pp==null){ List<Player> ply = Bukkit.getServer().matchPlayer(args[0]); if(ply.size()>1){ for(Player p:ply){ if(p.getName().equals(args[0])){ pp = p; break; } } } else if(ply.size()==1){ pp = ply.get(0); } } } else//Funky number of arguments, return false { return false; } PlayerStatBlob blob; //no player match found, attempt to poll DB directly if(pp==null){ blob = playerStatManager.findPlayerBlob(args[0]);//Try to find by exact name } else //poll using found player { blob = playerStatManager.findPlayerBlob(pp.getName()); seconds += BeardStat.self().getStatManager().getSessionTime(pp.getName()); } if(blob != null && blob.getStat("stats", "playedfor").getValue() != 0){ sender.sendMessage(ChatColor.GOLD + blob.getName()); seconds += blob.getStat("stats","playedfor").getValue() + BeardStat.self().getStatManager().getSessionTime(pp.getName()); sender.sendMessage(GetPlayedString(seconds)); return true; } else { sender.sendMessage(ChatColor.RED + LanguagePack.getMsg("command.error.noplayer",args[0])); return true; } }
diff --git a/kxen-projection/src/test/java/com/kxen/han/projection/fpg/ProjectionTest.java b/kxen-projection/src/test/java/com/kxen/han/projection/fpg/ProjectionTest.java index 4b46c70..907aab8 100644 --- a/kxen-projection/src/test/java/com/kxen/han/projection/fpg/ProjectionTest.java +++ b/kxen-projection/src/test/java/com/kxen/han/projection/fpg/ProjectionTest.java @@ -1,17 +1,14 @@ package com.kxen.han.projection.fpg; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class ProjectionTest { @Test public void testProject() throws Exception { - OutputLayer ol = OutputLayer.newInstance(); - Projection.project("src/test/resources/TestExampleAutoGen", - ol, 3); } }
true
true
public void testProject() throws Exception { OutputLayer ol = OutputLayer.newInstance(); Projection.project("src/test/resources/TestExampleAutoGen", ol, 3); }
public void testProject() throws Exception { }
diff --git a/src/test/java/au/net/netstorm/boost/test/cases/BoooostCase.java b/src/test/java/au/net/netstorm/boost/test/cases/BoooostCase.java index 9c55be8ec..dd83a70a3 100644 --- a/src/test/java/au/net/netstorm/boost/test/cases/BoooostCase.java +++ b/src/test/java/au/net/netstorm/boost/test/cases/BoooostCase.java @@ -1,85 +1,86 @@ package au.net.netstorm.boost.test.cases; import au.net.netstorm.boost.retire.reflect.AssertTestChecker; import au.net.netstorm.boost.retire.reflect.DefaultAssertTestChecker; import junit.framework.TestCase; // SUGGEST Remove the need for this altogether. // SUGGEST Check bottom level classes are final. // SUGGEST Check no-arg (single) constructor. /** * This class acts as a buffer to get us out of the * broken world` of JUnit. */ // OK GenericIllegalRegexp { public abstract class BoooostCase extends TestCase { // } OK GenericIllegalRegexp private final AssertTestChecker assertTestChecker = new DefaultAssertTestChecker(); protected final void setUp() throws Exception { + // FIX 1524 Fail. We're overriding runBare so don't even call setUp(); super.setUp(); gearup(); } protected final void tearDown() throws Exception { geardown(); super.tearDown(); } protected void gearup() { } protected void geardown() { } public final void assertEquals(Object[] expected, Object[] actual) { assertTestChecker.checkEquals(expected, actual); } public final void assertBagEquals(Object[] expected, Object[] actual) { assertTestChecker.checkBagEquals(expected, actual); } public final void assertEquals(byte[] expected, byte[] actual) { assertTestChecker.checkEquals(expected, actual); } public final void assertEquals(int[] expected, int[] actual) { assertTestChecker.checkEquals(expected, actual); } public final void assertNotEquals(byte[] v1, byte[] v2) { assertTestChecker.checkNotEquals(v1, v2); } public final void assertNotEquals(Object v1, Object v2) { assertEquals(false, v1.equals(v2)); } public final void assertNotEquals(int v1, int v2) { assertEquals(false, v1 == v2); } public static final void assertTrue(boolean expected) { suffer(); } public static final void assertTrue(String msg, boolean expected) { suffer(); } public static final void assertFalse(boolean expected) { suffer(); } public static final void assertFalse(String msg, boolean expected) { suffer(); } // OK LineLength { private static void suffer() { throw new UnsupportedOperationException("Use assertEquals(true|false, expected) ... assertTrue/assertFalse precludes refactoring opportunities (_x_)"); } // } OK LineLength - Abusing others is fine if they are doing the wrong thing ;-) }
true
true
protected final void setUp() throws Exception { super.setUp(); gearup(); }
protected final void setUp() throws Exception { // FIX 1524 Fail. We're overriding runBare so don't even call setUp(); super.setUp(); gearup(); }
diff --git a/GnuBackgammon/src/it/alcacoop/backgammon/GnuBackgammon.java b/GnuBackgammon/src/it/alcacoop/backgammon/GnuBackgammon.java index dfa7d17..431614f 100644 --- a/GnuBackgammon/src/it/alcacoop/backgammon/GnuBackgammon.java +++ b/GnuBackgammon/src/it/alcacoop/backgammon/GnuBackgammon.java @@ -1,340 +1,338 @@ /* ################################################################## # GNU BACKGAMMON MOBILE # ################################################################## # # # Authors: Domenico Martella - Davide Saurino # # E-mail: [email protected] # # Date: 19/12/2012 # # # ################################################################## # # # Copyright (C) 2012 Alca Societa' Cooperativa # # # # This file is part of GNU BACKGAMMON MOBILE. # # GNU BACKGAMMON MOBILE 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. # # # # GNU BACKGAMMON MOBILE 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 v3 along with this program. # # If not, see <http://http://www.gnu.org/licenses/> # # # ################################################################## */ package it.alcacoop.backgammon; import it.alcacoop.backgammon.actors.Board; import it.alcacoop.backgammon.fsm.BaseFSM; import it.alcacoop.backgammon.fsm.FIBSFSM; import it.alcacoop.backgammon.fsm.GServiceFSM; import it.alcacoop.backgammon.fsm.GameFSM; import it.alcacoop.backgammon.fsm.MenuFSM; import it.alcacoop.backgammon.fsm.SimulationFSM; import it.alcacoop.backgammon.gservice.GServiceClient; import it.alcacoop.backgammon.layers.AppearanceScreen; import it.alcacoop.backgammon.layers.BaseScreen; import it.alcacoop.backgammon.layers.FibsScreen; import it.alcacoop.backgammon.layers.GameScreen; import it.alcacoop.backgammon.layers.MainMenuScreen; import it.alcacoop.backgammon.layers.MatchOptionsScreen; import it.alcacoop.backgammon.layers.OptionsScreen; import it.alcacoop.backgammon.layers.SplashScreen; import it.alcacoop.backgammon.layers.TwoPlayersScreen; import it.alcacoop.backgammon.layers.WelcomeScreen; import it.alcacoop.backgammon.logic.MatchState; import it.alcacoop.backgammon.utils.FibsNetHandler; import it.alcacoop.backgammon.utils.JSONProperties; import it.alcacoop.backgammon.utils.MatchRecorder; import it.alcacoop.fibs.CommandDispatcherImpl; import it.alcacoop.fibs.Player; import java.util.Timer; import java.util.TimerTask; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Preferences; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.utils.Pool; public class GnuBackgammon extends Game implements ApplicationListener { public GameScreen gameScreen; private MatchOptionsScreen matchOptionsScreen; public MainMenuScreen menuScreen; public TwoPlayersScreen twoplayersScreen; private OptionsScreen optionsScreen; private WelcomeScreen welcomeScreen; private AppearanceScreen appearanceScreen; public FibsScreen fibsScreen; public static int chatHeight = 20; public int appVersionCode = 0; private int resolutions[][] = { {1280,740}, {800,480}, {480,320} }; public int ss; private String[] resname = {"hdpi", "mdpi", "ldpi"}; public int resolution[]; private GameFSM gameFSM; private SimulationFSM simulationFSM; private MenuFSM menuFSM; private FIBSFSM fibsFSM; private GServiceFSM gserviceFSM; public static BitmapFont font; public static TextureAtlas atlas; public static Skin skin; public static GnuBackgammon Instance; public static BaseFSM fsm; public Board board; public BaseScreen currentScreen; public JSONProperties jp; public Preferences optionPrefs, appearancePrefs; public SoundManager snd; public NativeFunctions nativeFunctions; public Preferences fibsPrefs; public MatchRecorder rec; public String fname; public String server; public CommandDispatcherImpl commandDispatcher; public FibsNetHandler fibs; public String FibsUsername; public String FibsPassword; public String FibsOpponent; public Pool<Player> fibsPlayersPool; private boolean skipSplashScreen; public String invitationId = ""; public boolean interstitialVisible = false; public GnuBackgammon(NativeFunctions n) { nativeFunctions = n; } public void isCR() { System.out.println("CR: "+Gdx.graphics.isContinuousRendering()); } private Timer transitionTimer; @Override public void create() { Instance = this; optionPrefs = Gdx.app.getPreferences("GameOptions"); appearancePrefs = Gdx.app.getPreferences("Appearance"); fibsPrefs = Gdx.app.getPreferences("FibsPreferences"); //CHECK SCREEN DIM AND SELECT CORRECT ATLAS int pWidth = Gdx.graphics.getWidth(); if (pWidth<=480) ss = 2; else if (pWidth<=800) ss = 1; else ss = 0; resolution = resolutions[ss]; transitionTimer = new Timer(); //System.out.println("=====> GSERVICE START: "+skipSplashScreen); if (!skipSplashScreen) { setScreen(new SplashScreen("data/"+resname[ss]+"/alca.png")); } else { initAssets(); setFSM("MENU_FSM"); //fsm.state(MenuFSM.States.TWO_PLAYERS); } } public void initAssets() { Gdx.graphics.setContinuousRendering(false); Gdx.graphics.requestRendering(); atlas = new TextureAtlas(Gdx.files.internal("data/"+resname[ss]+"/pack.atlas")); fibsPlayersPool = new Pool<Player>(50){ @Override protected Player newObject() { return new Player(); } }; snd = new SoundManager(); rec = new MatchRecorder(); fibs = new FibsNetHandler(); commandDispatcher = new CommandDispatcherImpl(); fname = nativeFunctions.getDataDir()+"/data/match."; GnuBackgammon.Instance.jp = new JSONProperties(Gdx.files.internal("data/"+GnuBackgammon.Instance.getResName()+"/pos.json")); skin = new Skin(Gdx.files.internal("data/"+resname[ss]+"/myskin.json")); font = new BitmapFont(Gdx.files.internal("data/"+resname[ss]+"/checker.fnt"), false); TextureRegion r = font.getRegion(); r.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear); BitmapFont f = skin.getFont("default-font"); f.getRegion().getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear); - f = skin.getFont("default-font"); - f.getRegion().getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear); GnuBackgammon.atlas.addRegion("board", atlas.findRegion("B1")); GnuBackgammon.atlas.addRegion("boardbg", atlas.findRegion("B1-BG")); GnuBackgammon.atlas.addRegion("cb", atlas.findRegion("CS1-B")); GnuBackgammon.atlas.addRegion("cw", atlas.findRegion("CS1-W")); GnuBackgammon.atlas.addRegion("ch", atlas.findRegion("CS1-H")); board = new Board(); gameFSM = new GameFSM(board); simulationFSM = new SimulationFSM(board); menuFSM = new MenuFSM(board); fibsFSM = new FIBSFSM(board); gserviceFSM = new GServiceFSM(board); fsm = simulationFSM; gameScreen = new GameScreen(); matchOptionsScreen = new MatchOptionsScreen(); menuScreen = new MainMenuScreen(); twoplayersScreen = new TwoPlayersScreen(); optionsScreen = new OptionsScreen(); welcomeScreen = new WelcomeScreen(); appearanceScreen = new AppearanceScreen(); fibsScreen = new FibsScreen(); nativeFunctions.injectBGInstance(); } @Override public void setScreen(final Screen screen) { if (currentScreen!=null) { ((BaseScreen)screen).initialize(); currentScreen.fadeOut(); TimerTask task = new TimerTask() { @Override public void run() { ((BaseScreen)(screen)).fixBGImg(); GnuBackgammon.super.setScreen(screen); } }; transitionTimer.schedule(task, (long)(currentScreen.animationTime*1000)); } else super.setScreen(screen); } public String getResName() { return resname[ss]; } public void goToScreen(final int s) { switch (s) { case 0: GnuBackgammon.Instance.setScreen(welcomeScreen); currentScreen = welcomeScreen; break; case 1: setScreen(optionsScreen); currentScreen = optionsScreen; break; case 2: setScreen(menuScreen); currentScreen = menuScreen; break; case 3: setScreen(matchOptionsScreen); currentScreen = matchOptionsScreen; break; case 4: setScreen(gameScreen); currentScreen = gameScreen; break; case 6: setScreen(welcomeScreen); currentScreen = welcomeScreen; break; case 7: setScreen(appearanceScreen); currentScreen = appearanceScreen; break; case 8: setScreen(fibsScreen); currentScreen = fibsScreen; break; case 9: setScreen(twoplayersScreen); currentScreen = twoplayersScreen; break; } } public void setFSM(String type) { if (fsm!=null) fsm.stop(); if (type == "SIMULATED_FSM") fsm = simulationFSM; else if (type == "MENU_FSM") fsm = menuFSM; else if (type == "GAME_FSM") fsm = gameFSM; else if (type == "FIBS_FSM") fsm = fibsFSM; else if (type == "GSERVICE_FSM") fsm = gserviceFSM; fsm.start(); } public void appendChatMessage(String msg, boolean direction) { if (MatchState.matchType==2) commandDispatcher.send("tell "+FibsOpponent+" "+msg); else if (MatchState.matchType==3) GServiceClient.getInstance().sendMessage("90 "+msg); if ((FibsUsername!=null)&&(!FibsUsername.equals(""))) appendChatMessage(FibsUsername, msg, direction); else appendChatMessage("You", msg, direction); } public void appendChatMessage(String username, String msg, boolean direction) { gameScreen.chatBox.appendMessage(username, msg, direction); } }
true
true
public void initAssets() { Gdx.graphics.setContinuousRendering(false); Gdx.graphics.requestRendering(); atlas = new TextureAtlas(Gdx.files.internal("data/"+resname[ss]+"/pack.atlas")); fibsPlayersPool = new Pool<Player>(50){ @Override protected Player newObject() { return new Player(); } }; snd = new SoundManager(); rec = new MatchRecorder(); fibs = new FibsNetHandler(); commandDispatcher = new CommandDispatcherImpl(); fname = nativeFunctions.getDataDir()+"/data/match."; GnuBackgammon.Instance.jp = new JSONProperties(Gdx.files.internal("data/"+GnuBackgammon.Instance.getResName()+"/pos.json")); skin = new Skin(Gdx.files.internal("data/"+resname[ss]+"/myskin.json")); font = new BitmapFont(Gdx.files.internal("data/"+resname[ss]+"/checker.fnt"), false); TextureRegion r = font.getRegion(); r.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear); BitmapFont f = skin.getFont("default-font"); f.getRegion().getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear); f = skin.getFont("default-font"); f.getRegion().getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear); GnuBackgammon.atlas.addRegion("board", atlas.findRegion("B1")); GnuBackgammon.atlas.addRegion("boardbg", atlas.findRegion("B1-BG")); GnuBackgammon.atlas.addRegion("cb", atlas.findRegion("CS1-B")); GnuBackgammon.atlas.addRegion("cw", atlas.findRegion("CS1-W")); GnuBackgammon.atlas.addRegion("ch", atlas.findRegion("CS1-H")); board = new Board(); gameFSM = new GameFSM(board); simulationFSM = new SimulationFSM(board); menuFSM = new MenuFSM(board); fibsFSM = new FIBSFSM(board); gserviceFSM = new GServiceFSM(board); fsm = simulationFSM; gameScreen = new GameScreen(); matchOptionsScreen = new MatchOptionsScreen(); menuScreen = new MainMenuScreen(); twoplayersScreen = new TwoPlayersScreen(); optionsScreen = new OptionsScreen(); welcomeScreen = new WelcomeScreen(); appearanceScreen = new AppearanceScreen(); fibsScreen = new FibsScreen(); nativeFunctions.injectBGInstance(); }
public void initAssets() { Gdx.graphics.setContinuousRendering(false); Gdx.graphics.requestRendering(); atlas = new TextureAtlas(Gdx.files.internal("data/"+resname[ss]+"/pack.atlas")); fibsPlayersPool = new Pool<Player>(50){ @Override protected Player newObject() { return new Player(); } }; snd = new SoundManager(); rec = new MatchRecorder(); fibs = new FibsNetHandler(); commandDispatcher = new CommandDispatcherImpl(); fname = nativeFunctions.getDataDir()+"/data/match."; GnuBackgammon.Instance.jp = new JSONProperties(Gdx.files.internal("data/"+GnuBackgammon.Instance.getResName()+"/pos.json")); skin = new Skin(Gdx.files.internal("data/"+resname[ss]+"/myskin.json")); font = new BitmapFont(Gdx.files.internal("data/"+resname[ss]+"/checker.fnt"), false); TextureRegion r = font.getRegion(); r.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear); BitmapFont f = skin.getFont("default-font"); f.getRegion().getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear); GnuBackgammon.atlas.addRegion("board", atlas.findRegion("B1")); GnuBackgammon.atlas.addRegion("boardbg", atlas.findRegion("B1-BG")); GnuBackgammon.atlas.addRegion("cb", atlas.findRegion("CS1-B")); GnuBackgammon.atlas.addRegion("cw", atlas.findRegion("CS1-W")); GnuBackgammon.atlas.addRegion("ch", atlas.findRegion("CS1-H")); board = new Board(); gameFSM = new GameFSM(board); simulationFSM = new SimulationFSM(board); menuFSM = new MenuFSM(board); fibsFSM = new FIBSFSM(board); gserviceFSM = new GServiceFSM(board); fsm = simulationFSM; gameScreen = new GameScreen(); matchOptionsScreen = new MatchOptionsScreen(); menuScreen = new MainMenuScreen(); twoplayersScreen = new TwoPlayersScreen(); optionsScreen = new OptionsScreen(); welcomeScreen = new WelcomeScreen(); appearanceScreen = new AppearanceScreen(); fibsScreen = new FibsScreen(); nativeFunctions.injectBGInstance(); }
diff --git a/src/com/android/settings/ChooseLockSettingsHelper.java b/src/com/android/settings/ChooseLockSettingsHelper.java index 5fe3118fb..6382891fe 100644 --- a/src/com/android/settings/ChooseLockSettingsHelper.java +++ b/src/com/android/settings/ChooseLockSettingsHelper.java @@ -1,86 +1,87 @@ /* * Copyright (C) 2010 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.settings; import android.app.Activity; import android.app.admin.DevicePolicyManager; import android.content.Intent; import com.android.internal.widget.LockPatternUtils; public class ChooseLockSettingsHelper { private LockPatternUtils mLockPatternUtils; private Activity mActivity; public ChooseLockSettingsHelper(Activity activity) { mActivity = activity; mLockPatternUtils = new LockPatternUtils(activity); } public LockPatternUtils utils() { return mLockPatternUtils; } /** * If a pattern, password or PIN exists, prompt the user before allowing them to change it. * @return true if one exists and we launched an activity to confirm it * @see #onActivityResult(int, int, android.content.Intent) */ protected boolean launchConfirmationActivity(int request) { boolean launched = false; switch (mLockPatternUtils.getKeyguardStoredPasswordQuality()) { case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING: launched = confirmPattern(request); break; case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC: case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC: + case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC: launched = confirmPassword(request); break; } return launched; } /** * Launch screen to confirm the existing lock pattern. * @see #onActivityResult(int, int, android.content.Intent) * @return true if we launched an activity to confirm pattern */ private boolean confirmPattern(int request) { if (!mLockPatternUtils.isLockPatternEnabled() || !mLockPatternUtils.savedPatternExists()) { return false; } final Intent intent = new Intent(); intent.setClassName("com.android.settings", "com.android.settings.ConfirmLockPattern"); mActivity.startActivityForResult(intent, request); return true; } /** * Launch screen to confirm the existing lock password. * @see #onActivityResult(int, int, android.content.Intent) * @return true if we launched an activity to confirm password */ private boolean confirmPassword(int request) { if (!mLockPatternUtils.isLockPasswordEnabled()) return false; final Intent intent = new Intent(); intent.setClassName("com.android.settings", "com.android.settings.ConfirmLockPassword"); mActivity.startActivityForResult(intent, request); return true; } }
true
true
protected boolean launchConfirmationActivity(int request) { boolean launched = false; switch (mLockPatternUtils.getKeyguardStoredPasswordQuality()) { case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING: launched = confirmPattern(request); break; case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC: case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC: launched = confirmPassword(request); break; } return launched; }
protected boolean launchConfirmationActivity(int request) { boolean launched = false; switch (mLockPatternUtils.getKeyguardStoredPasswordQuality()) { case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING: launched = confirmPattern(request); break; case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC: case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC: case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC: launched = confirmPassword(request); break; } return launched; }
diff --git a/src/main/java/com/ngdb/web/pages/Index.java b/src/main/java/com/ngdb/web/pages/Index.java index 715ba03..02280d3 100644 --- a/src/main/java/com/ngdb/web/pages/Index.java +++ b/src/main/java/com/ngdb/web/pages/Index.java @@ -1,95 +1,96 @@ package com.ngdb.web.pages; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; import org.apache.tapestry5.annotations.Property; import org.apache.tapestry5.annotations.SetupRender; import org.apache.tapestry5.ioc.annotations.Inject; import com.ngdb.entities.GameFactory; import com.ngdb.entities.HardwareFactory; import com.ngdb.entities.Population; import com.ngdb.entities.WishBox; import com.ngdb.entities.article.Game; public class Index { @Inject private GameFactory gameFactory; @Inject private WishBox wishBox; @Property private Long articleCount; @Inject private HardwareFactory hardwareFactory; @Inject private Population population; @Inject private com.ngdb.entities.Market market; private static Cache cache; static { CacheManager create = CacheManager.create(); cache = create.getCache("index.random.games"); } @SetupRender public void init() { this.articleCount = gameFactory.getNumGames() + hardwareFactory.getNumHardwares(); } public Long getNumWhishes() { return wishBox.getNumWishes(); } public Long getMemberCount() { return population.getNumUsers(); } public Long getShopItemCount() { return market.getNumForSaleItems(); } public Game getRandomGame1() { return getRandomGameFromCache(1); } public Game getRandomGame2() { return getRandomGameFromCache(2); } public Game getRandomGame3() { return getRandomGameFromCache(3); } private Game getRandomGameFromCache(int index) { - if (cache.isKeyInCache(index)) { - return (Game) cache.get(index).getValue(); + Element elementInCache = cache.get(index); + if (elementInCache != null) { + return (Game) elementInCache.getValue(); } Game randomGame = gameFactory.getRandomGameWithMainPicture(); Element element = new Element(index, randomGame); cache.put(element); return getRandomGameFromCache(index); } public String getRandomGame1MainPicture() { return getRandomGame1().getMainPicture().getUrl("medium"); } public String getRandomGame2MainPicture() { return getRandomGame2().getMainPicture().getUrl("medium"); } public String getRandomGame3MainPicture() { return getRandomGame3().getMainPicture().getUrl("medium"); } }
true
true
private Game getRandomGameFromCache(int index) { if (cache.isKeyInCache(index)) { return (Game) cache.get(index).getValue(); } Game randomGame = gameFactory.getRandomGameWithMainPicture(); Element element = new Element(index, randomGame); cache.put(element); return getRandomGameFromCache(index); }
private Game getRandomGameFromCache(int index) { Element elementInCache = cache.get(index); if (elementInCache != null) { return (Game) elementInCache.getValue(); } Game randomGame = gameFactory.getRandomGameWithMainPicture(); Element element = new Element(index, randomGame); cache.put(element); return getRandomGameFromCache(index); }
diff --git a/src/java/ctd/services/getSamples.java b/src/java/ctd/services/getSamples.java index 667d2e1..c5cd9f5 100644 --- a/src/java/ctd/services/getSamples.java +++ b/src/java/ctd/services/getSamples.java @@ -1,268 +1,268 @@ package ctd.services; import com.skaringa.javaxml.DeserializerException; import com.skaringa.javaxml.NoImplementationException; import com.skaringa.javaxml.ObjectTransformer; import com.skaringa.javaxml.ObjectTransformerFactory; import ctd.model.StudySampleAssay; import ctd.services.exceptions.Exception400BadRequest; import ctd.services.exceptions.Exception401Unauthorized; import ctd.services.exceptions.Exception403Forbidden; import ctd.services.exceptions.Exception500InternalServerError; import ctd.services.internal.GscfService; import ctd.services.internal.responseComparator; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Map.Entry; import java.util.ResourceBundle; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Query; import org.hibernate.cfg.Configuration; /** * @author Tjeerd van Dijk * @author Taco Steemers */ public class getSamples { private String strAssayToken; private String strSessionToken; private String strFilename; private boolean blnError = false; /*** * This function gets all available Assaytokens from GSCF that can be linked * to a specific assay. It also gets a filename of a zip containing .cel files * * @return the table with filenames and sampletokens * @throws Exception400BadRequest this exception is thrown if no sessionToken or assayToken is set * @throws Exception403Forbidden this exception is thrown if the sessionToken is invalide * @throws Exception500InternalServerError this exception is thrown if there is some kind of unknown error */ public String getSamples() throws Exception400BadRequest, Exception403Forbidden, Exception500InternalServerError { String strReturn = ""; // Check if the minimal parameters are set if(getSessionToken()==null){ Logger.getLogger(getTicket.class.getName()).log(Level.SEVERE, "getSamples(): strSessionToken==null"); throw new Exception400BadRequest(); } if(getAssayToken()==null){ Logger.getLogger(getTicket.class.getName()).log(Level.SEVERE, "getSamples(): strAssayToken==null"); throw new Exception400BadRequest(); } // Check if the provided sessionToken is valid GscfService objGSCFService = new GscfService(); ResourceBundle res = ResourceBundle.getBundle("settings"); HashMap<String, String> restParams = new HashMap<String, String>(); restParams.put("assayToken", getAssayToken()); String[] strGSCFRespons = objGSCFService.callGSCF(getSessionToken(),"isUser",restParams); if(!objGSCFService.isUser(strGSCFRespons[1])) { Logger.getLogger(getTicket.class.getName()).log(Level.SEVERE, "getSamples(): strSessionToken invalid: "+getSessionToken()); throw new Exception403Forbidden(); } LinkedList lstGetSamples = objGSCFService.callGSCF2(getSessionToken(),"getSamples",restParams); Collections.sort(lstGetSamples, new responseComparator("name")); strReturn = ""; strReturn += "<table style='width:100%'>"; - strReturn += "<tr class='fs_th'><th>Filenames</th><th>Samplenames</th></tr>"; + strReturn += "<tr class='fs_th'><th>Filenames</th><th>Samplenames <span class='fs_fontsize'>[<a href='#' onClick='resetall(); return false;'>clear all</a>]</span></th></tr>"; HashMap<String, String> mapFiles = getFilesFromDatabase(getAssayToken()); LinkedList<String> lstFilenames = new LinkedList<String>(); try { // Open the ZIP file ZipFile zf = new ZipFile(res.getString("ws.upload_folder")+strFilename); // Enumerate each entry String strUglyHack = ""; for (Enumeration entries = zf.entries(); entries.hasMoreElements();) { // Get the entry name String zipEntryName = ((ZipEntry)entries.nextElement()).getName(); if(!zipEntryName.equals(".") && !zipEntryName.equals("..")){ if(!strUglyHack.equals("")) strUglyHack += "!!SEP!!"; strUglyHack += zipEntryName; } } String[] arrFiles = strUglyHack.split("!!SEP!!"); Arrays.sort(arrFiles); lstFilenames.addAll(Arrays.asList(arrFiles)); } catch (IOException e) { Logger.getLogger(getSamples.class.getName()).log(Level.SEVERE, "ERROR getSamples: "+e.getMessage()); } if(lstGetSamples.size()<lstFilenames.size()) { blnError = true; return "<b>There are more files in the submitted .zip than there are available samples.</b><br />Go to the study in GSCF (<a href='"+res.getString("gscf.baseURL")+"/assay/showByToken/"+getAssayToken()+"'>link</a>) and add more samples.<br />"; } if(lstFilenames.size()==0) { blnError = true; return "<b>There are either no files in the submitted .zip, or the .zip is corrupted.</b><br/>No data has been processed!</br>Please make sure your .zip contains cel-files and is readable before you upload it.<br />"; } String strOptions = "<option value='none'>Select a sample for this file...</option>"; while(lstGetSamples.size()>0) { HashMap<String, String> mapSamples = (HashMap<String, String>) lstGetSamples.removeFirst(); if(!mapFiles.containsKey(mapSamples.get("sampleToken"))) { strOptions += "<option value='"+mapSamples.get("sampleToken")+"'>"+mapSamples.get("name")+" - "+mapSamples.get("event")+" - "+mapSamples.get("Text on vial")+"</option>"; } else { strReturn += "<tr><td class='fs_fontsize' style='width:50%; background-color:#CCC;'>"+mapFiles.get(mapSamples.get("sampleToken"))+"</td>" +"<td class='fs_fontsize' style='width:50%; background-color:#CCC;'>" +mapSamples.get("name")+" - "+mapSamples.get("event")+" - "+mapSamples.get("Text on vial") +"</td></tr>"; } } for(int i=0; i<lstFilenames.size(); i++) { String strColor = "#DDEFFF"; if(i%2==0) { strColor = "#FFFFFF"; } String fn = lstFilenames.get(i); strReturn += "<tr><td class='fs_fontsize' style='width:50%; background-color:"+strColor+";'>"+fn+"</td>" +"<td class='fs_fontsize' style='width:50%; background-color:"+strColor+";'>" +"<select id='"+fn+"' class='select_file' style='width:250px' onChange=\"updateOptions('"+fn+"');\">"+strOptions+"</select>" + "<a href='#' id='link_autofill_"+fn+"' style='visibility: hidden' onClick=\"autofill('"+fn+"'); return false;\"><img src='./images/lightningBolt.png' style='border: 0px;' alt='autofill' /></a>" + " <span id='errorspan_"+fn+"' style='visibility: hidden; color:red; font-weight:bold;'>!!!</span></td></tr>"; } strReturn += "</table>"; return strReturn; } public String getSamplesOverview() { String strRet = "<table class='overviewdet'>"; strRet += "<tr>" + "<th>Event</th>"+ "<th>Start time</th>"+ "<th>Subject</th>"+ "<th>Name</th>"+ "<th>Material</th>"+ "<th>File</th>"+ "</tr>\n"; if(getAssayToken()!=null && getSessionToken()!=null) { GscfService objGSCFService = new GscfService(); HashMap<String, String> restParams = new HashMap<String, String>(); restParams.put("assayToken", getAssayToken()); LinkedList lstGetSamples = objGSCFService.callGSCF2(getSessionToken(),"getSamples",restParams); Collections.sort(lstGetSamples, new responseComparator("name")); Collections.sort(lstGetSamples, new responseComparator("subject")); Collections.sort(lstGetSamples, new responseComparator("startTime")); Collections.sort(lstGetSamples, new responseComparator("event")); HashMap<String, String> mapFiles = getFilesFromDatabase(getAssayToken()); while(lstGetSamples.size()>0) { HashMap<String, String> mapSamples = (HashMap<String, String>) lstGetSamples.removeFirst(); String strFile = "<i>no file</i>"; if(mapFiles.containsKey(mapSamples.get("sampleToken"))) { strFile = mapFiles.get(mapSamples.get("sampleToken")); } strRet += "<tr style='border: 1px solid white;'>" + "<td>"+mapSamples.get("event")+"</td>"+ "<td>"+mapSamples.get("startTime")+"</td>"+ "<td>"+mapSamples.get("subject")+"</td>"+ "<td>"+mapSamples.get("name")+"</td>"+ "<td>"+mapSamples.get("material")+"</td>"+ "<td>"+strFile+"</td>"+ "</tr>\n"; } } strRet += "</table>"; return strRet; } public HashMap<String, String> getFilesFromDatabase(String strAssToken) { SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); HashMap<String, String> mapFiles = new HashMap<String, String>(); Query q1 = session.createQuery("from StudySampleAssay where X_REF='"+strAssToken+"'"); Iterator it1 = q1.iterate(); while (it1.hasNext()){ StudySampleAssay ssa = (StudySampleAssay) it1.next(); mapFiles.put(ssa.getSampleToken(), ssa.getNameRawfile()); } session.close(); sessionFactory.close(); //Logger.getLogger(getSamples.class.getName()).log(Level.SEVERE, "getFiles: "+mapFiles.size()+" "+strAssToken); return mapFiles; } /** * @return the strSessionToken */ public String getSessionToken() { return strSessionToken; } /** * @param strSessionToken the strSessionToken to set */ public void setSessionToken(String strSessionToken) { this.strSessionToken = strSessionToken; } /** * @return the strAssayToken */ public String getAssayToken() { return strAssayToken; } /** * @param strAssayToken the strAssayToken to set */ public void setAssayToken(String assayToken) { this.strAssayToken = assayToken; } /** * @return the strFilename */ public String getFilename() { return strFilename; } /** * @param strFilename the strFilename to set */ public void setFilename(String strFilename) { this.strFilename = strFilename; } /** * @return the blnError */ public boolean getError() { return blnError; } }
true
true
public String getSamples() throws Exception400BadRequest, Exception403Forbidden, Exception500InternalServerError { String strReturn = ""; // Check if the minimal parameters are set if(getSessionToken()==null){ Logger.getLogger(getTicket.class.getName()).log(Level.SEVERE, "getSamples(): strSessionToken==null"); throw new Exception400BadRequest(); } if(getAssayToken()==null){ Logger.getLogger(getTicket.class.getName()).log(Level.SEVERE, "getSamples(): strAssayToken==null"); throw new Exception400BadRequest(); } // Check if the provided sessionToken is valid GscfService objGSCFService = new GscfService(); ResourceBundle res = ResourceBundle.getBundle("settings"); HashMap<String, String> restParams = new HashMap<String, String>(); restParams.put("assayToken", getAssayToken()); String[] strGSCFRespons = objGSCFService.callGSCF(getSessionToken(),"isUser",restParams); if(!objGSCFService.isUser(strGSCFRespons[1])) { Logger.getLogger(getTicket.class.getName()).log(Level.SEVERE, "getSamples(): strSessionToken invalid: "+getSessionToken()); throw new Exception403Forbidden(); } LinkedList lstGetSamples = objGSCFService.callGSCF2(getSessionToken(),"getSamples",restParams); Collections.sort(lstGetSamples, new responseComparator("name")); strReturn = ""; strReturn += "<table style='width:100%'>"; strReturn += "<tr class='fs_th'><th>Filenames</th><th>Samplenames</th></tr>"; HashMap<String, String> mapFiles = getFilesFromDatabase(getAssayToken()); LinkedList<String> lstFilenames = new LinkedList<String>(); try { // Open the ZIP file ZipFile zf = new ZipFile(res.getString("ws.upload_folder")+strFilename); // Enumerate each entry String strUglyHack = ""; for (Enumeration entries = zf.entries(); entries.hasMoreElements();) { // Get the entry name String zipEntryName = ((ZipEntry)entries.nextElement()).getName(); if(!zipEntryName.equals(".") && !zipEntryName.equals("..")){ if(!strUglyHack.equals("")) strUglyHack += "!!SEP!!"; strUglyHack += zipEntryName; } } String[] arrFiles = strUglyHack.split("!!SEP!!"); Arrays.sort(arrFiles); lstFilenames.addAll(Arrays.asList(arrFiles)); } catch (IOException e) { Logger.getLogger(getSamples.class.getName()).log(Level.SEVERE, "ERROR getSamples: "+e.getMessage()); } if(lstGetSamples.size()<lstFilenames.size()) { blnError = true; return "<b>There are more files in the submitted .zip than there are available samples.</b><br />Go to the study in GSCF (<a href='"+res.getString("gscf.baseURL")+"/assay/showByToken/"+getAssayToken()+"'>link</a>) and add more samples.<br />"; } if(lstFilenames.size()==0) { blnError = true; return "<b>There are either no files in the submitted .zip, or the .zip is corrupted.</b><br/>No data has been processed!</br>Please make sure your .zip contains cel-files and is readable before you upload it.<br />"; } String strOptions = "<option value='none'>Select a sample for this file...</option>"; while(lstGetSamples.size()>0) { HashMap<String, String> mapSamples = (HashMap<String, String>) lstGetSamples.removeFirst(); if(!mapFiles.containsKey(mapSamples.get("sampleToken"))) { strOptions += "<option value='"+mapSamples.get("sampleToken")+"'>"+mapSamples.get("name")+" - "+mapSamples.get("event")+" - "+mapSamples.get("Text on vial")+"</option>"; } else { strReturn += "<tr><td class='fs_fontsize' style='width:50%; background-color:#CCC;'>"+mapFiles.get(mapSamples.get("sampleToken"))+"</td>" +"<td class='fs_fontsize' style='width:50%; background-color:#CCC;'>" +mapSamples.get("name")+" - "+mapSamples.get("event")+" - "+mapSamples.get("Text on vial") +"</td></tr>"; } } for(int i=0; i<lstFilenames.size(); i++) { String strColor = "#DDEFFF"; if(i%2==0) { strColor = "#FFFFFF"; } String fn = lstFilenames.get(i); strReturn += "<tr><td class='fs_fontsize' style='width:50%; background-color:"+strColor+";'>"+fn+"</td>" +"<td class='fs_fontsize' style='width:50%; background-color:"+strColor+";'>" +"<select id='"+fn+"' class='select_file' style='width:250px' onChange=\"updateOptions('"+fn+"');\">"+strOptions+"</select>" + "<a href='#' id='link_autofill_"+fn+"' style='visibility: hidden' onClick=\"autofill('"+fn+"'); return false;\"><img src='./images/lightningBolt.png' style='border: 0px;' alt='autofill' /></a>" + " <span id='errorspan_"+fn+"' style='visibility: hidden; color:red; font-weight:bold;'>!!!</span></td></tr>"; } strReturn += "</table>"; return strReturn; }
public String getSamples() throws Exception400BadRequest, Exception403Forbidden, Exception500InternalServerError { String strReturn = ""; // Check if the minimal parameters are set if(getSessionToken()==null){ Logger.getLogger(getTicket.class.getName()).log(Level.SEVERE, "getSamples(): strSessionToken==null"); throw new Exception400BadRequest(); } if(getAssayToken()==null){ Logger.getLogger(getTicket.class.getName()).log(Level.SEVERE, "getSamples(): strAssayToken==null"); throw new Exception400BadRequest(); } // Check if the provided sessionToken is valid GscfService objGSCFService = new GscfService(); ResourceBundle res = ResourceBundle.getBundle("settings"); HashMap<String, String> restParams = new HashMap<String, String>(); restParams.put("assayToken", getAssayToken()); String[] strGSCFRespons = objGSCFService.callGSCF(getSessionToken(),"isUser",restParams); if(!objGSCFService.isUser(strGSCFRespons[1])) { Logger.getLogger(getTicket.class.getName()).log(Level.SEVERE, "getSamples(): strSessionToken invalid: "+getSessionToken()); throw new Exception403Forbidden(); } LinkedList lstGetSamples = objGSCFService.callGSCF2(getSessionToken(),"getSamples",restParams); Collections.sort(lstGetSamples, new responseComparator("name")); strReturn = ""; strReturn += "<table style='width:100%'>"; strReturn += "<tr class='fs_th'><th>Filenames</th><th>Samplenames <span class='fs_fontsize'>[<a href='#' onClick='resetall(); return false;'>clear all</a>]</span></th></tr>"; HashMap<String, String> mapFiles = getFilesFromDatabase(getAssayToken()); LinkedList<String> lstFilenames = new LinkedList<String>(); try { // Open the ZIP file ZipFile zf = new ZipFile(res.getString("ws.upload_folder")+strFilename); // Enumerate each entry String strUglyHack = ""; for (Enumeration entries = zf.entries(); entries.hasMoreElements();) { // Get the entry name String zipEntryName = ((ZipEntry)entries.nextElement()).getName(); if(!zipEntryName.equals(".") && !zipEntryName.equals("..")){ if(!strUglyHack.equals("")) strUglyHack += "!!SEP!!"; strUglyHack += zipEntryName; } } String[] arrFiles = strUglyHack.split("!!SEP!!"); Arrays.sort(arrFiles); lstFilenames.addAll(Arrays.asList(arrFiles)); } catch (IOException e) { Logger.getLogger(getSamples.class.getName()).log(Level.SEVERE, "ERROR getSamples: "+e.getMessage()); } if(lstGetSamples.size()<lstFilenames.size()) { blnError = true; return "<b>There are more files in the submitted .zip than there are available samples.</b><br />Go to the study in GSCF (<a href='"+res.getString("gscf.baseURL")+"/assay/showByToken/"+getAssayToken()+"'>link</a>) and add more samples.<br />"; } if(lstFilenames.size()==0) { blnError = true; return "<b>There are either no files in the submitted .zip, or the .zip is corrupted.</b><br/>No data has been processed!</br>Please make sure your .zip contains cel-files and is readable before you upload it.<br />"; } String strOptions = "<option value='none'>Select a sample for this file...</option>"; while(lstGetSamples.size()>0) { HashMap<String, String> mapSamples = (HashMap<String, String>) lstGetSamples.removeFirst(); if(!mapFiles.containsKey(mapSamples.get("sampleToken"))) { strOptions += "<option value='"+mapSamples.get("sampleToken")+"'>"+mapSamples.get("name")+" - "+mapSamples.get("event")+" - "+mapSamples.get("Text on vial")+"</option>"; } else { strReturn += "<tr><td class='fs_fontsize' style='width:50%; background-color:#CCC;'>"+mapFiles.get(mapSamples.get("sampleToken"))+"</td>" +"<td class='fs_fontsize' style='width:50%; background-color:#CCC;'>" +mapSamples.get("name")+" - "+mapSamples.get("event")+" - "+mapSamples.get("Text on vial") +"</td></tr>"; } } for(int i=0; i<lstFilenames.size(); i++) { String strColor = "#DDEFFF"; if(i%2==0) { strColor = "#FFFFFF"; } String fn = lstFilenames.get(i); strReturn += "<tr><td class='fs_fontsize' style='width:50%; background-color:"+strColor+";'>"+fn+"</td>" +"<td class='fs_fontsize' style='width:50%; background-color:"+strColor+";'>" +"<select id='"+fn+"' class='select_file' style='width:250px' onChange=\"updateOptions('"+fn+"');\">"+strOptions+"</select>" + "<a href='#' id='link_autofill_"+fn+"' style='visibility: hidden' onClick=\"autofill('"+fn+"'); return false;\"><img src='./images/lightningBolt.png' style='border: 0px;' alt='autofill' /></a>" + " <span id='errorspan_"+fn+"' style='visibility: hidden; color:red; font-weight:bold;'>!!!</span></td></tr>"; } strReturn += "</table>"; return strReturn; }
diff --git a/src/main/java/com/seedboxer/seedboxer/sources/processors/QueueProcessor.java b/src/main/java/com/seedboxer/seedboxer/sources/processors/QueueProcessor.java index 7bcc31d..7f0ef6a 100644 --- a/src/main/java/com/seedboxer/seedboxer/sources/processors/QueueProcessor.java +++ b/src/main/java/com/seedboxer/seedboxer/sources/processors/QueueProcessor.java @@ -1,121 +1,121 @@ /******************************************************************************* * QueueProcessor.java * * Copyright (c) 2012 SeedBoxer Team. * * This file is part of SeedBoxer. * * SeedBoxer 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. * * SeedBoxer 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 SeedBoxer. If not, see <http ://www.gnu.org/licenses/>. ******************************************************************************/ package com.seedboxer.seedboxer.sources.processors; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; import java.util.Map; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.klomp.snark.bencode.BDecoder; import org.klomp.snark.bencode.BEValue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import com.seedboxer.seedboxer.core.domain.Content; import com.seedboxer.seedboxer.core.domain.User; import com.seedboxer.seedboxer.core.logic.DownloadsQueueManager; import com.seedboxer.seedboxer.sources.type.DownloadableItem; /** * * @author The-Sultan */ @Component public class QueueProcessor implements Processor{ private static final Logger LOGGER = LoggerFactory.getLogger(QueueProcessor.class); @Autowired private DownloadsQueueManager queueManager; @Value(value="${watchDownloaderPath}") private String path; @Value(value="${completePath}") private String completePath; @Override public void process(Exchange exchange) { DownloadableItem downloadableItem = (DownloadableItem) exchange.getIn().getBody(); Content content = downloadableItem.getContent(); URL url = content.getMatchableItem().getUrl(); try { String fileName = downloadFile(url,path); String dirName = getDirNameFromTorrentFile(path + File.separator + fileName); LOGGER.debug("Downloaded torrent: "+path); for(User user : downloadableItem.getUsers()){ String absoluteOutputDir = completePath + File.separator + dirName; queueManager.push(user, absoluteOutputDir); } } catch (IOException ex) { LOGGER.error("Error downloading file: {}", url, ex); } } @SuppressWarnings("rawtypes") private String getDirNameFromTorrentFile(String path) throws FileNotFoundException, IOException{ BDecoder decoder; decoder = new BDecoder(new FileInputStream(path)); Map map = decoder.bdecode().getMap(); BEValue info = (BEValue) map.get("info"); Map mapInfo = info.getMap(); return ((BEValue)mapInfo.get("name")).getString(); } private String downloadFile(URL url, String path) throws IOException { URLConnection conn = url.openConnection(); InputStream in = conn.getInputStream(); String disposition = conn.getHeaderField("Content-Disposition"); String fileNameProperty = "filename=\""; String fileName = disposition.substring(disposition.indexOf(fileNameProperty),disposition.lastIndexOf("\"")); fileName = fileName.substring(fileNameProperty.length(),fileName.length()); path += File.separator + fileName; File file = new File(path); OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); byte[] bytes = new byte[1024]; int read; while ((read = in.read(bytes)) != -1) { out.write(bytes, 0, read); } in.close(); out.close(); - file.setReadable(true, false); - file.setWritable(true, false); + file.setReadable(true, false); + file.setWritable(true, false); return fileName; } }
true
true
private String downloadFile(URL url, String path) throws IOException { URLConnection conn = url.openConnection(); InputStream in = conn.getInputStream(); String disposition = conn.getHeaderField("Content-Disposition"); String fileNameProperty = "filename=\""; String fileName = disposition.substring(disposition.indexOf(fileNameProperty),disposition.lastIndexOf("\"")); fileName = fileName.substring(fileNameProperty.length(),fileName.length()); path += File.separator + fileName; File file = new File(path); OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); byte[] bytes = new byte[1024]; int read; while ((read = in.read(bytes)) != -1) { out.write(bytes, 0, read); } in.close(); out.close(); file.setReadable(true, false); file.setWritable(true, false); return fileName; }
private String downloadFile(URL url, String path) throws IOException { URLConnection conn = url.openConnection(); InputStream in = conn.getInputStream(); String disposition = conn.getHeaderField("Content-Disposition"); String fileNameProperty = "filename=\""; String fileName = disposition.substring(disposition.indexOf(fileNameProperty),disposition.lastIndexOf("\"")); fileName = fileName.substring(fileNameProperty.length(),fileName.length()); path += File.separator + fileName; File file = new File(path); OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); byte[] bytes = new byte[1024]; int read; while ((read = in.read(bytes)) != -1) { out.write(bytes, 0, read); } in.close(); out.close(); file.setReadable(true, false); file.setWritable(true, false); return fileName; }
diff --git a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/actions/CommitActionHandler.java b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/actions/CommitActionHandler.java index da5c6006..147d8486 100644 --- a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/actions/CommitActionHandler.java +++ b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/actions/CommitActionHandler.java @@ -1,417 +1,418 @@ /******************************************************************************* * Copyright (C) 2007, Dave Watson <[email protected]> * Copyright (C) 2007, Jing Xue <[email protected]> * Copyright (C) 2007, Robin Rosenberg <[email protected]> * Copyright (C) 2008, Robin Rosenberg <[email protected]> * Copyright (C) 2008, Shawn O. Pearce <[email protected]> * Copyright (C) 2010, Stefan Lay <[email protected]> * * 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 *******************************************************************************/ package org.eclipse.egit.ui.internal.actions; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceVisitor; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.egit.core.op.CommitOperation; import org.eclipse.egit.core.project.GitProjectData; import org.eclipse.egit.core.project.RepositoryMapping; import org.eclipse.egit.ui.Activator; import org.eclipse.egit.ui.UIText; import org.eclipse.egit.ui.internal.decorators.GitLightweightDecorator; import org.eclipse.egit.ui.internal.dialogs.CommitDialog; import org.eclipse.egit.ui.internal.trace.GitTraceLocation; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jgit.lib.Commit; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.GitIndex; import org.eclipse.jgit.lib.IndexDiff; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.RepositoryConfig; import org.eclipse.jgit.lib.RepositoryState; import org.eclipse.jgit.lib.Tree; import org.eclipse.jgit.lib.TreeEntry; import org.eclipse.jgit.lib.GitIndex.Entry; import org.eclipse.osgi.util.NLS; import org.eclipse.team.core.Team; import org.eclipse.team.core.TeamException; import org.eclipse.ui.PlatformUI; /** * Scan for modified resources in the same project as the selected resources. */ public class CommitActionHandler extends RepositoryActionHandler { private ArrayList<IFile> notIndexed; private ArrayList<IFile> indexChanges; private ArrayList<IFile> notTracked; private ArrayList<IFile> files; private Commit previousCommit; private boolean amendAllowed; private boolean amending; public Object execute(final ExecutionEvent event) throws ExecutionException { // let's see if there is any dirty editor around and // ask the user if they want to save or abort if (!PlatformUI.getWorkbench().saveAllEditors(true)) { return null; } resetState(); try { buildIndexHeadDiffList(event); } catch (IOException e) { Activator.handleError(UIText.CommitAction_errorComputingDiffs, e, true); return null; } catch (CoreException e) { Activator.handleError(UIText.CommitAction_errorComputingDiffs, e, true); return null; } Repository[] repos = getRepositoriesFor(getProjectsForSelectedResources(event)); Repository repository = null; amendAllowed = repos.length == 1; for (Repository repo : repos) { repository = repo; RepositoryState state = repo.getRepositoryState(); // currently we don't support committing a merge commit if (state == RepositoryState.MERGING_RESOLVED || !state.canCommit()) { MessageDialog.openError(getShell(event), UIText.CommitAction_cannotCommit, NLS.bind( UIText.CommitAction_repositoryState, state .getDescription())); return null; } } loadPreviousCommit(event); if (files.isEmpty()) { if (amendAllowed && previousCommit != null) { boolean result = MessageDialog.openQuestion(getShell(event), UIText.CommitAction_noFilesToCommit, UIText.CommitAction_amendCommit); if (!result) return null; amending = true; } else { MessageDialog.openWarning(getShell(event), UIText.CommitAction_noFilesToCommit, UIText.CommitAction_amendNotPossible); return null; } } String author = null; String committer = null; if (repository != null) { final RepositoryConfig config = repository.getConfig(); author = config.getAuthorName(); final String authorEmail = config.getAuthorEmail(); author = author + " <" + authorEmail + ">"; //$NON-NLS-1$ //$NON-NLS-2$ committer = config.getCommitterName(); final String committerEmail = config.getCommitterEmail(); committer = committer + " <" + committerEmail + ">"; //$NON-NLS-1$ //$NON-NLS-2$ } CommitDialog commitDialog = new CommitDialog(getShell(event)); commitDialog.setAmending(amending); commitDialog.setAmendAllowed(amendAllowed); commitDialog.setFileList(files); commitDialog.setPreselectedFiles(getSelectedFiles(event)); commitDialog.setAuthor(author); commitDialog.setCommitter(committer); if (previousCommit != null) { commitDialog.setPreviousCommitMessage(previousCommit.getMessage()); PersonIdent previousAuthor = previousCommit.getAuthor(); commitDialog.setPreviousAuthor(previousAuthor.getName() + " <" + previousAuthor.getEmailAddress() + ">"); //$NON-NLS-1$ //$NON-NLS-2$ } if (commitDialog.open() != IDialogConstants.OK_ID) return null; final CommitOperation commitOperation = new CommitOperation( commitDialog.getSelectedFiles(), notIndexed, notTracked, commitDialog.getAuthor(), commitDialog.getCommitter(), commitDialog.getCommitMessage()); if (commitDialog.isAmending()) { commitOperation.setAmending(true); commitOperation.setPreviousCommit(previousCommit); commitOperation.setRepos(repos); } + commitOperation.setComputeChangeId(commitDialog.getCreateChangeId()); String jobname = UIText.CommitAction_CommittingChanges; Job job = new Job(jobname) { @Override protected IStatus run(IProgressMonitor monitor) { try { commitOperation.execute(monitor); for (IProject proj : getProjectsForSelectedResources(event)) { RepositoryMapping.getMapping(proj) .fireRepositoryChanged(); } } catch (CoreException e) { return Activator.createErrorStatus( UIText.CommitAction_CommittingFailed, e); } catch (ExecutionException e) { return Activator.createErrorStatus( UIText.CommitAction_CommittingFailed, e); } finally { GitLightweightDecorator.refresh(); } return Status.OK_STATUS; } }; job.setUser(true); job.schedule(); return null; } private void resetState() { files = new ArrayList<IFile>(); notIndexed = new ArrayList<IFile>(); indexChanges = new ArrayList<IFile>(); notTracked = new ArrayList<IFile>(); amending = false; previousCommit = null; } /** * Retrieves a collection of files that may be committed based on the user's * selection when they performed the commit action. That is, even if the * user only selected one folder when the action was performed, if the * folder contains any files that could be committed, they will be returned. * * @param event * * @return a collection of files that is eligible to be committed based on * the user's selection * @throws ExecutionException */ private Collection<IFile> getSelectedFiles(ExecutionEvent event) throws ExecutionException { List<IFile> preselectionCandidates = new ArrayList<IFile>(); // get the resources the user selected IResource[] selectedResources = getSelectedResources(event); // iterate through all the files that may be committed for (IFile file : files) { for (IResource resource : selectedResources) { // if any selected resource contains the file, add it as a // preselection candidate if (resource.contains(file)) { preselectionCandidates.add(file); break; } } } return preselectionCandidates; } private void loadPreviousCommit(ExecutionEvent event) throws ExecutionException { IProject project = getProjectsForSelectedResources(event)[0]; Repository repo = RepositoryMapping.getMapping(project).getRepository(); try { ObjectId parentId = repo.resolve(Constants.HEAD); if (parentId != null) previousCommit = repo.mapCommit(parentId); } catch (IOException e) { Activator.handleError(UIText.CommitAction_errorRetrievingCommit, e, true); } } private void buildIndexHeadDiffList(ExecutionEvent event) throws IOException, CoreException, ExecutionException { HashMap<Repository, HashSet<IProject>> repositories = new HashMap<Repository, HashSet<IProject>>(); for (IProject project : getProjectsInRepositoryOfSelectedResources(event)) { RepositoryMapping repositoryMapping = RepositoryMapping .getMapping(project); assert repositoryMapping != null; Repository repository = repositoryMapping.getRepository(); HashSet<IProject> projects = repositories.get(repository); if (projects == null) { projects = new HashSet<IProject>(); repositories.put(repository, projects); } projects.add(project); } for (Map.Entry<Repository, HashSet<IProject>> entry : repositories .entrySet()) { Repository repository = entry.getKey(); HashSet<IProject> projects = entry.getValue(); Tree head = repository.mapTree(Constants.HEAD); GitIndex index = repository.getIndex(); IndexDiff indexDiff = new IndexDiff(head, index); indexDiff.diff(); for (IProject project : projects) { includeList(project, indexDiff.getAdded(), indexChanges); includeList(project, indexDiff.getChanged(), indexChanges); includeList(project, indexDiff.getRemoved(), indexChanges); includeList(project, indexDiff.getMissing(), notIndexed); includeList(project, indexDiff.getModified(), notIndexed); addUntrackedFiles(repository, project); } } } private void addUntrackedFiles(final Repository repository, final IProject project) throws CoreException, IOException { final GitIndex index = repository.getIndex(); final Tree headTree = repository.mapTree(Constants.HEAD); project.accept(new IResourceVisitor() { public boolean visit(IResource resource) throws CoreException { if (Team.isIgnoredHint(resource)) return false; if (resource.getType() == IResource.FILE) { String repoRelativePath = RepositoryMapping.getMapping( project).getRepoRelativePath(resource); try { TreeEntry headEntry = (headTree == null ? null : headTree.findBlobMember(repoRelativePath)); if (headEntry == null) { Entry indexEntry = null; indexEntry = index.getEntry(repoRelativePath); if (indexEntry == null) { notTracked.add((IFile) resource); files.add((IFile) resource); } } } catch (IOException e) { throw new TeamException( UIText.CommitAction_InternalError, e); } } return true; } }); } private void includeList(IProject project, HashSet<String> added, ArrayList<IFile> category) { String repoRelativePath = RepositoryMapping.getMapping(project) .getRepoRelativePath(project); if (repoRelativePath.length() > 0) { repoRelativePath += "/"; //$NON-NLS-1$ } for (String filename : added) { try { if (!filename.startsWith(repoRelativePath)) continue; String projectRelativePath = filename .substring(repoRelativePath.length()); IFile member = project.getFile(projectRelativePath); if (!files.contains(member)) files.add(member); category.add(member); } catch (Exception e) { if (GitTraceLocation.UI.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.UI.getLocation(), e.getMessage(), e); continue; } // if it's outside the workspace, bad things happen } } boolean tryAddResource(IFile resource, GitProjectData projectData, ArrayList<IFile> category) { if (files.contains(resource)) return false; try { RepositoryMapping repositoryMapping = projectData .getRepositoryMapping(resource); if (isChanged(repositoryMapping, resource)) { files.add(resource); category.add(resource); return true; } } catch (Exception e) { if (GitTraceLocation.UI.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.UI.getLocation(), e.getMessage(), e); } return false; } private boolean isChanged(RepositoryMapping map, IFile resource) { try { Repository repository = map.getRepository(); GitIndex index = repository.getIndex(); String repoRelativePath = map.getRepoRelativePath(resource); Entry entry = index.getEntry(repoRelativePath); if (entry != null) return entry.isModified(map.getWorkDir()); return false; } catch (UnsupportedEncodingException e) { if (GitTraceLocation.UI.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.UI.getLocation(), e.getMessage(), e); } catch (IOException e) { if (GitTraceLocation.UI.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.UI.getLocation(), e.getMessage(), e); } return false; } @Override public boolean isEnabled() { try { return getProjectsInRepositoryOfSelectedResources(null).length > 0; } catch (ExecutionException e) { Activator.handleError(e.getMessage(), e, false); return false; } } }
true
true
public Object execute(final ExecutionEvent event) throws ExecutionException { // let's see if there is any dirty editor around and // ask the user if they want to save or abort if (!PlatformUI.getWorkbench().saveAllEditors(true)) { return null; } resetState(); try { buildIndexHeadDiffList(event); } catch (IOException e) { Activator.handleError(UIText.CommitAction_errorComputingDiffs, e, true); return null; } catch (CoreException e) { Activator.handleError(UIText.CommitAction_errorComputingDiffs, e, true); return null; } Repository[] repos = getRepositoriesFor(getProjectsForSelectedResources(event)); Repository repository = null; amendAllowed = repos.length == 1; for (Repository repo : repos) { repository = repo; RepositoryState state = repo.getRepositoryState(); // currently we don't support committing a merge commit if (state == RepositoryState.MERGING_RESOLVED || !state.canCommit()) { MessageDialog.openError(getShell(event), UIText.CommitAction_cannotCommit, NLS.bind( UIText.CommitAction_repositoryState, state .getDescription())); return null; } } loadPreviousCommit(event); if (files.isEmpty()) { if (amendAllowed && previousCommit != null) { boolean result = MessageDialog.openQuestion(getShell(event), UIText.CommitAction_noFilesToCommit, UIText.CommitAction_amendCommit); if (!result) return null; amending = true; } else { MessageDialog.openWarning(getShell(event), UIText.CommitAction_noFilesToCommit, UIText.CommitAction_amendNotPossible); return null; } } String author = null; String committer = null; if (repository != null) { final RepositoryConfig config = repository.getConfig(); author = config.getAuthorName(); final String authorEmail = config.getAuthorEmail(); author = author + " <" + authorEmail + ">"; //$NON-NLS-1$ //$NON-NLS-2$ committer = config.getCommitterName(); final String committerEmail = config.getCommitterEmail(); committer = committer + " <" + committerEmail + ">"; //$NON-NLS-1$ //$NON-NLS-2$ } CommitDialog commitDialog = new CommitDialog(getShell(event)); commitDialog.setAmending(amending); commitDialog.setAmendAllowed(amendAllowed); commitDialog.setFileList(files); commitDialog.setPreselectedFiles(getSelectedFiles(event)); commitDialog.setAuthor(author); commitDialog.setCommitter(committer); if (previousCommit != null) { commitDialog.setPreviousCommitMessage(previousCommit.getMessage()); PersonIdent previousAuthor = previousCommit.getAuthor(); commitDialog.setPreviousAuthor(previousAuthor.getName() + " <" + previousAuthor.getEmailAddress() + ">"); //$NON-NLS-1$ //$NON-NLS-2$ } if (commitDialog.open() != IDialogConstants.OK_ID) return null; final CommitOperation commitOperation = new CommitOperation( commitDialog.getSelectedFiles(), notIndexed, notTracked, commitDialog.getAuthor(), commitDialog.getCommitter(), commitDialog.getCommitMessage()); if (commitDialog.isAmending()) { commitOperation.setAmending(true); commitOperation.setPreviousCommit(previousCommit); commitOperation.setRepos(repos); } String jobname = UIText.CommitAction_CommittingChanges; Job job = new Job(jobname) { @Override protected IStatus run(IProgressMonitor monitor) { try { commitOperation.execute(monitor); for (IProject proj : getProjectsForSelectedResources(event)) { RepositoryMapping.getMapping(proj) .fireRepositoryChanged(); } } catch (CoreException e) { return Activator.createErrorStatus( UIText.CommitAction_CommittingFailed, e); } catch (ExecutionException e) { return Activator.createErrorStatus( UIText.CommitAction_CommittingFailed, e); } finally { GitLightweightDecorator.refresh(); } return Status.OK_STATUS; } }; job.setUser(true); job.schedule(); return null; }
public Object execute(final ExecutionEvent event) throws ExecutionException { // let's see if there is any dirty editor around and // ask the user if they want to save or abort if (!PlatformUI.getWorkbench().saveAllEditors(true)) { return null; } resetState(); try { buildIndexHeadDiffList(event); } catch (IOException e) { Activator.handleError(UIText.CommitAction_errorComputingDiffs, e, true); return null; } catch (CoreException e) { Activator.handleError(UIText.CommitAction_errorComputingDiffs, e, true); return null; } Repository[] repos = getRepositoriesFor(getProjectsForSelectedResources(event)); Repository repository = null; amendAllowed = repos.length == 1; for (Repository repo : repos) { repository = repo; RepositoryState state = repo.getRepositoryState(); // currently we don't support committing a merge commit if (state == RepositoryState.MERGING_RESOLVED || !state.canCommit()) { MessageDialog.openError(getShell(event), UIText.CommitAction_cannotCommit, NLS.bind( UIText.CommitAction_repositoryState, state .getDescription())); return null; } } loadPreviousCommit(event); if (files.isEmpty()) { if (amendAllowed && previousCommit != null) { boolean result = MessageDialog.openQuestion(getShell(event), UIText.CommitAction_noFilesToCommit, UIText.CommitAction_amendCommit); if (!result) return null; amending = true; } else { MessageDialog.openWarning(getShell(event), UIText.CommitAction_noFilesToCommit, UIText.CommitAction_amendNotPossible); return null; } } String author = null; String committer = null; if (repository != null) { final RepositoryConfig config = repository.getConfig(); author = config.getAuthorName(); final String authorEmail = config.getAuthorEmail(); author = author + " <" + authorEmail + ">"; //$NON-NLS-1$ //$NON-NLS-2$ committer = config.getCommitterName(); final String committerEmail = config.getCommitterEmail(); committer = committer + " <" + committerEmail + ">"; //$NON-NLS-1$ //$NON-NLS-2$ } CommitDialog commitDialog = new CommitDialog(getShell(event)); commitDialog.setAmending(amending); commitDialog.setAmendAllowed(amendAllowed); commitDialog.setFileList(files); commitDialog.setPreselectedFiles(getSelectedFiles(event)); commitDialog.setAuthor(author); commitDialog.setCommitter(committer); if (previousCommit != null) { commitDialog.setPreviousCommitMessage(previousCommit.getMessage()); PersonIdent previousAuthor = previousCommit.getAuthor(); commitDialog.setPreviousAuthor(previousAuthor.getName() + " <" + previousAuthor.getEmailAddress() + ">"); //$NON-NLS-1$ //$NON-NLS-2$ } if (commitDialog.open() != IDialogConstants.OK_ID) return null; final CommitOperation commitOperation = new CommitOperation( commitDialog.getSelectedFiles(), notIndexed, notTracked, commitDialog.getAuthor(), commitDialog.getCommitter(), commitDialog.getCommitMessage()); if (commitDialog.isAmending()) { commitOperation.setAmending(true); commitOperation.setPreviousCommit(previousCommit); commitOperation.setRepos(repos); } commitOperation.setComputeChangeId(commitDialog.getCreateChangeId()); String jobname = UIText.CommitAction_CommittingChanges; Job job = new Job(jobname) { @Override protected IStatus run(IProgressMonitor monitor) { try { commitOperation.execute(monitor); for (IProject proj : getProjectsForSelectedResources(event)) { RepositoryMapping.getMapping(proj) .fireRepositoryChanged(); } } catch (CoreException e) { return Activator.createErrorStatus( UIText.CommitAction_CommittingFailed, e); } catch (ExecutionException e) { return Activator.createErrorStatus( UIText.CommitAction_CommittingFailed, e); } finally { GitLightweightDecorator.refresh(); } return Status.OK_STATUS; } }; job.setUser(true); job.schedule(); return null; }